2010-09-20 22:08:53 +02:00
|
|
|
<!-- doc/src/sgml/ddl.sgml -->
|
2002-08-05 21:44:58 +02:00
|
|
|
|
|
|
|
<chapter id="ddl">
|
|
|
|
<title>Data Definition</title>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
This chapter covers how one creates the database structures that
|
|
|
|
will hold one's data. In a relational database, the raw data is
|
|
|
|
stored in tables, so the majority of this chapter is devoted to
|
|
|
|
explaining how tables are created and modified and what features are
|
|
|
|
available to control what data is stored in the tables.
|
|
|
|
Subsequently, we discuss how tables can be organized into
|
2002-10-20 07:05:46 +02:00
|
|
|
schemas, and how privileges can be assigned to tables. Finally,
|
2002-08-05 21:44:58 +02:00
|
|
|
we will briefly look at other features that affect the data storage,
|
2017-02-10 11:03:28 +01:00
|
|
|
such as inheritance, table partitioning, views, functions, and
|
|
|
|
triggers.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<sect1 id="ddl-basics">
|
|
|
|
<title>Table Basics</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="ddl-basics">
|
|
|
|
<primary>table</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>row</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>column</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A table in a relational database is much like a table on paper: It
|
|
|
|
consists of rows and columns. The number and order of the columns
|
|
|
|
is fixed, and each column has a name. The number of rows is
|
2006-07-14 02:13:05 +02:00
|
|
|
variable — it reflects how much data is stored at a given moment.
|
2002-08-05 21:44:58 +02:00
|
|
|
SQL does not make any guarantees about the order of the rows in a
|
2010-08-20 15:59:45 +02:00
|
|
|
table. When a table is read, the rows will appear in an unspecified order,
|
2002-08-05 21:44:58 +02:00
|
|
|
unless sorting is explicitly requested. This is covered in <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="queries"/>. Furthermore, SQL does not assign unique
|
2002-08-05 21:44:58 +02:00
|
|
|
identifiers to rows, so it is possible to have several completely
|
|
|
|
identical rows in a table. This is a consequence of the
|
|
|
|
mathematical model that underlies SQL but is usually not desirable.
|
|
|
|
Later in this chapter we will see how to deal with this issue.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Each column has a data type. The data type constrains the set of
|
|
|
|
possible values that can be assigned to a column and assigns
|
|
|
|
semantics to the data stored in the column so that it can be used
|
|
|
|
for computations. For instance, a column declared to be of a
|
|
|
|
numerical type will not accept arbitrary text strings, and the data
|
|
|
|
stored in such a column can be used for mathematical computations.
|
|
|
|
By contrast, a column declared to be of a character string type
|
|
|
|
will accept almost any kind of data but it does not lend itself to
|
|
|
|
mathematical calculations, although other operations such as string
|
|
|
|
concatenation are available.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<productname>PostgreSQL</productname> includes a sizable set of
|
|
|
|
built-in data types that fit many applications. Users can also
|
|
|
|
define their own data types. Most built-in data types have obvious
|
|
|
|
names and semantics, so we defer a detailed explanation to <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="datatype"/>. Some of the frequently used data types are
|
2002-08-05 21:44:58 +02:00
|
|
|
<type>integer</type> for whole numbers, <type>numeric</type> for
|
|
|
|
possibly fractional numbers, <type>text</type> for character
|
|
|
|
strings, <type>date</type> for dates, <type>time</type> for
|
|
|
|
time-of-day values, and <type>timestamp</type> for values
|
|
|
|
containing both date and time.
|
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>creating</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2006-02-19 00:14:45 +01:00
|
|
|
To create a table, you use the aptly named <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="sql-createtable"/> command.
|
2006-02-19 00:14:45 +01:00
|
|
|
In this command you specify at least a name for the new table, the
|
|
|
|
names of the columns and the data type of each column. For
|
|
|
|
example:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE my_first_table (
|
|
|
|
first_column text,
|
|
|
|
second_column integer
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
This creates a table named <literal>my_first_table</literal> with
|
|
|
|
two columns. The first column is named
|
|
|
|
<literal>first_column</literal> and has a data type of
|
|
|
|
<type>text</type>; the second column has the name
|
|
|
|
<literal>second_column</literal> and the type <type>integer</type>.
|
|
|
|
The table and column names follow the identifier syntax explained
|
2017-11-23 15:39:47 +01:00
|
|
|
in <xref linkend="sql-syntax-identifiers"/>. The type names are
|
2002-10-20 07:05:46 +02:00
|
|
|
usually also identifiers, but there are some exceptions. Note that the
|
2002-08-05 21:44:58 +02:00
|
|
|
column list is comma-separated and surrounded by parentheses.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Of course, the previous example was heavily contrived. Normally,
|
|
|
|
you would give names to your tables and columns that convey what
|
|
|
|
kind of data they store. So let's look at a more realistic
|
|
|
|
example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
(The <type>numeric</type> type can store fractional components, as
|
|
|
|
would be typical of monetary amounts.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<tip>
|
|
|
|
<para>
|
|
|
|
When you create many interrelated tables it is wise to choose a
|
2002-10-20 07:05:46 +02:00
|
|
|
consistent naming pattern for the tables and columns. For
|
2002-08-05 21:44:58 +02:00
|
|
|
instance, there is a choice of using singular or plural nouns for
|
|
|
|
table names, both of which are favored by some theorist or other.
|
|
|
|
</para>
|
|
|
|
</tip>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
There is a limit on how many columns a table can contain.
|
|
|
|
Depending on the column types, it is between 250 and 1600.
|
|
|
|
However, defining a table with anywhere near this many columns is
|
|
|
|
highly unusual and often a questionable design.
|
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>removing</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2006-02-19 00:14:45 +01:00
|
|
|
If you no longer need a table, you can remove it using the <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="sql-droptable"/> command.
|
2006-02-19 00:14:45 +01:00
|
|
|
For example:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
DROP TABLE my_first_table;
|
|
|
|
DROP TABLE products;
|
|
|
|
</programlisting>
|
|
|
|
Attempting to drop a table that does not exist is an error.
|
|
|
|
Nevertheless, it is common in SQL script files to unconditionally
|
2006-10-22 05:03:41 +02:00
|
|
|
try to drop each table before creating it, ignoring any error
|
|
|
|
messages, so that the script works whether or not the table exists.
|
2017-10-09 03:44:17 +02:00
|
|
|
(If you like, you can use the <literal>DROP TABLE IF EXISTS</literal> variant
|
2006-10-22 05:03:41 +02:00
|
|
|
to avoid the error messages, but this is not standard SQL.)
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
If you need to modify a table that already exists, see <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="ddl-alter"/> later in this chapter.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
With the tools discussed so far you can create fully functional
|
|
|
|
tables. The remainder of this chapter is concerned with adding
|
|
|
|
features to the table definition to ensure data integrity,
|
|
|
|
security, or convenience. If you are eager to fill your tables with
|
2017-11-23 15:39:47 +01:00
|
|
|
data now you can skip ahead to <xref linkend="dml"/> and read the
|
2002-08-05 21:44:58 +02:00
|
|
|
rest of this chapter later.
|
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2003-03-13 02:30:29 +01:00
|
|
|
<sect1 id="ddl-default">
|
2002-08-05 21:44:58 +02:00
|
|
|
<title>Default Values</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="ddl-default">
|
|
|
|
<primary>default value</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A column can be assigned a default value. When a new row is
|
2006-10-22 05:03:41 +02:00
|
|
|
created and no values are specified for some of the columns, those
|
2002-08-05 21:44:58 +02:00
|
|
|
columns will be filled with their respective default values. A
|
|
|
|
data manipulation command can also request explicitly that a column
|
2004-12-23 06:37:40 +01:00
|
|
|
be set to its default value, without having to know what that value is.
|
2017-11-23 15:39:47 +01:00
|
|
|
(Details about data manipulation commands are in <xref linkend="dml"/>.)
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm><primary>null value</primary><secondary>default value</secondary></indexterm>
|
2004-12-23 06:37:40 +01:00
|
|
|
If no default value is declared explicitly, the default value is the
|
|
|
|
null value. This usually makes sense because a null value can
|
|
|
|
be considered to represent unknown data.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
In a table definition, default values are listed after the column
|
|
|
|
data type. For example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
2003-03-13 02:30:29 +01:00
|
|
|
product_no integer,
|
2002-08-05 21:44:58 +02:00
|
|
|
name text,
|
|
|
|
price numeric <emphasis>DEFAULT 9.99</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
The default value can be an expression, which will be
|
2002-08-05 21:44:58 +02:00
|
|
|
evaluated whenever the default value is inserted
|
2004-12-23 06:37:40 +01:00
|
|
|
(<emphasis>not</emphasis> when the table is created). A common example
|
2017-10-09 03:44:17 +02:00
|
|
|
is for a <type>timestamp</type> column to have a default of <literal>CURRENT_TIMESTAMP</literal>,
|
2005-01-08 02:44:08 +01:00
|
|
|
so that it gets set to the time of row insertion. Another common
|
2017-10-09 03:44:17 +02:00
|
|
|
example is generating a <quote>serial number</quote> for each row.
|
2005-01-08 02:44:08 +01:00
|
|
|
In <productname>PostgreSQL</productname> this is typically done by
|
2007-02-01 01:28:19 +01:00
|
|
|
something like:
|
2005-01-08 02:44:08 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer <emphasis>DEFAULT nextval('products_product_no_seq')</emphasis>,
|
|
|
|
...
|
|
|
|
);
|
|
|
|
</programlisting>
|
2017-10-09 03:44:17 +02:00
|
|
|
where the <literal>nextval()</literal> function supplies successive values
|
|
|
|
from a <firstterm>sequence object</firstterm> (see <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="functions-sequence"/>). This arrangement is sufficiently common
|
2005-01-08 02:44:08 +01:00
|
|
|
that there's a special shorthand for it:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no <emphasis>SERIAL</emphasis>,
|
|
|
|
...
|
|
|
|
);
|
|
|
|
</programlisting>
|
2017-10-09 03:44:17 +02:00
|
|
|
The <literal>SERIAL</literal> shorthand is discussed further in <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="datatype-serial"/>.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2024-01-16 09:42:40 +01:00
|
|
|
<sect1 id="ddl-identity-columns">
|
|
|
|
<title>Identity Columns</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-identity-columns">
|
|
|
|
<primary>identity column</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
An identity column is a special column that is generated automatically from
|
|
|
|
an implicit sequence. It can be used to generate key values.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To create an identity column, use the <literal>GENERATED ...
|
|
|
|
AS IDENTITY</literal> clause in <command>CREATE TABLE</command>, for example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE people (
|
|
|
|
id bigint <emphasis>GENERATED ALWAYS AS IDENTITY</emphasis>,
|
|
|
|
...,
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
or alternatively
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE people (
|
|
|
|
id bigint <emphasis>GENERATED BY DEFAULT IDENTITY</emphasis>,
|
|
|
|
...,
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
See <xref linkend="sql-createtable"/> for more details.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
If an <command>INSERT</command> command is executed on the table with the
|
|
|
|
identity column and no value is explicitly specified for the identity
|
|
|
|
column, then a value generated by the implicit sequence is inserted. For
|
|
|
|
example, with the above definitions and assuming additional appropriate
|
|
|
|
columns, writing
|
|
|
|
<programlisting>
|
|
|
|
INSERT INTO people (name, address) VALUE ('A', 'foo');
|
|
|
|
INSERT INTO people (name, address) VALUE ('B', 'bar');
|
|
|
|
</programlisting>
|
|
|
|
would generate values for the <literal>id</literal> column starting at 1
|
|
|
|
and result in the following table data:
|
|
|
|
<screen>
|
|
|
|
id | name | address
|
|
|
|
----+------+---------
|
|
|
|
1 | A | foo
|
|
|
|
2 | B | bar
|
|
|
|
</screen>
|
|
|
|
Alternatively, the keyword <literal>DEFAULT</literal> can be specified in
|
|
|
|
place of a value to explicitly request the sequence-generated value, like
|
|
|
|
<programlisting>
|
|
|
|
INSERT INTO people (id, name, address) VALUE (<emphasis>DEFAULT</emphasis>, 'C', 'baz');
|
|
|
|
</programlisting>
|
|
|
|
Similarly, the keyword <literal>DEFAULT</literal> can be used in
|
|
|
|
<command>UPDATE</command> commands.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Thus, in many ways, an identity column behaves like a column with a default
|
|
|
|
value.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The clauses <literal>ALWAYS</literal> and <literal>BY DEFAULT</literal> in
|
|
|
|
the column definition determine how explicitly user-specified values are
|
|
|
|
handled in <command>INSERT</command> and <command>UPDATE</command>
|
|
|
|
commands. In an <command>INSERT</command> command, if
|
|
|
|
<literal>ALWAYS</literal> is selected, a user-specified value is only
|
|
|
|
accepted if the <command>INSERT</command> statement specifies
|
|
|
|
<literal>OVERRIDING SYSTEM VALUE</literal>. If <literal>BY
|
|
|
|
DEFAULT</literal> is selected, then the user-specified value takes
|
|
|
|
precedence. Thus, using <literal>BY DEFAULT</literal> results in a
|
|
|
|
behavior more similar to default values, where the default value can be
|
|
|
|
overridden by an explicit value, whereas <literal>ALWAYS</literal> provides
|
|
|
|
some more protection against accidentally inserting an explicit value.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The data type of an identity column must be one of the data types supported
|
|
|
|
by sequences. (See <xref linkend="sql-createsequence"/>.) The properties
|
|
|
|
of the associated sequence may be specified when creating an identity
|
|
|
|
column (see <xref linkend="sql-createtable"/>) or changed afterwards (see
|
|
|
|
<xref linkend="sql-altertable"/>).
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
An identity column is automatically marked as <literal>NOT NULL</literal>.
|
|
|
|
An identity column, however, does not guarantee uniqueness. (A sequence
|
|
|
|
normally returns unique values, but a sequence could be reset, or values
|
|
|
|
could be inserted manually into the identity column, as discussed above.)
|
|
|
|
Uniqueness would need to be enforced using a <literal>PRIMARY KEY</literal>
|
|
|
|
or <literal>UNIQUE</literal> constraint.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
In table inheritance hierarchies, identity columns and their properties in
|
|
|
|
a child table are independent of those in its parent tables. A child table
|
|
|
|
does not inherit identity columns or their properties automatically from
|
|
|
|
the parent. During <command>INSERT</command> or <command>UPDATE</command>,
|
|
|
|
a column is treated as an identity column if that column is an identity
|
|
|
|
column in the table named in the statement, and the corresponding identity
|
|
|
|
properties are applied.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2024-01-16 17:16:14 +01:00
|
|
|
Partitions inherit identity columns from the partitioned table. They
|
|
|
|
cannot have their own identity columns. The properties of a given identity
|
|
|
|
column are consistent across all the partitions in the partition hierarchy.
|
2024-01-16 09:42:40 +01:00
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2019-03-30 08:13:09 +01:00
|
|
|
<sect1 id="ddl-generated-columns">
|
|
|
|
<title>Generated Columns</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-generated-columns">
|
|
|
|
<primary>generated column</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A generated column is a special column that is always computed from other
|
|
|
|
columns. Thus, it is for columns what a view is for tables. There are two
|
|
|
|
kinds of generated columns: stored and virtual. A stored generated column
|
|
|
|
is computed when it is written (inserted or updated) and occupies storage
|
|
|
|
as if it were a normal column. A virtual generated column occupies no
|
|
|
|
storage and is computed when it is read. Thus, a virtual generated column
|
|
|
|
is similar to a view and a stored generated column is similar to a
|
|
|
|
materialized view (except that it is always updated automatically).
|
2024-01-16 08:56:00 +01:00
|
|
|
<productname>PostgreSQL</productname> currently implements only stored generated columns.
|
2019-03-30 08:13:09 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To create a generated column, use the <literal>GENERATED ALWAYS
|
|
|
|
AS</literal> clause in <command>CREATE TABLE</command>, for example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE people (
|
|
|
|
...,
|
|
|
|
height_cm numeric,
|
2019-06-13 05:05:40 +02:00
|
|
|
height_in numeric <emphasis>GENERATED ALWAYS AS (height_cm / 2.54) STORED</emphasis>
|
2019-03-30 08:13:09 +01:00
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
The keyword <literal>STORED</literal> must be specified to choose the
|
|
|
|
stored kind of generated column. See <xref linkend="sql-createtable"/> for
|
|
|
|
more details.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A generated column cannot be written to directly. In
|
|
|
|
<command>INSERT</command> or <command>UPDATE</command> commands, a value
|
|
|
|
cannot be specified for a generated column, but the keyword
|
|
|
|
<literal>DEFAULT</literal> may be specified.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Consider the differences between a column with a default and a generated
|
|
|
|
column. The column default is evaluated once when the row is first
|
|
|
|
inserted if no other value was provided; a generated column is updated
|
|
|
|
whenever the row changes and cannot be overridden. A column default may
|
|
|
|
not refer to other columns of the table; a generation expression would
|
|
|
|
normally do so. A column default can use volatile functions, for example
|
|
|
|
<literal>random()</literal> or functions referring to the current time;
|
|
|
|
this is not allowed for generated columns.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Several restrictions apply to the definition of generated columns and
|
|
|
|
tables involving generated columns:
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
The generation expression can only use immutable functions and cannot
|
|
|
|
use subqueries or reference anything other than the current row in any
|
|
|
|
way.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A generation expression cannot reference another generated column.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A generation expression cannot reference a system column, except
|
|
|
|
<varname>tableoid</varname>.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A generated column cannot have a column default or an identity definition.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A generated column cannot be part of a partition key.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Foreign tables can have generated columns. See <xref
|
|
|
|
linkend="sql-createforeigntable"/> for details.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2020-05-06 16:25:54 +02:00
|
|
|
<listitem>
|
Improve handling of inherited GENERATED expressions.
In both partitioning and traditional inheritance, require child
columns to be GENERATED if and only if their parent(s) are.
Formerly we allowed the case of an inherited column being
GENERATED when its parent isn't, but that results in inconsistent
behavior: the column can be directly updated through an UPDATE
on the parent table, leading to it containing a user-supplied
value that might not match the generation expression. This also
fixes an oversight that we enforced partition-key-columns-can't-
be-GENERATED against parent tables, but not against child tables
that were dynamically attached to them.
Also, remove the restriction that the child's generation expression
be equivalent to the parent's. In the wake of commit 3f7836ff6,
there doesn't seem to be any reason that we need that restriction,
since generation expressions are always computed per-table anyway.
By removing this, we can also allow a child to merge multiple
inheritance parents with inconsistent generation expressions, by
overriding them with its own expression, much as we've long allowed
for DEFAULT expressions.
Since we're rejecting a case that we used to accept, this doesn't
seem like a back-patchable change. Given the lack of field
complaints about the inconsistent behavior, it's likely that no
one is doing this anyway, but we won't change it in minor releases.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us
2023-01-11 21:55:02 +01:00
|
|
|
<para>For inheritance and partitioning:</para>
|
2020-05-06 16:25:54 +02:00
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve handling of inherited GENERATED expressions.
In both partitioning and traditional inheritance, require child
columns to be GENERATED if and only if their parent(s) are.
Formerly we allowed the case of an inherited column being
GENERATED when its parent isn't, but that results in inconsistent
behavior: the column can be directly updated through an UPDATE
on the parent table, leading to it containing a user-supplied
value that might not match the generation expression. This also
fixes an oversight that we enforced partition-key-columns-can't-
be-GENERATED against parent tables, but not against child tables
that were dynamically attached to them.
Also, remove the restriction that the child's generation expression
be equivalent to the parent's. In the wake of commit 3f7836ff6,
there doesn't seem to be any reason that we need that restriction,
since generation expressions are always computed per-table anyway.
By removing this, we can also allow a child to merge multiple
inheritance parents with inconsistent generation expressions, by
overriding them with its own expression, much as we've long allowed
for DEFAULT expressions.
Since we're rejecting a case that we used to accept, this doesn't
seem like a back-patchable change. Given the lack of field
complaints about the inconsistent behavior, it's likely that no
one is doing this anyway, but we won't change it in minor releases.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us
2023-01-11 21:55:02 +01:00
|
|
|
If a parent column is a generated column, its child column must also
|
|
|
|
be a generated column; however, the child column can have a
|
|
|
|
different generation expression. The generation expression that is
|
|
|
|
actually applied during insert or update of a row is the one
|
|
|
|
associated with the table that the row is physically in.
|
|
|
|
(This is unlike the behavior for column defaults: for those, the
|
|
|
|
default value associated with the table named in the query applies.)
|
2020-05-06 16:25:54 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve handling of inherited GENERATED expressions.
In both partitioning and traditional inheritance, require child
columns to be GENERATED if and only if their parent(s) are.
Formerly we allowed the case of an inherited column being
GENERATED when its parent isn't, but that results in inconsistent
behavior: the column can be directly updated through an UPDATE
on the parent table, leading to it containing a user-supplied
value that might not match the generation expression. This also
fixes an oversight that we enforced partition-key-columns-can't-
be-GENERATED against parent tables, but not against child tables
that were dynamically attached to them.
Also, remove the restriction that the child's generation expression
be equivalent to the parent's. In the wake of commit 3f7836ff6,
there doesn't seem to be any reason that we need that restriction,
since generation expressions are always computed per-table anyway.
By removing this, we can also allow a child to merge multiple
inheritance parents with inconsistent generation expressions, by
overriding them with its own expression, much as we've long allowed
for DEFAULT expressions.
Since we're rejecting a case that we used to accept, this doesn't
seem like a back-patchable change. Given the lack of field
complaints about the inconsistent behavior, it's likely that no
one is doing this anyway, but we won't change it in minor releases.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us
2023-01-11 21:55:02 +01:00
|
|
|
If a parent column is not a generated column, its child column must
|
|
|
|
not be generated either.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
For inherited tables, if you write a child column definition without
|
|
|
|
any <literal>GENERATED</literal> clause in <command>CREATE TABLE
|
|
|
|
... INHERITS</command>, then its <literal>GENERATED</literal> clause
|
|
|
|
will automatically be copied from the parent. <command>ALTER TABLE
|
|
|
|
... INHERIT</command> will insist that parent and child columns
|
|
|
|
already match as to generation status, but it will not require their
|
|
|
|
generation expressions to match.
|
2020-05-06 16:25:54 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve handling of inherited GENERATED expressions.
In both partitioning and traditional inheritance, require child
columns to be GENERATED if and only if their parent(s) are.
Formerly we allowed the case of an inherited column being
GENERATED when its parent isn't, but that results in inconsistent
behavior: the column can be directly updated through an UPDATE
on the parent table, leading to it containing a user-supplied
value that might not match the generation expression. This also
fixes an oversight that we enforced partition-key-columns-can't-
be-GENERATED against parent tables, but not against child tables
that were dynamically attached to them.
Also, remove the restriction that the child's generation expression
be equivalent to the parent's. In the wake of commit 3f7836ff6,
there doesn't seem to be any reason that we need that restriction,
since generation expressions are always computed per-table anyway.
By removing this, we can also allow a child to merge multiple
inheritance parents with inconsistent generation expressions, by
overriding them with its own expression, much as we've long allowed
for DEFAULT expressions.
Since we're rejecting a case that we used to accept, this doesn't
seem like a back-patchable change. Given the lack of field
complaints about the inconsistent behavior, it's likely that no
one is doing this anyway, but we won't change it in minor releases.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us
2023-01-11 21:55:02 +01:00
|
|
|
Similarly for partitioned tables, if you write a child column
|
|
|
|
definition without any <literal>GENERATED</literal> clause
|
|
|
|
in <command>CREATE TABLE ... PARTITION OF</command>, then
|
|
|
|
its <literal>GENERATED</literal> clause will automatically be copied
|
2023-01-12 04:19:49 +01:00
|
|
|
from the parent. <command>ALTER TABLE ... ATTACH PARTITION</command>
|
Improve handling of inherited GENERATED expressions.
In both partitioning and traditional inheritance, require child
columns to be GENERATED if and only if their parent(s) are.
Formerly we allowed the case of an inherited column being
GENERATED when its parent isn't, but that results in inconsistent
behavior: the column can be directly updated through an UPDATE
on the parent table, leading to it containing a user-supplied
value that might not match the generation expression. This also
fixes an oversight that we enforced partition-key-columns-can't-
be-GENERATED against parent tables, but not against child tables
that were dynamically attached to them.
Also, remove the restriction that the child's generation expression
be equivalent to the parent's. In the wake of commit 3f7836ff6,
there doesn't seem to be any reason that we need that restriction,
since generation expressions are always computed per-table anyway.
By removing this, we can also allow a child to merge multiple
inheritance parents with inconsistent generation expressions, by
overriding them with its own expression, much as we've long allowed
for DEFAULT expressions.
Since we're rejecting a case that we used to accept, this doesn't
seem like a back-patchable change. Given the lack of field
complaints about the inconsistent behavior, it's likely that no
one is doing this anyway, but we won't change it in minor releases.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/2793383.1672944799@sss.pgh.pa.us
2023-01-11 21:55:02 +01:00
|
|
|
will insist that parent and child columns already match as to
|
|
|
|
generation status, but it will not require their generation
|
|
|
|
expressions to match.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
In case of multiple inheritance, if one parent column is a generated
|
|
|
|
column, then all parent columns must be generated columns. If they
|
|
|
|
do not all have the same generation expression, then the desired
|
|
|
|
expression for the child must be specified explicitly.
|
2020-05-06 16:25:54 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</listitem>
|
2019-03-30 08:13:09 +01:00
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Additional considerations apply to the use of generated columns.
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Generated columns maintain access privileges separately from their
|
|
|
|
underlying base columns. So, it is possible to arrange it so that a
|
|
|
|
particular role can read from a generated column but not from the
|
|
|
|
underlying base columns.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Generated columns are, conceptually, updated after
|
|
|
|
<literal>BEFORE</literal> triggers have run. Therefore, changes made to
|
|
|
|
base columns in a <literal>BEFORE</literal> trigger will be reflected in
|
|
|
|
generated columns. But conversely, it is not allowed to access
|
|
|
|
generated columns in <literal>BEFORE</literal> triggers.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<sect1 id="ddl-constraints">
|
|
|
|
<title>Constraints</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="ddl-constraints">
|
|
|
|
<primary>constraint</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
Data types are a way to limit the kind of data that can be stored
|
|
|
|
in a table. For many applications, however, the constraint they
|
|
|
|
provide is too coarse. For example, a column containing a product
|
|
|
|
price should probably only accept positive values. But there is no
|
2005-10-23 21:29:49 +02:00
|
|
|
standard data type that accepts only positive numbers. Another issue is
|
2002-08-05 21:44:58 +02:00
|
|
|
that you might want to constrain column data with respect to other
|
|
|
|
columns or rows. For example, in a table containing product
|
2006-10-22 05:03:41 +02:00
|
|
|
information, there should be only one row for each product number.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To that end, SQL allows you to define constraints on columns and
|
|
|
|
tables. Constraints give you as much control over the data in your
|
|
|
|
tables as you wish. If a user attempts to store data in a column
|
|
|
|
that would violate a constraint, an error is raised. This applies
|
|
|
|
even if the value came from the default value definition.
|
|
|
|
</para>
|
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-constraints-check-constraints">
|
2002-08-05 21:44:58 +02:00
|
|
|
<title>Check Constraints</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>check constraint</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>check</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A check constraint is the most generic constraint type. It allows
|
2005-01-17 02:29:02 +01:00
|
|
|
you to specify that the value in a certain column must satisfy a
|
|
|
|
Boolean (truth-value) expression. For instance, to require positive
|
|
|
|
product prices, you could use:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
2005-01-22 23:56:36 +01:00
|
|
|
price numeric <emphasis>CHECK (price > 0)</emphasis>
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
As you see, the constraint definition comes after the data type,
|
|
|
|
just like default value definitions. Default values and
|
|
|
|
constraints can be listed in any order. A check constraint
|
|
|
|
consists of the key word <literal>CHECK</literal> followed by an
|
|
|
|
expression in parentheses. The check constraint expression should
|
|
|
|
involve the column thus constrained, otherwise the constraint
|
|
|
|
would not make too much sense.
|
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>name</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
You can also give the constraint a separate name. This clarifies
|
|
|
|
error messages and allows you to refer to the constraint when you
|
|
|
|
need to change it. The syntax is:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
2005-01-22 23:56:36 +01:00
|
|
|
price numeric <emphasis>CONSTRAINT positive_price</emphasis> CHECK (price > 0)
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
2002-11-11 21:14:04 +01:00
|
|
|
So, to specify a named constraint, use the key word
|
2002-08-05 21:44:58 +02:00
|
|
|
<literal>CONSTRAINT</literal> followed by an identifier followed
|
2005-01-17 02:29:02 +01:00
|
|
|
by the constraint definition. (If you don't specify a constraint
|
|
|
|
name in this way, the system chooses a name for you.)
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A check constraint can also refer to several columns. Say you
|
|
|
|
store a regular price and a discounted price, and you want to
|
2007-02-01 01:28:19 +01:00
|
|
|
ensure that the discounted price is lower than the regular price:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
2005-01-22 23:56:36 +01:00
|
|
|
price numeric CHECK (price > 0),
|
|
|
|
discounted_price numeric CHECK (discounted_price > 0),
|
|
|
|
<emphasis>CHECK (price > discounted_price)</emphasis>
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The first two constraints should look familiar. The third one
|
|
|
|
uses a new syntax. It is not attached to a particular column,
|
|
|
|
instead it appears as a separate item in the comma-separated
|
2002-09-05 23:32:23 +02:00
|
|
|
column list. Column definitions and these constraint
|
2002-08-05 21:44:58 +02:00
|
|
|
definitions can be listed in mixed order.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2002-11-11 21:14:04 +01:00
|
|
|
We say that the first two constraints are column constraints, whereas the
|
2002-08-05 21:44:58 +02:00
|
|
|
third one is a table constraint because it is written separately
|
2005-01-17 02:29:02 +01:00
|
|
|
from any one column definition. Column constraints can also be
|
2002-08-05 21:44:58 +02:00
|
|
|
written as table constraints, while the reverse is not necessarily
|
2005-01-17 02:29:02 +01:00
|
|
|
possible, since a column constraint is supposed to refer to only the
|
|
|
|
column it is attached to. (<productname>PostgreSQL</productname> doesn't
|
|
|
|
enforce that rule, but you should follow it if you want your table
|
|
|
|
definitions to work with other database systems.) The above example could
|
2007-02-01 01:28:19 +01:00
|
|
|
also be written as:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
|
|
|
price numeric,
|
2005-01-22 23:56:36 +01:00
|
|
|
CHECK (price > 0),
|
2002-08-05 21:44:58 +02:00
|
|
|
discounted_price numeric,
|
2005-01-22 23:56:36 +01:00
|
|
|
CHECK (discounted_price > 0),
|
|
|
|
CHECK (price > discounted_price)
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
or even:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
2005-01-22 23:56:36 +01:00
|
|
|
price numeric CHECK (price > 0),
|
2002-08-05 21:44:58 +02:00
|
|
|
discounted_price numeric,
|
2005-01-22 23:56:36 +01:00
|
|
|
CHECK (discounted_price > 0 AND price > discounted_price)
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
It's a matter of taste.
|
|
|
|
</para>
|
|
|
|
|
2005-01-17 02:29:02 +01:00
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
Names can be assigned to table constraints in the same way as
|
|
|
|
column constraints:
|
2005-01-17 02:29:02 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
|
|
|
price numeric,
|
2005-01-22 23:56:36 +01:00
|
|
|
CHECK (price > 0),
|
2005-01-17 02:29:02 +01:00
|
|
|
discounted_price numeric,
|
2005-01-22 23:56:36 +01:00
|
|
|
CHECK (discounted_price > 0),
|
2017-10-09 03:44:17 +02:00
|
|
|
<emphasis>CONSTRAINT valid_discount</emphasis> CHECK (price > discounted_price)
|
2005-01-17 02:29:02 +01:00
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>null value</primary>
|
|
|
|
<secondary sortas="check constraints">with check constraints</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
It should be noted that a check constraint is satisfied if the
|
2002-09-05 23:32:23 +02:00
|
|
|
check expression evaluates to true or the null value. Since most
|
2005-01-17 02:29:02 +01:00
|
|
|
expressions will evaluate to the null value if any operand is null,
|
2002-09-05 23:32:23 +02:00
|
|
|
they will not prevent null values in the constrained columns. To
|
|
|
|
ensure that a column does not contain null values, the not-null
|
2004-12-23 06:37:40 +01:00
|
|
|
constraint described in the next section can be used.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
2018-11-26 16:27:07 +01:00
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
<productname>PostgreSQL</productname> does not support
|
|
|
|
<literal>CHECK</literal> constraints that reference table data other than
|
|
|
|
the new or updated row being checked. While a <literal>CHECK</literal>
|
|
|
|
constraint that violates this rule may appear to work in simple
|
|
|
|
tests, it cannot guarantee that the database will not reach a state
|
|
|
|
in which the constraint condition is false (due to subsequent changes
|
|
|
|
of the other row(s) involved). This would cause a database dump and
|
2022-07-21 20:55:23 +02:00
|
|
|
restore to fail. The restore could fail even when the complete
|
2018-11-26 16:27:07 +01:00
|
|
|
database state is consistent with the constraint, due to rows not
|
|
|
|
being loaded in an order that will satisfy the constraint. If
|
|
|
|
possible, use <literal>UNIQUE</literal>, <literal>EXCLUDE</literal>,
|
|
|
|
or <literal>FOREIGN KEY</literal> constraints to express
|
|
|
|
cross-row and cross-table restrictions.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
If what you desire is a one-time check against other rows at row
|
|
|
|
insertion, rather than a continuously-maintained consistency
|
|
|
|
guarantee, a custom <link linkend="triggers">trigger</link> can be used
|
2022-07-21 20:55:23 +02:00
|
|
|
to implement that. (This approach avoids the dump/restore problem because
|
2018-11-26 16:27:07 +01:00
|
|
|
<application>pg_dump</application> does not reinstall triggers until after
|
2022-07-21 20:55:23 +02:00
|
|
|
restoring data, so that the check will not be enforced during a
|
|
|
|
dump/restore.)
|
2018-12-07 22:40:58 +01:00
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
<productname>PostgreSQL</productname> assumes that
|
|
|
|
<literal>CHECK</literal> constraints' conditions are immutable, that
|
|
|
|
is, they will always give the same result for the same input row.
|
|
|
|
This assumption is what justifies examining <literal>CHECK</literal>
|
|
|
|
constraints only when rows are inserted or updated, and not at other
|
|
|
|
times. (The warning above about not referencing other table data is
|
|
|
|
really a special case of this restriction.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
An example of a common way to break this assumption is to reference a
|
|
|
|
user-defined function in a <literal>CHECK</literal> expression, and
|
|
|
|
then change the behavior of that
|
|
|
|
function. <productname>PostgreSQL</productname> does not disallow
|
|
|
|
that, but it will not notice if there are rows in the table that now
|
|
|
|
violate the <literal>CHECK</literal> constraint. That would cause a
|
2022-07-21 20:55:23 +02:00
|
|
|
subsequent database dump and restore to fail.
|
2018-12-07 22:40:58 +01:00
|
|
|
The recommended way to handle such a change is to drop the constraint
|
|
|
|
(using <command>ALTER TABLE</command>), adjust the function definition,
|
|
|
|
and re-add the constraint, thereby rechecking it against all table rows.
|
2018-11-26 16:27:07 +01:00
|
|
|
</para>
|
|
|
|
</note>
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect2>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<sect2 id="ddl-constraints-not-null">
|
2002-08-05 21:44:58 +02:00
|
|
|
<title>Not-Null Constraints</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>not-null constraint</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>NOT NULL</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A not-null constraint simply specifies that a column must not
|
|
|
|
assume the null value. A syntax example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer <emphasis>NOT NULL</emphasis>,
|
|
|
|
name text <emphasis>NOT NULL</emphasis>,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2024-05-13 11:31:09 +02:00
|
|
|
A not-null constraint is always written as a column constraint. A
|
|
|
|
not-null constraint is functionally equivalent to creating a check
|
2002-09-05 23:32:23 +02:00
|
|
|
constraint <literal>CHECK (<replaceable>column_name</replaceable>
|
|
|
|
IS NOT NULL)</literal>, but in
|
|
|
|
<productname>PostgreSQL</productname> creating an explicit
|
2024-05-13 11:31:09 +02:00
|
|
|
not-null constraint is more efficient. The drawback is that you
|
|
|
|
cannot give explicit names to not-null constraints created this
|
|
|
|
way.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Of course, a column can have more than one constraint. Just write
|
2005-01-17 02:29:02 +01:00
|
|
|
the constraints one after another:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer NOT NULL,
|
|
|
|
name text NOT NULL,
|
2005-01-22 23:56:36 +01:00
|
|
|
price numeric NOT NULL CHECK (price > 0)
|
2002-08-05 21:44:58 +02:00
|
|
|
);
|
|
|
|
</programlisting>
|
2003-08-15 01:13:27 +02:00
|
|
|
The order doesn't matter. It does not necessarily determine in which
|
2002-08-05 21:44:58 +02:00
|
|
|
order the constraints are checked.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The <literal>NOT NULL</literal> constraint has an inverse: the
|
|
|
|
<literal>NULL</literal> constraint. This does not mean that the
|
|
|
|
column must be null, which would surely be useless. Instead, this
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
simply selects the default behavior that the column might be null.
|
2006-10-22 05:03:41 +02:00
|
|
|
The <literal>NULL</literal> constraint is not present in the SQL
|
2002-08-05 21:44:58 +02:00
|
|
|
standard and should not be used in portable applications. (It was
|
|
|
|
only added to <productname>PostgreSQL</productname> to be
|
2003-11-05 01:05:32 +01:00
|
|
|
compatible with some other database systems.) Some users, however,
|
2002-08-05 21:44:58 +02:00
|
|
|
like it because it makes it easy to toggle the constraint in a
|
2007-02-01 01:28:19 +01:00
|
|
|
script file. For example, you could start with:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer NULL,
|
|
|
|
name text NULL,
|
|
|
|
price numeric NULL
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
and then insert the <literal>NOT</literal> key word where desired.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<tip>
|
|
|
|
<para>
|
|
|
|
In most database designs the majority of columns should be marked
|
|
|
|
not null.
|
|
|
|
</para>
|
|
|
|
</tip>
|
|
|
|
</sect2>
|
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-constraints-unique-constraints">
|
2002-08-05 21:44:58 +02:00
|
|
|
<title>Unique Constraints</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>unique constraint</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>unique</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2016-02-07 22:02:44 +01:00
|
|
|
Unique constraints ensure that the data contained in a column, or a
|
|
|
|
group of columns, is unique among all the rows in the
|
2007-02-01 01:28:19 +01:00
|
|
|
table. The syntax is:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer <emphasis>UNIQUE</emphasis>,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
when written as a column constraint, and:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
|
|
|
price numeric,
|
|
|
|
<emphasis>UNIQUE (product_no)</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
when written as a table constraint.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-02-07 22:02:44 +01:00
|
|
|
To define a unique constraint for a group of columns, write it as a
|
|
|
|
table constraint with the column names separated by commas:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE example (
|
|
|
|
a integer,
|
|
|
|
b integer,
|
|
|
|
c integer,
|
|
|
|
<emphasis>UNIQUE (a, c)</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
2005-01-17 02:29:02 +01:00
|
|
|
This specifies that the combination of values in the indicated columns
|
|
|
|
is unique across the whole table, though any one of the columns
|
|
|
|
need not be (and ordinarily isn't) unique.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2005-01-17 02:29:02 +01:00
|
|
|
You can assign your own name for a unique constraint, in the usual way:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer <emphasis>CONSTRAINT must_be_different</emphasis> UNIQUE,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
2010-08-26 23:08:35 +02:00
|
|
|
<para>
|
2015-09-11 03:22:21 +02:00
|
|
|
Adding a unique constraint will automatically create a unique B-tree
|
2016-02-07 22:02:44 +01:00
|
|
|
index on the column or group of columns listed in the constraint.
|
|
|
|
A uniqueness restriction covering only some rows cannot be written as
|
|
|
|
a unique constraint, but it is possible to enforce such a restriction by
|
|
|
|
creating a unique <link linkend="indexes-partial">partial index</link>.
|
2010-08-26 23:08:35 +02:00
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>null value</primary>
|
|
|
|
<secondary sortas="unique constraints">with unique constraints</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2016-02-07 22:02:44 +01:00
|
|
|
In general, a unique constraint is violated if there is more than
|
2009-04-27 18:27:36 +02:00
|
|
|
one row in the table where the values of all of the
|
2004-12-23 06:37:40 +01:00
|
|
|
columns included in the constraint are equal.
|
2022-02-03 11:29:54 +01:00
|
|
|
By default, two null values are not considered equal in this
|
2004-12-23 06:37:40 +01:00
|
|
|
comparison. That means even in the presence of a
|
2005-10-23 21:29:49 +02:00
|
|
|
unique constraint it is possible to store duplicate
|
2002-08-05 21:44:58 +02:00
|
|
|
rows that contain a null value in at least one of the constrained
|
2022-02-03 11:29:54 +01:00
|
|
|
columns. This behavior can be changed by adding the clause <literal>NULLS
|
|
|
|
NOT DISTINCT</literal>, like
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer UNIQUE <emphasis>NULLS NOT DISTINCT</emphasis>,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
or
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer,
|
|
|
|
name text,
|
|
|
|
price numeric,
|
|
|
|
UNIQUE <emphasis>NULLS NOT DISTINCT</emphasis> (product_no)
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
The default behavior can be specified explicitly using <literal>NULLS
|
|
|
|
DISTINCT</literal>. The default null treatment in unique constraints is
|
|
|
|
implementation-defined according to the SQL standard, and other
|
|
|
|
implementations have a different behavior. So be careful when developing
|
|
|
|
applications that are intended to be portable.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-constraints-primary-keys">
|
2002-08-05 21:44:58 +02:00
|
|
|
<title>Primary Keys</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>primary key</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>primary key</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2016-02-07 22:02:44 +01:00
|
|
|
A primary key constraint indicates that a column, or group of columns,
|
|
|
|
can be used as a unique identifier for rows in the table. This
|
|
|
|
requires that the values be both unique and not null. So, the following
|
2002-08-05 21:44:58 +02:00
|
|
|
two table definitions accept the same data:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer UNIQUE NOT NULL,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer <emphasis>PRIMARY KEY</emphasis>,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-02-07 22:02:44 +01:00
|
|
|
Primary keys can span more than one column; the syntax
|
2002-08-05 21:44:58 +02:00
|
|
|
is similar to unique constraints:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE example (
|
|
|
|
a integer,
|
|
|
|
b integer,
|
|
|
|
c integer,
|
|
|
|
<emphasis>PRIMARY KEY (a, c)</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
2010-08-26 23:08:35 +02:00
|
|
|
<para>
|
2015-09-11 03:22:21 +02:00
|
|
|
Adding a primary key will automatically create a unique B-tree index
|
2016-02-07 22:02:44 +01:00
|
|
|
on the column or group of columns listed in the primary key, and will
|
2017-10-09 03:44:17 +02:00
|
|
|
force the column(s) to be marked <literal>NOT NULL</literal>.
|
2010-08-26 23:08:35 +02:00
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2006-10-22 05:03:41 +02:00
|
|
|
A table can have at most one primary key. (There can be any number
|
2024-05-13 11:31:09 +02:00
|
|
|
of unique and not-null constraints, which are functionally almost the
|
2016-02-07 22:02:44 +01:00
|
|
|
same thing, but only one can be identified as the primary key.)
|
2006-10-22 05:03:41 +02:00
|
|
|
Relational database theory
|
2002-08-05 21:44:58 +02:00
|
|
|
dictates that every table must have a primary key. This rule is
|
|
|
|
not enforced by <productname>PostgreSQL</productname>, but it is
|
|
|
|
usually best to follow it.
|
|
|
|
</para>
|
2016-02-07 22:02:44 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Primary keys are useful both for
|
|
|
|
documentation purposes and for client applications. For example,
|
|
|
|
a GUI application that allows modifying row values probably needs
|
|
|
|
to know the primary key of a table to be able to identify rows
|
|
|
|
uniquely. There are also various ways in which the database system
|
|
|
|
makes use of a primary key if one has been declared; for example,
|
|
|
|
the primary key defines the default target column(s) for foreign keys
|
|
|
|
referencing its table.
|
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="ddl-constraints-fk">
|
|
|
|
<title>Foreign Keys</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>foreign key</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>foreign key</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>referential integrity</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A foreign key constraint specifies that the values in a column (or
|
2002-10-20 07:05:46 +02:00
|
|
|
a group of columns) must match the values appearing in some row
|
|
|
|
of another table.
|
2002-08-05 21:44:58 +02:00
|
|
|
We say this maintains the <firstterm>referential
|
|
|
|
integrity</firstterm> between two related tables.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Say you have the product table that we have used several times already:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer PRIMARY KEY,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
Let's also assume you have a table storing orders of those
|
|
|
|
products. We want to ensure that the orders table only contains
|
|
|
|
orders of products that actually exist. So we define a foreign
|
|
|
|
key constraint in the orders table that references the products
|
|
|
|
table:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE orders (
|
|
|
|
order_id integer PRIMARY KEY,
|
|
|
|
product_no integer <emphasis>REFERENCES products (product_no)</emphasis>,
|
|
|
|
quantity integer
|
|
|
|
);
|
|
|
|
</programlisting>
|
2011-10-12 22:58:39 +02:00
|
|
|
Now it is impossible to create orders with non-NULL
|
2004-03-07 05:31:01 +01:00
|
|
|
<structfield>product_no</structfield> entries that do not appear in the
|
2002-08-05 21:44:58 +02:00
|
|
|
products table.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
We say that in this situation the orders table is the
|
|
|
|
<firstterm>referencing</firstterm> table and the products table is
|
|
|
|
the <firstterm>referenced</firstterm> table. Similarly, there are
|
|
|
|
referencing and referenced columns.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
You can also shorten the above command to:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE orders (
|
|
|
|
order_id integer PRIMARY KEY,
|
2005-01-17 02:29:02 +01:00
|
|
|
product_no integer <emphasis>REFERENCES products</emphasis>,
|
2002-08-05 21:44:58 +02:00
|
|
|
quantity integer
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
because in absence of a column list the primary key of the
|
2004-12-23 06:37:40 +01:00
|
|
|
referenced table is used as the referenced column(s).
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
2021-04-30 21:37:56 +02:00
|
|
|
<para>
|
|
|
|
You can assign your own name for a foreign key constraint,
|
|
|
|
in the usual way.
|
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
A foreign key can also constrain and reference a group of columns.
|
|
|
|
As usual, it then needs to be written in table constraint form.
|
|
|
|
Here is a contrived syntax example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE t1 (
|
|
|
|
a integer PRIMARY KEY,
|
|
|
|
b integer,
|
|
|
|
c integer,
|
|
|
|
<emphasis>FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
2005-01-17 02:29:02 +01:00
|
|
|
Of course, the number and type of the constrained columns need to
|
2002-09-05 23:32:23 +02:00
|
|
|
match the number and type of the referenced columns.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
2021-04-30 21:37:56 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>foreign key</primary>
|
|
|
|
<secondary>self-referential</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2005-01-17 02:29:02 +01:00
|
|
|
<para>
|
2021-04-30 21:37:56 +02:00
|
|
|
Sometimes it is useful for the <quote>other table</quote> of a
|
|
|
|
foreign key constraint to be the same table; this is called
|
|
|
|
a <firstterm>self-referential</firstterm> foreign key. For
|
|
|
|
example, if you want rows of a table to represent nodes of a tree
|
|
|
|
structure, you could write
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE tree (
|
|
|
|
node_id integer PRIMARY KEY,
|
|
|
|
parent_id integer REFERENCES tree,
|
|
|
|
name text,
|
|
|
|
...
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
A top-level node would have NULL <structfield>parent_id</structfield>,
|
2021-05-06 15:59:11 +02:00
|
|
|
while non-NULL <structfield>parent_id</structfield> entries would be
|
2021-04-30 21:37:56 +02:00
|
|
|
constrained to reference valid rows of the table.
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2012-06-18 18:12:52 +02:00
|
|
|
A table can have more than one foreign key constraint. This is
|
2002-08-05 21:44:58 +02:00
|
|
|
used to implement many-to-many relationships between tables. Say
|
|
|
|
you have tables about products and orders, but now you want to
|
|
|
|
allow one order to contain possibly many products (which the
|
|
|
|
structure above did not allow). You could use this table structure:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer PRIMARY KEY,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE orders (
|
|
|
|
order_id integer PRIMARY KEY,
|
|
|
|
shipping_address text,
|
|
|
|
...
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE order_items (
|
|
|
|
product_no integer REFERENCES products,
|
|
|
|
order_id integer REFERENCES orders,
|
|
|
|
quantity integer,
|
|
|
|
PRIMARY KEY (product_no, order_id)
|
|
|
|
);
|
|
|
|
</programlisting>
|
2005-01-17 02:29:02 +01:00
|
|
|
Notice that the primary key overlaps with the foreign keys in
|
2002-08-05 21:44:58 +02:00
|
|
|
the last table.
|
|
|
|
</para>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>CASCADE</primary>
|
|
|
|
<secondary>foreign key action</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>RESTRICT</primary>
|
|
|
|
<secondary>foreign key action</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
We know that the foreign keys disallow creation of orders that
|
2003-02-19 05:06:28 +01:00
|
|
|
do not relate to any products. But what if a product is removed
|
2002-08-05 21:44:58 +02:00
|
|
|
after an order is created that references it? SQL allows you to
|
2004-12-23 06:37:40 +01:00
|
|
|
handle that as well. Intuitively, we have a few options:
|
2002-08-05 21:44:58 +02:00
|
|
|
<itemizedlist spacing="compact">
|
|
|
|
<listitem><para>Disallow deleting a referenced product</para></listitem>
|
|
|
|
<listitem><para>Delete the orders as well</para></listitem>
|
|
|
|
<listitem><para>Something else?</para></listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To illustrate this, let's implement the following policy on the
|
2004-03-07 05:31:01 +01:00
|
|
|
many-to-many relationship example above: when someone wants to
|
2002-08-05 21:44:58 +02:00
|
|
|
remove a product that is still referenced by an order (via
|
|
|
|
<literal>order_items</literal>), we disallow it. If someone
|
2007-02-01 01:28:19 +01:00
|
|
|
removes an order, the order items are removed as well:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products (
|
|
|
|
product_no integer PRIMARY KEY,
|
|
|
|
name text,
|
|
|
|
price numeric
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE orders (
|
|
|
|
order_id integer PRIMARY KEY,
|
|
|
|
shipping_address text,
|
|
|
|
...
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE order_items (
|
|
|
|
product_no integer REFERENCES products <emphasis>ON DELETE RESTRICT</emphasis>,
|
|
|
|
order_id integer REFERENCES orders <emphasis>ON DELETE CASCADE</emphasis>,
|
|
|
|
quantity integer,
|
|
|
|
PRIMARY KEY (product_no, order_id)
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Restricting and cascading deletes are the two most common options.
|
2004-12-23 06:37:40 +01:00
|
|
|
<literal>RESTRICT</literal> prevents deletion of a
|
2004-10-21 23:33:59 +02:00
|
|
|
referenced row. <literal>NO ACTION</literal> means that if any
|
|
|
|
referencing rows still exist when the constraint is checked, an error
|
2004-12-23 06:37:40 +01:00
|
|
|
is raised; this is the default behavior if you do not specify anything.
|
|
|
|
(The essential difference between these two choices is that
|
2004-10-21 23:33:59 +02:00
|
|
|
<literal>NO ACTION</literal> allows the check to be deferred until
|
|
|
|
later in the transaction, whereas <literal>RESTRICT</literal> does not.)
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>CASCADE</literal> specifies that when a referenced row is deleted,
|
2004-12-23 06:37:40 +01:00
|
|
|
row(s) referencing it should be automatically deleted as well.
|
2004-10-21 23:33:59 +02:00
|
|
|
There are two other options:
|
2002-08-05 21:44:58 +02:00
|
|
|
<literal>SET NULL</literal> and <literal>SET DEFAULT</literal>.
|
2012-06-18 18:12:52 +02:00
|
|
|
These cause the referencing column(s) in the referencing row(s)
|
|
|
|
to be set to nulls or their default
|
2004-10-21 23:33:59 +02:00
|
|
|
values, respectively, when the referenced row is deleted.
|
2002-08-05 21:44:58 +02:00
|
|
|
Note that these do not excuse you from observing any constraints.
|
|
|
|
For example, if an action specifies <literal>SET DEFAULT</literal>
|
2012-06-18 18:12:52 +02:00
|
|
|
but the default value would not satisfy the foreign key constraint, the
|
2004-12-23 06:37:40 +01:00
|
|
|
operation will fail.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
2021-12-01 11:25:58 +01:00
|
|
|
<para>
|
|
|
|
The appropriate choice of <literal>ON DELETE</literal> action depends on
|
|
|
|
what kinds of objects the related tables represent. When the referencing
|
|
|
|
table represents something that is a component of what is represented by
|
|
|
|
the referenced table and cannot exist independently, then
|
|
|
|
<literal>CASCADE</literal> could be appropriate. If the two tables
|
|
|
|
represent independent objects, then <literal>RESTRICT</literal> or
|
|
|
|
<literal>NO ACTION</literal> is more appropriate; an application that
|
|
|
|
actually wants to delete both objects would then have to be explicit about
|
2022-01-25 01:40:04 +01:00
|
|
|
this and run two delete commands. In the above example, order items are
|
2021-12-01 11:25:58 +01:00
|
|
|
part of an order, and it is convenient if they are deleted automatically
|
|
|
|
if an order is deleted. But products and orders are different things, and
|
|
|
|
so making a deletion of a product automatically cause the deletion of some
|
|
|
|
order items could be considered problematic. The actions <literal>SET
|
|
|
|
NULL</literal> or <literal>SET DEFAULT</literal> can be appropriate if a
|
|
|
|
foreign-key relationship represents optional information. For example, if
|
|
|
|
the products table contained a reference to a product manager, and the
|
|
|
|
product manager entry gets deleted, then setting the product's product
|
|
|
|
manager to null or a default might be useful.
|
|
|
|
</para>
|
|
|
|
|
2021-12-08 11:09:44 +01:00
|
|
|
<para>
|
|
|
|
The actions <literal>SET NULL</literal> and <literal>SET DEFAULT</literal>
|
|
|
|
can take a column list to specify which columns to set. Normally, all
|
|
|
|
columns of the foreign-key constraint are set; setting only a subset is
|
|
|
|
useful in some special cases. Consider the following example:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE tenants (
|
|
|
|
tenant_id integer PRIMARY KEY
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE users (
|
|
|
|
tenant_id integer REFERENCES tenants ON DELETE CASCADE,
|
|
|
|
user_id integer NOT NULL,
|
|
|
|
PRIMARY KEY (tenant_id, user_id)
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE posts (
|
|
|
|
tenant_id integer REFERENCES tenants ON DELETE CASCADE,
|
|
|
|
post_id integer NOT NULL,
|
|
|
|
author_id integer,
|
|
|
|
PRIMARY KEY (tenant_id, post_id),
|
|
|
|
FOREIGN KEY (tenant_id, author_id) REFERENCES users ON DELETE SET NULL <emphasis>(author_id)</emphasis>
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
Without the specification of the column, the foreign key would also set
|
|
|
|
the column <literal>tenant_id</literal> to null, but that column is still
|
|
|
|
required as part of the primary key.
|
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
Analogous to <literal>ON DELETE</literal> there is also
|
2004-12-23 06:37:40 +01:00
|
|
|
<literal>ON UPDATE</literal> which is invoked when a referenced
|
2021-12-08 11:09:44 +01:00
|
|
|
column is changed (updated). The possible actions are the same,
|
|
|
|
except that column lists cannot be specified for <literal>SET
|
|
|
|
NULL</literal> and <literal>SET DEFAULT</literal>.
|
2017-10-09 03:44:17 +02:00
|
|
|
In this case, <literal>CASCADE</literal> means that the updated values of the
|
2012-06-18 18:12:52 +02:00
|
|
|
referenced column(s) should be copied into the referencing row(s).
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
2010-08-26 23:08:35 +02:00
|
|
|
<para>
|
2012-06-18 18:12:52 +02:00
|
|
|
Normally, a referencing row need not satisfy the foreign key constraint
|
2017-10-09 03:44:17 +02:00
|
|
|
if any of its referencing columns are null. If <literal>MATCH FULL</literal>
|
2012-06-18 18:12:52 +02:00
|
|
|
is added to the foreign key declaration, a referencing row escapes
|
|
|
|
satisfying the constraint only if all its referencing columns are null
|
|
|
|
(so a mix of null and non-null values is guaranteed to fail a
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>MATCH FULL</literal> constraint). If you don't want referencing rows
|
2012-06-18 18:12:52 +02:00
|
|
|
to be able to avoid satisfying the foreign key constraint, declare the
|
2017-10-09 03:44:17 +02:00
|
|
|
referencing column(s) as <literal>NOT NULL</literal>.
|
2012-06-18 18:12:52 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A foreign key must reference columns that either are a primary key or
|
2024-01-29 22:15:17 +01:00
|
|
|
form a unique constraint, or are columns from a non-partial unique index.
|
|
|
|
This means that the referenced columns always have an index to allow
|
|
|
|
efficient lookups on whether a referencing row has a match. Since a
|
|
|
|
<command>DELETE</command> of a row from the referenced table or an
|
|
|
|
<command>UPDATE</command> of a referenced column will require a scan of
|
|
|
|
the referencing table for rows matching the old value, it is often a good
|
|
|
|
idea to index the referencing columns too. Because this is not always
|
|
|
|
needed, and there are many choices available on how to index, the
|
|
|
|
declaration of a foreign key constraint does not automatically create an
|
|
|
|
index on the referencing columns.
|
2010-08-26 23:08:35 +02:00
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
More information about updating and deleting data is in <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="dml"/>. Also see the description of foreign key constraint
|
2012-06-18 18:12:52 +02:00
|
|
|
syntax in the reference documentation for
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="sql-createtable"/>.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
2010-04-01 03:18:17 +02:00
|
|
|
|
2010-08-23 04:43:25 +02:00
|
|
|
<sect2 id="ddl-constraints-exclusion">
|
2010-10-13 19:05:16 +02:00
|
|
|
<title>Exclusion Constraints</title>
|
2010-04-01 03:18:17 +02:00
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>exclusion constraint</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>exclusion</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Exclusion constraints ensure that if any two rows are compared on
|
|
|
|
the specified columns or expressions using the specified operators,
|
2010-04-06 04:18:04 +02:00
|
|
|
at least one of these operator comparisons will return false or null.
|
|
|
|
The syntax is:
|
2010-04-01 03:18:17 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE circles (
|
|
|
|
c circle,
|
|
|
|
EXCLUDE USING gist (c WITH &&)
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-20 03:16:39 +02:00
|
|
|
See also <link linkend="sql-createtable-exclude"><command>CREATE
|
2017-10-09 03:44:17 +02:00
|
|
|
TABLE ... CONSTRAINT ... EXCLUDE</command></link> for details.
|
2010-04-01 03:18:17 +02:00
|
|
|
</para>
|
2010-08-26 23:08:35 +02:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Adding an exclusion constraint will automatically create an index
|
|
|
|
of the type specified in the constraint declaration.
|
|
|
|
</para>
|
2010-04-01 03:18:17 +02:00
|
|
|
</sect2>
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect1>
|
|
|
|
|
2005-01-17 02:29:02 +01:00
|
|
|
<sect1 id="ddl-system-columns">
|
|
|
|
<title>System Columns</title>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Every table has several <firstterm>system columns</firstterm> that are
|
2005-01-17 02:29:02 +01:00
|
|
|
implicitly defined by the system. Therefore, these names cannot be
|
|
|
|
used as names of user-defined columns. (Note that these
|
|
|
|
restrictions are separate from whether the name is a key word or
|
|
|
|
not; quoting a name will not allow you to escape these
|
|
|
|
restrictions.) You do not really need to be concerned about these
|
2009-04-27 18:27:36 +02:00
|
|
|
columns; just know they exist.
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>column</primary>
|
|
|
|
<secondary>system column</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<variablelist>
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-tableoid">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tableoid</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>tableoid</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The OID of the table containing this row. This column is
|
2020-11-21 08:26:20 +01:00
|
|
|
particularly handy for queries that select from partitioned
|
|
|
|
tables (see <xref linkend="ddl-partitioning"/>) or inheritance
|
2017-11-23 15:39:47 +01:00
|
|
|
hierarchies (see <xref linkend="ddl-inherit"/>), since without it,
|
2005-11-05 00:53:18 +01:00
|
|
|
it's difficult to tell which individual table a row came from. The
|
2005-01-17 02:29:02 +01:00
|
|
|
<structfield>tableoid</structfield> can be joined against the
|
|
|
|
<structfield>oid</structfield> column of
|
|
|
|
<structname>pg_class</structname> to obtain the table name.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-xmin">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>xmin</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>xmin</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The identity (transaction ID) of the inserting transaction for
|
|
|
|
this row version. (A row version is an individual state of a
|
|
|
|
row; each update of a row creates a new row version for the same
|
|
|
|
logical row.)
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-cmin">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>cmin</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>cmin</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The command identifier (starting at zero) within the inserting
|
|
|
|
transaction.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-xmax">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>xmax</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>xmax</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The identity (transaction ID) of the deleting transaction, or
|
|
|
|
zero for an undeleted row version. It is possible for this column to
|
|
|
|
be nonzero in a visible row version. That usually indicates that the
|
|
|
|
deleting transaction hasn't committed yet, or that an attempted
|
|
|
|
deletion was rolled back.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-cmax">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>cmax</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>cmax</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The command identifier within the deleting transaction, or zero.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-system-columns-ctid">
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>ctid</structfield></term>
|
2005-01-17 02:29:02 +01:00
|
|
|
<listitem>
|
|
|
|
<indexterm>
|
|
|
|
<primary>ctid</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The physical location of the row version within its table. Note that
|
|
|
|
although the <structfield>ctid</structfield> can be used to
|
|
|
|
locate the row version very quickly, a row's
|
2006-12-30 21:31:11 +01:00
|
|
|
<structfield>ctid</structfield> will change if it is
|
2017-10-09 03:44:17 +02:00
|
|
|
updated or moved by <command>VACUUM FULL</command>. Therefore
|
2005-01-17 02:29:02 +01:00
|
|
|
<structfield>ctid</structfield> is useless as a long-term row
|
2019-04-18 02:22:56 +02:00
|
|
|
identifier. A primary key should be used to identify logical rows.
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
</variablelist>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Transaction identifiers are also 32-bit quantities. In a
|
|
|
|
long-lived database it is possible for transaction IDs to wrap
|
|
|
|
around. This is not a fatal problem given appropriate maintenance
|
2017-11-23 15:39:47 +01:00
|
|
|
procedures; see <xref linkend="maintenance"/> for details. It is
|
2005-01-17 02:29:02 +01:00
|
|
|
unwise, however, to depend on the uniqueness of transaction IDs
|
|
|
|
over the long term (more than one billion transactions).
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2008-01-13 18:58:54 +01:00
|
|
|
Command identifiers are also 32-bit quantities. This creates a hard limit
|
2017-10-09 03:44:17 +02:00
|
|
|
of 2<superscript>32</superscript> (4 billion) <acronym>SQL</acronym> commands
|
2005-01-17 02:29:02 +01:00
|
|
|
within a single transaction. In practice this limit is not a
|
2009-04-27 18:27:36 +02:00
|
|
|
problem — note that the limit is on the number of
|
|
|
|
<acronym>SQL</acronym> commands, not the number of rows processed.
|
2014-02-24 18:56:37 +01:00
|
|
|
Also, only commands that actually modify the database contents will
|
|
|
|
consume a command identifier.
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect1 id="ddl-alter">
|
|
|
|
<title>Modifying Tables</title>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm zone="ddl-alter">
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>modifying</secondary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
When you create a table and you realize that you made a mistake, or
|
2009-04-27 18:27:36 +02:00
|
|
|
the requirements of the application change, you can drop the
|
2005-11-05 00:53:18 +01:00
|
|
|
table and create it again. But this is not a convenient option if
|
|
|
|
the table is already filled with data, or if the table is
|
|
|
|
referenced by other database objects (for instance a foreign key
|
|
|
|
constraint). Therefore <productname>PostgreSQL</productname>
|
|
|
|
provides a family of commands to make modifications to existing
|
|
|
|
tables. Note that this is conceptually distinct from altering
|
|
|
|
the data contained in the table: here we are interested in altering
|
|
|
|
the definition, or structure, of the table.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
You can:
|
2005-11-05 00:53:18 +01:00
|
|
|
<itemizedlist spacing="compact">
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Add columns</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Remove columns</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Add constraints</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Remove constraints</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Change default values</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Change column data types</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Rename columns</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
<listitem>
|
2009-04-27 18:27:36 +02:00
|
|
|
<para>Rename tables</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
All these actions are performed using the
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="sql-altertable"/>
|
2007-05-15 21:43:51 +02:00
|
|
|
command, whose reference page contains details beyond those given
|
|
|
|
here.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-alter-adding-a-column">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Adding a Column</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>column</primary>
|
|
|
|
<secondary>adding</secondary>
|
|
|
|
</indexterm>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
To add a column, use a command like:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products ADD COLUMN description text;
|
2002-08-05 21:44:58 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
The new column is initially filled with whatever default
|
2017-10-09 03:44:17 +02:00
|
|
|
value is given (null if you don't specify a <literal>DEFAULT</literal> clause).
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2019-07-19 04:42:33 +02:00
|
|
|
<tip>
|
|
|
|
<para>
|
|
|
|
From <productname>PostgreSQL</productname> 11, adding a column with
|
|
|
|
a constant default value no longer means that each row of the table
|
|
|
|
needs to be updated when the <command>ALTER TABLE</command> statement
|
|
|
|
is executed. Instead, the default value will be returned the next time
|
|
|
|
the row is accessed, and applied when the table is rewritten, making
|
|
|
|
the <command>ALTER TABLE</command> very fast even on large tables.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2020-09-01 00:33:37 +02:00
|
|
|
However, if the default value is volatile (e.g.,
|
2019-07-19 04:42:33 +02:00
|
|
|
<function>clock_timestamp()</function>)
|
|
|
|
each row will need to be updated with the value calculated at the time
|
|
|
|
<command>ALTER TABLE</command> is executed. To avoid a potentially
|
|
|
|
lengthy update operation, particularly if you intend to fill the column
|
|
|
|
with mostly nondefault values anyway, it may be preferable to add the
|
|
|
|
column with no default, insert the correct values using
|
|
|
|
<command>UPDATE</command>, and then add any desired default as described
|
|
|
|
below.
|
|
|
|
</para>
|
|
|
|
</tip>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
You can also define constraints on the column at the same time,
|
|
|
|
using the usual syntax:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products ADD COLUMN description text CHECK (description <> '');
|
2002-08-05 21:44:58 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
In fact all the options that can be applied to a column description
|
2017-10-09 03:44:17 +02:00
|
|
|
in <command>CREATE TABLE</command> can be used here. Keep in mind however
|
2005-11-05 00:53:18 +01:00
|
|
|
that the default value must satisfy the given constraints, or the
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>ADD</literal> will fail. Alternatively, you can add
|
2005-11-05 00:53:18 +01:00
|
|
|
constraints later (see below) after you've filled in the new column
|
|
|
|
correctly.
|
|
|
|
</para>
|
2006-10-22 05:03:41 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
</sect2>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-alter-removing-a-column">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Removing a Column</title>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>column</primary>
|
|
|
|
<secondary>removing</secondary>
|
|
|
|
</indexterm>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
To remove a column, use a command like:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products DROP COLUMN description;
|
2005-11-02 00:19:05 +01:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
Whatever data was in the column disappears. Table constraints involving
|
|
|
|
the column are dropped, too. However, if the column is referenced by a
|
|
|
|
foreign key constraint of another table,
|
|
|
|
<productname>PostgreSQL</productname> will not silently drop that
|
|
|
|
constraint. You can authorize dropping everything that depends on
|
2017-10-09 03:44:17 +02:00
|
|
|
the column by adding <literal>CASCADE</literal>:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products DROP COLUMN description CASCADE;
|
|
|
|
</programlisting>
|
2017-11-23 15:39:47 +01:00
|
|
|
See <xref linkend="ddl-depend"/> for a description of the general
|
2005-11-05 00:53:18 +01:00
|
|
|
mechanism behind this.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-alter-adding-a-constraint">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Adding a Constraint</title>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>adding</secondary>
|
|
|
|
</indexterm>
|
2004-08-08 23:33:11 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
To add a constraint, the table constraint syntax is used. For example:
|
2005-11-02 00:19:05 +01:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products ADD CHECK (name <> '');
|
|
|
|
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
|
|
|
|
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
|
2005-11-02 00:19:05 +01:00
|
|
|
</programlisting>
|
2024-05-13 11:31:09 +02:00
|
|
|
To add a not-null constraint, which cannot be written as a table
|
|
|
|
constraint, use this syntax:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
|
2002-08-05 21:44:58 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
The constraint will be checked immediately, so the table data must
|
|
|
|
satisfy the constraint before it can be added.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2013-05-08 03:23:21 +02:00
|
|
|
<sect2 id="ddl-alter-removing-a-constraint">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Removing a Constraint</title>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>constraint</primary>
|
|
|
|
<secondary>removing</secondary>
|
|
|
|
</indexterm>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
To remove a constraint you need to know its name. If you gave it
|
|
|
|
a name then that's easy. Otherwise the system assigned a
|
|
|
|
generated name, which you need to find out. The
|
|
|
|
<application>psql</application> command <literal>\d
|
|
|
|
<replaceable>tablename</replaceable></literal> can be helpful
|
|
|
|
here; other interfaces might also provide a way to inspect table
|
|
|
|
details. Then the command is:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products DROP CONSTRAINT some_name;
|
2002-08-05 21:44:58 +02:00
|
|
|
</programlisting>
|
2017-10-09 03:44:17 +02:00
|
|
|
(If you are dealing with a generated constraint name like <literal>$2</literal>,
|
2005-11-05 00:53:18 +01:00
|
|
|
don't forget that you'll need to double-quote it to make it a valid
|
|
|
|
identifier.)
|
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
As with dropping a column, you need to add <literal>CASCADE</literal> if you
|
2005-11-05 00:53:18 +01:00
|
|
|
want to drop a constraint that something else depends on. An example
|
|
|
|
is that a foreign key constraint depends on a unique or primary key
|
|
|
|
constraint on the referenced column(s).
|
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2024-05-13 11:31:09 +02:00
|
|
|
This works the same for all constraint types except not-null
|
|
|
|
constraints. To drop a not-null constraint use:
|
2002-08-05 21:44:58 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
|
2002-08-05 21:44:58 +02:00
|
|
|
</programlisting>
|
2024-05-13 11:31:09 +02:00
|
|
|
(Recall that not-null constraints do not have names.)
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<sect2 id="ddl-alter-column-default">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Changing a Column's Default Value</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>default value</primary>
|
|
|
|
<secondary>changing</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
To set a new default for a column, use a command like:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
|
|
|
|
</programlisting>
|
|
|
|
Note that this doesn't affect any existing rows in the table, it
|
2017-10-09 03:44:17 +02:00
|
|
|
just changes the default for future <command>INSERT</command> commands.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
To remove any default value, use:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
|
|
|
|
</programlisting>
|
|
|
|
This is effectively the same as setting the default to null.
|
|
|
|
As a consequence, it is not an error
|
|
|
|
to drop a default where one hadn't been defined, because the
|
|
|
|
default is implicitly the null value.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<sect2 id="ddl-alter-column-type">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Changing a Column's Data Type</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>column data type</primary>
|
|
|
|
<secondary>changing</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2009-04-27 18:27:36 +02:00
|
|
|
To convert a column to a different data type, use a command like:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
|
|
|
|
</programlisting>
|
|
|
|
This will succeed only if each existing entry in the column can be
|
|
|
|
converted to the new type by an implicit cast. If a more complex
|
2017-10-09 03:44:17 +02:00
|
|
|
conversion is needed, you can add a <literal>USING</literal> clause that
|
2005-11-05 00:53:18 +01:00
|
|
|
specifies how to compute the new values from the old.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
<productname>PostgreSQL</productname> will attempt to convert the column's
|
2005-11-05 00:53:18 +01:00
|
|
|
default value (if any) to the new type, as well as any constraints
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
that involve the column. But these conversions might fail, or might
|
2005-11-05 00:53:18 +01:00
|
|
|
produce surprising results. It's often best to drop any constraints
|
|
|
|
on the column before altering its type, and then add back suitably
|
|
|
|
modified constraints afterwards.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<sect2 id="ddl-alter-renaming-column">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Renaming a Column</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>column</primary>
|
|
|
|
<secondary>renaming</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To rename a column:
|
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products RENAME COLUMN product_no TO product_number;
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<sect2 id="ddl-alter-renaming-table">
|
2005-11-05 00:53:18 +01:00
|
|
|
<title>Renaming a Table</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>renaming</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To rename a table:
|
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE products RENAME TO items;
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
</sect1>
|
|
|
|
|
|
|
|
<sect1 id="ddl-priv">
|
|
|
|
<title>Privileges</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-priv">
|
|
|
|
<primary>privilege</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>permission</primary>
|
|
|
|
<see>privilege</see>
|
|
|
|
</indexterm>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2011-02-21 04:20:57 +01:00
|
|
|
<indexterm zone="ddl-priv">
|
|
|
|
<primary>owner</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-priv">
|
|
|
|
<primary>GRANT</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-priv">
|
|
|
|
<primary>REVOKE</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2018-12-03 17:40:49 +01:00
|
|
|
<indexterm zone="ddl-priv">
|
|
|
|
<primary>ACL</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2023-11-13 21:41:27 +01:00
|
|
|
<indexterm zone="ddl-priv-default">
|
|
|
|
<primary>privilege</primary>
|
|
|
|
<secondary>default</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2005-01-08 02:44:08 +01:00
|
|
|
<para>
|
2011-02-21 04:20:57 +01:00
|
|
|
When an object is created, it is assigned an owner. The
|
|
|
|
owner is normally the role that executed the creation statement.
|
|
|
|
For most kinds of objects, the initial state is that only the owner
|
|
|
|
(or a superuser) can do anything with the object. To allow
|
|
|
|
other roles to use it, <firstterm>privileges</firstterm> must be
|
|
|
|
granted.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
There are different kinds of privileges: <literal>SELECT</literal>,
|
|
|
|
<literal>INSERT</literal>, <literal>UPDATE</literal>, <literal>DELETE</literal>,
|
|
|
|
<literal>TRUNCATE</literal>, <literal>REFERENCES</literal>, <literal>TRIGGER</literal>,
|
|
|
|
<literal>CREATE</literal>, <literal>CONNECT</literal>, <literal>TEMPORARY</literal>,
|
2024-03-13 20:49:26 +01:00
|
|
|
<literal>EXECUTE</literal>, <literal>USAGE</literal>, <literal>SET</literal>,
|
|
|
|
<literal>ALTER SYSTEM</literal>, and <literal>MAINTAIN</literal>.
|
2006-04-30 23:15:33 +02:00
|
|
|
The privileges applicable to a particular
|
2022-05-19 09:27:34 +02:00
|
|
|
object vary depending on the object's type (table, function, etc.).
|
2018-12-03 17:40:49 +01:00
|
|
|
More detail about the meanings of these privileges appears below.
|
|
|
|
The following sections and chapters will also show you how
|
|
|
|
these privileges are used.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2019-11-20 18:27:00 +01:00
|
|
|
The right to modify or destroy an object is inherent in being the
|
|
|
|
object's owner, and cannot be granted or revoked in itself.
|
|
|
|
(However, like all privileges, that right can be inherited by
|
|
|
|
members of the owning role; see <xref linkend="role-membership"/>.)
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
2011-02-21 04:20:57 +01:00
|
|
|
<para>
|
|
|
|
An object can be assigned to a new owner with an <command>ALTER</command>
|
2018-12-03 17:40:49 +01:00
|
|
|
command of the appropriate kind for the object, for example
|
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE <replaceable>table_name</replaceable> OWNER TO <replaceable>new_owner</replaceable>;
|
|
|
|
</programlisting>
|
|
|
|
Superusers can always do this; ordinary roles can only do it if they are
|
2023-01-16 16:35:29 +01:00
|
|
|
both the current owner of the object (or inherit the privileges of the
|
|
|
|
owning role) and able to <literal>SET ROLE</literal> to the new owning role.
|
2011-02-21 04:20:57 +01:00
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2005-11-02 00:19:05 +01:00
|
|
|
<para>
|
2018-12-03 17:40:49 +01:00
|
|
|
To assign privileges, the <xref linkend="sql-grant"/> command is
|
2016-04-16 18:54:56 +02:00
|
|
|
used. For example, if <literal>joe</literal> is an existing role, and
|
2005-11-05 00:53:18 +01:00
|
|
|
<literal>accounts</literal> is an existing table, the privilege to
|
2007-02-01 01:28:19 +01:00
|
|
|
update the table can be granted with:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
GRANT UPDATE ON accounts TO joe;
|
|
|
|
</programlisting>
|
2006-10-22 05:03:41 +02:00
|
|
|
Writing <literal>ALL</literal> in place of a specific privilege grants all
|
2005-11-05 00:53:18 +01:00
|
|
|
privileges that are relevant for the object type.
|
|
|
|
</para>
|
|
|
|
|
2006-10-22 05:03:41 +02:00
|
|
|
<para>
|
2016-04-16 18:54:56 +02:00
|
|
|
The special <quote>role</quote> name <literal>PUBLIC</literal> can
|
|
|
|
be used to grant a privilege to every role on the system. Also,
|
2017-10-09 03:44:17 +02:00
|
|
|
<quote>group</quote> roles can be set up to help manage privileges when
|
2006-10-22 05:03:41 +02:00
|
|
|
there are many users of a database — for details see
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="user-manag"/>.
|
2006-10-22 05:03:41 +02:00
|
|
|
</para>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2019-11-20 18:27:00 +01:00
|
|
|
To revoke a previously-granted privilege, use the fittingly named
|
2018-12-03 17:40:49 +01:00
|
|
|
<xref linkend="sql-revoke"/> command:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
REVOKE ALL ON accounts FROM PUBLIC;
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Ordinarily, only the object's owner (or a superuser) can grant or
|
|
|
|
revoke privileges on an object. However, it is possible to grant a
|
2017-10-09 03:44:17 +02:00
|
|
|
privilege <quote>with grant option</quote>, which gives the recipient
|
2005-11-05 00:53:18 +01:00
|
|
|
the right to grant it in turn to others. If the grant option is
|
|
|
|
subsequently revoked then all who received the privilege from that
|
|
|
|
recipient (directly or through a chain of grants) will lose the
|
2017-11-23 15:39:47 +01:00
|
|
|
privilege. For details see the <xref linkend="sql-grant"/> and
|
|
|
|
<xref linkend="sql-revoke"/> reference pages.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2018-12-03 17:40:49 +01:00
|
|
|
|
2019-11-20 18:27:00 +01:00
|
|
|
<para>
|
|
|
|
An object's owner can choose to revoke their own ordinary privileges,
|
|
|
|
for example to make a table read-only for themselves as well as others.
|
|
|
|
But owners are always treated as holding all grant options, so they
|
|
|
|
can always re-grant their own privileges.
|
|
|
|
</para>
|
|
|
|
|
2018-12-03 17:40:49 +01:00
|
|
|
<para>
|
|
|
|
The available privileges are:
|
|
|
|
|
|
|
|
<variablelist>
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-select">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>SELECT</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Allows <command>SELECT</command> from
|
2018-12-03 17:40:49 +01:00
|
|
|
any column, or specific column(s), of a table, view, materialized
|
|
|
|
view, or other table-like object.
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Also allows use of <command>COPY TO</command>.
|
2018-12-03 17:40:49 +01:00
|
|
|
This privilege is also needed to reference existing column values in
|
2023-02-26 10:06:04 +01:00
|
|
|
<command>UPDATE</command>, <command>DELETE</command>,
|
|
|
|
or <command>MERGE</command>.
|
2018-12-03 17:40:49 +01:00
|
|
|
For sequences, this privilege also allows use of the
|
|
|
|
<function>currval</function> function.
|
|
|
|
For large objects, this privilege allows the object to be read.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-insert">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>INSERT</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Allows <command>INSERT</command> of a new row into a table, view,
|
2018-12-03 17:40:49 +01:00
|
|
|
etc. Can be granted on specific column(s), in which case
|
|
|
|
only those columns may be assigned to in the <command>INSERT</command>
|
|
|
|
command (other columns will therefore receive default values).
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Also allows use of <command>COPY FROM</command>.
|
2018-12-03 17:40:49 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-update">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>UPDATE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Allows <command>UPDATE</command> of any
|
2018-12-03 17:40:49 +01:00
|
|
|
column, or specific column(s), of a table, view, etc.
|
|
|
|
(In practice, any nontrivial <command>UPDATE</command> command will
|
|
|
|
require <literal>SELECT</literal> privilege as well, since it must
|
|
|
|
reference table columns to determine which rows to update, and/or to
|
|
|
|
compute new values for columns.)
|
|
|
|
<literal>SELECT ... FOR UPDATE</literal>
|
|
|
|
and <literal>SELECT ... FOR SHARE</literal>
|
|
|
|
also require this privilege on at least one column, in addition to the
|
|
|
|
<literal>SELECT</literal> privilege. For sequences, this
|
|
|
|
privilege allows use of the <function>nextval</function> and
|
|
|
|
<function>setval</function> functions.
|
|
|
|
For large objects, this privilege allows writing or truncating the
|
|
|
|
object.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-delete">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>DELETE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
Allows <command>DELETE</command> of a row from a table, view, etc.
|
2018-12-03 17:40:49 +01:00
|
|
|
(In practice, any nontrivial <command>DELETE</command> command will
|
|
|
|
require <literal>SELECT</literal> privilege as well, since it must
|
|
|
|
reference table columns to determine which rows to delete.)
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-truncate">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>TRUNCATE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2021-01-27 05:40:33 +01:00
|
|
|
Allows <command>TRUNCATE</command> on a table.
|
2018-12-03 17:40:49 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-references">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>REFERENCES</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows creation of a foreign key constraint referencing a
|
|
|
|
table, or specific column(s) of a table.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-trigger">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>TRIGGER</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows creation of a trigger on a table, view, etc.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-create">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>CREATE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
For databases, allows new schemas and publications to be created within
|
Invent "trusted" extensions, and remove the pg_pltemplate catalog.
This patch creates a new extension property, "trusted". An extension
that's marked that way in its control file can be installed by a
non-superuser who has the CREATE privilege on the current database,
even if the extension contains objects that normally would have to be
created by a superuser. The objects within the extension will (by
default) be owned by the bootstrap superuser, but the extension itself
will be owned by the calling user. This allows replicating the old
behavior around trusted procedural languages, without all the
special-case logic in CREATE LANGUAGE. We have, however, chosen to
loosen the rules slightly: formerly, only a database owner could take
advantage of the special case that allowed installation of a trusted
language, but now anyone who has CREATE privilege can do so.
Having done that, we can delete the pg_pltemplate catalog, moving the
knowledge it contained into the extension script files for the various
PLs. This ends up being no change at all for the in-core PLs, but it is
a large step forward for external PLs: they can now have the same ease
of installation as core PLs do. The old "trusted PL" behavior was only
available to PLs that had entries in pg_pltemplate, but now any
extension can be marked trusted if appropriate.
This also removes one of the stumbling blocks for our Python 2 -> 3
migration, since the association of "plpythonu" with Python 2 is no
longer hard-wired into pg_pltemplate's initial contents. Exactly where
we go from here on that front remains to be settled, but one problem
is fixed.
Patch by me, reviewed by Peter Eisentraut, Stephen Frost, and others.
Discussion: https://postgr.es/m/5889.1566415762@sss.pgh.pa.us
2020-01-30 00:42:43 +01:00
|
|
|
the database, and allows trusted extensions to be installed within
|
2018-12-03 17:40:49 +01:00
|
|
|
the database.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For schemas, allows new objects to be created within the schema.
|
|
|
|
To rename an existing object, you must own the
|
|
|
|
object <emphasis>and</emphasis> have this privilege for the containing
|
|
|
|
schema.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For tablespaces, allows tables, indexes, and temporary files to be
|
|
|
|
created within the tablespace, and allows databases to be created that
|
Invent "trusted" extensions, and remove the pg_pltemplate catalog.
This patch creates a new extension property, "trusted". An extension
that's marked that way in its control file can be installed by a
non-superuser who has the CREATE privilege on the current database,
even if the extension contains objects that normally would have to be
created by a superuser. The objects within the extension will (by
default) be owned by the bootstrap superuser, but the extension itself
will be owned by the calling user. This allows replicating the old
behavior around trusted procedural languages, without all the
special-case logic in CREATE LANGUAGE. We have, however, chosen to
loosen the rules slightly: formerly, only a database owner could take
advantage of the special case that allowed installation of a trusted
language, but now anyone who has CREATE privilege can do so.
Having done that, we can delete the pg_pltemplate catalog, moving the
knowledge it contained into the extension script files for the various
PLs. This ends up being no change at all for the in-core PLs, but it is
a large step forward for external PLs: they can now have the same ease
of installation as core PLs do. The old "trusted PL" behavior was only
available to PLs that had entries in pg_pltemplate, but now any
extension can be marked trusted if appropriate.
This also removes one of the stumbling blocks for our Python 2 -> 3
migration, since the association of "plpythonu" with Python 2 is no
longer hard-wired into pg_pltemplate's initial contents. Exactly where
we go from here on that front remains to be settled, but one problem
is fixed.
Patch by me, reviewed by Peter Eisentraut, Stephen Frost, and others.
Discussion: https://postgr.es/m/5889.1566415762@sss.pgh.pa.us
2020-01-30 00:42:43 +01:00
|
|
|
have the tablespace as their default tablespace.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
Note that revoking this privilege will not alter the existence or
|
|
|
|
location of existing objects.
|
2018-12-03 17:40:49 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-connect">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>CONNECT</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows the grantee to connect to the database. This
|
|
|
|
privilege is checked at connection startup (in addition to checking
|
|
|
|
any restrictions imposed by <filename>pg_hba.conf</filename>).
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-temporary">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>TEMPORARY</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows temporary tables to be created while using the database.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-execute">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>EXECUTE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows calling a function or procedure, including use of
|
|
|
|
any operators that are implemented on top of the function. This is the
|
|
|
|
only type of privilege that is applicable to functions and procedures.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-usage">
|
2018-12-03 17:40:49 +01:00
|
|
|
<term><literal>USAGE</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
For procedural languages, allows use of the language for
|
|
|
|
the creation of functions in that language. This is the only type
|
|
|
|
of privilege that is applicable to procedural languages.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For schemas, allows access to objects contained in the
|
|
|
|
schema (assuming that the objects' own privilege requirements are
|
|
|
|
also met). Essentially this allows the grantee to <quote>look up</quote>
|
|
|
|
objects within the schema. Without this permission, it is still
|
2020-09-01 00:33:37 +02:00
|
|
|
possible to see the object names, e.g., by querying system catalogs.
|
2018-12-03 17:40:49 +01:00
|
|
|
Also, after revoking this permission, existing sessions might have
|
|
|
|
statements that have previously performed this lookup, so this is not
|
|
|
|
a completely secure way to prevent object access.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For sequences, allows use of the
|
|
|
|
<function>currval</function> and <function>nextval</function> functions.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For types and domains, allows use of the type or domain in the
|
|
|
|
creation of tables, functions, and other schema objects. (Note that
|
|
|
|
this privilege does not control all <quote>usage</quote> of the
|
|
|
|
type, such as values of the type appearing in queries. It only
|
|
|
|
prevents objects from being created that depend on the type. The
|
|
|
|
main purpose of this privilege is controlling which users can create
|
|
|
|
dependencies on a type, which could prevent the owner from changing
|
|
|
|
the type later.)
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For foreign-data wrappers, allows creation of new servers using the
|
|
|
|
foreign-data wrapper.
|
|
|
|
</para>
|
|
|
|
<para>
|
|
|
|
For foreign servers, allows creation of foreign tables using the
|
|
|
|
server. Grantees may also create, alter, or drop their own user
|
|
|
|
mappings associated with that server.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2022-04-06 19:24:33 +02:00
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-set">
|
2022-04-06 19:24:33 +02:00
|
|
|
<term><literal>SET</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows a server configuration parameter to be set to a new value
|
|
|
|
within the current session. (While this privilege can be granted
|
|
|
|
on any parameter, it is meaningless except for parameters that would
|
|
|
|
normally require superuser privilege to set.)
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-priv-alter-system">
|
2022-04-06 19:24:33 +02:00
|
|
|
<term><literal>ALTER SYSTEM</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows a server configuration parameter to be configured to a new
|
|
|
|
value using the <xref linkend="sql-altersystem"/> command.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2024-03-13 20:49:26 +01:00
|
|
|
|
|
|
|
<varlistentry id="ddl-priv-maintain">
|
|
|
|
<term><literal>MAINTAIN</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Allows <command>VACUUM</command>, <command>ANALYZE</command>,
|
|
|
|
<command>CLUSTER</command>, <command>REFRESH MATERIALIZED VIEW</command>,
|
|
|
|
<command>REINDEX</command>, and <command>LOCK TABLE</command> on a
|
|
|
|
relation.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
</variablelist>
|
2018-12-03 17:40:49 +01:00
|
|
|
|
|
|
|
The privileges required by other commands are listed on the
|
|
|
|
reference page of the respective command.
|
|
|
|
</para>
|
|
|
|
|
2023-11-13 21:41:27 +01:00
|
|
|
<para id="ddl-priv-default">
|
2018-12-03 17:40:49 +01:00
|
|
|
PostgreSQL grants privileges on some types of objects to
|
|
|
|
<literal>PUBLIC</literal> by default when the objects are created.
|
|
|
|
No privileges are granted to <literal>PUBLIC</literal> by default on
|
|
|
|
tables,
|
|
|
|
table columns,
|
|
|
|
sequences,
|
|
|
|
foreign data wrappers,
|
|
|
|
foreign servers,
|
|
|
|
large objects,
|
|
|
|
schemas,
|
2022-04-06 19:24:33 +02:00
|
|
|
tablespaces,
|
|
|
|
or configuration parameters.
|
2018-12-03 17:40:49 +01:00
|
|
|
For other types of objects, the default privileges
|
|
|
|
granted to <literal>PUBLIC</literal> are as follows:
|
|
|
|
<literal>CONNECT</literal> and <literal>TEMPORARY</literal> (create
|
|
|
|
temporary tables) privileges for databases;
|
|
|
|
<literal>EXECUTE</literal> privilege for functions and procedures; and
|
|
|
|
<literal>USAGE</literal> privilege for languages and data types
|
|
|
|
(including domains).
|
|
|
|
The object owner can, of course, <command>REVOKE</command>
|
|
|
|
both default and expressly granted privileges. (For maximum
|
|
|
|
security, issue the <command>REVOKE</command> in the same transaction that
|
|
|
|
creates the object; then there is no window in which another user
|
|
|
|
can use the object.)
|
|
|
|
Also, these default privilege settings can be overridden using the
|
|
|
|
<xref linkend="sql-alterdefaultprivileges"/> command.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<xref linkend="privilege-abbrevs-table"/> shows the one-letter
|
|
|
|
abbreviations that are used for these privilege types in
|
|
|
|
<firstterm>ACL</firstterm> (Access Control List) values.
|
|
|
|
You will see these letters in the output of the <xref linkend="app-psql"/>
|
|
|
|
commands listed below, or when looking at ACL columns of system catalogs.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<table id="privilege-abbrevs-table">
|
|
|
|
<title>ACL Privilege Abbreviations</title>
|
|
|
|
<tgroup cols="3">
|
2020-05-06 18:23:43 +02:00
|
|
|
<colspec colname="col1" colwidth="1*"/>
|
|
|
|
<colspec colname="col2" colwidth="1*"/>
|
|
|
|
<colspec colname="col3" colwidth="2*"/>
|
2018-12-03 17:40:49 +01:00
|
|
|
<thead>
|
|
|
|
<row>
|
|
|
|
<entry>Privilege</entry>
|
|
|
|
<entry>Abbreviation</entry>
|
|
|
|
<entry>Applicable Object Types</entry>
|
|
|
|
</row>
|
|
|
|
</thead>
|
|
|
|
<tbody>
|
|
|
|
<row>
|
|
|
|
<entry><literal>SELECT</literal></entry>
|
|
|
|
<entry><literal>r</literal> (<quote>read</quote>)</entry>
|
|
|
|
<entry>
|
|
|
|
<literal>LARGE OBJECT</literal>,
|
|
|
|
<literal>SEQUENCE</literal>,
|
|
|
|
<literal>TABLE</literal> (and table-like objects),
|
|
|
|
table column
|
|
|
|
</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>INSERT</literal></entry>
|
|
|
|
<entry><literal>a</literal> (<quote>append</quote>)</entry>
|
|
|
|
<entry><literal>TABLE</literal>, table column</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>UPDATE</literal></entry>
|
|
|
|
<entry><literal>w</literal> (<quote>write</quote>)</entry>
|
|
|
|
<entry>
|
|
|
|
<literal>LARGE OBJECT</literal>,
|
|
|
|
<literal>SEQUENCE</literal>,
|
|
|
|
<literal>TABLE</literal>,
|
|
|
|
table column
|
|
|
|
</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>DELETE</literal></entry>
|
|
|
|
<entry><literal>d</literal></entry>
|
|
|
|
<entry><literal>TABLE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TRUNCATE</literal></entry>
|
|
|
|
<entry><literal>D</literal></entry>
|
|
|
|
<entry><literal>TABLE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>REFERENCES</literal></entry>
|
|
|
|
<entry><literal>x</literal></entry>
|
|
|
|
<entry><literal>TABLE</literal>, table column</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TRIGGER</literal></entry>
|
|
|
|
<entry><literal>t</literal></entry>
|
|
|
|
<entry><literal>TABLE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>CREATE</literal></entry>
|
|
|
|
<entry><literal>C</literal></entry>
|
|
|
|
<entry>
|
|
|
|
<literal>DATABASE</literal>,
|
|
|
|
<literal>SCHEMA</literal>,
|
|
|
|
<literal>TABLESPACE</literal>
|
|
|
|
</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>CONNECT</literal></entry>
|
|
|
|
<entry><literal>c</literal></entry>
|
|
|
|
<entry><literal>DATABASE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TEMPORARY</literal></entry>
|
|
|
|
<entry><literal>T</literal></entry>
|
|
|
|
<entry><literal>DATABASE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>EXECUTE</literal></entry>
|
|
|
|
<entry><literal>X</literal></entry>
|
|
|
|
<entry><literal>FUNCTION</literal>, <literal>PROCEDURE</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>USAGE</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry>
|
|
|
|
<literal>DOMAIN</literal>,
|
|
|
|
<literal>FOREIGN DATA WRAPPER</literal>,
|
|
|
|
<literal>FOREIGN SERVER</literal>,
|
|
|
|
<literal>LANGUAGE</literal>,
|
|
|
|
<literal>SCHEMA</literal>,
|
|
|
|
<literal>SEQUENCE</literal>,
|
|
|
|
<literal>TYPE</literal>
|
|
|
|
</entry>
|
|
|
|
</row>
|
2022-04-06 19:24:33 +02:00
|
|
|
<row>
|
|
|
|
<entry><literal>SET</literal></entry>
|
|
|
|
<entry><literal>s</literal></entry>
|
|
|
|
<entry><literal>PARAMETER</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>ALTER SYSTEM</literal></entry>
|
|
|
|
<entry><literal>A</literal></entry>
|
|
|
|
<entry><literal>PARAMETER</literal></entry>
|
|
|
|
</row>
|
2024-03-13 20:49:26 +01:00
|
|
|
<row>
|
|
|
|
<entry><literal>MAINTAIN</literal></entry>
|
|
|
|
<entry><literal>m</literal></entry>
|
|
|
|
<entry><literal>TABLE</literal></entry>
|
|
|
|
</row>
|
2018-12-03 17:40:49 +01:00
|
|
|
</tbody>
|
|
|
|
</tgroup>
|
|
|
|
</table>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<xref linkend="privileges-summary-table"/> summarizes the privileges
|
|
|
|
available for each type of SQL object, using the abbreviations shown
|
|
|
|
above.
|
|
|
|
It also shows the <application>psql</application> command
|
|
|
|
that can be used to examine privilege settings for each object type.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<table id="privileges-summary-table">
|
|
|
|
<title>Summary of Access Privileges</title>
|
|
|
|
<tgroup cols="4">
|
2020-05-06 18:23:43 +02:00
|
|
|
<colspec colname="col1" colwidth="2*"/>
|
|
|
|
<colspec colname="col2" colwidth="1*"/>
|
|
|
|
<colspec colname="col3" colwidth="1*"/>
|
|
|
|
<colspec colname="col4" colwidth="1*"/>
|
2018-12-03 17:40:49 +01:00
|
|
|
<thead>
|
|
|
|
<row>
|
|
|
|
<entry>Object Type</entry>
|
|
|
|
<entry>All Privileges</entry>
|
|
|
|
<entry>Default <literal>PUBLIC</literal> Privileges</entry>
|
|
|
|
<entry><application>psql</application> Command</entry>
|
|
|
|
</row>
|
|
|
|
</thead>
|
|
|
|
<tbody>
|
|
|
|
<row>
|
|
|
|
<entry><literal>DATABASE</literal></entry>
|
|
|
|
<entry><literal>CTc</literal></entry>
|
|
|
|
<entry><literal>Tc</literal></entry>
|
|
|
|
<entry><literal>\l</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>DOMAIN</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>\dD+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>FUNCTION</literal> or <literal>PROCEDURE</literal></entry>
|
|
|
|
<entry><literal>X</literal></entry>
|
|
|
|
<entry><literal>X</literal></entry>
|
|
|
|
<entry><literal>\df+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>FOREIGN DATA WRAPPER</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\dew+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>FOREIGN SERVER</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\des+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>LANGUAGE</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>\dL+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>LARGE OBJECT</literal></entry>
|
|
|
|
<entry><literal>rw</literal></entry>
|
|
|
|
<entry>none</entry>
|
2022-01-06 19:09:05 +01:00
|
|
|
<entry><literal>\dl+</literal></entry>
|
2018-12-03 17:40:49 +01:00
|
|
|
</row>
|
2022-04-06 19:24:33 +02:00
|
|
|
<row>
|
|
|
|
<entry><literal>PARAMETER</literal></entry>
|
|
|
|
<entry><literal>sA</literal></entry>
|
|
|
|
<entry>none</entry>
|
2022-04-07 23:09:44 +02:00
|
|
|
<entry><literal>\dconfig+</literal></entry>
|
2022-04-06 19:24:33 +02:00
|
|
|
</row>
|
2018-12-03 17:40:49 +01:00
|
|
|
<row>
|
|
|
|
<entry><literal>SCHEMA</literal></entry>
|
|
|
|
<entry><literal>UC</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\dn+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>SEQUENCE</literal></entry>
|
|
|
|
<entry><literal>rwU</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\dp</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TABLE</literal> (and table-like objects)</entry>
|
2024-03-13 20:49:26 +01:00
|
|
|
<entry><literal>arwdDxtm</literal></entry>
|
2018-12-03 17:40:49 +01:00
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\dp</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry>Table column</entry>
|
|
|
|
<entry><literal>arwx</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\dp</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TABLESPACE</literal></entry>
|
|
|
|
<entry><literal>C</literal></entry>
|
|
|
|
<entry>none</entry>
|
|
|
|
<entry><literal>\db+</literal></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><literal>TYPE</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>U</literal></entry>
|
|
|
|
<entry><literal>\dT+</literal></entry>
|
|
|
|
</row>
|
|
|
|
</tbody>
|
|
|
|
</tgroup>
|
|
|
|
</table>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<indexterm>
|
|
|
|
<primary><type>aclitem</type></primary>
|
|
|
|
</indexterm>
|
|
|
|
The privileges that have been granted for a particular object are
|
2023-12-27 19:52:01 +01:00
|
|
|
displayed as a list of <type>aclitem</type> entries, each having the
|
|
|
|
format:
|
|
|
|
<synopsis>
|
|
|
|
<replaceable>grantee</replaceable><literal>=</literal><replaceable>privilege-abbreviation</replaceable><optional><literal>*</literal></optional>...<literal>/</literal><replaceable>grantor</replaceable>
|
|
|
|
</synopsis>
|
|
|
|
Each <type>aclitem</type> lists all the permissions of one grantee that
|
|
|
|
have been granted by a particular grantor. Specific privileges are
|
|
|
|
represented by one-letter abbreviations from
|
|
|
|
<xref linkend="privilege-abbrevs-table"/>, with <literal>*</literal>
|
|
|
|
appended if the privilege was granted with grant option. For example,
|
2018-12-03 17:40:49 +01:00
|
|
|
<literal>calvin=r*w/hobbes</literal> specifies that the role
|
|
|
|
<literal>calvin</literal> has the privilege
|
|
|
|
<literal>SELECT</literal> (<literal>r</literal>) with grant option
|
|
|
|
(<literal>*</literal>) as well as the non-grantable
|
|
|
|
privilege <literal>UPDATE</literal> (<literal>w</literal>), both granted
|
|
|
|
by the role <literal>hobbes</literal>. If <literal>calvin</literal>
|
|
|
|
also has some privileges on the same object granted by a different
|
|
|
|
grantor, those would appear as a separate <type>aclitem</type> entry.
|
|
|
|
An empty grantee field in an <type>aclitem</type> stands
|
|
|
|
for <literal>PUBLIC</literal>.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
As an example, suppose that user <literal>miriam</literal> creates
|
|
|
|
table <literal>mytable</literal> and does:
|
|
|
|
<programlisting>
|
|
|
|
GRANT SELECT ON mytable TO PUBLIC;
|
|
|
|
GRANT SELECT, UPDATE, INSERT ON mytable TO admin;
|
|
|
|
GRANT SELECT (col1), UPDATE (col1) ON mytable TO miriam_rw;
|
|
|
|
</programlisting>
|
|
|
|
Then <application>psql</application>'s <literal>\dp</literal> command
|
|
|
|
would show:
|
|
|
|
<programlisting>
|
|
|
|
=> \dp mytable
|
2022-12-14 02:33:28 +01:00
|
|
|
Access privileges
|
2024-03-13 20:49:26 +01:00
|
|
|
Schema | Name | Type | Access privileges | Column privileges | Policies
|
|
|
|
--------+---------+-------+------------------------+-----------------------+----------
|
|
|
|
public | mytable | table | miriam=arwdDxtm/miriam+| col1: +|
|
|
|
|
| | | =r/miriam +| miriam_rw=rw/miriam |
|
|
|
|
| | | admin=arw/miriam | |
|
2018-12-03 17:40:49 +01:00
|
|
|
(1 row)
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
If the <quote>Access privileges</quote> column is empty for a given
|
|
|
|
object, it means the object has default privileges (that is, its
|
|
|
|
privileges entry in the relevant system catalog is null). Default
|
|
|
|
privileges always include all privileges for the owner, and can include
|
|
|
|
some privileges for <literal>PUBLIC</literal> depending on the object
|
|
|
|
type, as explained above. The first <command>GRANT</command>
|
|
|
|
or <command>REVOKE</command> on an object will instantiate the default
|
|
|
|
privileges (producing, for
|
|
|
|
example, <literal>miriam=arwdDxt/miriam</literal>) and then modify them
|
|
|
|
per the specified request. Similarly, entries are shown in <quote>Column
|
|
|
|
privileges</quote> only for columns with nondefault privileges.
|
|
|
|
(Note: for this purpose, <quote>default privileges</quote> always means
|
|
|
|
the built-in default privileges for the object's type. An object whose
|
|
|
|
privileges have been affected by an <command>ALTER DEFAULT
|
|
|
|
PRIVILEGES</command> command will always be shown with an explicit
|
|
|
|
privilege entry that includes the effects of
|
|
|
|
the <command>ALTER</command>.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Notice that the owner's implicit grant options are not marked in the
|
|
|
|
access privileges display. A <literal>*</literal> will appear only when
|
|
|
|
grant options have been explicitly granted to someone.
|
|
|
|
</para>
|
2023-11-13 21:41:27 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
The <quote>Access privileges</quote> column
|
|
|
|
shows <literal>(none)</literal> when the object's privileges entry is
|
|
|
|
non-null but empty. This means that no privileges are granted at all,
|
|
|
|
even to the object's owner — a rare situation. (The owner still
|
|
|
|
has implicit grant options in this case, and so could re-grant her own
|
|
|
|
privileges; but she has none at the moment.)
|
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</sect1>
|
|
|
|
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
<sect1 id="ddl-rowsecurity">
|
|
|
|
<title>Row Security Policies</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-rowsecurity">
|
2016-01-04 02:04:11 +01:00
|
|
|
<primary>row-level security</primary>
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-rowsecurity">
|
2015-10-03 03:22:44 +02:00
|
|
|
<primary>policy</primary>
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
In addition to the SQL-standard <link linkend="ddl-priv">privilege
|
2017-11-23 15:39:47 +01:00
|
|
|
system</link> available through <xref linkend="sql-grant"/>,
|
2017-10-09 03:44:17 +02:00
|
|
|
tables can have <firstterm>row security policies</firstterm> that restrict,
|
2016-01-04 02:04:11 +01:00
|
|
|
on a per-user basis, which rows can be returned by normal queries
|
|
|
|
or inserted, updated, or deleted by data modification commands.
|
2017-10-09 03:44:17 +02:00
|
|
|
This feature is also known as <firstterm>Row-Level Security</firstterm>.
|
2016-01-04 02:04:11 +01:00
|
|
|
By default, tables do not have any policies, so that if a user has
|
|
|
|
access privileges to a table according to the SQL privilege system,
|
|
|
|
all rows within it are equally available for querying or updating.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
When row security is enabled on a table (with
|
|
|
|
<link linkend="sql-altertable">ALTER TABLE ... ENABLE ROW LEVEL
|
2017-10-09 03:44:17 +02:00
|
|
|
SECURITY</link>), all normal access to the table for selecting rows or
|
2016-01-04 02:04:11 +01:00
|
|
|
modifying rows must be allowed by a row security policy. (However, the
|
|
|
|
table's owner is typically not subject to row security policies.) If no
|
|
|
|
policy exists for the table, a default-deny policy is used, meaning that
|
|
|
|
no rows are visible or can be modified. Operations that apply to the
|
2017-10-09 03:44:17 +02:00
|
|
|
whole table, such as <command>TRUNCATE</command> and <literal>REFERENCES</literal>,
|
2016-01-04 02:04:11 +01:00
|
|
|
are not subject to row security.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Row security policies can be specific to commands, or to roles, or to
|
2016-01-04 02:04:11 +01:00
|
|
|
both. A policy can be specified to apply to <literal>ALL</literal>
|
2017-10-09 03:44:17 +02:00
|
|
|
commands, or to <literal>SELECT</literal>, <literal>INSERT</literal>, <literal>UPDATE</literal>,
|
|
|
|
or <literal>DELETE</literal>. Multiple roles can be assigned to a given
|
2016-01-04 02:04:11 +01:00
|
|
|
policy, and normal role membership and inheritance rules apply.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
To specify which rows are visible or modifiable according to a policy,
|
|
|
|
an expression is required that returns a Boolean result. This
|
|
|
|
expression will be evaluated for each row prior to any conditions or
|
|
|
|
functions coming from the user's query. (The only exceptions to this
|
|
|
|
rule are <literal>leakproof</literal> functions, which are guaranteed to
|
|
|
|
not leak information; the optimizer may choose to apply such functions
|
|
|
|
ahead of the row-security check.) Rows for which the expression does
|
2017-10-09 03:44:17 +02:00
|
|
|
not return <literal>true</literal> will not be processed. Separate expressions
|
2016-01-04 02:04:11 +01:00
|
|
|
may be specified to provide independent control over the rows which are
|
|
|
|
visible and the rows which are allowed to be modified. Policy
|
|
|
|
expressions are run as part of the query and with the privileges of the
|
|
|
|
user running the query, although security-definer functions can be used
|
|
|
|
to access data not available to the calling user.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Superusers and roles with the <literal>BYPASSRLS</literal> attribute always
|
2016-01-04 02:04:11 +01:00
|
|
|
bypass the row security system when accessing a table. Table owners
|
|
|
|
normally bypass row security as well, though a table owner can choose to
|
|
|
|
be subject to row security with <link linkend="sql-altertable">ALTER
|
2017-10-09 03:44:17 +02:00
|
|
|
TABLE ... FORCE ROW LEVEL SECURITY</link>.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Enabling and disabling row security, as well as adding policies to a
|
2016-01-04 02:04:11 +01:00
|
|
|
table, is always the privilege of the table owner only.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
Policies are created using the <xref linkend="sql-createpolicy"/>
|
|
|
|
command, altered using the <xref linkend="sql-alterpolicy"/> command,
|
|
|
|
and dropped using the <xref linkend="sql-droppolicy"/> command. To
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
enable and disable row security for a given table, use the
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="sql-altertable"/> command.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Each policy has a name and multiple policies can be defined for a
|
|
|
|
table. As policies are table-specific, each policy for a table must
|
|
|
|
have a unique name. Different tables may have policies with the
|
|
|
|
same name.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
When multiple policies apply to a given query, they are combined using
|
2016-12-05 21:50:55 +01:00
|
|
|
either <literal>OR</literal> (for permissive policies, which are the
|
|
|
|
default) or using <literal>AND</literal> (for restrictive policies).
|
|
|
|
This is similar to the rule that a given role has the privileges
|
|
|
|
of all roles that they are a member of. Permissive vs. restrictive
|
|
|
|
policies are discussed further below.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
As a simple example, here is how to create a policy on
|
2017-10-09 03:44:17 +02:00
|
|
|
the <literal>account</literal> relation to allow only members of
|
|
|
|
the <literal>managers</literal> role to access rows, and only rows of their
|
2016-01-04 02:04:11 +01:00
|
|
|
accounts:
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE accounts (manager text, company text, contact_email text);
|
|
|
|
|
2016-01-04 02:04:11 +01:00
|
|
|
ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
|
|
|
|
CREATE POLICY account_managers ON accounts TO managers
|
|
|
|
USING (manager = current_user);
|
|
|
|
</programlisting>
|
|
|
|
|
2018-07-30 17:54:41 +02:00
|
|
|
<para>
|
|
|
|
The policy above implicitly provides a <literal>WITH CHECK</literal>
|
|
|
|
clause identical to its <literal>USING</literal> clause, so that the
|
|
|
|
constraint applies both to rows selected by a command (so a manager
|
|
|
|
cannot <command>SELECT</command>, <command>UPDATE</command>,
|
|
|
|
or <command>DELETE</command> existing rows belonging to a different
|
|
|
|
manager) and to rows modified by a command (so rows belonging to a
|
|
|
|
different manager cannot be created via <command>INSERT</command>
|
|
|
|
or <command>UPDATE</command>).
|
|
|
|
</para>
|
|
|
|
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
If no role is specified, or the special user name
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
<literal>PUBLIC</literal> is used, then the policy applies to all
|
2018-07-30 17:54:41 +02:00
|
|
|
users on the system. To allow all users to access only their own row in
|
2017-10-09 03:44:17 +02:00
|
|
|
a <literal>users</literal> table, a simple policy can be used:
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE POLICY user_policy ON users
|
2016-09-13 01:19:24 +02:00
|
|
|
USING (user_name = current_user);
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2018-07-30 17:54:41 +02:00
|
|
|
<para>
|
|
|
|
This works similarly to the previous example.
|
|
|
|
</para>
|
|
|
|
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
To use a different policy for rows that are being added to the table
|
2018-07-30 17:54:41 +02:00
|
|
|
compared to those rows that are visible, multiple policies can be
|
|
|
|
combined. This pair of policies would allow all users to view all rows
|
2017-10-09 03:44:17 +02:00
|
|
|
in the <literal>users</literal> table, but only modify their own:
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
2018-07-30 17:54:41 +02:00
|
|
|
CREATE POLICY user_sel_policy ON users
|
|
|
|
FOR SELECT
|
|
|
|
USING (true);
|
|
|
|
CREATE POLICY user_mod_policy ON users
|
|
|
|
USING (user_name = current_user);
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2018-07-30 17:54:41 +02:00
|
|
|
<para>
|
|
|
|
In a <command>SELECT</command> command, these two policies are combined
|
|
|
|
using <literal>OR</literal>, with the net effect being that all rows
|
|
|
|
can be selected. In other command types, only the second policy applies,
|
|
|
|
so that the effects are the same as before.
|
|
|
|
</para>
|
|
|
|
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Row security can also be disabled with the <command>ALTER TABLE</command>
|
2016-01-04 02:04:11 +01:00
|
|
|
command. Disabling row security does not remove any policies that are
|
|
|
|
defined on the table; they are simply ignored. Then all rows in the
|
|
|
|
table are visible and modifiable, subject to the standard SQL privileges
|
|
|
|
system.
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</para>
|
|
|
|
|
2014-09-26 18:46:26 +02:00
|
|
|
<para>
|
2016-01-04 02:04:11 +01:00
|
|
|
Below is a larger example of how this feature can be used in production
|
2017-10-09 03:44:17 +02:00
|
|
|
environments. The table <literal>passwd</literal> emulates a Unix password
|
2016-01-04 02:04:11 +01:00
|
|
|
file:
|
2014-09-26 18:46:26 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
-- Simple passwd-file based example
|
|
|
|
CREATE TABLE passwd (
|
2016-09-13 01:19:24 +02:00
|
|
|
user_name text UNIQUE NOT NULL,
|
2014-09-26 18:46:26 +02:00
|
|
|
pwhash text,
|
|
|
|
uid int PRIMARY KEY,
|
|
|
|
gid int NOT NULL,
|
|
|
|
real_name text NOT NULL,
|
|
|
|
home_phone text,
|
|
|
|
extra_info text,
|
|
|
|
home_dir text NOT NULL,
|
|
|
|
shell text NOT NULL
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE ROLE admin; -- Administrator
|
|
|
|
CREATE ROLE bob; -- Normal user
|
|
|
|
CREATE ROLE alice; -- Normal user
|
|
|
|
|
|
|
|
-- Populate the table
|
|
|
|
INSERT INTO passwd VALUES
|
|
|
|
('admin','xxx',0,0,'Admin','111-222-3333',null,'/root','/bin/dash');
|
|
|
|
INSERT INTO passwd VALUES
|
|
|
|
('bob','xxx',1,1,'Bob','123-456-7890',null,'/home/bob','/bin/zsh');
|
|
|
|
INSERT INTO passwd VALUES
|
|
|
|
('alice','xxx',2,1,'Alice','098-765-4321',null,'/home/alice','/bin/zsh');
|
|
|
|
|
2021-04-21 08:14:43 +02:00
|
|
|
-- Be sure to enable row-level security on the table
|
2014-09-26 18:46:26 +02:00
|
|
|
ALTER TABLE passwd ENABLE ROW LEVEL SECURITY;
|
|
|
|
|
|
|
|
-- Create policies
|
|
|
|
-- Administrator can see all rows and add any rows
|
|
|
|
CREATE POLICY admin_all ON passwd TO admin USING (true) WITH CHECK (true);
|
|
|
|
-- Normal users can view all rows
|
|
|
|
CREATE POLICY all_view ON passwd FOR SELECT USING (true);
|
|
|
|
-- Normal users can update their own records, but
|
|
|
|
-- limit which shells a normal user is allowed to set
|
|
|
|
CREATE POLICY user_mod ON passwd FOR UPDATE
|
2016-09-13 01:19:24 +02:00
|
|
|
USING (current_user = user_name)
|
2014-09-26 18:46:26 +02:00
|
|
|
WITH CHECK (
|
2016-09-13 01:19:24 +02:00
|
|
|
current_user = user_name AND
|
2014-09-26 18:46:26 +02:00
|
|
|
shell IN ('/bin/bash','/bin/sh','/bin/dash','/bin/zsh','/bin/tcsh')
|
|
|
|
);
|
|
|
|
|
|
|
|
-- Allow admin all normal rights
|
|
|
|
GRANT SELECT, INSERT, UPDATE, DELETE ON passwd TO admin;
|
|
|
|
-- Users only get select access on public columns
|
|
|
|
GRANT SELECT
|
2016-09-13 01:19:24 +02:00
|
|
|
(user_name, uid, gid, real_name, home_phone, extra_info, home_dir, shell)
|
2014-09-26 18:46:26 +02:00
|
|
|
ON passwd TO public;
|
|
|
|
-- Allow users to update certain columns
|
|
|
|
GRANT UPDATE
|
|
|
|
(pwhash, real_name, home_phone, extra_info, shell)
|
|
|
|
ON passwd TO public;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
As with any security settings, it's important to test and ensure that
|
|
|
|
the system is behaving as expected. Using the example above, this
|
|
|
|
demonstrates that the permission system is working properly.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
-- admin can view all rows and fields
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> set role admin;
|
2014-09-26 18:46:26 +02:00
|
|
|
SET
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> table passwd;
|
2016-09-13 01:19:24 +02:00
|
|
|
user_name | pwhash | uid | gid | real_name | home_phone | extra_info | home_dir | shell
|
|
|
|
-----------+--------+-----+-----+-----------+--------------+------------+-------------+-----------
|
|
|
|
admin | xxx | 0 | 0 | Admin | 111-222-3333 | | /root | /bin/dash
|
|
|
|
bob | xxx | 1 | 1 | Bob | 123-456-7890 | | /home/bob | /bin/zsh
|
|
|
|
alice | xxx | 2 | 1 | Alice | 098-765-4321 | | /home/alice | /bin/zsh
|
2014-09-26 18:46:26 +02:00
|
|
|
(3 rows)
|
|
|
|
|
|
|
|
-- Test what Alice is able to do
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> set role alice;
|
2014-09-26 18:46:26 +02:00
|
|
|
SET
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> table passwd;
|
2023-04-05 09:16:19 +02:00
|
|
|
ERROR: permission denied for table passwd
|
2016-09-13 01:19:24 +02:00
|
|
|
postgres=> select user_name,real_name,home_phone,extra_info,home_dir,shell from passwd;
|
|
|
|
user_name | real_name | home_phone | extra_info | home_dir | shell
|
|
|
|
-----------+-----------+--------------+------------+-------------+-----------
|
|
|
|
admin | Admin | 111-222-3333 | | /root | /bin/dash
|
|
|
|
bob | Bob | 123-456-7890 | | /home/bob | /bin/zsh
|
|
|
|
alice | Alice | 098-765-4321 | | /home/alice | /bin/zsh
|
2014-09-26 18:46:26 +02:00
|
|
|
(3 rows)
|
|
|
|
|
2016-09-13 01:19:24 +02:00
|
|
|
postgres=> update passwd set user_name = 'joe';
|
2023-04-05 09:16:19 +02:00
|
|
|
ERROR: permission denied for table passwd
|
2016-01-04 02:04:11 +01:00
|
|
|
-- Alice is allowed to change her own real_name, but no others
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> update passwd set real_name = 'Alice Doe';
|
2014-09-26 18:46:26 +02:00
|
|
|
UPDATE 1
|
2016-09-13 01:19:24 +02:00
|
|
|
postgres=> update passwd set real_name = 'John Doe' where user_name = 'admin';
|
2014-09-26 18:46:26 +02:00
|
|
|
UPDATE 0
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> update passwd set shell = '/bin/xx';
|
2014-09-26 18:46:26 +02:00
|
|
|
ERROR: new row violates WITH CHECK OPTION for "passwd"
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> delete from passwd;
|
2023-04-05 09:16:19 +02:00
|
|
|
ERROR: permission denied for table passwd
|
2016-09-13 01:19:24 +02:00
|
|
|
postgres=> insert into passwd (user_name) values ('xxx');
|
2023-04-05 09:16:19 +02:00
|
|
|
ERROR: permission denied for table passwd
|
2016-01-04 02:04:11 +01:00
|
|
|
-- Alice can change her own password; RLS silently prevents updating other rows
|
2015-08-06 05:03:45 +02:00
|
|
|
postgres=> update passwd set pwhash = 'abc';
|
2014-09-26 18:46:26 +02:00
|
|
|
UPDATE 1
|
2016-12-05 21:50:55 +01:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
All of the policies constructed thus far have been permissive policies,
|
|
|
|
meaning that when multiple policies are applied they are combined using
|
2017-06-18 20:01:45 +02:00
|
|
|
the <quote>OR</quote> Boolean operator. While permissive policies can be constructed
|
2016-12-05 21:50:55 +01:00
|
|
|
to only allow access to rows in the intended cases, it can be simpler to
|
|
|
|
combine permissive policies with restrictive policies (which the records
|
2017-06-18 20:01:45 +02:00
|
|
|
must pass and which are combined using the <quote>AND</quote> Boolean operator).
|
2016-12-05 21:50:55 +01:00
|
|
|
Building on the example above, we add a restrictive policy to require
|
2017-06-18 20:01:45 +02:00
|
|
|
the administrator to be connected over a local Unix socket to access the
|
|
|
|
records of the <literal>passwd</literal> table:
|
2016-12-05 21:50:55 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE POLICY admin_local_only ON passwd AS RESTRICTIVE TO admin
|
|
|
|
USING (pg_catalog.inet_client_addr() IS NULL);
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
We can then see that an administrator connecting over a network will not
|
|
|
|
see any records, due to the restrictive policy:
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
=> SELECT current_user;
|
2022-04-20 17:04:28 +02:00
|
|
|
current_user
|
2016-12-05 21:50:55 +01:00
|
|
|
--------------
|
|
|
|
admin
|
|
|
|
(1 row)
|
|
|
|
|
|
|
|
=> select inet_client_addr();
|
2022-04-20 17:04:28 +02:00
|
|
|
inet_client_addr
|
2016-12-05 21:50:55 +01:00
|
|
|
------------------
|
|
|
|
127.0.0.1
|
|
|
|
(1 row)
|
|
|
|
|
|
|
|
=> TABLE passwd;
|
|
|
|
user_name | pwhash | uid | gid | real_name | home_phone | extra_info | home_dir | shell
|
|
|
|
-----------+--------+-----+-----+-----------+------------+------------+----------+-------
|
|
|
|
(0 rows)
|
|
|
|
|
|
|
|
=> UPDATE passwd set pwhash = NULL;
|
|
|
|
UPDATE 0
|
2014-09-26 18:46:26 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2016-01-04 18:21:31 +01:00
|
|
|
<para>
|
|
|
|
Referential integrity checks, such as unique or primary key constraints
|
|
|
|
and foreign key references, always bypass row security to ensure that
|
|
|
|
data integrity is maintained. Care must be taken when developing
|
2017-10-09 03:44:17 +02:00
|
|
|
schemas and row level policies to avoid <quote>covert channel</quote> leaks of
|
2016-01-04 18:21:31 +01:00
|
|
|
information through such referential integrity checks.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
In some contexts it is important to be sure that row security is
|
|
|
|
not being applied. For example, when taking a backup, it could be
|
|
|
|
disastrous if row security silently caused some rows to be omitted
|
|
|
|
from the backup. In such a situation, you can set the
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="guc-row-security"/> configuration parameter
|
2017-10-09 03:44:17 +02:00
|
|
|
to <literal>off</literal>. This does not in itself bypass row security;
|
2016-01-04 18:21:31 +01:00
|
|
|
what it does is throw an error if any query's results would get filtered
|
|
|
|
by a policy. The reason for the error can then be investigated and
|
|
|
|
fixed.
|
|
|
|
</para>
|
|
|
|
|
2016-01-04 21:11:43 +01:00
|
|
|
<para>
|
|
|
|
In the examples above, the policy expressions consider only the current
|
|
|
|
values in the row to be accessed or updated. This is the simplest and
|
|
|
|
best-performing case; when possible, it's best to design row security
|
|
|
|
applications to work this way. If it is necessary to consult other rows
|
|
|
|
or other tables to make a policy decision, that can be accomplished using
|
2017-10-09 03:44:17 +02:00
|
|
|
sub-<command>SELECT</command>s, or functions that contain <command>SELECT</command>s,
|
2016-01-04 21:11:43 +01:00
|
|
|
in the policy expressions. Be aware however that such accesses can
|
|
|
|
create race conditions that could allow information leakage if care is
|
|
|
|
not taken. As an example, consider the following table design:
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
-- definition of privilege groups
|
|
|
|
CREATE TABLE groups (group_id int PRIMARY KEY,
|
|
|
|
group_name text NOT NULL);
|
|
|
|
|
|
|
|
INSERT INTO groups VALUES
|
|
|
|
(1, 'low'),
|
|
|
|
(2, 'medium'),
|
|
|
|
(5, 'high');
|
|
|
|
|
|
|
|
GRANT ALL ON groups TO alice; -- alice is the administrator
|
|
|
|
GRANT SELECT ON groups TO public;
|
|
|
|
|
|
|
|
-- definition of users' privilege levels
|
|
|
|
CREATE TABLE users (user_name text PRIMARY KEY,
|
|
|
|
group_id int NOT NULL REFERENCES groups);
|
|
|
|
|
|
|
|
INSERT INTO users VALUES
|
|
|
|
('alice', 5),
|
|
|
|
('bob', 2),
|
|
|
|
('mallory', 2);
|
|
|
|
|
|
|
|
GRANT ALL ON users TO alice;
|
|
|
|
GRANT SELECT ON users TO public;
|
|
|
|
|
|
|
|
-- table holding the information to be protected
|
|
|
|
CREATE TABLE information (info text,
|
|
|
|
group_id int NOT NULL REFERENCES groups);
|
|
|
|
|
|
|
|
INSERT INTO information VALUES
|
|
|
|
('barely secret', 1),
|
|
|
|
('slightly secret', 2),
|
|
|
|
('very secret', 5);
|
|
|
|
|
|
|
|
ALTER TABLE information ENABLE ROW LEVEL SECURITY;
|
|
|
|
|
|
|
|
-- a row should be visible to/updatable by users whose security group_id is
|
|
|
|
-- greater than or equal to the row's group_id
|
|
|
|
CREATE POLICY fp_s ON information FOR SELECT
|
|
|
|
USING (group_id <= (SELECT group_id FROM users WHERE user_name = current_user));
|
|
|
|
CREATE POLICY fp_u ON information FOR UPDATE
|
|
|
|
USING (group_id <= (SELECT group_id FROM users WHERE user_name = current_user));
|
|
|
|
|
|
|
|
-- we rely only on RLS to protect the information table
|
|
|
|
GRANT ALL ON information TO public;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Now suppose that <literal>alice</literal> wishes to change the <quote>slightly
|
|
|
|
secret</quote> information, but decides that <literal>mallory</literal> should not
|
2016-01-04 21:11:43 +01:00
|
|
|
be trusted with the new content of that row, so she does:
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
BEGIN;
|
|
|
|
UPDATE users SET group_id = 1 WHERE user_name = 'mallory';
|
|
|
|
UPDATE information SET info = 'secret from mallory' WHERE group_id = 2;
|
|
|
|
COMMIT;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
That looks safe; there is no window wherein <literal>mallory</literal> should be
|
|
|
|
able to see the <quote>secret from mallory</quote> string. However, there is
|
|
|
|
a race condition here. If <literal>mallory</literal> is concurrently doing,
|
2016-01-04 21:11:43 +01:00
|
|
|
say,
|
|
|
|
<programlisting>
|
|
|
|
SELECT * FROM information WHERE group_id = 2 FOR UPDATE;
|
|
|
|
</programlisting>
|
2017-10-09 03:44:17 +02:00
|
|
|
and her transaction is in <literal>READ COMMITTED</literal> mode, it is possible
|
|
|
|
for her to see <quote>secret from mallory</quote>. That happens if her
|
|
|
|
transaction reaches the <structname>information</structname> row just
|
|
|
|
after <literal>alice</literal>'s does. It blocks waiting
|
|
|
|
for <literal>alice</literal>'s transaction to commit, then fetches the updated
|
|
|
|
row contents thanks to the <literal>FOR UPDATE</literal> clause. However, it
|
|
|
|
does <emphasis>not</emphasis> fetch an updated row for the
|
|
|
|
implicit <command>SELECT</command> from <structname>users</structname>, because that
|
|
|
|
sub-<command>SELECT</command> did not have <literal>FOR UPDATE</literal>; instead
|
|
|
|
the <structname>users</structname> row is read with the snapshot taken at the start
|
2016-01-04 21:11:43 +01:00
|
|
|
of the query. Therefore, the policy expression tests the old value
|
2017-10-09 03:44:17 +02:00
|
|
|
of <literal>mallory</literal>'s privilege level and allows her to see the
|
2016-01-04 21:11:43 +01:00
|
|
|
updated row.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
There are several ways around this problem. One simple answer is to use
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>SELECT ... FOR SHARE</literal> in sub-<command>SELECT</command>s in row
|
|
|
|
security policies. However, that requires granting <literal>UPDATE</literal>
|
|
|
|
privilege on the referenced table (here <structname>users</structname>) to the
|
2016-01-04 21:11:43 +01:00
|
|
|
affected users, which might be undesirable. (But another row security
|
|
|
|
policy could be applied to prevent them from actually exercising that
|
2017-10-09 03:44:17 +02:00
|
|
|
privilege; or the sub-<command>SELECT</command> could be embedded into a security
|
2016-01-04 21:11:43 +01:00
|
|
|
definer function.) Also, heavy concurrent use of row share locks on the
|
|
|
|
referenced table could pose a performance problem, especially if updates
|
|
|
|
of it are frequent. Another solution, practical if updates of the
|
2021-04-01 08:28:37 +02:00
|
|
|
referenced table are infrequent, is to take an
|
|
|
|
<literal>ACCESS EXCLUSIVE</literal> lock on the
|
2016-01-04 21:11:43 +01:00
|
|
|
referenced table when updating it, so that no concurrent transactions
|
|
|
|
could be examining old row values. Or one could just wait for all
|
|
|
|
concurrent transactions to end after committing an update of the
|
|
|
|
referenced table and before making changes that rely on the new security
|
|
|
|
situation.
|
|
|
|
</para>
|
|
|
|
|
2016-01-04 02:04:11 +01:00
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
For additional details see <xref linkend="sql-createpolicy"/>
|
|
|
|
and <xref linkend="sql-altertable"/>.
|
2016-01-04 02:04:11 +01:00
|
|
|
</para>
|
|
|
|
|
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
|
|
|
</sect1>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect1 id="ddl-schemas">
|
|
|
|
<title>Schemas</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-schemas">
|
|
|
|
<primary>schema</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2020-04-01 00:10:39 +02:00
|
|
|
A <productname>PostgreSQL</productname> database cluster contains
|
|
|
|
one or more named databases. Roles and a few other object types are
|
|
|
|
shared across the entire cluster. A client connection to the server
|
|
|
|
can only access data in a single database, the one specified in the
|
|
|
|
connection request.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
Users of a cluster do not necessarily have the privilege to access every
|
2020-04-01 00:10:39 +02:00
|
|
|
database in the cluster. Sharing of role names means that there
|
|
|
|
cannot be different roles named, say, <literal>joe</literal> in two databases
|
2005-11-05 00:53:18 +01:00
|
|
|
in the same cluster; but the system can be configured to allow
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>joe</literal> access to only some of the databases.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
A database contains one or more named <firstterm>schemas</firstterm>, which
|
2005-11-05 00:53:18 +01:00
|
|
|
in turn contain tables. Schemas also contain other kinds of named
|
2024-01-31 11:53:56 +01:00
|
|
|
objects, including data types, functions, and operators. Within one
|
|
|
|
schema, two objects of the same type cannot have the same name.
|
|
|
|
Furthermore, tables, sequences, indexes, views, materialized views, and
|
|
|
|
foreign tables share the same namespace, so that, for example, an index and
|
|
|
|
a table must have different names if they are in the same schema. The same
|
2005-11-05 00:53:18 +01:00
|
|
|
object name can be used in different schemas without conflict; for
|
2017-10-09 03:44:17 +02:00
|
|
|
example, both <literal>schema1</literal> and <literal>myschema</literal> can
|
|
|
|
contain tables named <literal>mytable</literal>. Unlike databases,
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
schemas are not rigidly separated: a user can access objects in any
|
2015-09-22 04:57:29 +02:00
|
|
|
of the schemas in the database they are connected to, if they have
|
2005-11-05 00:53:18 +01:00
|
|
|
privileges to do so.
|
2005-01-08 02:44:08 +01:00
|
|
|
</para>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
There are several reasons why one might want to use schemas:
|
2004-08-08 23:33:11 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
To allow many users to use one database without interfering with
|
|
|
|
each other.
|
2004-08-08 23:33:11 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
To organize database objects into logical groups to make them
|
|
|
|
more manageable.
|
2004-08-08 23:33:11 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
Third-party applications can be put into separate schemas so
|
2009-04-27 18:27:36 +02:00
|
|
|
they do not collide with the names of other objects.
|
2004-08-08 23:33:11 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
Schemas are analogous to directories at the operating system level,
|
|
|
|
except that schemas cannot be nested.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-create">
|
|
|
|
<title>Creating a Schema</title>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-schemas-create">
|
|
|
|
<primary>schema</primary>
|
|
|
|
<secondary>creating</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2005-11-02 00:19:05 +01:00
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
To create a schema, use the <xref linkend="sql-createschema"/>
|
2010-04-03 09:23:02 +02:00
|
|
|
command. Give the schema a name
|
2006-02-19 00:14:45 +01:00
|
|
|
of your choice. For example:
|
2005-11-02 00:19:05 +01:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
CREATE SCHEMA myschema;
|
2005-11-02 00:19:05 +01:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<indexterm>
|
2005-11-05 00:53:18 +01:00
|
|
|
<primary>qualified name</primary>
|
2005-11-02 00:19:05 +01:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
2005-11-05 00:53:18 +01:00
|
|
|
<primary>name</primary>
|
|
|
|
<secondary>qualified</secondary>
|
2005-11-02 00:19:05 +01:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
To create or access objects in a schema, write a
|
2017-10-09 03:44:17 +02:00
|
|
|
<firstterm>qualified name</firstterm> consisting of the schema name and
|
2005-11-05 00:53:18 +01:00
|
|
|
table name separated by a dot:
|
|
|
|
<synopsis>
|
2017-10-09 03:44:17 +02:00
|
|
|
<replaceable>schema</replaceable><literal>.</literal><replaceable>table</replaceable>
|
2005-11-05 00:53:18 +01:00
|
|
|
</synopsis>
|
|
|
|
This works anywhere a table name is expected, including the table
|
|
|
|
modification commands and the data access commands discussed in
|
|
|
|
the following chapters.
|
|
|
|
(For brevity we will speak of tables only, but the same ideas apply
|
|
|
|
to other kinds of named objects, such as types and functions.)
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
Actually, the even more general syntax
|
|
|
|
<synopsis>
|
2017-10-09 03:44:17 +02:00
|
|
|
<replaceable>database</replaceable><literal>.</literal><replaceable>schema</replaceable><literal>.</literal><replaceable>table</replaceable>
|
2005-11-05 00:53:18 +01:00
|
|
|
</synopsis>
|
2021-03-10 18:38:43 +01:00
|
|
|
can be used too, but at present this is just for pro forma
|
|
|
|
compliance with the SQL standard. If you write a database name,
|
2005-11-05 00:53:18 +01:00
|
|
|
it must be the same as the database you are connected to.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
So to create a table in the new schema, use:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE myschema.mytable (
|
|
|
|
...
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>schema</primary>
|
|
|
|
<secondary>removing</secondary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
To drop a schema if it's empty (all objects in it have been
|
2007-02-01 01:28:19 +01:00
|
|
|
dropped), use:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
DROP SCHEMA myschema;
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
To drop a schema including all contained objects, use:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
DROP SCHEMA myschema CASCADE;
|
|
|
|
</programlisting>
|
2017-11-23 15:39:47 +01:00
|
|
|
See <xref linkend="ddl-depend"/> for a description of the general
|
2005-11-05 00:53:18 +01:00
|
|
|
mechanism behind this.
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
Often you will want to create a schema owned by someone else
|
|
|
|
(since this is one of the ways to restrict the activities of your
|
|
|
|
users to well-defined namespaces). The syntax for that is:
|
|
|
|
<programlisting>
|
2016-09-13 01:19:24 +02:00
|
|
|
CREATE SCHEMA <replaceable>schema_name</replaceable> AUTHORIZATION <replaceable>user_name</replaceable>;
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
|
|
|
You can even omit the schema name, in which case the schema name
|
|
|
|
will be the same as the user name. See <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="ddl-schemas-patterns"/> for how this can be useful.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Schema names beginning with <literal>pg_</literal> are reserved for
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
system purposes and cannot be created by users.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</sect2>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-public">
|
|
|
|
<title>The Public Schema</title>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm zone="ddl-schemas-public">
|
|
|
|
<primary>schema</primary>
|
|
|
|
<secondary>public</secondary>
|
|
|
|
</indexterm>
|
2005-11-03 01:51:43 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
In the previous sections we created tables without specifying any
|
2009-04-27 18:27:36 +02:00
|
|
|
schema names. By default such tables (and other objects) are
|
2005-11-05 00:53:18 +01:00
|
|
|
automatically put into a schema named <quote>public</quote>. Every new
|
|
|
|
database contains such a schema. Thus, the following are equivalent:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE products ( ... );
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
and:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE public.products ( ... );
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</sect2>
|
2005-11-03 01:51:43 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-path">
|
|
|
|
<title>The Schema Search Path</title>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>search path</primary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>unqualified name</primary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>name</primary>
|
|
|
|
<secondary>unqualified</secondary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
Qualified names are tedious to write, and it's often best not to
|
|
|
|
wire a particular schema name into applications anyway. Therefore
|
2017-10-09 03:44:17 +02:00
|
|
|
tables are often referred to by <firstterm>unqualified names</firstterm>,
|
2005-11-05 00:53:18 +01:00
|
|
|
which consist of just the table name. The system determines which table
|
2017-10-09 03:44:17 +02:00
|
|
|
is meant by following a <firstterm>search path</firstterm>, which is a list
|
2005-11-05 00:53:18 +01:00
|
|
|
of schemas to look in. The first matching table in the search path
|
|
|
|
is taken to be the one wanted. If there is no match in the search
|
|
|
|
path, an error is reported, even if matching table names exist
|
|
|
|
in other schemas in the database.
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
<para>
|
|
|
|
The ability to create like-named objects in different schemas complicates
|
|
|
|
writing a query that references precisely the same objects every time. It
|
|
|
|
also opens up the potential for users to change the behavior of other
|
|
|
|
users' queries, maliciously or accidentally. Due to the prevalence of
|
|
|
|
unqualified names in queries and their use
|
|
|
|
in <productname>PostgreSQL</productname> internals, adding a schema
|
|
|
|
to <varname>search_path</varname> effectively trusts all users having
|
|
|
|
<literal>CREATE</literal> privilege on that schema. When you run an
|
|
|
|
ordinary query, a malicious user able to create objects in a schema of
|
|
|
|
your search path can take control and execute arbitrary SQL functions as
|
|
|
|
though you executed them.
|
|
|
|
</para>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>schema</primary>
|
|
|
|
<secondary>current</secondary>
|
|
|
|
</indexterm>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
The first schema named in the search path is called the current schema.
|
|
|
|
Aside from being the first schema searched, it is also the schema in
|
2017-10-09 03:44:17 +02:00
|
|
|
which new tables will be created if the <command>CREATE TABLE</command>
|
2005-11-05 00:53:18 +01:00
|
|
|
command does not specify a schema name.
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
2013-01-26 03:01:17 +01:00
|
|
|
<primary><varname>search_path</varname> configuration parameter</primary>
|
2005-11-05 00:53:18 +01:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To show the current search path, use the following command:
|
2005-11-02 00:19:05 +01:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
SHOW search_path;
|
2005-11-02 00:19:05 +01:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
In the default setup this returns:
|
|
|
|
<screen>
|
|
|
|
search_path
|
|
|
|
--------------
|
2014-08-20 11:04:32 +02:00
|
|
|
"$user", public
|
2005-11-05 00:53:18 +01:00
|
|
|
</screen>
|
|
|
|
The first element specifies that a schema with the same name as
|
|
|
|
the current user is to be searched. If no such schema exists,
|
|
|
|
the entry is ignored. The second element refers to the
|
|
|
|
public schema that we have seen already.
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
The first schema in the search path that exists is the default
|
|
|
|
location for creating new objects. That is the reason that by
|
|
|
|
default objects are created in the public schema. When objects
|
|
|
|
are referenced in any other context without schema qualification
|
|
|
|
(table modification, data modification, or query commands) the
|
|
|
|
search path is traversed until a matching object is found.
|
|
|
|
Therefore, in the default configuration, any unqualified access
|
|
|
|
again can only refer to the public schema.
|
|
|
|
</para>
|
2005-11-02 00:19:05 +01:00
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
To put our new schema in the path, we use:
|
2005-11-02 00:19:05 +01:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
SET search_path TO myschema,public;
|
2005-11-02 00:19:05 +01:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
(We omit the <literal>$user</literal> here because we have no
|
|
|
|
immediate need for it.) And then we can access the table without
|
|
|
|
schema qualification:
|
|
|
|
<programlisting>
|
|
|
|
DROP TABLE mytable;
|
|
|
|
</programlisting>
|
|
|
|
Also, since <literal>myschema</literal> is the first element in
|
|
|
|
the path, new objects would by default be created in it.
|
2005-11-02 00:19:05 +01:00
|
|
|
</para>
|
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
We could also have written:
|
2002-09-05 23:32:23 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
SET search_path TO myschema;
|
2002-09-05 23:32:23 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
Then we no longer have access to the public schema without
|
|
|
|
explicit qualification. There is nothing special about the public
|
|
|
|
schema except that it exists by default. It can be dropped, too.
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
See also <xref linkend="functions-info"/> for other ways to manipulate
|
2005-11-05 00:53:18 +01:00
|
|
|
the schema search path.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The search path works in the same way for data type names, function names,
|
|
|
|
and operator names as it does for table names. Data type and function
|
|
|
|
names can be qualified in exactly the same way as table names. If you
|
|
|
|
need to write a qualified operator name in an expression, there is a
|
|
|
|
special provision: you must write
|
|
|
|
<synopsis>
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>OPERATOR(</literal><replaceable>schema</replaceable><literal>.</literal><replaceable>operator</replaceable><literal>)</literal>
|
2005-11-05 00:53:18 +01:00
|
|
|
</synopsis>
|
2007-02-01 01:28:19 +01:00
|
|
|
This is needed to avoid syntactic ambiguity. An example is:
|
2002-09-05 23:32:23 +02:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
SELECT 3 OPERATOR(pg_catalog.+) 4;
|
2002-09-05 23:32:23 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
In practice one usually relies on the search path for operators,
|
|
|
|
so as not to have to write anything so ugly as that.
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-priv">
|
|
|
|
<title>Schemas and Privileges</title>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm zone="ddl-schemas-priv">
|
|
|
|
<primary>privilege</primary>
|
|
|
|
<secondary sortas="schemas">for schemas</secondary>
|
2003-08-31 19:32:24 +02:00
|
|
|
</indexterm>
|
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
By default, users cannot access any objects in schemas they do not
|
2009-04-27 18:27:36 +02:00
|
|
|
own. To allow that, the owner of the schema must grant the
|
2021-09-10 08:38:09 +02:00
|
|
|
<literal>USAGE</literal> privilege on the schema. By default, everyone
|
|
|
|
has that privilege on the schema <literal>public</literal>. To allow
|
|
|
|
users to make use of the objects in a schema, additional privileges might
|
|
|
|
need to be granted, as appropriate for the object.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2021-09-10 08:38:09 +02:00
|
|
|
A user can also be allowed to create objects in someone else's schema. To
|
|
|
|
allow that, the <literal>CREATE</literal> privilege on the schema needs to
|
|
|
|
be granted. In databases upgraded from
|
|
|
|
<productname>PostgreSQL</productname> 14 or earlier, everyone has that
|
|
|
|
privilege on the schema <literal>public</literal>.
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
Some <link linkend="ddl-schemas-patterns">usage patterns</link> call for
|
|
|
|
revoking that privilege:
|
2005-01-17 02:29:02 +01:00
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
2005-01-17 02:29:02 +01:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
(The first <quote>public</quote> is the schema, the second
|
|
|
|
<quote>public</quote> means <quote>every user</quote>. In the
|
|
|
|
first sense it is an identifier, in the second sense it is a
|
|
|
|
key word, hence the different capitalization; recall the
|
2017-11-23 15:39:47 +01:00
|
|
|
guidelines from <xref linkend="sql-syntax-identifiers"/>.)
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-catalog">
|
|
|
|
<title>The System Catalog Schema</title>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm zone="ddl-schemas-catalog">
|
|
|
|
<primary>system catalog</primary>
|
|
|
|
<secondary>schema</secondary>
|
2003-08-31 19:32:24 +02:00
|
|
|
</indexterm>
|
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
In addition to <literal>public</literal> and user-created schemas, each
|
|
|
|
database contains a <literal>pg_catalog</literal> schema, which contains
|
2005-11-05 00:53:18 +01:00
|
|
|
the system tables and all the built-in data types, functions, and
|
2017-10-09 03:44:17 +02:00
|
|
|
operators. <literal>pg_catalog</literal> is always effectively part of
|
2005-11-05 00:53:18 +01:00
|
|
|
the search path. If it is not named explicitly in the path then
|
2017-10-09 03:44:17 +02:00
|
|
|
it is implicitly searched <emphasis>before</emphasis> searching the path's
|
2005-11-05 00:53:18 +01:00
|
|
|
schemas. This ensures that built-in names will always be
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
findable. However, you can explicitly place
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>pg_catalog</literal> at the end of your search path if you
|
2005-11-05 00:53:18 +01:00
|
|
|
prefer to have user-defined names override built-in names.
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Since system table names begin with <literal>pg_</literal>, it is best to
|
2014-02-24 18:56:37 +01:00
|
|
|
avoid such names to ensure that you won't suffer a conflict if some
|
2010-02-24 16:54:31 +01:00
|
|
|
future version defines a system table named the same as your
|
|
|
|
table. (With the default search path, an unqualified reference to
|
|
|
|
your table name would then be resolved as the system table instead.)
|
|
|
|
System tables will continue to follow the convention of having
|
2017-10-09 03:44:17 +02:00
|
|
|
names beginning with <literal>pg_</literal>, so that they will not
|
2010-02-24 16:54:31 +01:00
|
|
|
conflict with unqualified user-table names so long as users avoid
|
2017-10-09 03:44:17 +02:00
|
|
|
the <literal>pg_</literal> prefix.
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect2 id="ddl-schemas-patterns">
|
|
|
|
<title>Usage Patterns</title>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2019-12-08 20:06:26 +01:00
|
|
|
Schemas can be used to organize your data in many ways.
|
|
|
|
A <firstterm>secure schema usage pattern</firstterm> prevents untrusted
|
|
|
|
users from changing the behavior of other users' queries. When a database
|
|
|
|
does not use a secure schema usage pattern, users wishing to securely
|
|
|
|
query that database would take protective action at the beginning of each
|
|
|
|
session. Specifically, they would begin each session by
|
|
|
|
setting <varname>search_path</varname> to the empty string or otherwise
|
2022-12-01 18:10:25 +01:00
|
|
|
removing schemas that are writable by non-superusers
|
2019-12-08 20:06:26 +01:00
|
|
|
from <varname>search_path</varname>. There are a few usage patterns
|
|
|
|
easily supported by the default configuration:
|
2005-11-05 00:53:18 +01:00
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
2022-12-01 18:10:25 +01:00
|
|
|
<para>
|
|
|
|
Constrain ordinary users to user-private schemas.
|
|
|
|
To implement this pattern, first ensure that no schemas have
|
|
|
|
public <literal>CREATE</literal> privileges. Then, for every user
|
|
|
|
needing to create non-temporary objects, create a schema with the
|
|
|
|
same name as that user, for example
|
|
|
|
<literal>CREATE SCHEMA alice AUTHORIZATION alice</literal>.
|
|
|
|
(Recall that the default search path starts
|
|
|
|
with <literal>$user</literal>, which resolves to the user
|
|
|
|
name. Therefore, if each user has a separate schema, they access
|
|
|
|
their own schemas by default.) This pattern is a secure schema
|
|
|
|
usage pattern unless an untrusted user is the database owner or
|
Restrict the privileges of CREATEROLE users.
Previously, CREATEROLE users were permitted to make nearly arbitrary
changes to roles that they didn't create, with certain exceptions,
particularly superuser roles. Instead, allow CREATEROLE users to make such
changes to roles for which they possess ADMIN OPTION, and to
grant membership only in roles for which they possess ADMIN OPTION.
When a CREATEROLE user who is not a superuser creates a role, grant
ADMIN OPTION on the newly-created role to the creator, so that they
can administer roles they create or for which they have been given
privileges.
With these changes, CREATEROLE users still have very significant
powers that unprivileged users do not receive: they can alter, rename,
drop, comment on, change the password for, and change security labels
on roles. However, they can now do these things only for roles for
which they possess appropriate privileges, rather than all
non-superuser roles; moreover, they cannot grant a role such as
pg_execute_server_program unless they themselves possess it.
Patch by me, reviewed by Mark Dilger.
Discussion: https://postgr.es/m/CA+TgmobN59ct+Emmz6ig1Nua2Q-_o=r6DSD98KfU53kctq_kQw@mail.gmail.com
2023-01-10 18:44:30 +01:00
|
|
|
has been granted <literal>ADMIN OPTION</literal> on a relevant role,
|
|
|
|
in which case no secure schema usage pattern exists.
|
2022-12-01 18:10:25 +01:00
|
|
|
</para>
|
|
|
|
<!-- A database owner can attack the database's users via "CREATE SCHEMA
|
Restrict the privileges of CREATEROLE users.
Previously, CREATEROLE users were permitted to make nearly arbitrary
changes to roles that they didn't create, with certain exceptions,
particularly superuser roles. Instead, allow CREATEROLE users to make such
changes to roles for which they possess ADMIN OPTION, and to
grant membership only in roles for which they possess ADMIN OPTION.
When a CREATEROLE user who is not a superuser creates a role, grant
ADMIN OPTION on the newly-created role to the creator, so that they
can administer roles they create or for which they have been given
privileges.
With these changes, CREATEROLE users still have very significant
powers that unprivileged users do not receive: they can alter, rename,
drop, comment on, change the password for, and change security labels
on roles. However, they can now do these things only for roles for
which they possess appropriate privileges, rather than all
non-superuser roles; moreover, they cannot grant a role such as
pg_execute_server_program unless they themselves possess it.
Patch by me, reviewed by Mark Dilger.
Discussion: https://postgr.es/m/CA+TgmobN59ct+Emmz6ig1Nua2Q-_o=r6DSD98KfU53kctq_kQw@mail.gmail.com
2023-01-10 18:44:30 +01:00
|
|
|
trojan; ALTER DATABASE $mydb SET search_path = trojan, public;". -->
|
2022-12-01 18:10:25 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2022-12-01 18:10:25 +01:00
|
|
|
In <productname>PostgreSQL</productname> 15 and later, the default
|
|
|
|
configuration supports this usage pattern. In prior versions, or
|
|
|
|
when using a database that has been upgraded from a prior version,
|
|
|
|
you will need to remove the public <literal>CREATE</literal>
|
|
|
|
privilege from the <literal>public</literal> schema (issue
|
|
|
|
<literal>REVOKE CREATE ON SCHEMA public FROM PUBLIC</literal>).
|
|
|
|
Then consider auditing the <literal>public</literal> schema for
|
|
|
|
objects named like objects in schema <literal>pg_catalog</literal>.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2022-12-01 18:10:25 +01:00
|
|
|
<!-- "DROP SCHEMA public" is inferior to this REVOKE, because pg_dump
|
|
|
|
doesn't preserve that DROP. -->
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
</listitem>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
<listitem>
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2019-12-08 20:06:26 +01:00
|
|
|
Remove the public schema from the default search path, by modifying
|
|
|
|
<link linkend="config-setting-configuration-file"><filename>postgresql.conf</filename></link>
|
|
|
|
or by issuing <literal>ALTER ROLE ALL SET search_path =
|
2021-09-10 08:38:09 +02:00
|
|
|
"$user"</literal>. Then, grant privileges to create in the public
|
|
|
|
schema. Only qualified names will choose public schema objects. While
|
|
|
|
qualified table references are fine, calls to functions in the public
|
|
|
|
schema <link linkend="typeconv-func">will be unsafe or
|
2019-12-08 20:06:26 +01:00
|
|
|
unreliable</link>. If you create functions or extensions in the public
|
|
|
|
schema, use the first pattern instead. Otherwise, like the first
|
|
|
|
pattern, this is secure unless an untrusted user is the database owner
|
Restrict the privileges of CREATEROLE users.
Previously, CREATEROLE users were permitted to make nearly arbitrary
changes to roles that they didn't create, with certain exceptions,
particularly superuser roles. Instead, allow CREATEROLE users to make such
changes to roles for which they possess ADMIN OPTION, and to
grant membership only in roles for which they possess ADMIN OPTION.
When a CREATEROLE user who is not a superuser creates a role, grant
ADMIN OPTION on the newly-created role to the creator, so that they
can administer roles they create or for which they have been given
privileges.
With these changes, CREATEROLE users still have very significant
powers that unprivileged users do not receive: they can alter, rename,
drop, comment on, change the password for, and change security labels
on roles. However, they can now do these things only for roles for
which they possess appropriate privileges, rather than all
non-superuser roles; moreover, they cannot grant a role such as
pg_execute_server_program unless they themselves possess it.
Patch by me, reviewed by Mark Dilger.
Discussion: https://postgr.es/m/CA+TgmobN59ct+Emmz6ig1Nua2Q-_o=r6DSD98KfU53kctq_kQw@mail.gmail.com
2023-01-10 18:44:30 +01:00
|
|
|
or has been granted <literal>ADMIN OPTION</literal> on a relevant role.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2021-09-10 08:38:09 +02:00
|
|
|
Keep the default search path, and grant privileges to create in the
|
|
|
|
public schema. All users access the public schema implicitly. This
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
simulates the situation where schemas are not available at all, giving
|
2019-12-08 20:06:26 +01:00
|
|
|
a smooth transition from the non-schema-aware world. However, this is
|
|
|
|
never a secure pattern. It is acceptable only when the database has a
|
2021-09-10 08:38:09 +02:00
|
|
|
single user or a few mutually-trusting users. In databases upgraded
|
|
|
|
from <productname>PostgreSQL</productname> 14 or earlier, this is the
|
|
|
|
default.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
For any pattern, to install shared applications (tables to be used by
|
|
|
|
everyone, additional functions provided by third parties, etc.), put them
|
|
|
|
into separate schemas. Remember to grant appropriate privileges to allow
|
|
|
|
the other users to access them. Users can then refer to these additional
|
|
|
|
objects by qualifying the names with a schema name, or they can put the
|
|
|
|
additional schemas into their search path, as they choose.
|
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="ddl-schemas-portability">
|
|
|
|
<title>Portability</title>
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
In the SQL standard, the notion of objects in the same schema
|
|
|
|
being owned by different users does not exist. Moreover, some
|
|
|
|
implementations do not allow you to create schemas that have a
|
|
|
|
different name than their owner. In fact, the concepts of schema
|
|
|
|
and user are nearly equivalent in a database system that
|
|
|
|
implements only the basic schema support specified in the
|
|
|
|
standard. Therefore, many users consider qualified names to
|
|
|
|
really consist of
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal><replaceable>user_name</replaceable>.<replaceable>table_name</replaceable></literal>.
|
2005-11-05 00:53:18 +01:00
|
|
|
This is how <productname>PostgreSQL</productname> will effectively
|
|
|
|
behave if you create a per-user schema for every user.
|
2003-11-05 01:05:32 +01:00
|
|
|
</para>
|
|
|
|
|
2005-01-17 02:29:02 +01:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Also, there is no concept of a <literal>public</literal> schema in the
|
2005-11-05 00:53:18 +01:00
|
|
|
SQL standard. For maximum conformance to the standard, you should
|
Document security implications of search_path and the public schema.
The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally. When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege. If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity. "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session. As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo. Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench. PostgreSQL encourages non-core
client applications to do likewise.
Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns. The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack. After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.
Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.
Back-patch to 9.3 (all supported versions).
Reviewed by Michael Paquier and Jonathan S. Katz. Reported by Arseniy
Sharoglazov.
Security: CVE-2018-1058
2018-02-26 16:39:44 +01:00
|
|
|
not use the <literal>public</literal> schema.
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
|
2003-11-05 01:05:32 +01:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
Of course, some SQL database systems might not implement schemas
|
|
|
|
at all, or provide namespace support by allowing (possibly
|
|
|
|
limited) cross-database access. If you need to work with those
|
|
|
|
systems, then maximum portability would be achieved by not using
|
|
|
|
schemas at all.
|
2002-09-05 23:32:23 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
2005-11-05 00:53:18 +01:00
|
|
|
</sect1>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<sect1 id="ddl-inherit">
|
|
|
|
<title>Inheritance</title>
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>inheritance</primary>
|
|
|
|
</indexterm>
|
2005-01-09 18:47:30 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>inheritance</secondary>
|
|
|
|
</indexterm>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2006-10-22 05:03:41 +02:00
|
|
|
<productname>PostgreSQL</productname> implements table inheritance,
|
2005-11-05 00:53:18 +01:00
|
|
|
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.)
|
|
|
|
</para>
|
2004-12-23 06:37:40 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
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>:
|
2004-12-23 06:37:40 +01:00
|
|
|
|
|
|
|
<programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
CREATE TABLE cities (
|
|
|
|
name text,
|
|
|
|
population float,
|
2020-04-22 22:23:19 +02:00
|
|
|
elevation int -- in feet
|
2005-11-05 00:53:18 +01:00
|
|
|
);
|
2004-12-23 06:37:40 +01:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
CREATE TABLE capitals (
|
|
|
|
state char(2)
|
|
|
|
) INHERITS (cities);
|
|
|
|
</programlisting>
|
2004-12-23 06:37:40 +01:00
|
|
|
|
2017-10-09 03:44:17 +02:00
|
|
|
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
|
2005-11-05 00:53:18 +01:00
|
|
|
their state.
|
|
|
|
</para>
|
2002-09-05 23:32:23 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
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,
|
2020-04-22 22:23:19 +02:00
|
|
|
including state capitals, that are located at an elevation over
|
2007-02-01 01:28:19 +01:00
|
|
|
500 feet:
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT name, elevation
|
2005-11-05 00:53:18 +01:00
|
|
|
FROM cities
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE elevation > 500;
|
2002-09-05 23:32:23 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
Given the sample data from the <productname>PostgreSQL</productname>
|
2017-11-23 15:39:47 +01:00
|
|
|
tutorial (see <xref linkend="tutorial-sql-intro"/>), this returns:
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2002-09-05 23:32:23 +02:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
name | elevation
|
|
|
|
-----------+-----------
|
|
|
|
Las Vegas | 2174
|
|
|
|
Mariposa | 1953
|
|
|
|
Madison | 845
|
2002-09-05 23:32:23 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
On the other hand, the following query finds all the cities that
|
2020-04-22 22:23:19 +02:00
|
|
|
are not state capitals and are situated at an elevation over 500 feet:
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT name, elevation
|
2005-11-05 00:53:18 +01:00
|
|
|
FROM ONLY cities
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE elevation > 500;
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2020-04-22 22:23:19 +02:00
|
|
|
name | elevation
|
|
|
|
-----------+-----------
|
|
|
|
Las Vegas | 2174
|
|
|
|
Mariposa | 1953
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
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 —
|
|
|
|
<command>SELECT</command>, <command>UPDATE</command> and
|
|
|
|
<command>DELETE</command> — support the
|
|
|
|
<literal>ONLY</literal> keyword.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
2012-09-17 20:59:31 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
You can also write the table name with a trailing <literal>*</literal>
|
2012-09-17 20:59:31 +02:00
|
|
|
to explicitly specify that descendant tables are included:
|
|
|
|
|
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT name, elevation
|
2012-09-17 20:59:31 +02:00
|
|
|
FROM cities*
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE elevation > 500;
|
2012-09-17 20:59:31 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2017-10-09 03:44:17 +02:00
|
|
|
Writing <literal>*</literal> is not necessary, since this behavior is always
|
2016-12-23 13:35:01 +01:00
|
|
|
the default. However, this syntax is still supported for
|
|
|
|
compatibility with older releases where the default could be changed.
|
2012-09-17 20:59:31 +02:00
|
|
|
</para>
|
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
In some cases you might wish to know which table a particular row
|
2005-11-05 00:53:18 +01:00
|
|
|
originated from. There is a system column called
|
|
|
|
<structfield>tableoid</structfield> in each table which can tell you the
|
|
|
|
originating table:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT c.tableoid, c.name, c.elevation
|
2005-11-05 00:53:18 +01:00
|
|
|
FROM cities c
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE c.elevation > 500;
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
which returns:
|
2004-08-07 22:44:50 +02:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
tableoid | name | elevation
|
|
|
|
----------+-----------+-----------
|
|
|
|
139793 | Las Vegas | 2174
|
|
|
|
139793 | Mariposa | 1953
|
|
|
|
139798 | Madison | 845
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
|
|
|
(If you try to reproduce this example, you will probably get
|
|
|
|
different numeric OIDs.) By doing a join with
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>pg_class</structname> you can see the actual table names:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT p.relname, c.name, c.elevation
|
2005-11-05 00:53:18 +01:00
|
|
|
FROM cities c, pg_class p
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE c.elevation > 500 AND c.tableoid = p.oid;
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
which returns:
|
|
|
|
|
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
relname | name | elevation
|
|
|
|
----------+-----------+-----------
|
|
|
|
cities | Las Vegas | 2174
|
|
|
|
cities | Mariposa | 1953
|
|
|
|
capitals | Madison | 845
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Another way to get the same effect is to use the <type>regclass</type>
|
2017-01-25 15:27:09 +01:00
|
|
|
alias type, which will print the table OID symbolically:
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
|
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
SELECT c.tableoid::regclass, c.name, c.elevation
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
FROM cities c
|
2020-04-22 22:23:19 +02:00
|
|
|
WHERE c.elevation > 500;
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
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:
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2020-04-22 22:23:19 +02:00
|
|
|
INSERT INTO cities (name, population, elevation, state)
|
2014-08-15 08:57:46 +02:00
|
|
|
VALUES ('Albany', NULL, NULL, 'NY');
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
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
|
2017-11-23 15:39:47 +01:00
|
|
|
using a rule (see <xref linkend="rules"/>). However that does not
|
2017-10-09 03:44:17 +02:00
|
|
|
help for the above case because the <structname>cities</structname> table
|
|
|
|
does not contain the column <structfield>state</structfield>, and so the
|
2005-11-05 00:53:18 +01:00
|
|
|
command will be rejected before the rule can be applied.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
2004-08-07 22:44:50 +02:00
|
|
|
|
|
|
|
<para>
|
2006-11-28 02:09:01 +01:00
|
|
|
All check constraints and not-null constraints on a parent table are
|
2016-10-26 17:46:25 +02:00
|
|
|
automatically inherited by its children, unless explicitly specified
|
2017-10-09 03:44:17 +02:00
|
|
|
otherwise with <literal>NO INHERIT</literal> clauses. Other types of constraints
|
2006-11-28 02:09:01 +01:00
|
|
|
(unique, primary key, and foreign key constraints) are not inherited.
|
2004-08-07 22:44:50 +02:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
|
|
|
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
|
2017-10-09 03:44:17 +02:00
|
|
|
table and the child's definition, then these columns are <quote>merged</quote>
|
2005-11-05 00:53:18 +01:00
|
|
|
so that there is only one such column in the child table. To be merged,
|
2016-10-26 17:46:25 +02:00
|
|
|
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.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2006-10-13 23:43:19 +02:00
|
|
|
Table inheritance is typically established when the child table is
|
2017-10-09 03:44:17 +02:00
|
|
|
created, using the <literal>INHERITS</literal> clause of the
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
<link linkend="sql-createtable"><command>CREATE TABLE</command></link>
|
2006-10-22 05:03:41 +02:00
|
|
|
statement.
|
2006-10-13 23:43:19 +02:00
|
|
|
Alternatively, a table which is already defined in a compatible way can
|
|
|
|
have a new parent relationship added, using the <literal>INHERIT</literal>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
variant of <link linkend="sql-altertable"><command>ALTER TABLE</command></link>.
|
2006-10-13 23:43:19 +02:00
|
|
|
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
|
2006-07-02 03:58:36 +02:00
|
|
|
parent. Similarly an inheritance link can be removed from a child using the
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>NO INHERIT</literal> variant of <command>ALTER TABLE</command>.
|
2006-10-13 23:43:19 +02:00
|
|
|
Dynamically adding and removing inheritance links like this can be useful
|
|
|
|
when the inheritance relationship is being used for table
|
2017-11-23 15:39:47 +01:00
|
|
|
partitioning (see <xref linkend="ddl-partitioning"/>).
|
2006-07-03 18:43:14 +02:00
|
|
|
</para>
|
2006-07-02 03:58:36 +02:00
|
|
|
|
|
|
|
<para>
|
2006-10-13 23:43:19 +02:00
|
|
|
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
|
2006-09-20 03:20:38 +02:00
|
|
|
TABLE</command>. This creates a new table with the same columns as
|
2006-10-13 23:43:19 +02:00
|
|
|
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.
|
2006-07-03 18:43:14 +02:00
|
|
|
</para>
|
2006-07-02 03:58:36 +02:00
|
|
|
|
|
|
|
<para>
|
2006-10-13 23:43:19 +02:00
|
|
|
A parent table cannot be dropped while any of its children remain. Neither
|
2008-05-10 01:32:05 +02:00
|
|
|
can columns or check constraints of child tables be dropped or altered
|
|
|
|
if they are inherited
|
2006-10-13 23:43:19 +02:00
|
|
|
from any parent tables. If you wish to remove a table and all of its
|
2006-07-02 03:58:36 +02:00
|
|
|
descendants, one easy way is to drop the parent table with the
|
2017-11-23 15:39:47 +01:00
|
|
|
<literal>CASCADE</literal> option (see <xref linkend="ddl-depend"/>).
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
|
|
|
<para>
|
Improve <xref> vs. <command> formatting in the documentation
SQL commands are generally marked up as <command>, except when a link
to a reference page is used using <xref>. But the latter doesn't
create monospace markup, so this looks strange especially when a
paragraph contains a mix of links and non-links.
We considered putting <command> in the <refentrytitle> on the target
side, but that creates some formatting side effects elsewhere.
Generally, it seems safer to solve this on the link source side.
We can't put the <xref> inside the <command>; the DTD doesn't allow
this. DocBook 5 would allow the <command> to have the linkend
attribute itself, but we are not there yet.
So to solve this for now, convert the <xref>s to <link> plus
<command>. This gives the correct look and also gives some more
flexibility what we can put into the link text (e.g., subcommands or
other clauses). In the future, these could then be converted to
DocBook 5 style.
I haven't converted absolutely all xrefs to SQL command reference
pages, only those where we care about the appearance of the link text
or where it was otherwise appropriate to make the appearance match a
bit better. Also in some cases, the links where repetitive, so in
those cases the links where just removed and replaced by a plain
<command>. In cases where we just want the link and don't
specifically care about the generated link text (typically phrased
"for further information see <xref ...>") the xref is kept.
Reported-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://www.postgresql.org/message-id/flat/87o8pco34z.fsf@wibble.ilmari.org
2020-10-03 16:16:51 +02:00
|
|
|
<command>ALTER TABLE</command> will
|
2006-10-13 23:43:19 +02:00
|
|
|
propagate any changes in column data definitions and check
|
|
|
|
constraints down the inheritance hierarchy. Again, dropping
|
2008-05-10 01:32:05 +02:00
|
|
|
columns that are depended on by other tables is only possible when using
|
2006-10-13 23:43:19 +02:00
|
|
|
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>.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2016-10-26 17:46:25 +02:00
|
|
|
Inherited queries perform access permission checks on the parent table
|
2017-10-09 03:44:17 +02:00
|
|
|
only. Thus, for example, granting <literal>UPDATE</literal> permission on
|
|
|
|
the <structname>cities</structname> table implies permission to update rows in
|
2016-10-26 17:46:25 +02:00
|
|
|
the <structname>capitals</structname> table as well, when they are
|
2017-10-09 03:44:17 +02:00
|
|
|
accessed through <structname>cities</structname>. This preserves the appearance
|
2016-10-26 17:46:25 +02:00
|
|
|
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
|
2017-11-23 15:39:47 +01:00
|
|
|
security policies (see <xref linkend="ddl-rowsecurity"/>) are applied to
|
2016-10-26 17:46:25 +02:00
|
|
|
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.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
2009-01-07 23:40:49 +01:00
|
|
|
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
Foreign tables (see <xref linkend="ddl-foreign-data"/>) can also
|
Allow foreign tables to participate in inheritance.
Foreign tables can now be inheritance children, or parents. Much of the
system was already ready for this, but we had to fix a few things of
course, mostly in the area of planner and executor handling of row locks.
As side effects of this, allow foreign tables to have NOT VALID CHECK
constraints (and hence to accept ALTER ... VALIDATE CONSTRAINT), and to
accept ALTER SET STORAGE and ALTER SET WITH/WITHOUT OIDS. Continuing to
disallow these things would've required bizarre and inconsistent special
cases in inheritance behavior. Since foreign tables don't enforce CHECK
constraints anyway, a NOT VALID one is a complete no-op, but that doesn't
mean we shouldn't allow it. And it's possible that some FDWs might have
use for SET STORAGE or SET WITH OIDS, though doubtless they will be no-ops
for most.
An additional change in support of this is that when a ModifyTable node
has multiple target tables, they will all now be explicitly identified
in EXPLAIN output, for example:
Update on pt1 (cost=0.00..321.05 rows=3541 width=46)
Update on pt1
Foreign Update on ft1
Foreign Update on ft2
Update on child3
-> Seq Scan on pt1 (cost=0.00..0.00 rows=1 width=46)
-> Foreign Scan on ft1 (cost=100.00..148.03 rows=1170 width=46)
-> Foreign Scan on ft2 (cost=100.00..148.03 rows=1170 width=46)
-> Seq Scan on child3 (cost=0.00..25.00 rows=1200 width=46)
This was done mainly to provide an unambiguous place to attach "Remote SQL"
fields, but it is useful for inherited updates even when no foreign tables
are involved.
Shigeru Hanada and Etsuro Fujita, reviewed by Ashutosh Bapat and Kyotaro
Horiguchi, some additional hacking by me
2015-03-22 18:53:11 +01:00
|
|
|
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.
|
|
|
|
</para>
|
|
|
|
|
2009-10-23 07:24:52 +02:00
|
|
|
<sect2 id="ddl-inherit-caveats">
|
|
|
|
<title>Caveats</title>
|
|
|
|
|
2009-01-08 13:47:58 +01:00
|
|
|
<para>
|
2009-10-23 07:24:52 +02:00
|
|
|
Note that not all SQL commands are able to work on
|
2009-01-08 13:47:58 +01:00
|
|
|
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
|
2012-09-17 20:59:31 +02:00
|
|
|
not <literal>INSERT</literal> or <literal>ALTER TABLE ...
|
2009-01-08 13:47:58 +01:00
|
|
|
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>)
|
2012-09-17 20:59:31 +02:00
|
|
|
typically only work on individual, physical tables and do not
|
2009-01-08 13:47:58 +01:00
|
|
|
support recursing over inheritance hierarchies. The respective
|
2012-09-17 20:59:31 +02:00
|
|
|
behavior of each individual command is documented in its reference
|
2017-11-23 15:39:47 +01:00
|
|
|
page (<xref linkend="sql-commands"/>).
|
2009-01-08 13:47:58 +01:00
|
|
|
</para>
|
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
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:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
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,
|
2005-11-05 00:53:18 +01:00
|
|
|
and so could contain multiple rows with the same name.
|
2017-10-09 03:44:17 +02:00
|
|
|
You could add a unique constraint to <structname>capitals</structname>, but this
|
|
|
|
would not prevent duplication compared to <structname>cities</structname>.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
Similarly, if we were to specify that
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>cities</structname>.<structfield>name</structfield> <literal>REFERENCES</literal> some
|
2005-11-05 00:53:18 +01:00
|
|
|
other table, this constraint would not automatically propagate to
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>capitals</structname>. In this case you could work around it by
|
|
|
|
manually adding the same <literal>REFERENCES</literal> constraint to
|
|
|
|
<structname>capitals</structname>.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
Specifying that another table's column <literal>REFERENCES
|
2017-10-09 03:44:17 +02:00
|
|
|
cities(name)</literal> would allow the other table to contain city names, but
|
2005-11-05 00:53:18 +01:00
|
|
|
not capital names. There is no good workaround for this case.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
|
2019-06-11 22:08:57 +02:00
|
|
|
Some functionality not implemented for inheritance hierarchies is
|
|
|
|
implemented for declarative partitioning.
|
|
|
|
Considerable care is needed in deciding whether partitioning with legacy
|
2009-04-27 18:27:36 +02:00
|
|
|
inheritance is useful for your application.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
</sect2>
|
|
|
|
</sect1>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect1 id="ddl-partitioning">
|
|
|
|
<title>Table Partitioning</title>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
|
|
|
<indexterm>
|
2017-03-31 23:33:34 +02:00
|
|
|
<primary>partitioning</primary>
|
2017-02-10 11:03:28 +01:00
|
|
|
</indexterm>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>table</primary>
|
|
|
|
<secondary>partitioning</secondary>
|
|
|
|
</indexterm>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>partitioned table</primary>
|
|
|
|
</indexterm>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
<productname>PostgreSQL</productname> supports basic table
|
|
|
|
partitioning. This section describes why and how to implement
|
|
|
|
partitioning as part of your database design.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect2 id="ddl-partitioning-overview">
|
|
|
|
<title>Overview</title>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Partitioning refers to splitting what is logically one large table into
|
|
|
|
smaller physical pieces. Partitioning can provide several benefits:
|
2017-02-10 11:03:28 +01:00
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
Query performance can be improved dramatically in certain situations,
|
|
|
|
particularly when most of the heavily accessed rows of the table are in a
|
2020-11-14 19:09:53 +01:00
|
|
|
single partition or a small number of partitions. Partitioning
|
|
|
|
effectively substitutes for the upper tree levels of indexes,
|
2017-03-31 23:33:34 +02:00
|
|
|
making it more likely that the heavily-used parts of the indexes
|
|
|
|
fit in memory.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
When queries or updates access a large percentage of a single
|
2020-11-14 19:09:53 +01:00
|
|
|
partition, performance can be improved by using a
|
|
|
|
sequential scan of that partition instead of using an
|
|
|
|
index, which would require random-access reads scattered across the
|
|
|
|
whole table.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
Bulk loads and deletes can be accomplished by adding or removing
|
2020-11-14 19:09:53 +01:00
|
|
|
partitions, if the usage pattern is accounted for in the
|
|
|
|
partitioning design. Dropping an individual partition
|
|
|
|
using <command>DROP TABLE</command>, or doing <command>ALTER TABLE
|
|
|
|
DETACH PARTITION</command>, is far faster than a bulk
|
2017-03-31 23:33:34 +02:00
|
|
|
operation. These commands also entirely avoid the
|
2017-10-09 03:44:17 +02:00
|
|
|
<command>VACUUM</command> overhead caused by a bulk <command>DELETE</command>.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
Seldom-used data can be migrated to cheaper and slower storage media.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2020-11-14 19:09:53 +01:00
|
|
|
These benefits will normally be worthwhile only when a table would
|
2017-03-31 23:33:34 +02:00
|
|
|
otherwise be very large. The exact point at which a table will
|
|
|
|
benefit from partitioning depends on the application, although a
|
|
|
|
rule of thumb is that the size of the table should exceed the physical
|
|
|
|
memory of the database server.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<productname>PostgreSQL</productname> offers built-in support for the
|
|
|
|
following forms of partitioning:
|
|
|
|
|
|
|
|
<variablelist>
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-partitioning-overview-range">
|
2017-03-31 23:33:34 +02:00
|
|
|
<term>Range Partitioning</term>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
The table is partitioned into <quote>ranges</quote> defined
|
|
|
|
by a key column or set of columns, with no overlap between
|
|
|
|
the ranges of values assigned to different partitions. For
|
|
|
|
example, one might partition by date ranges, or by ranges of
|
|
|
|
identifiers for particular business objects.
|
2020-11-14 19:09:53 +01:00
|
|
|
Each range's bounds are understood as being inclusive at the
|
|
|
|
lower end and exclusive at the upper end. For example, if one
|
|
|
|
partition's range is from <literal>1</literal>
|
|
|
|
to <literal>10</literal>, and the next one's range is
|
|
|
|
from <literal>10</literal> to <literal>20</literal>, then
|
|
|
|
value <literal>10</literal> belongs to the second partition not
|
|
|
|
the first.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-partitioning-overview-list">
|
2017-03-31 23:33:34 +02:00
|
|
|
<term>List Partitioning</term>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
The table is partitioned by explicitly listing which key value(s)
|
2017-03-31 23:33:34 +02:00
|
|
|
appear in each partition.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
Add hash partitioning.
Hash partitioning is useful when you want to partition a growing data
set evenly. This can be useful to keep table sizes reasonable, which
makes maintenance operations such as VACUUM faster, or to enable
partition-wise join.
At present, we still depend on constraint exclusion for partitioning
pruning, and the shape of the partition constraints for hash
partitioning is such that that doesn't work. Work is underway to fix
that, which should both improve performance and make partitioning
pruning work with hash partitioning.
Amul Sul, reviewed and tested by Dilip Kumar, Ashutosh Bapat, Yugo
Nagata, Rajkumar Raghuwanshi, Jesper Pedersen, and by me. A few
final tweaks also by me.
Discussion: http://postgr.es/m/CAAJ_b96fhpJAP=ALbETmeLk1Uni_GFZD938zgenhF49qgDTjaQ@mail.gmail.com
2017-11-10 00:07:25 +01:00
|
|
|
|
2023-01-09 21:08:24 +01:00
|
|
|
<varlistentry id="ddl-partitioning-overview-hash">
|
Add hash partitioning.
Hash partitioning is useful when you want to partition a growing data
set evenly. This can be useful to keep table sizes reasonable, which
makes maintenance operations such as VACUUM faster, or to enable
partition-wise join.
At present, we still depend on constraint exclusion for partitioning
pruning, and the shape of the partition constraints for hash
partitioning is such that that doesn't work. Work is underway to fix
that, which should both improve performance and make partitioning
pruning work with hash partitioning.
Amul Sul, reviewed and tested by Dilip Kumar, Ashutosh Bapat, Yugo
Nagata, Rajkumar Raghuwanshi, Jesper Pedersen, and by me. A few
final tweaks also by me.
Discussion: http://postgr.es/m/CAAJ_b96fhpJAP=ALbETmeLk1Uni_GFZD938zgenhF49qgDTjaQ@mail.gmail.com
2017-11-10 00:07:25 +01:00
|
|
|
<term>Hash Partitioning</term>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
The table is partitioned by specifying a modulus and a remainder for
|
|
|
|
each partition. Each partition will hold the rows for which the hash
|
|
|
|
value of the partition key divided by the specified modulus will
|
|
|
|
produce the specified remainder.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2017-03-31 23:33:34 +02:00
|
|
|
</variablelist>
|
|
|
|
|
|
|
|
If your application needs to use other forms of partitioning not listed
|
|
|
|
above, alternative methods such as inheritance and
|
|
|
|
<literal>UNION ALL</literal> views can be used instead. Such methods
|
|
|
|
offer flexibility but do not have some of the performance benefits
|
|
|
|
of built-in declarative partitioning.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="ddl-partitioning-declarative">
|
|
|
|
<title>Declarative Partitioning</title>
|
|
|
|
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
<productname>PostgreSQL</productname> allows you to declare
|
|
|
|
that a table is divided into partitions. The table that is divided
|
2017-03-31 23:33:34 +02:00
|
|
|
is referred to as a <firstterm>partitioned table</firstterm>. The
|
2020-11-14 19:09:53 +01:00
|
|
|
declaration includes the <firstterm>partitioning method</firstterm>
|
|
|
|
as described above, plus a list of columns or expressions to be used
|
|
|
|
as the <firstterm>partition key</firstterm>.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
The partitioned table itself is a <quote>virtual</quote> table having
|
|
|
|
no storage of its own. Instead, the storage belongs
|
|
|
|
to <firstterm>partitions</firstterm>, which are otherwise-ordinary
|
|
|
|
tables associated with the partitioned table.
|
|
|
|
Each partition stores a subset of the data as defined by its
|
|
|
|
<firstterm>partition bounds</firstterm>.
|
|
|
|
All rows inserted into a partitioned table will be routed to the
|
|
|
|
appropriate one of the partitions based on the values of the partition
|
|
|
|
key column(s).
|
|
|
|
Updating the partition key of a row will cause it to be moved into a
|
|
|
|
different partition if it no longer satisfies the partition bounds
|
|
|
|
of its original partition.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
Partitions may themselves be defined as partitioned tables, resulting
|
|
|
|
in <firstterm>sub-partitioning</firstterm>. Although all partitions
|
|
|
|
must have the same columns as their partitioned parent, partitions may
|
|
|
|
have their
|
2017-03-31 23:33:34 +02:00
|
|
|
own indexes, constraints and default values, distinct from those of other
|
2018-03-12 15:38:20 +01:00
|
|
|
partitions. See <xref linkend="sql-createtable"/> for more details on
|
|
|
|
creating partitioned tables and partitions.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
It is not possible to turn a regular table into a partitioned table or
|
2020-11-14 19:09:53 +01:00
|
|
|
vice versa. However, it is possible to add an existing regular or
|
|
|
|
partitioned table as a partition of a partitioned table, or remove a
|
2017-03-31 23:33:34 +02:00
|
|
|
partition from a partitioned table turning it into a standalone table;
|
2020-11-14 19:09:53 +01:00
|
|
|
this can simplify and speed up many maintenance processes.
|
|
|
|
See <xref linkend="sql-altertable"/> to learn more about the
|
2017-10-09 03:44:17 +02:00
|
|
|
<command>ATTACH PARTITION</command> and <command>DETACH PARTITION</command>
|
2017-03-31 23:33:34 +02:00
|
|
|
sub-commands.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2022-02-05 18:55:44 +01:00
|
|
|
Partitions can also be <link linkend="ddl-foreign-data">foreign
|
|
|
|
tables</link>, although considerable care is needed because it is then
|
|
|
|
the user's responsibility that the contents of the foreign table
|
|
|
|
satisfy the partitioning rule. There are some other restrictions as
|
|
|
|
well. See <xref linkend="sql-createforeigntable"/> for more
|
|
|
|
information.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect3 id="ddl-partitioning-declarative-example">
|
|
|
|
<title>Example</title>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Suppose we are constructing a database for a large ice cream company.
|
|
|
|
The company measures peak temperatures every day as well as ice cream
|
|
|
|
sales in each region. Conceptually, we want a table like:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE measurement (
|
|
|
|
city_id int not null,
|
|
|
|
logdate date not null,
|
|
|
|
peaktemp int,
|
|
|
|
unitsales int
|
|
|
|
);
|
|
|
|
</programlisting>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
We know that most queries will access just the last week's, month's or
|
|
|
|
quarter's data, since the main use of this table will be to prepare
|
|
|
|
online reports for management. To reduce the amount of old data that
|
2020-11-14 19:09:53 +01:00
|
|
|
needs to be stored, we decide to keep only the most recent 3 years
|
2017-03-31 23:33:34 +02:00
|
|
|
worth of data. At the beginning of each month we will remove the oldest
|
|
|
|
month's data. In this situation we can use partitioning to help us meet
|
|
|
|
all of our different requirements for the measurements table.
|
2004-08-07 22:44:50 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
To use declarative partitioning in this case, use the following steps:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<orderedlist spacing="compact">
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
Create the <structname>measurement</structname> table as a partitioned
|
2017-03-31 23:33:34 +02:00
|
|
|
table by specifying the <literal>PARTITION BY</literal> clause, which
|
|
|
|
includes the partitioning method (<literal>RANGE</literal> in this
|
|
|
|
case) and the list of column(s) to use as the partition key.
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE measurement (
|
|
|
|
city_id int not null,
|
|
|
|
logdate date not null,
|
|
|
|
peaktemp int,
|
|
|
|
unitsales int
|
|
|
|
) PARTITION BY RANGE (logdate);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
Create partitions. Each partition's definition must specify bounds
|
2017-03-31 23:33:34 +02:00
|
|
|
that correspond to the partitioning method and partition key of the
|
|
|
|
parent. Note that specifying bounds such that the new partition's
|
2020-11-14 19:09:53 +01:00
|
|
|
values would overlap with those in one or more existing partitions will
|
|
|
|
cause an error.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Partitions thus created are in every way normal
|
2017-10-09 03:44:17 +02:00
|
|
|
<productname>PostgreSQL</productname>
|
2017-03-31 23:33:34 +02:00
|
|
|
tables (or, possibly, foreign tables). It is possible to specify a
|
|
|
|
tablespace and storage parameters for each partition separately.
|
|
|
|
</para>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
For our example, each partition should hold one month's worth of
|
|
|
|
data, to match the requirement of deleting one month's data at a
|
|
|
|
time. So the commands might look like:
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
|
2018-01-27 13:13:52 +01:00
|
|
|
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01');
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2006m03 PARTITION OF measurement
|
2018-01-27 13:13:52 +01:00
|
|
|
FOR VALUES FROM ('2006-03-01') TO ('2006-04-01');
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
...
|
|
|
|
CREATE TABLE measurement_y2007m11 PARTITION OF measurement
|
2018-01-27 13:13:52 +01:00
|
|
|
FOR VALUES FROM ('2007-11-01') TO ('2007-12-01');
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2007m12 PARTITION OF measurement
|
|
|
|
FOR VALUES FROM ('2007-12-01') TO ('2008-01-01')
|
|
|
|
TABLESPACE fasttablespace;
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2008m01 PARTITION OF measurement
|
|
|
|
FOR VALUES FROM ('2008-01-01') TO ('2008-02-01')
|
2017-11-08 23:20:53 +01:00
|
|
|
WITH (parallel_workers = 4)
|
|
|
|
TABLESPACE fasttablespace;
|
2017-03-31 23:33:34 +02:00
|
|
|
</programlisting>
|
2020-11-14 19:09:53 +01:00
|
|
|
|
|
|
|
(Recall that adjacent partitions can share a bound value, since
|
|
|
|
range upper bounds are treated as exclusive bounds.)
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
If you wish to implement sub-partitioning, again specify the
|
2017-03-31 23:33:34 +02:00
|
|
|
<literal>PARTITION BY</literal> clause in the commands used to create
|
|
|
|
individual partitions, for example:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
|
|
|
|
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01')
|
|
|
|
PARTITION BY RANGE (peaktemp);
|
|
|
|
</programlisting>
|
|
|
|
|
2017-10-09 03:44:17 +02:00
|
|
|
After creating partitions of <structname>measurement_y2006m02</structname>,
|
|
|
|
any data inserted into <structname>measurement</structname> that is mapped to
|
2020-11-14 19:09:53 +01:00
|
|
|
<structname>measurement_y2006m02</structname> (or data that is
|
|
|
|
directly inserted into <structname>measurement_y2006m02</structname>,
|
|
|
|
which is allowed provided its partition constraint is satisfied)
|
|
|
|
will be further redirected to one of its
|
2017-10-09 03:44:17 +02:00
|
|
|
partitions based on the <structfield>peaktemp</structfield> column. The partition
|
2017-03-31 23:33:34 +02:00
|
|
|
key specified may overlap with the parent's partition key, although
|
|
|
|
care should be taken when specifying the bounds of a sub-partition
|
|
|
|
such that the set of data it accepts constitutes a subset of what
|
2020-11-14 19:09:53 +01:00
|
|
|
the partition's own bounds allow; the system does not try to check
|
2017-03-31 23:33:34 +02:00
|
|
|
whether that's really the case.
|
|
|
|
</para>
|
2020-11-14 19:09:53 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Inserting data into the parent table that does not map
|
|
|
|
to one of the existing partitions will cause an error; an appropriate
|
|
|
|
partition must be added manually.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
It is not necessary to manually create table constraints describing
|
|
|
|
the partition boundary conditions for partitions. Such constraints
|
|
|
|
will be created automatically.
|
|
|
|
</para>
|
2017-03-31 23:33:34 +02:00
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Create an index on the key column(s), as well as any other indexes you
|
2018-02-10 14:01:37 +01:00
|
|
|
might want, on the partitioned table. (The key index is not strictly
|
2018-02-19 20:59:37 +01:00
|
|
|
necessary, but in most scenarios it is helpful.)
|
2020-11-14 19:09:53 +01:00
|
|
|
This automatically creates a matching index on each partition, and
|
|
|
|
any partitions you create or attach later will also have such an
|
|
|
|
index.
|
|
|
|
An index or unique constraint declared on a partitioned table
|
|
|
|
is <quote>virtual</quote> in the same way that the partitioned table
|
|
|
|
is: the actual data is in child indexes on the individual partition
|
|
|
|
tables.
|
2017-03-31 23:33:34 +02:00
|
|
|
|
|
|
|
<programlisting>
|
2018-02-10 14:01:37 +01:00
|
|
|
CREATE INDEX ON measurement (logdate);
|
2017-03-31 23:33:34 +02:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-04-23 22:57:43 +02:00
|
|
|
Ensure that the <xref linkend="guc-enable-partition-pruning"/>
|
2017-10-09 03:44:17 +02:00
|
|
|
configuration parameter is not disabled in <filename>postgresql.conf</filename>.
|
2017-03-31 23:33:34 +02:00
|
|
|
If it is, queries will not be optimized as desired.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-03-31 23:33:34 +02:00
|
|
|
</orderedlist>
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
In the above example we would be creating a new partition each month, so
|
|
|
|
it might be wise to write a script that generates the required DDL
|
|
|
|
automatically.
|
|
|
|
</para>
|
|
|
|
</sect3>
|
|
|
|
|
|
|
|
<sect3 id="ddl-partitioning-declarative-maintenance">
|
|
|
|
<title>Partition Maintenance</title>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
Normally the set of partitions established when initially defining the
|
2020-11-02 07:14:41 +01:00
|
|
|
table is not intended to remain static. It is common to want to
|
2020-11-14 19:09:53 +01:00
|
|
|
remove partitions holding old data and periodically add new partitions for
|
2017-03-31 23:33:34 +02:00
|
|
|
new data. One of the most important advantages of partitioning is
|
|
|
|
precisely that it allows this otherwise painful task to be executed
|
|
|
|
nearly instantaneously by manipulating the partition structure, rather
|
|
|
|
than physically moving large amounts of data around.
|
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2017-04-04 05:10:16 +02:00
|
|
|
The simplest option for removing old data is to drop the partition that
|
|
|
|
is no longer necessary:
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
DROP TABLE measurement_y2006m02;
|
|
|
|
</programlisting>
|
|
|
|
This can very quickly delete millions of records because it doesn't have
|
|
|
|
to individually delete every record. Note however that the above command
|
|
|
|
requires taking an <literal>ACCESS EXCLUSIVE</literal> lock on the parent
|
|
|
|
table.
|
|
|
|
</para>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Another option that is often preferable is to remove the partition from
|
|
|
|
the partitioned table but retain access to it as a table in its own
|
2021-05-06 22:42:30 +02:00
|
|
|
right. This has two forms:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE measurement DETACH PARTITION measurement_y2006m02;
|
2021-05-06 22:42:30 +02:00
|
|
|
ALTER TABLE measurement DETACH PARTITION measurement_y2006m02 CONCURRENTLY;
|
2017-03-31 23:33:34 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2021-05-06 22:42:30 +02:00
|
|
|
These allow further operations to be performed on the data before
|
2017-03-31 23:33:34 +02:00
|
|
|
it is dropped. For example, this is often a useful time to back up
|
2017-10-09 03:44:17 +02:00
|
|
|
the data using <command>COPY</command>, <application>pg_dump</application>, or
|
2017-03-31 23:33:34 +02:00
|
|
|
similar tools. It might also be a useful time to aggregate data
|
|
|
|
into smaller formats, perform other data manipulations, or run
|
2021-05-06 22:42:30 +02:00
|
|
|
reports. The first form of the command requires an
|
|
|
|
<literal>ACCESS EXCLUSIVE</literal> lock on the parent table.
|
|
|
|
Adding the <literal>CONCURRENTLY</literal> qualifier as in the second
|
|
|
|
form allows the detach operation to require only
|
|
|
|
<literal>SHARE UPDATE EXCLUSIVE</literal> lock on the parent table, but see
|
|
|
|
<link linkend="sql-altertable-detach-partition"><literal>ALTER TABLE ... DETACH PARTITION</literal></link>
|
|
|
|
for details on the restrictions.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Similarly we can add a new partition to handle new data. We can create an
|
|
|
|
empty partition in the partitioned table just as the original partitions
|
|
|
|
were created above:
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2008m02 PARTITION OF measurement
|
|
|
|
FOR VALUES FROM ('2008-02-01') TO ('2008-03-01')
|
|
|
|
TABLESPACE fasttablespace;
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2024-03-30 14:08:13 +01:00
|
|
|
As an alternative to creating a new partition, it is sometimes more
|
|
|
|
convenient to create a new table separate from the partition structure
|
|
|
|
and attach it as a partition later. This allows new data to be loaded,
|
|
|
|
checked, and transformed prior to it appearing in the partitioned table.
|
2023-03-16 21:50:56 +01:00
|
|
|
Moreover, the <literal>ATTACH PARTITION</literal> operation requires
|
2024-03-30 14:08:13 +01:00
|
|
|
only a <literal>SHARE UPDATE EXCLUSIVE</literal> lock on the
|
|
|
|
partitioned table rather than the <literal>ACCESS EXCLUSIVE</literal>
|
|
|
|
lock required by <command>CREATE TABLE ... PARTITION OF</command>,
|
|
|
|
so it is more friendly to concurrent operations on the partitioned table;
|
|
|
|
see <link linkend="sql-altertable-attach-partition"><literal>ALTER TABLE ... ATTACH PARTITION</literal></link>
|
|
|
|
for additional details. The
|
|
|
|
<link linkend="sql-createtable-parms-like"><literal>CREATE TABLE ... LIKE</literal></link>
|
|
|
|
option can be helpful to avoid tediously repeating the parent table's
|
|
|
|
definition; for example:
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2008m02
|
|
|
|
(LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
|
|
|
|
TABLESPACE fasttablespace;
|
|
|
|
|
|
|
|
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
|
|
|
|
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );
|
|
|
|
|
|
|
|
\copy measurement_y2008m02 from 'measurement_y2008m02'
|
|
|
|
-- possibly some other data preparation work
|
|
|
|
|
|
|
|
ALTER TABLE measurement ATTACH PARTITION measurement_y2008m02
|
|
|
|
FOR VALUES FROM ('2008-02-01') TO ('2008-03-01' );
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2024-03-30 14:08:13 +01:00
|
|
|
Note that when running the <command>ATTACH PARTITION</command> command,
|
2019-11-05 02:17:33 +01:00
|
|
|
the table will be scanned to validate the partition constraint while
|
2021-07-28 05:02:37 +02:00
|
|
|
holding an <literal>ACCESS EXCLUSIVE</literal> lock on that partition.
|
2024-03-30 14:08:13 +01:00
|
|
|
As shown above, it is recommended to avoid this scan by creating a
|
|
|
|
<literal>CHECK</literal> constraint matching the expected partition
|
|
|
|
constraint on the table prior to attaching it. Once the
|
|
|
|
<command>ATTACH PARTITION</command> is complete, it is recommended to drop
|
|
|
|
the now-redundant <literal>CHECK</literal> constraint.
|
|
|
|
If the table being attached is itself a partitioned table, then each of its
|
2021-07-28 05:02:37 +02:00
|
|
|
sub-partitions will be recursively locked and scanned until either a
|
|
|
|
suitable <literal>CHECK</literal> constraint is encountered or the leaf
|
|
|
|
partitions are reached.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Similarly, if the partitioned table has a <literal>DEFAULT</literal>
|
|
|
|
partition, it is recommended to create a <literal>CHECK</literal>
|
|
|
|
constraint which excludes the to-be-attached partition's constraint. If
|
2024-03-30 14:08:13 +01:00
|
|
|
this is not done, the <literal>DEFAULT</literal> partition will be
|
2021-07-28 05:02:37 +02:00
|
|
|
scanned to verify that it contains no records which should be located in
|
|
|
|
the partition being attached. This operation will be performed whilst
|
|
|
|
holding an <literal>ACCESS EXCLUSIVE</literal> lock on the <literal>
|
|
|
|
DEFAULT</literal> partition. If the <literal>DEFAULT</literal> partition
|
2022-01-25 01:40:04 +01:00
|
|
|
is itself a partitioned table, then each of its partitions will be
|
2021-07-28 05:02:37 +02:00
|
|
|
recursively checked in the same way as the table being attached, as
|
|
|
|
mentioned above.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2019-06-04 22:42:40 +02:00
|
|
|
|
|
|
|
<para>
|
2024-03-30 14:08:13 +01:00
|
|
|
As mentioned earlier, it is possible to create indexes on partitioned
|
|
|
|
tables so that they are applied automatically to the entire hierarchy.
|
|
|
|
This can be very convenient as not only will all existing partitions be
|
|
|
|
indexed, but any future partitions will be as well. However, one
|
|
|
|
limitation when creating new indexes on partitioned tables is that it
|
|
|
|
is not possible to use the <literal>CONCURRENTLY</literal>
|
|
|
|
qualifier, which could lead to long lock times. To avoid this, you can
|
|
|
|
use <command>CREATE INDEX ON ONLY</command> the partitioned table, which
|
|
|
|
creates the new index marked as invalid, preventing automatic application
|
|
|
|
to existing partitions. Instead, indexes can then be created individually
|
|
|
|
on each partition using <literal>CONCURRENTLY</literal> and
|
|
|
|
<firstterm>attached</firstterm> to the partitioned index on the parent
|
|
|
|
using <command>ALTER INDEX ... ATTACH PARTITION</command>. Once indexes for
|
|
|
|
all the partitions are attached to the parent index, the parent index will
|
|
|
|
be marked valid automatically. Example:
|
2019-06-04 22:42:40 +02:00
|
|
|
<programlisting>
|
|
|
|
CREATE INDEX measurement_usls_idx ON ONLY measurement (unitsales);
|
|
|
|
|
2023-11-27 19:18:03 +01:00
|
|
|
CREATE INDEX CONCURRENTLY measurement_usls_200602_idx
|
2019-06-04 22:42:40 +02:00
|
|
|
ON measurement_y2006m02 (unitsales);
|
|
|
|
ALTER INDEX measurement_usls_idx
|
|
|
|
ATTACH PARTITION measurement_usls_200602_idx;
|
|
|
|
...
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
This technique can be used with <literal>UNIQUE</literal> and
|
|
|
|
<literal>PRIMARY KEY</literal> constraints too; the indexes are created
|
|
|
|
implicitly when the constraint is created. Example:
|
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE ONLY measurement ADD UNIQUE (city_id, logdate);
|
|
|
|
|
|
|
|
ALTER TABLE measurement_y2006m02 ADD UNIQUE (city_id, logdate);
|
|
|
|
ALTER INDEX measurement_city_id_logdate_key
|
|
|
|
ATTACH PARTITION measurement_y2006m02_city_id_logdate_key;
|
|
|
|
...
|
2024-04-06 23:57:22 +02:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
There is also an option for merging multiple table partitions into
|
|
|
|
a single partition using the
|
|
|
|
<link linkend="sql-altertable-merge-partitions"><command>ALTER TABLE ... MERGE PARTITIONS</command></link>.
|
|
|
|
This feature simplifies the management of partitioned tables by allowing
|
2024-04-15 14:41:37 +02:00
|
|
|
users to combine partitions that are no longer needed as
|
2024-04-06 23:57:22 +02:00
|
|
|
separate entities. It's important to note that this operation is not
|
|
|
|
supported for hash-partitioned tables and acquires an
|
|
|
|
<literal>ACCESS EXCLUSIVE</literal> lock, which could impact high-load
|
|
|
|
systems due to the lock's restrictive nature. For example, we can
|
|
|
|
merge three monthly partitions into one quarter partition:
|
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE measurement
|
|
|
|
MERGE PARTITIONS (measurement_y2006m01,
|
|
|
|
measurement_y2006m02,
|
|
|
|
measurement_y2006m03) INTO measurement_y2006q1;
|
2019-06-04 22:42:40 +02:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
2024-04-06 23:58:09 +02:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Similarly to merging multiple table partitions, there is an option for
|
|
|
|
splitting a single partition into multiple using the
|
|
|
|
<link linkend="sql-altertable-split-partition"><command>ALTER TABLE ... SPLIT PARTITION</command></link>.
|
|
|
|
This feature could come in handy when one partition grows too big
|
|
|
|
and needs to be split into multiple. It's important to note that
|
|
|
|
this operation is not supported for hash-partitioned tables and acquires
|
|
|
|
an <literal>ACCESS EXCLUSIVE</literal> lock, which could impact high-load
|
|
|
|
systems due to the lock's restrictive nature. For example, we can split
|
2024-04-09 11:32:48 +02:00
|
|
|
the quarter partition back to monthly partitions:
|
2024-04-06 23:58:09 +02:00
|
|
|
<programlisting>
|
|
|
|
ALTER TABLE measurement SPLIT PARTITION measurement_y2006q1 INTO
|
|
|
|
(PARTITION measurement_y2006m01 FOR VALUES FROM ('2006-01-01') TO ('2006-02-01'),
|
|
|
|
PARTITION measurement_y2006m02 FOR VALUES FROM ('2006-02-01') TO ('2006-03-01'),
|
|
|
|
PARTITION measurement_y2006m03 FOR VALUES FROM ('2006-03-01') TO ('2006-04-01'));
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
</sect3>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect3 id="ddl-partitioning-declarative-limitations">
|
|
|
|
<title>Limitations</title>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
The following limitations apply to partitioned tables:
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2022-09-05 08:43:03 +02:00
|
|
|
To create a unique or primary key constraint on a partitioned table,
|
|
|
|
the partition keys must not include any expressions or function calls
|
|
|
|
and the constraint's columns must include all of the partition key
|
|
|
|
columns. This limitation exists because the individual indexes making
|
|
|
|
up the constraint can only directly enforce uniqueness within their own
|
|
|
|
partitions; therefore, the partition structure itself must guarantee
|
|
|
|
that there are not duplicates in different partitions.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2019-07-10 14:58:41 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2023-07-12 09:24:43 +02:00
|
|
|
Similarly an exclusion constraint must include all the
|
|
|
|
partition key columns. Furthermore the constraint must compare those
|
|
|
|
columns for equality (not e.g. <literal>&&</literal>).
|
|
|
|
Again, this limitation stems from not being able to enforce
|
|
|
|
cross-partition restrictions. The constraint may include additional
|
|
|
|
columns that aren't part of the partition key, and it may compare
|
|
|
|
those with any operators you like.
|
2019-07-10 14:58:41 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2021-01-28 20:56:07 +01:00
|
|
|
<literal>BEFORE ROW</literal> triggers on <literal>INSERT</literal>
|
|
|
|
cannot change which partition is the final destination for a new row.
|
2018-05-02 18:06:25 +02:00
|
|
|
</para>
|
2017-03-31 23:33:34 +02:00
|
|
|
</listitem>
|
Clarify use of temporary tables within partition trees
Since their introduction, partition trees have been a bit lossy
regarding temporary relations. Inheritance trees respect the following
patterns:
1) a child relation can be temporary if the parent is permanent.
2) a child relation can be temporary if the parent is temporary.
3) a child relation cannot be permanent if the parent is temporary.
4) The use of temporary relations also imply that when both parent and
child need to be from the same sessions.
Partitions share many similar patterns with inheritance, however the
handling of the partition bounds make the situation a bit tricky for
case 1) as the partition code bases a lot of its lookup code upon
PartitionDesc which does not really look after relpersistence. This
causes for example a temporary partition created by session A to be
visible by another session B, preventing this session B to create an
extra partition which overlaps with the temporary one created by A with
a non-intuitive error message. There could be use-cases where mixing
permanent partitioned tables with temporary partitions make sense, but
that would be a new feature. Partitions respect 2), 3) and 4) already.
It is a bit depressing to see those error checks happening in
MergeAttributes() whose purpose is different, but that's left as future
refactoring work.
Back-patch down to 10, which is where partitioning has been introduced,
except that default partitions do not apply there. Documentation also
includes limitations related to the use of temporary tables with
partition trees.
Reported-by: David Rowley
Author: Amit Langote, Michael Paquier
Reviewed-by: Ashutosh Bapat, Amit Langote, Michael Paquier
Discussion: https://postgr.es/m/CAKJS1f94Ojk0og9GMkRHGt8wHTW=ijq5KzJKuoBoqWLwSVwGmw@mail.gmail.com
2018-06-20 03:42:25 +02:00
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Mixing temporary and permanent relations in the same partition tree is
|
|
|
|
not allowed. Hence, if the partitioned table is permanent, so must be
|
|
|
|
its partitions and likewise if the partitioned table is temporary. When
|
|
|
|
using temporary relations, all members of the partition tree have to be
|
|
|
|
from the same session.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-03-31 23:33:34 +02:00
|
|
|
</itemizedlist>
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
2020-11-14 19:09:53 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Individual partitions are linked to their partitioned table using
|
|
|
|
inheritance behind-the-scenes. However, it is not possible to use
|
|
|
|
all of the generic features of inheritance with declaratively
|
|
|
|
partitioned tables or their partitions, as discussed below. Notably,
|
|
|
|
a partition cannot have any parents other than the partitioned table
|
|
|
|
it is a partition of, nor can a table inherit from both a partitioned
|
|
|
|
table and a regular table. That means partitioned tables and their
|
|
|
|
partitions never share an inheritance hierarchy with regular tables.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Since a partition hierarchy consisting of the partitioned table and its
|
2021-08-03 17:11:51 +02:00
|
|
|
partitions is still an inheritance hierarchy,
|
|
|
|
<structfield>tableoid</structfield> and all the normal rules of
|
2020-11-14 19:09:53 +01:00
|
|
|
inheritance apply as described in <xref linkend="ddl-inherit"/>, with
|
|
|
|
a few exceptions:
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Partitions cannot have columns that are not present in the parent. It
|
|
|
|
is not possible to specify columns when creating partitions with
|
|
|
|
<command>CREATE TABLE</command>, nor is it possible to add columns to
|
|
|
|
partitions after-the-fact using <command>ALTER TABLE</command>.
|
|
|
|
Tables may be added as a partition with <command>ALTER TABLE
|
|
|
|
... ATTACH PARTITION</command> only if their columns exactly match
|
|
|
|
the parent.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Both <literal>CHECK</literal> and <literal>NOT NULL</literal>
|
|
|
|
constraints of a partitioned table are always inherited by all its
|
|
|
|
partitions. <literal>CHECK</literal> constraints that are marked
|
|
|
|
<literal>NO INHERIT</literal> are not allowed to be created on
|
|
|
|
partitioned tables.
|
|
|
|
You cannot drop a <literal>NOT NULL</literal> constraint on a
|
|
|
|
partition's column if the same constraint is present in the parent
|
|
|
|
table.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Using <literal>ONLY</literal> to add or drop a constraint on only
|
|
|
|
the partitioned table is supported as long as there are no
|
|
|
|
partitions. Once partitions exist, using <literal>ONLY</literal>
|
2024-01-11 14:27:10 +01:00
|
|
|
will result in an error for any constraints other than
|
|
|
|
<literal>UNIQUE</literal> and <literal>PRIMARY KEY</literal>.
|
|
|
|
Instead, constraints on the partitions
|
2020-11-14 19:09:53 +01:00
|
|
|
themselves can be added and (if they are not present in the parent
|
|
|
|
table) dropped.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
As a partitioned table does not have any data itself, attempts to use
|
|
|
|
<command>TRUNCATE</command> <literal>ONLY</literal> on a partitioned
|
|
|
|
table will always return an error.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
2017-03-31 23:33:34 +02:00
|
|
|
</sect3>
|
|
|
|
</sect2>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2020-11-14 19:09:53 +01:00
|
|
|
<sect2 id="ddl-partitioning-using-inheritance">
|
|
|
|
<title>Partitioning Using Inheritance</title>
|
|
|
|
|
2017-02-10 11:03:28 +01:00
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
While the built-in declarative partitioning is suitable for most
|
|
|
|
common use cases, there are some circumstances where a more flexible
|
|
|
|
approach may be useful. Partitioning can be implemented using table
|
2018-06-01 20:54:43 +02:00
|
|
|
inheritance, which allows for several features not supported
|
2017-03-31 23:33:34 +02:00
|
|
|
by declarative partitioning, such as:
|
|
|
|
|
|
|
|
<itemizedlist>
|
2017-02-10 11:03:28 +01:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-06-01 20:54:43 +02:00
|
|
|
For declarative partitioning, partitions must have exactly the same set
|
|
|
|
of columns as the partitioned table, whereas with table inheritance,
|
|
|
|
child tables may have extra columns not present in the parent.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
Table inheritance allows for multiple inheritance.
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
Add hash partitioning.
Hash partitioning is useful when you want to partition a growing data
set evenly. This can be useful to keep table sizes reasonable, which
makes maintenance operations such as VACUUM faster, or to enable
partition-wise join.
At present, we still depend on constraint exclusion for partitioning
pruning, and the shape of the partition constraints for hash
partitioning is such that that doesn't work. Work is underway to fix
that, which should both improve performance and make partitioning
pruning work with hash partitioning.
Amul Sul, reviewed and tested by Dilip Kumar, Ashutosh Bapat, Yugo
Nagata, Rajkumar Raghuwanshi, Jesper Pedersen, and by me. A few
final tweaks also by me.
Discussion: http://postgr.es/m/CAAJ_b96fhpJAP=ALbETmeLk1Uni_GFZD938zgenhF49qgDTjaQ@mail.gmail.com
2017-11-10 00:07:25 +01:00
|
|
|
Declarative partitioning only supports range, list and hash
|
|
|
|
partitioning, whereas table inheritance allows data to be divided in a
|
|
|
|
manner of the user's choosing. (Note, however, that if constraint
|
2018-07-05 23:08:56 +02:00
|
|
|
exclusion is unable to prune child tables effectively, query performance
|
|
|
|
might be poor.)
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-03-31 23:33:34 +02:00
|
|
|
</itemizedlist>
|
2017-02-10 11:03:28 +01:00
|
|
|
</para>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect3 id="ddl-partitioning-inheritance-example">
|
|
|
|
<title>Example</title>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
This example builds a partitioning structure equivalent to the
|
|
|
|
declarative partitioning example above. Use
|
2017-03-31 23:33:34 +02:00
|
|
|
the following steps:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<orderedlist spacing="compact">
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2020-06-15 19:18:41 +02:00
|
|
|
Create the <quote>root</quote> table, from which all of the
|
2018-07-05 23:08:56 +02:00
|
|
|
<quote>child</quote> tables will inherit. This table will contain no data. Do not
|
2017-03-31 23:33:34 +02:00
|
|
|
define any check constraints on this table, unless you intend them
|
2018-07-05 23:08:56 +02:00
|
|
|
to be applied equally to all child tables. There is no point in
|
2017-03-31 23:33:34 +02:00
|
|
|
defining any indexes or unique constraints on it, either. For our
|
2020-06-15 19:18:41 +02:00
|
|
|
example, the root table is the <structname>measurement</structname>
|
2020-11-14 19:09:53 +01:00
|
|
|
table as originally defined:
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE measurement (
|
|
|
|
city_id int not null,
|
|
|
|
logdate date not null,
|
|
|
|
peaktemp int,
|
|
|
|
unitsales int
|
|
|
|
);
|
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Create several <quote>child</quote> tables that each inherit from
|
2020-06-15 19:18:41 +02:00
|
|
|
the root table. Normally, these tables will not add any columns
|
|
|
|
to the set inherited from the root. Just as with declarative
|
2018-07-05 23:08:56 +02:00
|
|
|
partitioning, these tables are in every way normal
|
2017-10-09 03:44:17 +02:00
|
|
|
<productname>PostgreSQL</productname> tables (or foreign tables).
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2006m02 () INHERITS (measurement);
|
|
|
|
CREATE TABLE measurement_y2006m03 () INHERITS (measurement);
|
2005-11-05 00:53:18 +01:00
|
|
|
...
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2007m11 () INHERITS (measurement);
|
|
|
|
CREATE TABLE measurement_y2007m12 () INHERITS (measurement);
|
|
|
|
CREATE TABLE measurement_y2008m01 () INHERITS (measurement);
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
Add non-overlapping table constraints to the child tables to
|
|
|
|
define the allowed key values in each.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Typical examples would be:
|
|
|
|
<programlisting>
|
|
|
|
CHECK ( x = 1 )
|
|
|
|
CHECK ( county IN ( 'Oxfordshire', 'Buckinghamshire', 'Warwickshire' ))
|
|
|
|
CHECK ( outletID >= 100 AND outletID < 200 )
|
|
|
|
</programlisting>
|
|
|
|
Ensure that the constraints guarantee that there is no overlap
|
2018-07-05 23:08:56 +02:00
|
|
|
between the key values permitted in different child tables. A common
|
2017-03-31 23:33:34 +02:00
|
|
|
mistake is to set up range constraints like:
|
|
|
|
<programlisting>
|
|
|
|
CHECK ( outletID BETWEEN 100 AND 200 )
|
|
|
|
CHECK ( outletID BETWEEN 200 AND 300 )
|
|
|
|
</programlisting>
|
2018-07-05 23:08:56 +02:00
|
|
|
This is wrong since it is not clear which child table the key
|
|
|
|
value 200 belongs in.
|
2020-11-14 19:09:53 +01:00
|
|
|
Instead, ranges should be defined in this style:
|
2003-08-31 19:32:24 +02:00
|
|
|
|
2010-07-29 21:34:41 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2006m02 (
|
|
|
|
CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
|
2005-11-05 00:53:18 +01:00
|
|
|
) INHERITS (measurement);
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2006m03 (
|
|
|
|
CHECK ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
|
2005-11-05 00:53:18 +01:00
|
|
|
) INHERITS (measurement);
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
...
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2007m11 (
|
|
|
|
CHECK ( logdate >= DATE '2007-11-01' AND logdate < DATE '2007-12-01' )
|
2005-11-05 00:53:18 +01:00
|
|
|
) INHERITS (measurement);
|
2017-03-31 23:33:34 +02:00
|
|
|
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2007m12 (
|
|
|
|
CHECK ( logdate >= DATE '2007-12-01' AND logdate < DATE '2008-01-01' )
|
2005-11-05 00:53:18 +01:00
|
|
|
) INHERITS (measurement);
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE TABLE measurement_y2008m01 (
|
|
|
|
CHECK ( logdate >= DATE '2008-01-01' AND logdate < DATE '2008-02-01' )
|
|
|
|
) INHERITS (measurement);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
For each child table, create an index on the key column(s),
|
2017-03-31 23:33:34 +02:00
|
|
|
as well as any other indexes you might want.
|
2010-07-29 21:34:41 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
|
|
|
|
CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
|
|
|
|
CREATE INDEX measurement_y2007m11_logdate ON measurement_y2007m11 (logdate);
|
|
|
|
CREATE INDEX measurement_y2007m12_logdate ON measurement_y2007m12 (logdate);
|
|
|
|
CREATE INDEX measurement_y2008m01_logdate ON measurement_y2008m01 (logdate);
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
We want our application to be able to say <literal>INSERT INTO
|
2017-10-09 03:44:17 +02:00
|
|
|
measurement ...</literal> and have the data be redirected into the
|
2018-07-05 23:08:56 +02:00
|
|
|
appropriate child table. We can arrange that by attaching
|
2020-06-15 19:18:41 +02:00
|
|
|
a suitable trigger function to the root table.
|
2018-07-05 23:08:56 +02:00
|
|
|
If data will be added only to the latest child, we can
|
2017-03-31 23:33:34 +02:00
|
|
|
use a very simple trigger function:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE OR REPLACE FUNCTION measurement_insert_trigger()
|
|
|
|
RETURNS TRIGGER AS $$
|
|
|
|
BEGIN
|
|
|
|
INSERT INTO measurement_y2008m01 VALUES (NEW.*);
|
|
|
|
RETURN NULL;
|
|
|
|
END;
|
|
|
|
$$
|
|
|
|
LANGUAGE plpgsql;
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
After creating the function, we create a trigger which
|
|
|
|
calls the trigger function:
|
2007-12-02 20:20:32 +01:00
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE TRIGGER insert_measurement_trigger
|
|
|
|
BEFORE INSERT ON measurement
|
2018-08-15 23:08:34 +02:00
|
|
|
FOR EACH ROW EXECUTE FUNCTION measurement_insert_trigger();
|
2007-12-02 20:20:32 +01:00
|
|
|
</programlisting>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
We must redefine the trigger function each month so that it always
|
2020-11-14 19:09:53 +01:00
|
|
|
inserts into the current child table. The trigger definition does
|
2017-03-31 23:33:34 +02:00
|
|
|
not need to be updated, however.
|
|
|
|
</para>
|
2007-12-02 20:20:32 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
We might want to insert data and have the server automatically
|
2018-07-05 23:08:56 +02:00
|
|
|
locate the child table into which the row should be added. We
|
2017-03-31 23:33:34 +02:00
|
|
|
could do this with a more complex trigger function, for example:
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE OR REPLACE FUNCTION measurement_insert_trigger()
|
|
|
|
RETURNS TRIGGER AS $$
|
|
|
|
BEGIN
|
2009-06-17 23:58:49 +02:00
|
|
|
IF ( NEW.logdate >= DATE '2006-02-01' AND
|
2009-04-27 18:27:36 +02:00
|
|
|
NEW.logdate < DATE '2006-03-01' ) THEN
|
2007-12-02 20:20:32 +01:00
|
|
|
INSERT INTO measurement_y2006m02 VALUES (NEW.*);
|
2009-06-17 23:58:49 +02:00
|
|
|
ELSIF ( NEW.logdate >= DATE '2006-03-01' AND
|
2009-04-27 18:27:36 +02:00
|
|
|
NEW.logdate < DATE '2006-04-01' ) THEN
|
2007-12-02 20:20:32 +01:00
|
|
|
INSERT INTO measurement_y2006m03 VALUES (NEW.*);
|
|
|
|
...
|
2009-06-17 23:58:49 +02:00
|
|
|
ELSIF ( NEW.logdate >= DATE '2008-01-01' AND
|
2009-04-27 18:27:36 +02:00
|
|
|
NEW.logdate < DATE '2008-02-01' ) THEN
|
2007-12-02 20:20:32 +01:00
|
|
|
INSERT INTO measurement_y2008m01 VALUES (NEW.*);
|
|
|
|
ELSE
|
|
|
|
RAISE EXCEPTION 'Date out of range. Fix the measurement_insert_trigger() function!';
|
|
|
|
END IF;
|
|
|
|
RETURN NULL;
|
|
|
|
END;
|
|
|
|
$$
|
|
|
|
LANGUAGE plpgsql;
|
|
|
|
</programlisting>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
The trigger definition is the same as before.
|
|
|
|
Note that each <literal>IF</literal> test must exactly match the
|
2018-07-05 23:08:56 +02:00
|
|
|
<literal>CHECK</literal> constraint for its child table.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2007-12-03 05:59:55 +01:00
|
|
|
|
|
|
|
<para>
|
2017-03-31 23:33:34 +02:00
|
|
|
While this function is more complex than the single-month case,
|
|
|
|
it doesn't need to be updated as often, since branches can be
|
|
|
|
added in advance of being needed.
|
2007-12-03 05:59:55 +01:00
|
|
|
</para>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<note>
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
In practice, it might be best to check the newest child first,
|
|
|
|
if most inserts go into that child. For simplicity, we have
|
2017-03-31 23:33:34 +02:00
|
|
|
shown the trigger's tests in the same order as in other parts
|
|
|
|
of this example.
|
|
|
|
</para>
|
|
|
|
</note>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
A different approach to redirecting inserts into the appropriate
|
2018-07-05 23:08:56 +02:00
|
|
|
child table is to set up rules, instead of a trigger, on the
|
2020-06-15 19:18:41 +02:00
|
|
|
root table. For example:
|
2017-02-10 11:03:28 +01:00
|
|
|
|
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE RULE measurement_insert_y2006m02 AS
|
|
|
|
ON INSERT TO measurement WHERE
|
|
|
|
( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
|
|
|
|
DO INSTEAD
|
|
|
|
INSERT INTO measurement_y2006m02 VALUES (NEW.*);
|
2017-02-10 11:03:28 +01:00
|
|
|
...
|
2017-03-31 23:33:34 +02:00
|
|
|
CREATE RULE measurement_insert_y2008m01 AS
|
|
|
|
ON INSERT TO measurement WHERE
|
|
|
|
( logdate >= DATE '2008-01-01' AND logdate < DATE '2008-02-01' )
|
|
|
|
DO INSTEAD
|
|
|
|
INSERT INTO measurement_y2008m01 VALUES (NEW.*);
|
2017-02-10 11:03:28 +01:00
|
|
|
</programlisting>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
A rule has significantly more overhead than a trigger, but the
|
|
|
|
overhead is paid once per query rather than once per row, so this
|
|
|
|
method might be advantageous for bulk-insert situations. In most
|
|
|
|
cases, however, the trigger method will offer better performance.
|
|
|
|
</para>
|
2006-10-13 23:43:19 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Be aware that <command>COPY</command> ignores rules. If you want to
|
|
|
|
use <command>COPY</command> to insert data, you'll need to copy into the
|
2020-06-15 19:18:41 +02:00
|
|
|
correct child table rather than directly into the root. <command>COPY</command>
|
2017-03-31 23:33:34 +02:00
|
|
|
does fire triggers, so you can use it normally if you use the trigger
|
|
|
|
approach.
|
|
|
|
</para>
|
2006-09-20 03:20:38 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
|
|
|
Another disadvantage of the rule approach is that there is no simple
|
|
|
|
way to force an error if the set of rules doesn't cover the insertion
|
2020-06-15 19:18:41 +02:00
|
|
|
date; the data will silently go into the root table instead.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2006-09-20 03:20:38 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-11-23 15:39:47 +01:00
|
|
|
Ensure that the <xref linkend="guc-constraint-exclusion"/>
|
2017-03-31 23:33:34 +02:00
|
|
|
configuration parameter is not disabled in
|
2018-07-05 23:08:56 +02:00
|
|
|
<filename>postgresql.conf</filename>; otherwise
|
|
|
|
child tables may be accessed unnecessarily.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</orderedlist>
|
|
|
|
</para>
|
2006-07-02 03:58:36 +02:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
As we can see, a complex table hierarchy could require a
|
2017-03-31 23:33:34 +02:00
|
|
|
substantial amount of DDL. In the above example we would be creating
|
2018-07-05 23:08:56 +02:00
|
|
|
a new child table each month, so it might be wise to write a script that
|
2017-03-31 23:33:34 +02:00
|
|
|
generates the required DDL automatically.
|
|
|
|
</para>
|
|
|
|
</sect3>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<sect3 id="ddl-partitioning-inheritance-maintenance">
|
2018-07-05 23:08:56 +02:00
|
|
|
<title>Maintenance for Inheritance Partitioning</title>
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
To remove old data quickly, simply drop the child table that is no longer
|
2017-04-04 05:10:16 +02:00
|
|
|
necessary:
|
2006-07-02 03:58:36 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
DROP TABLE measurement_y2006m02;
|
2006-07-02 03:58:36 +02:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
To remove the child table from the inheritance hierarchy table but retain access to
|
2017-03-31 23:33:34 +02:00
|
|
|
it as a table in its own right:
|
2017-02-10 11:03:28 +01:00
|
|
|
|
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
ALTER TABLE measurement_y2006m02 NO INHERIT measurement;
|
2017-02-10 11:03:28 +01:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
To add a new child table to handle new data, create an empty child table
|
|
|
|
just as the original children were created above:
|
2006-07-02 03:58:36 +02:00
|
|
|
|
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2008m02 (
|
|
|
|
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' )
|
2006-09-20 03:20:38 +02:00
|
|
|
) INHERITS (measurement);
|
2006-07-02 03:58:36 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2018-07-05 23:08:56 +02:00
|
|
|
Alternatively, one may want to create and populate the new child table
|
|
|
|
before adding it to the table hierarchy. This could allow data to be
|
|
|
|
loaded, checked, and transformed before being made visible to queries on
|
|
|
|
the parent table.
|
2006-07-02 03:58:36 +02:00
|
|
|
|
2006-09-20 03:20:38 +02:00
|
|
|
<programlisting>
|
2007-12-02 20:20:32 +01:00
|
|
|
CREATE TABLE measurement_y2008m02
|
2006-10-13 23:43:19 +02:00
|
|
|
(LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
|
2007-12-02 20:20:32 +01:00
|
|
|
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
|
|
|
|
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );
|
|
|
|
\copy measurement_y2008m02 from 'measurement_y2008m02'
|
2006-10-13 23:43:19 +02:00
|
|
|
-- possibly some other data preparation work
|
2007-12-02 20:20:32 +01:00
|
|
|
ALTER TABLE measurement_y2008m02 INHERIT measurement;
|
2017-02-10 11:03:28 +01:00
|
|
|
</programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</sect3>
|
|
|
|
|
|
|
|
<sect3 id="ddl-partitioning-inheritance-caveats">
|
|
|
|
<title>Caveats</title>
|
|
|
|
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
The following caveats apply to partitioning implemented using
|
2017-03-31 23:33:34 +02:00
|
|
|
inheritance:
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
There is no automatic way to verify that all of the
|
|
|
|
<literal>CHECK</literal> constraints are mutually
|
|
|
|
exclusive. It is safer to create code that generates
|
2018-07-05 23:08:56 +02:00
|
|
|
child tables and creates and/or modifies associated objects than
|
2017-03-31 23:33:34 +02:00
|
|
|
to write each by hand.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2019-05-29 17:19:06 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Indexes and foreign key constraints apply to single tables and not
|
|
|
|
to their inheritance children, hence they have some
|
|
|
|
<link linkend="ddl-inherit-caveats">caveats</link> to be aware of.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
The schemes shown here assume that the values of a row's key column(s)
|
|
|
|
never change, or at least do not change enough to require it to move to another partition.
|
|
|
|
An <command>UPDATE</command> that attempts
|
2017-10-09 03:44:17 +02:00
|
|
|
to do that will fail because of the <literal>CHECK</literal> constraints.
|
2017-03-31 23:33:34 +02:00
|
|
|
If you need to handle such cases, you can put suitable update triggers
|
2018-07-05 23:08:56 +02:00
|
|
|
on the child tables, but it makes management of the structure
|
2017-03-31 23:33:34 +02:00
|
|
|
much more complicated.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
If you are using manual <command>VACUUM</command> or
|
|
|
|
<command>ANALYZE</command> commands, don't forget that
|
2018-07-05 23:08:56 +02:00
|
|
|
you need to run them on each child table individually. A command like:
|
2017-02-10 11:03:28 +01:00
|
|
|
<programlisting>
|
2017-03-31 23:33:34 +02:00
|
|
|
ANALYZE measurement;
|
2006-09-20 03:20:38 +02:00
|
|
|
</programlisting>
|
2020-06-15 19:18:41 +02:00
|
|
|
will only process the root table.
|
2017-03-31 23:33:34 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2017-02-10 11:03:28 +01:00
|
|
|
|
2017-03-31 23:33:34 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
<command>INSERT</command> statements with <literal>ON CONFLICT</literal>
|
|
|
|
clauses are unlikely to work as expected, as the <literal>ON CONFLICT</literal>
|
2017-03-31 23:33:34 +02:00
|
|
|
action is only taken in case of unique violations on the specified
|
|
|
|
target relation, not its child relations.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Triggers or rules will be needed to route rows to the desired
|
2018-07-05 23:08:56 +02:00
|
|
|
child table, unless the application is explicitly aware of the
|
2017-03-31 23:33:34 +02:00
|
|
|
partitioning scheme. Triggers may be complicated to write, and will
|
2017-04-04 05:10:16 +02:00
|
|
|
be much slower than the tuple routing performed internally by
|
2017-03-31 23:33:34 +02:00
|
|
|
declarative partitioning.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
</sect3>
|
|
|
|
</sect2>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2018-05-12 17:08:17 +02:00
|
|
|
<sect2 id="ddl-partition-pruning">
|
|
|
|
<title>Partition Pruning</title>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<indexterm>
|
2018-05-12 17:08:17 +02:00
|
|
|
<primary>partition pruning</primary>
|
2003-08-31 19:32:24 +02:00
|
|
|
</indexterm>
|
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<para>
|
2018-05-12 17:08:17 +02:00
|
|
|
<firstterm>Partition pruning</firstterm> is a query optimization technique
|
2018-06-01 20:54:43 +02:00
|
|
|
that improves performance for declaratively partitioned tables.
|
|
|
|
As an example:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
|
|
|
<programlisting>
|
2018-05-12 17:08:17 +02:00
|
|
|
SET enable_partition_pruning = on; -- the default
|
2007-12-02 20:20:32 +01:00
|
|
|
SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
|
2002-09-13 00:05:36 +02:00
|
|
|
</programlisting>
|
2005-11-05 00:53:18 +01:00
|
|
|
|
2018-05-12 17:08:17 +02:00
|
|
|
Without partition pruning, the above query would scan each of the
|
|
|
|
partitions of the <structname>measurement</structname> table. With
|
|
|
|
partition pruning enabled, the planner will examine the definition
|
|
|
|
of each partition and prove that the partition need not
|
2009-06-17 23:58:49 +02:00
|
|
|
be scanned because it could not contain any rows meeting the query's
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>WHERE</literal> clause. When the planner can prove this, it
|
2018-05-12 17:08:17 +02:00
|
|
|
excludes (<firstterm>prunes</firstterm>) the partition from the query
|
|
|
|
plan.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<para>
|
2018-06-01 20:54:43 +02:00
|
|
|
By using the EXPLAIN command and the <xref
|
|
|
|
linkend="guc-enable-partition-pruning"/> configuration parameter, it's
|
|
|
|
possible to show the difference between a plan for which partitions have
|
|
|
|
been pruned and one for which they have not. A typical unoptimized
|
|
|
|
plan for this type of table setup is:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
2018-05-12 17:08:17 +02:00
|
|
|
SET enable_partition_pruning = off;
|
2007-12-02 20:20:32 +01:00
|
|
|
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
|
2018-05-12 17:08:17 +02:00
|
|
|
QUERY PLAN
|
2020-05-15 00:13:08 +02:00
|
|
|
-------------------------------------------------------------------&zwsp;----------------
|
2018-05-12 17:08:17 +02:00
|
|
|
Aggregate (cost=188.76..188.77 rows=1 width=8)
|
|
|
|
-> Append (cost=0.00..181.05 rows=3085 width=0)
|
|
|
|
-> Seq Scan on measurement_y2006m02 (cost=0.00..33.12 rows=617 width=0)
|
2007-12-02 20:20:32 +01:00
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
2018-05-12 17:08:17 +02:00
|
|
|
-> Seq Scan on measurement_y2006m03 (cost=0.00..33.12 rows=617 width=0)
|
2007-12-02 20:20:32 +01:00
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
2005-11-05 00:53:18 +01:00
|
|
|
...
|
2018-05-12 17:08:17 +02:00
|
|
|
-> Seq Scan on measurement_y2007m11 (cost=0.00..33.12 rows=617 width=0)
|
2007-12-02 20:20:32 +01:00
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
2018-05-12 17:08:17 +02:00
|
|
|
-> Seq Scan on measurement_y2007m12 (cost=0.00..33.12 rows=617 width=0)
|
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
|
|
|
-> Seq Scan on measurement_y2008m01 (cost=0.00..33.12 rows=617 width=0)
|
2007-12-02 20:20:32 +01:00
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
Some or all of the partitions might use index scans instead of
|
|
|
|
full-table sequential scans, but the point here is that there
|
|
|
|
is no need to scan the older partitions at all to answer this query.
|
2018-05-12 17:08:17 +02:00
|
|
|
When we enable partition pruning, we get a significantly
|
2009-01-07 23:40:49 +01:00
|
|
|
cheaper plan that will deliver the same answer:
|
2005-11-05 00:53:18 +01:00
|
|
|
<programlisting>
|
2018-05-12 17:08:17 +02:00
|
|
|
SET enable_partition_pruning = on;
|
2007-12-02 20:20:32 +01:00
|
|
|
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
|
2018-05-12 17:08:17 +02:00
|
|
|
QUERY PLAN
|
2020-05-15 00:13:08 +02:00
|
|
|
-------------------------------------------------------------------&zwsp;----------------
|
2018-05-12 17:08:17 +02:00
|
|
|
Aggregate (cost=37.75..37.76 rows=1 width=8)
|
2019-09-25 06:44:30 +02:00
|
|
|
-> Seq Scan on measurement_y2008m01 (cost=0.00..33.12 rows=617 width=0)
|
|
|
|
Filter: (logdate >= '2008-01-01'::date)
|
2005-11-05 00:53:18 +01:00
|
|
|
</programlisting>
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2018-05-12 17:08:17 +02:00
|
|
|
Note that partition pruning is driven only by the constraints defined
|
|
|
|
implicitly by the partition keys, not by the presence of indexes.
|
|
|
|
Therefore it isn't necessary to define indexes on the key columns.
|
|
|
|
Whether an index needs to be created for a given partition depends on
|
|
|
|
whether you expect that queries that scan the partition will
|
|
|
|
generally scan a large part of the partition or just a small part.
|
|
|
|
An index will be helpful in the latter case but not the former.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Partition pruning can be performed not only during the planning of a
|
|
|
|
given query, but also during its execution. This is useful as it can
|
|
|
|
allow more partitions to be pruned when clauses contain expressions
|
2018-11-12 14:47:58 +01:00
|
|
|
whose values are not known at query planning time, for example,
|
2018-05-12 17:08:17 +02:00
|
|
|
parameters defined in a <command>PREPARE</command> statement, using a
|
2018-11-12 14:47:58 +01:00
|
|
|
value obtained from a subquery, or using a parameterized value on the
|
2018-05-12 17:08:17 +02:00
|
|
|
inner side of a nested loop join. Partition pruning during execution
|
|
|
|
can be performed at any of the following times:
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
During initialization of the query plan. Partition pruning can be
|
|
|
|
performed here for parameter values which are known during the
|
|
|
|
initialization phase of execution. Partitions which are pruned
|
|
|
|
during this stage will not show up in the query's
|
|
|
|
<command>EXPLAIN</command> or <command>EXPLAIN ANALYZE</command>.
|
|
|
|
It is possible to determine the number of partitions which were
|
|
|
|
removed during this phase by observing the
|
|
|
|
<quote>Subplans Removed</quote> property in the
|
|
|
|
<command>EXPLAIN</command> output.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
During actual execution of the query plan. Partition pruning may
|
|
|
|
also be performed here to remove partitions using values which are
|
|
|
|
only known during actual query execution. This includes values
|
|
|
|
from subqueries and values from execution-time parameters such as
|
|
|
|
those from parameterized nested loop joins. Since the value of
|
|
|
|
these parameters may change many times during the execution of the
|
|
|
|
query, partition pruning is performed whenever one of the
|
|
|
|
execution parameters being used by partition pruning changes.
|
|
|
|
Determining if partitions were pruned during this phase requires
|
2018-12-17 15:44:36 +01:00
|
|
|
careful inspection of the <literal>loops</literal> property in
|
|
|
|
the <command>EXPLAIN ANALYZE</command> output. Subplans
|
|
|
|
corresponding to different partitions may have different values
|
|
|
|
for it depending on how many times each of them was pruned during
|
|
|
|
execution. Some may be shown as <literal>(never executed)</literal>
|
|
|
|
if they were pruned every time.
|
2018-05-12 17:08:17 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Partition pruning can be disabled using the
|
|
|
|
<xref linkend="guc-enable-partition-pruning"/> setting.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="ddl-partitioning-constraint-exclusion">
|
|
|
|
<title>Partitioning and Constraint Exclusion</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>constraint exclusion</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<firstterm>Constraint exclusion</firstterm> is a query optimization
|
|
|
|
technique similar to partition pruning. While it is primarily used
|
2018-07-05 23:08:56 +02:00
|
|
|
for partitioning implemented using the legacy inheritance method, it can be
|
2018-05-12 17:08:17 +02:00
|
|
|
used for other purposes, including with declarative partitioning.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Constraint exclusion works in a very similar way to partition
|
|
|
|
pruning, except that it uses each table's <literal>CHECK</literal>
|
|
|
|
constraints — which gives it its name — whereas partition
|
2018-07-05 22:51:08 +02:00
|
|
|
pruning uses the table's partition bounds, which exist only in the
|
2018-06-01 20:54:43 +02:00
|
|
|
case of declarative partitioning. Another difference is that
|
|
|
|
constraint exclusion is only applied at plan time; there is no attempt
|
|
|
|
to remove partitions at execution time.
|
2018-05-12 17:08:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The fact that constraint exclusion uses <literal>CHECK</literal>
|
|
|
|
constraints, which makes it slow compared to partition pruning, can
|
|
|
|
sometimes be used as an advantage: because constraints can be defined
|
2018-07-05 23:08:56 +02:00
|
|
|
even on declaratively-partitioned tables, in addition to their internal
|
|
|
|
partition bounds, constraint exclusion may be able
|
|
|
|
to elide additional partitions from the query plan.
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
2007-12-02 20:20:32 +01:00
|
|
|
|
2009-01-07 23:40:49 +01:00
|
|
|
<para>
|
|
|
|
The default (and recommended) setting of
|
2018-05-12 17:08:17 +02:00
|
|
|
<xref linkend="guc-constraint-exclusion"/> is neither
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>on</literal> nor <literal>off</literal>, but an intermediate setting
|
|
|
|
called <literal>partition</literal>, which causes the technique to be
|
2018-05-12 17:08:17 +02:00
|
|
|
applied only to queries that are likely to be working on inheritance partitioned
|
2017-10-09 03:44:17 +02:00
|
|
|
tables. The <literal>on</literal> setting causes the planner to examine
|
|
|
|
<literal>CHECK</literal> constraints in all queries, even simple ones that
|
2009-01-07 23:40:49 +01:00
|
|
|
are unlikely to benefit.
|
|
|
|
</para>
|
|
|
|
|
2002-09-13 00:05:36 +02:00
|
|
|
<para>
|
2018-05-12 17:08:17 +02:00
|
|
|
The following caveats apply to constraint exclusion:
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<itemizedlist>
|
2018-05-12 17:08:17 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2019-02-12 04:01:56 +01:00
|
|
|
Constraint exclusion is only applied during query planning, unlike
|
|
|
|
partition pruning, which can also be applied during query execution.
|
2018-05-12 17:08:17 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Constraint exclusion only works when the query's <literal>WHERE</literal>
|
2012-08-23 05:55:34 +02:00
|
|
|
clause contains constants (or externally supplied parameters).
|
|
|
|
For example, a comparison against a non-immutable function such as
|
|
|
|
<function>CURRENT_TIMESTAMP</function> cannot be optimized, since the
|
2018-07-05 23:08:56 +02:00
|
|
|
planner cannot know which child table the function's value might fall
|
2012-08-23 05:55:34 +02:00
|
|
|
into at run time.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2009-06-17 23:58:49 +02:00
|
|
|
Keep the partitioning constraints simple, else the planner may not be
|
2018-07-05 23:08:56 +02:00
|
|
|
able to prove that child tables might not need to be visited. Use simple
|
2007-06-21 01:11:38 +02:00
|
|
|
equality conditions for list partitioning, or simple
|
|
|
|
range tests for range partitioning, as illustrated in the preceding
|
|
|
|
examples. A good rule of thumb is that partitioning constraints should
|
|
|
|
contain only comparisons of the partitioning column(s) to constants
|
2018-05-12 17:08:17 +02:00
|
|
|
using B-tree-indexable operators, because only B-tree-indexable
|
|
|
|
column(s) are allowed in the partition key.
|
2007-06-21 01:11:38 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2018-07-05 23:08:56 +02:00
|
|
|
All constraints on all children of the parent table are examined
|
|
|
|
during constraint exclusion, so large numbers of children are likely
|
2018-05-12 17:08:17 +02:00
|
|
|
to increase query planning time considerably. So the legacy
|
|
|
|
inheritance based partitioning will work well with up to perhaps a
|
2018-07-05 23:08:56 +02:00
|
|
|
hundred child tables; don't try to use many thousands of children.
|
2005-11-05 00:53:18 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2002-09-13 00:05:36 +02:00
|
|
|
|
2005-11-05 00:53:18 +01:00
|
|
|
</itemizedlist>
|
2002-09-13 00:05:36 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
2019-11-20 18:27:00 +01:00
|
|
|
|
2019-06-11 22:08:57 +02:00
|
|
|
<sect2 id="ddl-partitioning-declarative-best-practices">
|
2020-11-14 19:09:53 +01:00
|
|
|
<title>Best Practices for Declarative Partitioning</title>
|
2019-06-11 22:08:57 +02:00
|
|
|
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
The choice of how to partition a table should be made carefully, as the
|
2019-06-11 22:08:57 +02:00
|
|
|
performance of query planning and execution can be negatively affected by
|
|
|
|
poor design.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
One of the most critical design decisions will be the column or columns
|
|
|
|
by which you partition your data. Often the best choice will be to
|
|
|
|
partition by the column or set of columns which most commonly appear in
|
|
|
|
<literal>WHERE</literal> clauses of queries being executed on the
|
2020-11-14 19:09:53 +01:00
|
|
|
partitioned table. <literal>WHERE</literal> clauses that are compatible
|
|
|
|
with the partition bound constraints can be used to prune unneeded
|
2019-06-11 22:08:57 +02:00
|
|
|
partitions. However, you may be forced into making other decisions by
|
|
|
|
requirements for the <literal>PRIMARY KEY</literal> or a
|
|
|
|
<literal>UNIQUE</literal> constraint. Removal of unwanted data is also a
|
|
|
|
factor to consider when planning your partitioning strategy. An entire
|
|
|
|
partition can be detached fairly quickly, so it may be beneficial to
|
|
|
|
design the partition strategy in such a way that all data to be removed
|
|
|
|
at once is located in a single partition.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Choosing the target number of partitions that the table should be divided
|
|
|
|
into is also a critical decision to make. Not having enough partitions
|
|
|
|
may mean that indexes remain too large and that data locality remains poor
|
|
|
|
which could result in low cache hit ratios. However, dividing the table
|
|
|
|
into too many partitions can also cause issues. Too many partitions can
|
|
|
|
mean longer query planning times and higher memory consumption during both
|
2020-11-14 19:09:53 +01:00
|
|
|
query planning and execution, as further described below.
|
|
|
|
When choosing how to partition your table,
|
2019-06-11 22:08:57 +02:00
|
|
|
it's also important to consider what changes may occur in the future. For
|
|
|
|
example, if you choose to have one partition per customer and you
|
|
|
|
currently have a small number of large customers, consider the
|
|
|
|
implications if in several years you instead find yourself with a large
|
|
|
|
number of small customers. In this case, it may be better to choose to
|
|
|
|
partition by <literal>HASH</literal> and choose a reasonable number of
|
|
|
|
partitions rather than trying to partition by <literal>LIST</literal> and
|
|
|
|
hoping that the number of customers does not increase beyond what it is
|
|
|
|
practical to partition the data by.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Sub-partitioning can be useful to further divide partitions that are
|
2020-11-14 19:09:53 +01:00
|
|
|
expected to become larger than other partitions.
|
|
|
|
Another option is to use range partitioning with multiple columns in
|
|
|
|
the partition key.
|
|
|
|
Either of these can easily lead to excessive numbers of partitions,
|
|
|
|
so restraint is advisable.
|
2019-06-11 22:08:57 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2020-11-14 19:09:53 +01:00
|
|
|
It is important to consider the overhead of partitioning during
|
2019-06-11 22:08:57 +02:00
|
|
|
query planning and execution. The query planner is generally able to
|
2019-06-13 00:35:11 +02:00
|
|
|
handle partition hierarchies with up to a few thousand partitions fairly
|
|
|
|
well, provided that typical queries allow the query planner to prune all
|
|
|
|
but a small number of partitions. Planning times become longer and memory
|
2019-06-11 22:08:57 +02:00
|
|
|
consumption becomes higher when more partitions remain after the planner
|
Rework planning and execution of UPDATE and DELETE.
This patch makes two closely related sets of changes:
1. For UPDATE, the subplan of the ModifyTable node now only delivers
the new values of the changed columns (i.e., the expressions computed
in the query's SET clause) plus row identity information such as CTID.
ModifyTable must re-fetch the original tuple to merge in the old
values of any unchanged columns. The core advantage of this is that
the changed columns are uniform across all tables of an inherited or
partitioned target relation, whereas the other columns might not be.
A secondary advantage, when the UPDATE involves joins, is that less
data needs to pass through the plan tree. The disadvantage of course
is an extra fetch of each tuple to be updated. However, that seems to
be very nearly free in context; even worst-case tests don't show it to
add more than a couple percent to the total query cost. At some point
it might be interesting to combine the re-fetch with the tuple access
that ModifyTable must do anyway to mark the old tuple dead; but that
would require a good deal of refactoring and it seems it wouldn't buy
all that much, so this patch doesn't attempt it.
2. For inherited UPDATE/DELETE, instead of generating a separate
subplan for each target relation, we now generate a single subplan
that is just exactly like a SELECT's plan, then stick ModifyTable
on top of that. To let ModifyTable know which target relation a
given incoming row refers to, a tableoid junk column is added to
the row identity information. This gets rid of the horrid hack
that was inheritance_planner(), eliminating O(N^2) planning cost
and memory consumption in cases where there were many unprunable
target relations.
Point 2 of course requires point 1, so that there is a uniform
definition of the non-junk columns to be returned by the subplan.
We can't insist on uniform definition of the row identity junk
columns however, if we want to keep the ability to have both
plain and foreign tables in a partitioning hierarchy. Since
it wouldn't scale very far to have every child table have its
own row identity column, this patch includes provisions to merge
similar row identity columns into one column of the subplan result.
In particular, we can merge the whole-row Vars typically used as
row identity by FDWs into one column by pretending they are type
RECORD. (It's still okay for the actual composite Datums to be
labeled with the table's rowtype OID, though.)
There is more that can be done to file down residual inefficiencies
in this patch, but it seems to be committable now.
FDW authors should note several API changes:
* The argument list for AddForeignUpdateTargets() has changed, and so
has the method it must use for adding junk columns to the query. Call
add_row_identity_var() instead of manipulating the parse tree directly.
You might want to reconsider exactly what you're adding, too.
* PlanDirectModify() must now work a little harder to find the
ForeignScan plan node; if the foreign table is part of a partitioning
hierarchy then the ForeignScan might not be the direct child of
ModifyTable. See postgres_fdw for sample code.
* To check whether a relation is a target relation, it's no
longer sufficient to compare its relid to root->parse->resultRelation.
Instead, check it against all_result_relids or leaf_result_relids,
as appropriate.
Amit Langote and Tom Lane
Discussion: https://postgr.es/m/CA+HiwqHpHdqdDn48yCEhynnniahH78rwcrv1rEX65-fsZGBOLQ@mail.gmail.com
2021-03-31 17:52:34 +02:00
|
|
|
performs partition pruning. Another
|
2019-06-11 22:08:57 +02:00
|
|
|
reason to be concerned about having a large number of partitions is that
|
2020-11-14 19:09:53 +01:00
|
|
|
the server's memory consumption may grow significantly over
|
2019-06-11 22:08:57 +02:00
|
|
|
time, especially if many sessions touch large numbers of partitions.
|
|
|
|
That's because each partition requires its metadata to be loaded into the
|
|
|
|
local memory of each session that touches it.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
With data warehouse type workloads, it can make sense to use a larger
|
|
|
|
number of partitions than with an <acronym>OLTP</acronym> type workload.
|
|
|
|
Generally, in data warehouses, query planning time is less of a concern as
|
|
|
|
the majority of processing time is spent during query execution. With
|
|
|
|
either of these two types of workload, it is important to make the right
|
|
|
|
decisions early, as re-partitioning large quantities of data can be
|
|
|
|
painfully slow. Simulations of the intended workload are often beneficial
|
2020-11-14 19:09:53 +01:00
|
|
|
for optimizing the partitioning strategy. Never just assume that more
|
|
|
|
partitions are better than fewer partitions, nor vice-versa.
|
2019-06-11 22:08:57 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect1>
|
|
|
|
|
2011-02-20 06:17:18 +01:00
|
|
|
<sect1 id="ddl-foreign-data">
|
|
|
|
<title>Foreign Data</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>foreign data</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm>
|
|
|
|
<primary>foreign table</primary>
|
|
|
|
</indexterm>
|
2011-07-25 15:37:06 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>user mapping</primary>
|
|
|
|
</indexterm>
|
2011-02-20 06:17:18 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
<productname>PostgreSQL</productname> implements portions of the SQL/MED
|
|
|
|
specification, allowing you to access data that resides outside
|
|
|
|
PostgreSQL using regular SQL queries. Such data is referred to as
|
2017-10-09 03:44:17 +02:00
|
|
|
<firstterm>foreign data</firstterm>. (Note that this usage is not to be confused
|
2011-02-20 06:17:18 +01:00
|
|
|
with foreign keys, which are a type of constraint within the database.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Foreign data is accessed with help from a
|
|
|
|
<firstterm>foreign data wrapper</firstterm>. A foreign data wrapper is a
|
|
|
|
library that can communicate with an external data source, hiding the
|
2013-03-10 19:14:53 +01:00
|
|
|
details of connecting to the data source and obtaining data from it.
|
2017-10-09 03:44:17 +02:00
|
|
|
There are some foreign data wrappers available as <filename>contrib</filename>
|
2017-11-23 15:39:47 +01:00
|
|
|
modules; see <xref linkend="contrib"/>. Other kinds of foreign data
|
2013-03-10 19:14:53 +01:00
|
|
|
wrappers might be found as third party products. If none of the existing
|
|
|
|
foreign data wrappers suit your needs, you can write your own; see <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="fdwhandler"/>.
|
2011-02-20 06:17:18 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
To access foreign data, you need to create a <firstterm>foreign server</firstterm>
|
2013-03-10 19:14:53 +01:00
|
|
|
object, which defines how to connect to a particular external data source
|
|
|
|
according to the set of options used by its supporting foreign data
|
2011-02-20 06:17:18 +01:00
|
|
|
wrapper. Then you need to create one or more <firstterm>foreign
|
|
|
|
tables</firstterm>, which define the structure of the remote data. A
|
|
|
|
foreign table can be used in queries just like a normal table, but a
|
|
|
|
foreign table has no storage in the PostgreSQL server. Whenever it is
|
2011-07-25 15:37:06 +02:00
|
|
|
used, <productname>PostgreSQL</productname> asks the foreign data wrapper
|
2013-03-10 19:14:53 +01:00
|
|
|
to fetch data from the external source, or transmit data to the external
|
|
|
|
source in the case of update commands.
|
2011-07-25 15:37:06 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2013-03-10 19:14:53 +01:00
|
|
|
Accessing remote data may require authenticating to the external
|
2011-07-25 15:37:06 +02:00
|
|
|
data source. This information can be provided by a
|
2017-10-09 03:44:17 +02:00
|
|
|
<firstterm>user mapping</firstterm>, which can provide additional data
|
2013-03-10 19:14:53 +01:00
|
|
|
such as user names and passwords based
|
2011-07-25 15:37:06 +02:00
|
|
|
on the current <productname>PostgreSQL</productname> role.
|
2011-02-20 06:17:18 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2013-03-10 19:14:53 +01:00
|
|
|
For additional information, see
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="sql-createforeigndatawrapper"/>,
|
|
|
|
<xref linkend="sql-createserver"/>,
|
|
|
|
<xref linkend="sql-createusermapping"/>,
|
|
|
|
<xref linkend="sql-createforeigntable"/>, and
|
|
|
|
<xref linkend="sql-importforeignschema"/>.
|
2011-02-20 06:17:18 +01:00
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<sect1 id="ddl-others">
|
|
|
|
<title>Other Database Objects</title>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Tables are the central objects in a relational database structure,
|
|
|
|
because they hold your data. But they are not the only objects
|
|
|
|
that exist in a database. Many other kinds of objects can be
|
|
|
|
created to make the use and management of the data more efficient
|
|
|
|
or convenient. They are not discussed in this chapter, but we give
|
2009-04-27 18:27:36 +02:00
|
|
|
you a list here so that you are aware of what is possible:
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Views
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-11-30 14:46:13 +01:00
|
|
|
Functions, procedures, and operators
|
2005-01-17 02:29:02 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Data types and domains
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Triggers and rewrite rules
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
2003-11-05 01:05:32 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Detailed information on
|
2017-11-23 15:39:47 +01:00
|
|
|
these topics appears in <xref linkend="server-programming"/>.
|
2003-11-05 01:05:32 +01:00
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect1>
|
|
|
|
|
|
|
|
<sect1 id="ddl-depend">
|
|
|
|
<title>Dependency Tracking</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="ddl-depend">
|
|
|
|
<primary>CASCADE</primary>
|
|
|
|
<secondary sortas="DROP">with DROP</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm zone="ddl-depend">
|
|
|
|
<primary>RESTRICT</primary>
|
|
|
|
<secondary sortas="DROP">with DROP</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-05 21:44:58 +02:00
|
|
|
<para>
|
|
|
|
When you create complex database structures involving many tables
|
|
|
|
with foreign key constraints, views, triggers, functions, etc. you
|
2009-04-27 18:27:36 +02:00
|
|
|
implicitly create a net of dependencies between the objects.
|
2002-08-05 21:44:58 +02:00
|
|
|
For instance, a table with a foreign key constraint depends on the
|
|
|
|
table it references.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To ensure the integrity of the entire database structure,
|
|
|
|
<productname>PostgreSQL</productname> makes sure that you cannot
|
|
|
|
drop objects that other objects still depend on. For example,
|
2016-06-22 02:07:58 +02:00
|
|
|
attempting to drop the products table we considered in <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="ddl-constraints-fk"/>, with the orders table depending on
|
2016-06-22 02:07:58 +02:00
|
|
|
it, would result in an error message like this:
|
2002-08-05 21:44:58 +02:00
|
|
|
<screen>
|
2003-03-13 02:30:29 +01:00
|
|
|
DROP TABLE products;
|
|
|
|
|
2003-09-13 00:17:24 +02:00
|
|
|
ERROR: cannot drop table products because other objects depend on it
|
2016-06-22 02:07:58 +02:00
|
|
|
DETAIL: constraint orders_product_no_fkey on table orders depends on table products
|
2003-09-13 00:17:24 +02:00
|
|
|
HINT: Use DROP ... CASCADE to drop the dependent objects too.
|
2002-08-05 21:44:58 +02:00
|
|
|
</screen>
|
2003-02-19 05:06:28 +01:00
|
|
|
The error message contains a useful hint: if you do not want to
|
2009-04-27 18:27:36 +02:00
|
|
|
bother deleting all the dependent objects individually, you can run:
|
2002-08-05 21:44:58 +02:00
|
|
|
<screen>
|
|
|
|
DROP TABLE products CASCADE;
|
|
|
|
</screen>
|
2016-08-13 00:45:18 +02:00
|
|
|
and all the dependent objects will be removed, as will any objects
|
|
|
|
that depend on them, recursively. In this case, it doesn't remove
|
|
|
|
the orders table, it only removes the foreign key constraint.
|
|
|
|
It stops there because nothing depends on the foreign key constraint.
|
2017-10-09 03:44:17 +02:00
|
|
|
(If you want to check what <command>DROP ... CASCADE</command> will do,
|
|
|
|
run <command>DROP</command> without <literal>CASCADE</literal> and read the
|
|
|
|
<literal>DETAIL</literal> output.)
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Almost all <command>DROP</command> commands in <productname>PostgreSQL</productname> support
|
2002-08-05 21:44:58 +02:00
|
|
|
specifying <literal>CASCADE</literal>. Of course, the nature of
|
|
|
|
the possible dependencies varies with the type of the object. You
|
|
|
|
can also write <literal>RESTRICT</literal> instead of
|
2003-09-13 00:17:24 +02:00
|
|
|
<literal>CASCADE</literal> to get the default behavior, which is to
|
2016-08-13 00:45:18 +02:00
|
|
|
prevent dropping objects that any other objects depend on.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
According to the SQL standard, specifying either
|
|
|
|
<literal>RESTRICT</literal> or <literal>CASCADE</literal> is
|
2017-10-09 03:44:17 +02:00
|
|
|
required in a <command>DROP</command> command. No database system actually
|
2016-06-22 02:07:58 +02:00
|
|
|
enforces that rule, but whether the default behavior
|
|
|
|
is <literal>RESTRICT</literal> or <literal>CASCADE</literal> varies
|
|
|
|
across systems.
|
2002-08-05 21:44:58 +02:00
|
|
|
</para>
|
|
|
|
</note>
|
2002-08-28 22:17:44 +02:00
|
|
|
|
2016-08-13 00:45:18 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
If a <command>DROP</command> command lists multiple
|
2016-08-13 00:45:18 +02:00
|
|
|
objects, <literal>CASCADE</literal> is only required when there are
|
|
|
|
dependencies outside the specified group. For example, when saying
|
|
|
|
<literal>DROP TABLE tab1, tab2</literal> the existence of a foreign
|
2017-10-09 03:44:17 +02:00
|
|
|
key referencing <literal>tab1</literal> from <literal>tab2</literal> would not mean
|
2016-08-13 00:45:18 +02:00
|
|
|
that <literal>CASCADE</literal> is needed to succeed.
|
|
|
|
</para>
|
|
|
|
|
2016-06-22 02:07:58 +02:00
|
|
|
<para>
|
2023-06-04 19:27:34 +02:00
|
|
|
For a user-defined function or procedure whose body is defined as a string
|
|
|
|
literal, <productname>PostgreSQL</productname> tracks
|
|
|
|
dependencies associated with the function's externally-visible properties,
|
2017-10-09 03:44:17 +02:00
|
|
|
such as its argument and result types, but <emphasis>not</emphasis> dependencies
|
2016-06-22 02:07:58 +02:00
|
|
|
that could only be known by examining the function body. As an example,
|
|
|
|
consider this situation:
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow',
|
|
|
|
'green', 'blue', 'purple');
|
|
|
|
|
|
|
|
CREATE TABLE my_colors (color rainbow, note text);
|
|
|
|
|
|
|
|
CREATE FUNCTION get_color_note (rainbow) RETURNS text AS
|
|
|
|
'SELECT note FROM my_colors WHERE color = $1'
|
|
|
|
LANGUAGE SQL;
|
|
|
|
</programlisting>
|
|
|
|
|
2017-11-23 15:39:47 +01:00
|
|
|
(See <xref linkend="xfunc-sql"/> for an explanation of SQL-language
|
2016-06-22 02:07:58 +02:00
|
|
|
functions.) <productname>PostgreSQL</productname> will be aware that
|
2017-10-09 03:44:17 +02:00
|
|
|
the <function>get_color_note</function> function depends on the <type>rainbow</type>
|
2016-06-22 02:07:58 +02:00
|
|
|
type: dropping the type would force dropping the function, because its
|
2017-10-09 03:44:17 +02:00
|
|
|
argument type would no longer be defined. But <productname>PostgreSQL</productname>
|
|
|
|
will not consider <function>get_color_note</function> to depend on
|
|
|
|
the <structname>my_colors</structname> table, and so will not drop the function if
|
2016-06-22 02:07:58 +02:00
|
|
|
the table is dropped. While there are disadvantages to this approach,
|
|
|
|
there are also benefits. The function is still valid in some sense if the
|
|
|
|
table is missing, though executing it would cause an error; creating a new
|
|
|
|
table of the same name would allow the function to work again.
|
|
|
|
</para>
|
2023-06-04 19:27:34 +02:00
|
|
|
|
|
|
|
<para>
|
2024-04-10 00:43:31 +02:00
|
|
|
On the other hand, for an SQL-language function or procedure whose body
|
2023-06-04 19:27:34 +02:00
|
|
|
is written in SQL-standard style, the body is parsed at function
|
|
|
|
definition time and all dependencies recognized by the parser are
|
|
|
|
stored. Thus, if we write the function above as
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION get_color_note (rainbow) RETURNS text
|
|
|
|
BEGIN ATOMIC
|
|
|
|
SELECT note FROM my_colors WHERE color = $1;
|
|
|
|
END;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
then the function's dependency on the <structname>my_colors</structname>
|
|
|
|
table will be known and enforced by <command>DROP</command>.
|
|
|
|
</para>
|
2002-08-05 21:44:58 +02:00
|
|
|
</sect1>
|
|
|
|
|
|
|
|
</chapter>
|