diff options
Diffstat (limited to 'doc/src/sgml/ref')
217 files changed, 72169 insertions, 0 deletions
diff --git a/doc/src/sgml/ref/abort.sgml b/doc/src/sgml/ref/abort.sgml new file mode 100644 index 0000000..16b5602 --- /dev/null +++ b/doc/src/sgml/ref/abort.sgml @@ -0,0 +1,112 @@ +<!-- +doc/src/sgml/ref/abort.sgml +PostgreSQL documentation +--> + +<refentry id="sql-abort"> + <indexterm zone="sql-abort"> + <primary>ABORT</primary> + </indexterm> + + <refmeta> + <refentrytitle>ABORT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ABORT</refname> + <refpurpose>abort the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ABORT [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ABORT</command> rolls back the current transaction and causes + all the updates made by the transaction to be discarded. + This command is identical + in behavior to the standard <acronym>SQL</acronym> command + <link linkend="sql-rollback"><command>ROLLBACK</command></link>, + and is present only for historical reasons. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>WORK</literal></term> + <term><literal>TRANSACTION</literal></term> + <listitem> + <para> + Optional key words. They have no effect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>AND CHAIN</literal></term> + <listitem> + <para> + If <literal>AND CHAIN</literal> is specified, a new transaction is + immediately started with the same transaction characteristics (see <link + linkend="sql-set-transaction"><command>SET TRANSACTION</command></link>) as the just finished one. Otherwise, + no new transaction is started. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-commit"><command>COMMIT</command></link> to + successfully terminate a transaction. + </para> + + <para> + Issuing <command>ABORT</command> outside of a transaction block + emits a warning and otherwise has no effect. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To abort all changes: +<programlisting> +ABORT; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command is a <productname>PostgreSQL</productname> extension + present for historical reasons. <command>ROLLBACK</command> is the + equivalent standard SQL command. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/allfiles.sgml b/doc/src/sgml/ref/allfiles.sgml new file mode 100644 index 0000000..e90a0e1 --- /dev/null +++ b/doc/src/sgml/ref/allfiles.sgml @@ -0,0 +1,225 @@ +<!-- +doc/src/sgml/ref/allfiles.sgml +PostgreSQL documentation +Complete list of usable sgml source files in this directory. +--> + +<!-- SQL commands --> +<!ENTITY abort SYSTEM "abort.sgml"> +<!ENTITY alterAggregate SYSTEM "alter_aggregate.sgml"> +<!ENTITY alterCollation SYSTEM "alter_collation.sgml"> +<!ENTITY alterConversion SYSTEM "alter_conversion.sgml"> +<!ENTITY alterDatabase SYSTEM "alter_database.sgml"> +<!ENTITY alterDefaultPrivileges SYSTEM "alter_default_privileges.sgml"> +<!ENTITY alterDomain SYSTEM "alter_domain.sgml"> +<!ENTITY alterEventTrigger SYSTEM "alter_event_trigger.sgml"> +<!ENTITY alterExtension SYSTEM "alter_extension.sgml"> +<!ENTITY alterForeignDataWrapper SYSTEM "alter_foreign_data_wrapper.sgml"> +<!ENTITY alterForeignTable SYSTEM "alter_foreign_table.sgml"> +<!ENTITY alterFunction SYSTEM "alter_function.sgml"> +<!ENTITY alterGroup SYSTEM "alter_group.sgml"> +<!ENTITY alterIndex SYSTEM "alter_index.sgml"> +<!ENTITY alterLanguage SYSTEM "alter_language.sgml"> +<!ENTITY alterLargeObject SYSTEM "alter_large_object.sgml"> +<!ENTITY alterMaterializedView SYSTEM "alter_materialized_view.sgml"> +<!ENTITY alterOperator SYSTEM "alter_operator.sgml"> +<!ENTITY alterOperatorClass SYSTEM "alter_opclass.sgml"> +<!ENTITY alterOperatorFamily SYSTEM "alter_opfamily.sgml"> +<!ENTITY alterPolicy SYSTEM "alter_policy.sgml"> +<!ENTITY alterProcedure SYSTEM "alter_procedure.sgml"> +<!ENTITY alterPublication SYSTEM "alter_publication.sgml"> +<!ENTITY alterRole SYSTEM "alter_role.sgml"> +<!ENTITY alterRoutine SYSTEM "alter_routine.sgml"> +<!ENTITY alterRule SYSTEM "alter_rule.sgml"> +<!ENTITY alterSchema SYSTEM "alter_schema.sgml"> +<!ENTITY alterServer SYSTEM "alter_server.sgml"> +<!ENTITY alterSequence SYSTEM "alter_sequence.sgml"> +<!ENTITY alterSubscription SYSTEM "alter_subscription.sgml"> +<!ENTITY alterSystem SYSTEM "alter_system.sgml"> +<!ENTITY alterStatistics SYSTEM "alter_statistics.sgml"> +<!ENTITY alterTable SYSTEM "alter_table.sgml"> +<!ENTITY alterTableSpace SYSTEM "alter_tablespace.sgml"> +<!ENTITY alterTSConfig SYSTEM "alter_tsconfig.sgml"> +<!ENTITY alterTSDictionary SYSTEM "alter_tsdictionary.sgml"> +<!ENTITY alterTSParser SYSTEM "alter_tsparser.sgml"> +<!ENTITY alterTSTemplate SYSTEM "alter_tstemplate.sgml"> +<!ENTITY alterTrigger SYSTEM "alter_trigger.sgml"> +<!ENTITY alterType SYSTEM "alter_type.sgml"> +<!ENTITY alterUser SYSTEM "alter_user.sgml"> +<!ENTITY alterUserMapping SYSTEM "alter_user_mapping.sgml"> +<!ENTITY alterView SYSTEM "alter_view.sgml"> +<!ENTITY analyze SYSTEM "analyze.sgml"> +<!ENTITY begin SYSTEM "begin.sgml"> +<!ENTITY call SYSTEM "call.sgml"> +<!ENTITY checkpoint SYSTEM "checkpoint.sgml"> +<!ENTITY close SYSTEM "close.sgml"> +<!ENTITY cluster SYSTEM "cluster.sgml"> +<!ENTITY commentOn SYSTEM "comment.sgml"> +<!ENTITY commit SYSTEM "commit.sgml"> +<!ENTITY commitPrepared SYSTEM "commit_prepared.sgml"> +<!ENTITY copyTable SYSTEM "copy.sgml"> +<!ENTITY createAccessMethod SYSTEM "create_access_method.sgml"> +<!ENTITY createAggregate SYSTEM "create_aggregate.sgml"> +<!ENTITY createCast SYSTEM "create_cast.sgml"> +<!ENTITY createCollation SYSTEM "create_collation.sgml"> +<!ENTITY createConversion SYSTEM "create_conversion.sgml"> +<!ENTITY createDatabase SYSTEM "create_database.sgml"> +<!ENTITY createDomain SYSTEM "create_domain.sgml"> +<!ENTITY createEventTrigger SYSTEM "create_event_trigger.sgml"> +<!ENTITY createExtension SYSTEM "create_extension.sgml"> +<!ENTITY createForeignDataWrapper SYSTEM "create_foreign_data_wrapper.sgml"> +<!ENTITY createForeignTable SYSTEM "create_foreign_table.sgml"> +<!ENTITY createFunction SYSTEM "create_function.sgml"> +<!ENTITY createGroup SYSTEM "create_group.sgml"> +<!ENTITY createIndex SYSTEM "create_index.sgml"> +<!ENTITY createLanguage SYSTEM "create_language.sgml"> +<!ENTITY createMaterializedView SYSTEM "create_materialized_view.sgml"> +<!ENTITY createOperator SYSTEM "create_operator.sgml"> +<!ENTITY createOperatorClass SYSTEM "create_opclass.sgml"> +<!ENTITY createOperatorFamily SYSTEM "create_opfamily.sgml"> +<!ENTITY createPolicy SYSTEM "create_policy.sgml"> +<!ENTITY createProcedure SYSTEM "create_procedure.sgml"> +<!ENTITY createPublication SYSTEM "create_publication.sgml"> +<!ENTITY createRole SYSTEM "create_role.sgml"> +<!ENTITY createRule SYSTEM "create_rule.sgml"> +<!ENTITY createSchema SYSTEM "create_schema.sgml"> +<!ENTITY createSequence SYSTEM "create_sequence.sgml"> +<!ENTITY createServer SYSTEM "create_server.sgml"> +<!ENTITY createStatistics SYSTEM "create_statistics.sgml"> +<!ENTITY createSubscription SYSTEM "create_subscription.sgml"> +<!ENTITY createTable SYSTEM "create_table.sgml"> +<!ENTITY createTableAs SYSTEM "create_table_as.sgml"> +<!ENTITY createTableSpace SYSTEM "create_tablespace.sgml"> +<!ENTITY createTransform SYSTEM "create_transform.sgml"> +<!ENTITY createTrigger SYSTEM "create_trigger.sgml"> +<!ENTITY createTSConfig SYSTEM "create_tsconfig.sgml"> +<!ENTITY createTSDictionary SYSTEM "create_tsdictionary.sgml"> +<!ENTITY createTSParser SYSTEM "create_tsparser.sgml"> +<!ENTITY createTSTemplate SYSTEM "create_tstemplate.sgml"> +<!ENTITY createType SYSTEM "create_type.sgml"> +<!ENTITY createUser SYSTEM "create_user.sgml"> +<!ENTITY createUserMapping SYSTEM "create_user_mapping.sgml"> +<!ENTITY createView SYSTEM "create_view.sgml"> +<!ENTITY deallocate SYSTEM "deallocate.sgml"> +<!ENTITY declare SYSTEM "declare.sgml"> +<!ENTITY delete SYSTEM "delete.sgml"> +<!ENTITY discard SYSTEM "discard.sgml"> +<!ENTITY do SYSTEM "do.sgml"> +<!ENTITY dropAccessMethod SYSTEM "drop_access_method.sgml"> +<!ENTITY dropAggregate SYSTEM "drop_aggregate.sgml"> +<!ENTITY dropCast SYSTEM "drop_cast.sgml"> +<!ENTITY dropCollation SYSTEM "drop_collation.sgml"> +<!ENTITY dropConversion SYSTEM "drop_conversion.sgml"> +<!ENTITY dropDatabase SYSTEM "drop_database.sgml"> +<!ENTITY dropDomain SYSTEM "drop_domain.sgml"> +<!ENTITY dropEventTrigger SYSTEM "drop_event_trigger.sgml"> +<!ENTITY dropExtension SYSTEM "drop_extension.sgml"> +<!ENTITY dropForeignDataWrapper SYSTEM "drop_foreign_data_wrapper.sgml"> +<!ENTITY dropForeignTable SYSTEM "drop_foreign_table.sgml"> +<!ENTITY dropFunction SYSTEM "drop_function.sgml"> +<!ENTITY dropGroup SYSTEM "drop_group.sgml"> +<!ENTITY dropIndex SYSTEM "drop_index.sgml"> +<!ENTITY dropLanguage SYSTEM "drop_language.sgml"> +<!ENTITY dropMaterializedView SYSTEM "drop_materialized_view.sgml"> +<!ENTITY dropOperator SYSTEM "drop_operator.sgml"> +<!ENTITY dropOperatorClass SYSTEM "drop_opclass.sgml"> +<!ENTITY dropOperatorFamily SYSTEM "drop_opfamily.sgml"> +<!ENTITY dropOwned SYSTEM "drop_owned.sgml"> +<!ENTITY dropPolicy SYSTEM "drop_policy.sgml"> +<!ENTITY dropProcedure SYSTEM "drop_procedure.sgml"> +<!ENTITY dropPublication SYSTEM "drop_publication.sgml"> +<!ENTITY dropRole SYSTEM "drop_role.sgml"> +<!ENTITY dropRoutine SYSTEM "drop_routine.sgml"> +<!ENTITY dropRule SYSTEM "drop_rule.sgml"> +<!ENTITY dropSchema SYSTEM "drop_schema.sgml"> +<!ENTITY dropSequence SYSTEM "drop_sequence.sgml"> +<!ENTITY dropServer SYSTEM "drop_server.sgml"> +<!ENTITY dropStatistics SYSTEM "drop_statistics.sgml"> +<!ENTITY dropSubscription SYSTEM "drop_subscription.sgml"> +<!ENTITY dropTable SYSTEM "drop_table.sgml"> +<!ENTITY dropTableSpace SYSTEM "drop_tablespace.sgml"> +<!ENTITY dropTransform SYSTEM "drop_transform.sgml"> +<!ENTITY dropTrigger SYSTEM "drop_trigger.sgml"> +<!ENTITY dropTSConfig SYSTEM "drop_tsconfig.sgml"> +<!ENTITY dropTSDictionary SYSTEM "drop_tsdictionary.sgml"> +<!ENTITY dropTSParser SYSTEM "drop_tsparser.sgml"> +<!ENTITY dropTSTemplate SYSTEM "drop_tstemplate.sgml"> +<!ENTITY dropType SYSTEM "drop_type.sgml"> +<!ENTITY dropUser SYSTEM "drop_user.sgml"> +<!ENTITY dropUserMapping SYSTEM "drop_user_mapping.sgml"> +<!ENTITY dropView SYSTEM "drop_view.sgml"> +<!ENTITY end SYSTEM "end.sgml"> +<!ENTITY execute SYSTEM "execute.sgml"> +<!ENTITY explain SYSTEM "explain.sgml"> +<!ENTITY fetch SYSTEM "fetch.sgml"> +<!ENTITY grant SYSTEM "grant.sgml"> +<!ENTITY importForeignSchema SYSTEM "import_foreign_schema.sgml"> +<!ENTITY insert SYSTEM "insert.sgml"> +<!ENTITY listen SYSTEM "listen.sgml"> +<!ENTITY load SYSTEM "load.sgml"> +<!ENTITY lock SYSTEM "lock.sgml"> +<!ENTITY merge SYSTEM "merge.sgml"> +<!ENTITY move SYSTEM "move.sgml"> +<!ENTITY notify SYSTEM "notify.sgml"> +<!ENTITY prepare SYSTEM "prepare.sgml"> +<!ENTITY prepareTransaction SYSTEM "prepare_transaction.sgml"> +<!ENTITY reassignOwned SYSTEM "reassign_owned.sgml"> +<!ENTITY refreshMaterializedView SYSTEM "refresh_materialized_view.sgml"> +<!ENTITY reindex SYSTEM "reindex.sgml"> +<!ENTITY releaseSavepoint SYSTEM "release_savepoint.sgml"> +<!ENTITY reset SYSTEM "reset.sgml"> +<!ENTITY revoke SYSTEM "revoke.sgml"> +<!ENTITY rollback SYSTEM "rollback.sgml"> +<!ENTITY rollbackPrepared SYSTEM "rollback_prepared.sgml"> +<!ENTITY rollbackTo SYSTEM "rollback_to.sgml"> +<!ENTITY savepoint SYSTEM "savepoint.sgml"> +<!ENTITY securityLabel SYSTEM "security_label.sgml"> +<!ENTITY select SYSTEM "select.sgml"> +<!ENTITY selectInto SYSTEM "select_into.sgml"> +<!ENTITY set SYSTEM "set.sgml"> +<!ENTITY setConstraints SYSTEM "set_constraints.sgml"> +<!ENTITY setRole SYSTEM "set_role.sgml"> +<!ENTITY setSessionAuth SYSTEM "set_session_auth.sgml"> +<!ENTITY setTransaction SYSTEM "set_transaction.sgml"> +<!ENTITY show SYSTEM "show.sgml"> +<!ENTITY startTransaction SYSTEM "start_transaction.sgml"> +<!ENTITY truncate SYSTEM "truncate.sgml"> +<!ENTITY unlisten SYSTEM "unlisten.sgml"> +<!ENTITY update SYSTEM "update.sgml"> +<!ENTITY vacuum SYSTEM "vacuum.sgml"> +<!ENTITY values SYSTEM "values.sgml"> + +<!-- applications and utilities --> +<!ENTITY clusterdb SYSTEM "clusterdb.sgml"> +<!ENTITY createdb SYSTEM "createdb.sgml"> +<!ENTITY createuser SYSTEM "createuser.sgml"> +<!ENTITY dropdb SYSTEM "dropdb.sgml"> +<!ENTITY dropuser SYSTEM "dropuser.sgml"> +<!ENTITY ecpgRef SYSTEM "ecpg-ref.sgml"> +<!ENTITY initdb SYSTEM "initdb.sgml"> +<!ENTITY pgamcheck SYSTEM "pg_amcheck.sgml"> +<!ENTITY pgarchivecleanup SYSTEM "pgarchivecleanup.sgml"> +<!ENTITY pgBasebackup SYSTEM "pg_basebackup.sgml"> +<!ENTITY pgbench SYSTEM "pgbench.sgml"> +<!ENTITY pgChecksums SYSTEM "pg_checksums.sgml"> +<!ENTITY pgConfig SYSTEM "pg_config-ref.sgml"> +<!ENTITY pgControldata SYSTEM "pg_controldata.sgml"> +<!ENTITY pgCtl SYSTEM "pg_ctl-ref.sgml"> +<!ENTITY pgDump SYSTEM "pg_dump.sgml"> +<!ENTITY pgDumpall SYSTEM "pg_dumpall.sgml"> +<!ENTITY pgIsready SYSTEM "pg_isready.sgml"> +<!ENTITY pgReceivewal SYSTEM "pg_receivewal.sgml"> +<!ENTITY pgRecvlogical SYSTEM "pg_recvlogical.sgml"> +<!ENTITY pgResetwal SYSTEM "pg_resetwal.sgml"> +<!ENTITY pgRestore SYSTEM "pg_restore.sgml"> +<!ENTITY pgRewind SYSTEM "pg_rewind.sgml"> +<!ENTITY pgVerifyBackup SYSTEM "pg_verifybackup.sgml"> +<!ENTITY pgtestfsync SYSTEM "pgtestfsync.sgml"> +<!ENTITY pgtesttiming SYSTEM "pgtesttiming.sgml"> +<!ENTITY pgupgrade SYSTEM "pgupgrade.sgml"> +<!ENTITY pgwaldump SYSTEM "pg_waldump.sgml"> +<!ENTITY postgres SYSTEM "postgres-ref.sgml"> +<!ENTITY postmaster SYSTEM "postmaster.sgml"> +<!ENTITY psqlRef SYSTEM "psql-ref.sgml"> +<!ENTITY reindexdb SYSTEM "reindexdb.sgml"> +<!ENTITY vacuumdb SYSTEM "vacuumdb.sgml"> diff --git a/doc/src/sgml/ref/alter_aggregate.sgml b/doc/src/sgml/ref/alter_aggregate.sgml new file mode 100644 index 0000000..aee10a5 --- /dev/null +++ b/doc/src/sgml/ref/alter_aggregate.sgml @@ -0,0 +1,202 @@ +<!-- +doc/src/sgml/ref/alter_aggregate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alteraggregate"> + <indexterm zone="sql-alteraggregate"> + <primary>ALTER AGGREGATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER AGGREGATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER AGGREGATE</refname> + <refpurpose>change the definition of an aggregate function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) RENAME TO <replaceable>new_name</replaceable> +ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) SET SCHEMA <replaceable>new_schema</replaceable> + +<phrase>where <replaceable>aggregate_signature</replaceable> is:</phrase> + +* | +[ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] | +[ [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] ] ORDER BY [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER AGGREGATE</command> changes the definition of an + aggregate function. + </para> + + <para> + You must own the aggregate function to use <command>ALTER AGGREGATE</command>. + To change the schema of an aggregate function, you must also have + <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the aggregate function's schema. (These restrictions enforce that altering + the owner doesn't do anything you couldn't do by dropping and recreating + the aggregate function. However, a superuser can alter ownership of any + aggregate function anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing aggregate function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal> or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>ALTER AGGREGATE</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the aggregate function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + <listitem> + <para> + An input data type on which the aggregate function operates. + To reference a zero-argument aggregate function, write <literal>*</literal> + in place of the list of argument specifications. + To reference an ordered-set aggregate function, write + <literal>ORDER BY</literal> between the direct and aggregated argument + specifications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the aggregate function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the aggregate function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the aggregate function. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The recommended syntax for referencing an ordered-set aggregate + is to write <literal>ORDER BY</literal> between the direct and aggregated + argument specifications, in the same style as in + <link linkend="sql-createaggregate"><command>CREATE AGGREGATE</command></link>. However, it will also work to + omit <literal>ORDER BY</literal> and just run the direct and aggregated + argument specifications into a single list. In this abbreviated form, + if <literal>VARIADIC "any"</literal> was used in both the direct and + aggregated argument lists, write <literal>VARIADIC "any"</literal> only once. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the aggregate function <literal>myavg</literal> for type + <type>integer</type> to <literal>my_average</literal>: +<programlisting> +ALTER AGGREGATE myavg(integer) RENAME TO my_average; +</programlisting> + </para> + + <para> + To change the owner of the aggregate function <literal>myavg</literal> for type + <type>integer</type> to <literal>joe</literal>: +<programlisting> +ALTER AGGREGATE myavg(integer) OWNER TO joe; +</programlisting> + </para> + + <para> + To move the ordered-set aggregate <literal>mypercentile</literal> with + direct argument of type <type>float8</type> and aggregated argument + of type <type>integer</type> into schema <literal>myschema</literal>: +<programlisting> +ALTER AGGREGATE mypercentile(float8 ORDER BY integer) SET SCHEMA myschema; +</programlisting> + This will work too: +<programlisting> +ALTER AGGREGATE mypercentile(float8, integer) SET SCHEMA myschema; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER AGGREGATE</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createaggregate"/></member> + <member><xref linkend="sql-dropaggregate"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_collation.sgml b/doc/src/sgml/ref/alter_collation.sgml new file mode 100644 index 0000000..a8c831d --- /dev/null +++ b/doc/src/sgml/ref/alter_collation.sgml @@ -0,0 +1,207 @@ +<!-- +doc/src/sgml/ref/alter_collation.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altercollation"> + <indexterm zone="sql-altercollation"> + <primary>ALTER COLLATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER COLLATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER COLLATION</refname> + <refpurpose>change the definition of a collation</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER COLLATION <replaceable>name</replaceable> REFRESH VERSION + +ALTER COLLATION <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER COLLATION <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER COLLATION <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER COLLATION</command> changes the definition of a + collation. + </para> + + <para> + You must own the collation to use <command>ALTER COLLATION</command>. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the collation's schema. (These restrictions enforce that altering the + owner doesn't do anything you couldn't do by dropping and recreating the + collation. However, a superuser can alter ownership of any collation + anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing collation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the collation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the collation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the collation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REFRESH VERSION</literal></term> + <listitem> + <para> + Update the collation's version. + See <xref linkend="sql-altercollation-notes"/> below. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-altercollation-notes" xreflabel="Notes"> + <title>Notes</title> + + <para> + When a collation object is created, the provider-specific version of the + collation is recorded in the system catalog. When the collation is used, + the current version is + checked against the recorded version, and a warning is issued when there is + a mismatch, for example: +<screen> +WARNING: collation "xx-x-icu" has version mismatch +DETAIL: The collation in the database was created using version 1.2.3.4, but the operating system provides version 2.3.4.5. +HINT: Rebuild all objects affected by this collation and run ALTER COLLATION pg_catalog."xx-x-icu" REFRESH VERSION, or build PostgreSQL with the right library version. +</screen> + A change in collation definitions can lead to corrupt indexes and other + problems because the database system relies on stored objects having a + certain sort order. Generally, this should be avoided, but it can happen + in legitimate circumstances, such as when upgrading the operating system + to a new major version or when + using <command>pg_upgrade</command> to upgrade to server binaries linked + with a newer version of ICU. When this happens, all objects depending on + the collation should be rebuilt, for example, + using <command>REINDEX</command>. When that is done, the collation version + can be refreshed using the command <literal>ALTER COLLATION ... REFRESH + VERSION</literal>. This will update the system catalog to record the + current collation version and will make the warning go away. Note that this + does not actually check whether all affected objects have been rebuilt + correctly. + </para> + <para> + When using collations provided by <literal>libc</literal>, version + information is recorded on systems using the GNU C library (most Linux + systems), FreeBSD and Windows. When using collations provided by ICU, the + version information is provided by the ICU library and is available on all + platforms. + </para> + <note> + <para> + When using the GNU C library for collations, the C library's version + is used as a proxy for the collation version. Many Linux distributions + change collation definitions only when upgrading the C library, but this + approach is imperfect as maintainers are free to back-port newer + collation definitions to older C library releases. + </para> + <para> + When using Windows for collations, version information is only available + for collations defined with BCP 47 language tags such as + <literal>en-US</literal>. + </para> + </note> + <para> + For the database default collation, there is an analogous command + <literal>ALTER DATABASE ... REFRESH COLLATION VERSION</literal>. + </para> + + <para> + The following query can be used to identify all collations in the current + database that need to be refreshed and the objects that depend on them: +<programlisting><![CDATA[ +SELECT pg_describe_object(refclassid, refobjid, refobjsubid) AS "Collation", + pg_describe_object(classid, objid, objsubid) AS "Object" + FROM pg_depend d JOIN pg_collation c + ON refclassid = 'pg_collation'::regclass AND refobjid = c.oid + WHERE c.collversion <> pg_collation_actual_version(c.oid) + ORDER BY 1, 2; +]]></programlisting></para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the collation <literal>de_DE</literal> to + <literal>german</literal>: +<programlisting> +ALTER COLLATION "de_DE" RENAME TO german; +</programlisting> + </para> + + <para> + To change the owner of the collation <literal>en_US</literal> to + <literal>joe</literal>: +<programlisting> +ALTER COLLATION "en_US" OWNER TO joe; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER COLLATION</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createcollation"/></member> + <member><xref linkend="sql-dropcollation"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_conversion.sgml b/doc/src/sgml/ref/alter_conversion.sgml new file mode 100644 index 0000000..a128f20 --- /dev/null +++ b/doc/src/sgml/ref/alter_conversion.sgml @@ -0,0 +1,127 @@ +<!-- +doc/src/sgml/ref/alter_conversion.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterconversion"> + <indexterm zone="sql-alterconversion"> + <primary>ALTER CONVERSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER CONVERSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER CONVERSION</refname> + <refpurpose>change the definition of a conversion</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER CONVERSION <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER CONVERSION <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER CONVERSION <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER CONVERSION</command> changes the definition of a + conversion. + </para> + + <para> + You must own the conversion to use <command>ALTER CONVERSION</command>. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the conversion's schema. (These restrictions enforce that altering the + owner doesn't do anything you couldn't do by dropping and recreating the + conversion. However, a superuser can alter ownership of any conversion + anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing conversion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the conversion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the conversion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the conversion. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the conversion <literal>iso_8859_1_to_utf8</literal> to + <literal>latin1_to_unicode</literal>: +<programlisting> +ALTER CONVERSION iso_8859_1_to_utf8 RENAME TO latin1_to_unicode; +</programlisting> + </para> + + <para> + To change the owner of the conversion <literal>iso_8859_1_to_utf8</literal> to + <literal>joe</literal>: +<programlisting> +ALTER CONVERSION iso_8859_1_to_utf8 OWNER TO joe; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER CONVERSION</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createconversion"/></member> + <member><xref linkend="sql-dropconversion"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_database.sgml b/doc/src/sgml/ref/alter_database.sgml new file mode 100644 index 0000000..89ed261 --- /dev/null +++ b/doc/src/sgml/ref/alter_database.sgml @@ -0,0 +1,255 @@ +<!-- +doc/src/sgml/ref/alter_database.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterdatabase"> + <indexterm zone="sql-alterdatabase"> + <primary>ALTER DATABASE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER DATABASE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER DATABASE</refname> + <refpurpose>change a database</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER DATABASE <replaceable class="parameter">name</replaceable> [ [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + ALLOW_CONNECTIONS <replaceable class="parameter">allowconn</replaceable> + CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + IS_TEMPLATE <replaceable class="parameter">istemplate</replaceable> + +ALTER DATABASE <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> + +ALTER DATABASE <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + +ALTER DATABASE <replaceable class="parameter">name</replaceable> SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> + +ALTER DATABASE <replaceable class="parameter">name</replaceable> REFRESH COLLATION VERSION + +ALTER DATABASE <replaceable class="parameter">name</replaceable> SET <replaceable>configuration_parameter</replaceable> { TO | = } { <replaceable>value</replaceable> | DEFAULT } +ALTER DATABASE <replaceable class="parameter">name</replaceable> SET <replaceable>configuration_parameter</replaceable> FROM CURRENT +ALTER DATABASE <replaceable class="parameter">name</replaceable> RESET <replaceable>configuration_parameter</replaceable> +ALTER DATABASE <replaceable class="parameter">name</replaceable> RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER DATABASE</command> changes the attributes + of a database. + </para> + + <para> + The first form changes certain per-database settings. (See below for + details.) Only the database owner or a superuser can change these settings. + </para> + + <para> + The second form changes the name of the database. Only the database + owner or a superuser can rename a database; non-superuser owners must + also have the + <literal>CREATEDB</literal> privilege. The current database cannot + be renamed. (Connect to a different database if you need to do + that.) + </para> + + <para> + The third form changes the owner of the database. + To alter the owner, you must own the database and also be a direct or + indirect member of the new owning role, and you must have the + <literal>CREATEDB</literal> privilege. + (Note that superusers have all these privileges automatically.) + </para> + + <para> + The fourth form changes the default tablespace of the database. + Only the database owner or a superuser can do this; you must also have + create privilege for the new tablespace. + This command physically moves any tables or indexes in the database's old + default tablespace to the new tablespace. The new default tablespace + must be empty for this database, and no one can be connected to + the database. Tables and indexes in non-default tablespaces are + unaffected. + </para> + + <para> + The remaining forms change the session default for a run-time + configuration variable for a <productname>PostgreSQL</productname> + database. Whenever a new session is subsequently started in that + database, the specified value becomes the session default value. + The database-specific default overrides whatever setting is present + in <filename>postgresql.conf</filename> or has been received from the + <command>postgres</command> command line. Only the database + owner or a superuser can change the session defaults for a + database. Certain variables cannot be set this way, or can only be + set by a superuser. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the database whose attributes are to be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">allowconn</replaceable></term> + <listitem> + <para> + If false then no one can connect to this database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">connlimit</replaceable></term> + <listitem> + <para> + How many concurrent connections can be made + to this database. -1 means no limit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">istemplate</replaceable></term> + <listitem> + <para> + If true, then this database can be cloned by any user with <literal>CREATEDB</literal> + privileges; if false, then only superusers or the owner of the + database can clone it. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_name</replaceable></term> + <listitem> + <para> + The new name of the database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_tablespace</replaceable></term> + <listitem> + <para> + The new default tablespace of the database. + </para> + + <para> + This form of the command cannot be executed inside a transaction block. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REFRESH COLLATION VERSION</literal></term> + <listitem> + <para> + Update the database collation version. See <xref + linkend="sql-altercollation-notes"/> for background. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + Set this database's session default for the specified configuration + parameter to the given value. If + <replaceable>value</replaceable> is <literal>DEFAULT</literal> + or, equivalently, <literal>RESET</literal> is used, the + database-specific setting is removed, so the system-wide default + setting will be inherited in new sessions. Use <literal>RESET + ALL</literal> to clear all database-specific settings. + <literal>SET FROM CURRENT</literal> saves the session's current value of + the parameter as the database-specific value. + </para> + + <para> + See <xref linkend="sql-set"/> and <xref linkend="runtime-config"/> + for more information about allowed parameter names + and values. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + It is also possible to tie a session default to a specific role + rather than to a database; see + <xref linkend="sql-alterrole"/>. + Role-specific settings override database-specific + ones if there is a conflict. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To disable index scans by default in the database + <literal>test</literal>: + +<programlisting> +ALTER DATABASE test SET enable_indexscan TO off; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>ALTER DATABASE</command> statement is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createdatabase"/></member> + <member><xref linkend="sql-dropdatabase"/></member> + <member><xref linkend="sql-set"/></member> + <member><xref linkend="sql-createtablespace"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_default_privileges.sgml b/doc/src/sgml/ref/alter_default_privileges.sgml new file mode 100644 index 0000000..8a60061 --- /dev/null +++ b/doc/src/sgml/ref/alter_default_privileges.sgml @@ -0,0 +1,259 @@ +<!-- +doc/src/sgml/ref/alter_default_privileges.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterdefaultprivileges"> + <indexterm zone="sql-alterdefaultprivileges"> + <primary>ALTER DEFAULT PRIVILEGES</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER DEFAULT PRIVILEGES</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER DEFAULT PRIVILEGES</refname> + <refpurpose>define default access privileges</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER DEFAULT PRIVILEGES + [ FOR { ROLE | USER } <replaceable>target_role</replaceable> [, ...] ] + [ IN SCHEMA <replaceable>schema_name</replaceable> [, ...] ] + <replaceable class="parameter">abbreviated_grant_or_revoke</replaceable> + +<phrase>where <replaceable class="parameter">abbreviated_grant_or_revoke</replaceable> is one of:</phrase> + +GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER } + [, ...] | ALL [ PRIVILEGES ] } + ON TABLES + TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ] + +GRANT { { USAGE | SELECT | UPDATE } + [, ...] | ALL [ PRIVILEGES ] } + ON SEQUENCES + TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ] + +GRANT { EXECUTE | ALL [ PRIVILEGES ] } + ON { FUNCTIONS | ROUTINES } + TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON TYPES + TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ] + +GRANT { USAGE | CREATE | ALL [ PRIVILEGES ] } + ON SCHEMAS + TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ] + +REVOKE [ GRANT OPTION FOR ] + { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER } + [, ...] | ALL [ PRIVILEGES ] } + ON TABLES + FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { USAGE | SELECT | UPDATE } + [, ...] | ALL [ PRIVILEGES ] } + ON SEQUENCES + FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { EXECUTE | ALL [ PRIVILEGES ] } + ON { FUNCTIONS | ROUTINES } + FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON TYPES + FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | CREATE | ALL [ PRIVILEGES ] } + ON SCHEMAS + FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] + [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-alterdefaultprivileges-description"> + <title>Description</title> + + <para> + <command>ALTER DEFAULT PRIVILEGES</command> allows you to set the privileges + that will be applied to objects created in the future. (It does not + affect privileges assigned to already-existing objects.) Currently, + only the privileges for schemas, tables (including views and foreign + tables), sequences, functions, and types (including domains) can be + altered. For this command, functions include aggregates and procedures. + The words <literal>FUNCTIONS</literal> and <literal>ROUTINES</literal> are + equivalent in this command. (<literal>ROUTINES</literal> is preferred + going forward as the standard term for functions and procedures taken + together. In earlier PostgreSQL releases, only the + word <literal>FUNCTIONS</literal> was allowed. It is not possible to set + default privileges for functions and procedures separately.) + </para> + + <para> + You can change default privileges only for objects that will be created by + yourself or by roles that you are a member of. The privileges can be set + globally (i.e., for all objects created in the current database), + or just for objects created in specified schemas. + </para> + + <para> + As explained in <xref linkend="ddl-priv"/>, + the default privileges for any object type normally grant all grantable + permissions to the object owner, and may grant some privileges to + <literal>PUBLIC</literal> as well. However, this behavior can be changed by + altering the global default privileges with + <command>ALTER DEFAULT PRIVILEGES</command>. + </para> + + <para> + Default privileges that are specified per-schema are added to whatever + the global default privileges are for the particular object type. + This means you cannot revoke privileges per-schema if they are granted + globally (either by default, or according to a previous <command>ALTER + DEFAULT PRIVILEGES</command> command that did not specify a schema). + Per-schema <literal>REVOKE</literal> is only useful to reverse the + effects of a previous per-schema <literal>GRANT</literal>. + </para> + + <refsect2> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>target_role</replaceable></term> + <listitem> + <para> + The name of an existing role of which the current role is a member. + Default access privileges are not inherited, so member roles + must use <command>SET ROLE</command> to access these privileges, + or <command>ALTER DEFAULT PRIVILEGES</command> must be run for + each member role. If <literal>FOR ROLE</literal> is omitted, + the current role is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>schema_name</replaceable></term> + <listitem> + <para> + The name of an existing schema. If specified, the default privileges + are altered for objects later created in that schema. + If <literal>IN SCHEMA</literal> is omitted, the global default privileges + are altered. + <literal>IN SCHEMA</literal> is not allowed when setting privileges + for schemas, since schemas can't be nested. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>role_name</replaceable></term> + <listitem> + <para> + The name of an existing role to grant or revoke privileges for. + This parameter, and all the other parameters in + <replaceable class="parameter">abbreviated_grant_or_revoke</replaceable>, + act as described under + <xref linkend="sql-grant"/> or + <xref linkend="sql-revoke"/>, + except that one is setting permissions for a whole class of objects + rather than specific named objects. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + </refsect1> + + <refsect1 id="sql-alterdefaultprivileges-notes"> + <title>Notes</title> + + <para> + Use <xref linkend="app-psql"/>'s <command>\ddp</command> command + to obtain information about existing assignments of default privileges. + The meaning of the privilege display is the same as explained for + <command>\dp</command> in <xref linkend="ddl-priv"/>. + </para> + + <para> + If you wish to drop a role for which the default privileges have been + altered, it is necessary to reverse the changes in its default privileges + or use <command>DROP OWNED BY</command> to get rid of the default privileges entry + for the role. + </para> + </refsect1> + + <refsect1 id="sql-alterdefaultprivileges-examples"> + <title>Examples</title> + + <para> + Grant SELECT privilege to everyone for all tables (and views) you + subsequently create in schema <literal>myschema</literal>, and allow + role <literal>webuser</literal> to INSERT into them too: + +<programlisting> +ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO PUBLIC; +ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT INSERT ON TABLES TO webuser; +</programlisting> + </para> + + <para> + Undo the above, so that subsequently-created tables won't have any + more permissions than normal: + +<programlisting> +ALTER DEFAULT PRIVILEGES IN SCHEMA myschema REVOKE SELECT ON TABLES FROM PUBLIC; +ALTER DEFAULT PRIVILEGES IN SCHEMA myschema REVOKE INSERT ON TABLES FROM webuser; +</programlisting> + </para> + + <para> + Remove the public EXECUTE permission that is normally granted on functions, + for all functions subsequently created by role <literal>admin</literal>: +<programlisting> +ALTER DEFAULT PRIVILEGES FOR ROLE admin REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; +</programlisting> + Note however that you <emphasis>cannot</emphasis> accomplish that effect + with a command limited to a single schema. This command has no effect, + unless it is undoing a matching <literal>GRANT</literal>: +<programlisting> +ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; +</programlisting> + That's because per-schema default privileges can only add privileges to + the global setting, not remove privileges granted by it. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER DEFAULT PRIVILEGES</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-revoke"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_domain.sgml b/doc/src/sgml/ref/alter_domain.sgml new file mode 100644 index 0000000..2db5372 --- /dev/null +++ b/doc/src/sgml/ref/alter_domain.sgml @@ -0,0 +1,365 @@ +<!-- +doc/src/sgml/ref/alter_domain.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterdomain"> + <indexterm zone="sql-alterdomain"> + <primary>ALTER DOMAIN</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER DOMAIN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER DOMAIN</refname> + <refpurpose> + change the definition of a domain + </refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + { SET DEFAULT <replaceable class="parameter">expression</replaceable> | DROP DEFAULT } +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + { SET | DROP } NOT NULL +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + ADD <replaceable class="parameter">domain_constraint</replaceable> [ NOT VALID ] +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + DROP CONSTRAINT [ IF EXISTS ] <replaceable class="parameter">constraint_name</replaceable> [ RESTRICT | CASCADE ] +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + RENAME CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> TO <replaceable class="parameter">new_constraint_name</replaceable> +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + VALIDATE CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER DOMAIN <replaceable class="parameter">name</replaceable> + SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER DOMAIN</command> changes the definition of an existing domain. + There are several sub-forms: + </para> + + <variablelist> + <varlistentry> + <term><literal>SET</literal>/<literal>DROP DEFAULT</literal></term> + <listitem> + <para> + These forms set or remove the default value for a domain. Note + that defaults only apply to subsequent <command>INSERT</command> + commands; they do not affect rows already in a table using the domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP NOT NULL</literal></term> + <listitem> + <para> + These forms change whether a domain is marked to allow NULL + values or to reject NULL values. You can only <literal>SET NOT NULL</literal> + when the columns using the domain contain no null values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD <replaceable class="parameter">domain_constraint</replaceable> [ NOT VALID ]</literal></term> + <listitem> + <para> + This form adds a new constraint to a domain using the same syntax as + <link linkend="sql-createdomain"><command>CREATE DOMAIN</command></link>. + When a new constraint is added to a domain, all columns using that + domain will be checked against the newly added constraint. These + checks can be suppressed by adding the new constraint using the + <literal>NOT VALID</literal> option; the constraint can later be made + valid using <command>ALTER DOMAIN ... VALIDATE CONSTRAINT</command>. + Newly inserted or updated rows are always checked against all + constraints, even those marked <literal>NOT VALID</literal>. + <literal>NOT VALID</literal> is only accepted for <literal>CHECK</literal> constraints. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP CONSTRAINT [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops constraints on a domain. + If <literal>IF EXISTS</literal> is specified and the constraint + does not exist, no error is thrown. In this case a notice is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME CONSTRAINT</literal></term> + <listitem> + <para> + This form changes the name of a constraint on a domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATE CONSTRAINT</literal></term> + <listitem> + <para> + This form validates a constraint previously added as + <literal>NOT VALID</literal>, that is, it verifies that all values in + table columns of the domain type satisfy the specified constraint. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OWNER</literal></term> + <listitem> + <para> + This form changes the owner of the domain to the specified user. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME</literal></term> + <listitem> + <para> + This form changes the name of the domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET SCHEMA</literal></term> + <listitem> + <para> + This form changes the schema of the domain. Any constraints + associated with the domain are moved into the new schema as well. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + You must own the domain to use <command>ALTER DOMAIN</command>. + To change the schema of a domain, you must also have + <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the domain's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the domain. + However, a superuser can alter ownership of any domain anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of an existing domain to + alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">domain_constraint</replaceable></term> + <listitem> + <para> + New domain constraint for the domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">constraint_name</replaceable></term> + <listitem> + <para> + Name of an existing constraint to drop or rename. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOT VALID</literal></term> + <listitem> + <para> + Do not verify existing stored data for constraint validity. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the constraint, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the constraint if there are any dependent + objects. This is the default behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_constraint_name</replaceable></term> + <listitem> + <para> + The new name for the constraint. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the domain. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Although <command>ALTER DOMAIN ADD CONSTRAINT</command> attempts to verify + that existing stored data satisfies the new constraint, this check is not + bulletproof, because the command cannot <quote>see</quote> table rows that + are newly inserted or updated and not yet committed. If there is a hazard + that concurrent operations might insert bad data, the way to proceed is to + add the constraint using the <literal>NOT VALID</literal> option, commit + that command, wait until all transactions started before that commit have + finished, and then issue <command>ALTER DOMAIN VALIDATE + CONSTRAINT</command> to search for data violating the constraint. This + method is reliable because once the constraint is committed, all new + transactions are guaranteed to enforce it against new values of the domain + type. + </para> + + <para> + Currently, <command>ALTER DOMAIN ADD CONSTRAINT</command>, <command>ALTER + DOMAIN VALIDATE CONSTRAINT</command>, and <command>ALTER DOMAIN SET NOT + NULL</command> will fail if the named domain or any derived domain is used + within a container-type column (a composite, array, or range column) in + any table in the database. They should eventually be improved to be able + to verify the new constraint for such nested values. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To add a <literal>NOT NULL</literal> constraint to a domain: +<programlisting> +ALTER DOMAIN zipcode SET NOT NULL; +</programlisting> + To remove a <literal>NOT NULL</literal> constraint from a domain: +<programlisting> +ALTER DOMAIN zipcode DROP NOT NULL; +</programlisting> + </para> + + <para> + To add a check constraint to a domain: +<programlisting> +ALTER DOMAIN zipcode ADD CONSTRAINT zipchk CHECK (char_length(VALUE) = 5); +</programlisting> + </para> + + <para> + To remove a check constraint from a domain: +<programlisting> +ALTER DOMAIN zipcode DROP CONSTRAINT zipchk; +</programlisting> + </para> + + <para> + To rename a check constraint on a domain: +<programlisting> +ALTER DOMAIN zipcode RENAME CONSTRAINT zipchk TO zip_check; +</programlisting> + </para> + + <para> + To move the domain into a different schema: +<programlisting> +ALTER DOMAIN zipcode SET SCHEMA customers; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-alterdomain-compatibility"> + <title>Compatibility</title> + + <para> + <command>ALTER DOMAIN</command> conforms to the <acronym>SQL</acronym> + standard, except for the <literal>OWNER</literal>, <literal>RENAME</literal>, <literal>SET SCHEMA</literal>, and + <literal>VALIDATE CONSTRAINT</literal> variants, which are + <productname>PostgreSQL</productname> extensions. The <literal>NOT VALID</literal> + clause of the <literal>ADD CONSTRAINT</literal> variant is also a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1 id="sql-alterdomain-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createdomain"/></member> + <member><xref linkend="sql-dropdomain"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_event_trigger.sgml b/doc/src/sgml/ref/alter_event_trigger.sgml new file mode 100644 index 0000000..ef5253b --- /dev/null +++ b/doc/src/sgml/ref/alter_event_trigger.sgml @@ -0,0 +1,105 @@ +<!-- +doc/src/sgml/ref/alter_event_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altereventtrigger"> + <indexterm zone="sql-altereventtrigger"> + <primary>ALTER EVENT TRIGGER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER EVENT TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER EVENT TRIGGER</refname> + <refpurpose>change the definition of an event trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER EVENT TRIGGER <replaceable class="parameter">name</replaceable> DISABLE +ALTER EVENT TRIGGER <replaceable class="parameter">name</replaceable> ENABLE [ REPLICA | ALWAYS ] +ALTER EVENT TRIGGER <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER EVENT TRIGGER <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER EVENT TRIGGER</command> changes properties of an + existing event trigger. + </para> + + <para> + You must be superuser to alter an event trigger. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing trigger to alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the event trigger. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the event trigger. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] TRIGGER</literal></term> + <listitem> + <para> + These forms configure the firing of event triggers. A disabled trigger + is still known to the system, but is not executed when its triggering + event occurs. See also <xref linkend="guc-session-replication-role"/>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-alterventtrigger-compatibility"> + <title>Compatibility</title> + + <para> + There is no <command>ALTER EVENT TRIGGER</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createeventtrigger"/></member> + <member><xref linkend="sql-dropeventtrigger"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_extension.sgml b/doc/src/sgml/ref/alter_extension.sgml new file mode 100644 index 0000000..c819c7b --- /dev/null +++ b/doc/src/sgml/ref/alter_extension.sgml @@ -0,0 +1,334 @@ +<!-- +doc/src/sgml/ref/alter_extension.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterextension"> + <indexterm zone="sql-alterextension"> + <primary>ALTER EXTENSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER EXTENSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER EXTENSION</refname> + <refpurpose> + change the definition of an extension + </refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER EXTENSION <replaceable class="parameter">name</replaceable> UPDATE [ TO <replaceable class="parameter">new_version</replaceable> ] +ALTER EXTENSION <replaceable class="parameter">name</replaceable> SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER EXTENSION <replaceable class="parameter">name</replaceable> ADD <replaceable class="parameter">member_object</replaceable> +ALTER EXTENSION <replaceable class="parameter">name</replaceable> DROP <replaceable class="parameter">member_object</replaceable> + +<phrase>where <replaceable class="parameter">member_object</replaceable> is:</phrase> + + ACCESS METHOD <replaceable class="parameter">object_name</replaceable> | + AGGREGATE <replaceable class="parameter">aggregate_name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) | + CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) | + COLLATION <replaceable class="parameter">object_name</replaceable> | + CONVERSION <replaceable class="parameter">object_name</replaceable> | + DOMAIN <replaceable class="parameter">object_name</replaceable> | + EVENT TRIGGER <replaceable class="parameter">object_name</replaceable> | + FOREIGN DATA WRAPPER <replaceable class="parameter">object_name</replaceable> | + FOREIGN TABLE <replaceable class="parameter">object_name</replaceable> | + FUNCTION <replaceable class="parameter">function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + MATERIALIZED VIEW <replaceable class="parameter">object_name</replaceable> | + OPERATOR <replaceable class="parameter">operator_name</replaceable> (<replaceable class="parameter">left_type</replaceable>, <replaceable class="parameter">right_type</replaceable>) | + OPERATOR CLASS <replaceable class="parameter">object_name</replaceable> USING <replaceable class="parameter">index_method</replaceable> | + OPERATOR FAMILY <replaceable class="parameter">object_name</replaceable> USING <replaceable class="parameter">index_method</replaceable> | + [ PROCEDURAL ] LANGUAGE <replaceable class="parameter">object_name</replaceable> | + PROCEDURE <replaceable class="parameter">procedure_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + ROUTINE <replaceable class="parameter">routine_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + SCHEMA <replaceable class="parameter">object_name</replaceable> | + SEQUENCE <replaceable class="parameter">object_name</replaceable> | + SERVER <replaceable class="parameter">object_name</replaceable> | + TABLE <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH CONFIGURATION <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH DICTIONARY <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH PARSER <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH TEMPLATE <replaceable class="parameter">object_name</replaceable> | + TRANSFORM FOR <replaceable>type_name</replaceable> LANGUAGE <replaceable>lang_name</replaceable> | + TYPE <replaceable class="parameter">object_name</replaceable> | + VIEW <replaceable class="parameter">object_name</replaceable> + +<phrase>and <replaceable>aggregate_signature</replaceable> is:</phrase> + +* | +[ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] | +[ [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] ] ORDER BY [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER EXTENSION</command> changes the definition of an installed + extension. There are several subforms: + + <variablelist> + <varlistentry> + <term><literal>UPDATE</literal></term> + <listitem> + <para> + This form updates the extension to a newer version. The extension + must supply a suitable update script (or series of scripts) that can + modify the currently-installed version into the requested version. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET SCHEMA</literal></term> + <listitem> + <para> + This form moves the extension's objects into another schema. The + extension has to be <firstterm>relocatable</firstterm> for this command to + succeed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD <replaceable class="parameter">member_object</replaceable></literal></term> + <listitem> + <para> + This form adds an existing object to the extension. This is mainly + useful in extension update scripts. The object will subsequently + be treated as a member of the extension; notably, it can only be + dropped by dropping the extension. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP <replaceable class="parameter">member_object</replaceable></literal></term> + <listitem> + <para> + This form removes a member object from the extension. This is mainly + useful in extension update scripts. The object is not dropped, only + disassociated from the extension. + </para> + </listitem> + </varlistentry> + </variablelist> + + See <xref linkend="extend-extensions"/> for more information about these + operations. + </para> + + <para> + You must own the extension to use <command>ALTER EXTENSION</command>. + The <literal>ADD</literal>/<literal>DROP</literal> forms require ownership of the + added/dropped object as well. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an installed extension. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_version</replaceable></term> + <listitem> + <para> + The desired new version of the extension. This can be written as + either an identifier or a string literal. If not specified, + <command>ALTER EXTENSION UPDATE</command> attempts to update to whatever is + shown as the default version in the extension's control file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the extension. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">object_name</replaceable></term> + <term><replaceable class="parameter">aggregate_name</replaceable></term> + <term><replaceable class="parameter">function_name</replaceable></term> + <term><replaceable class="parameter">operator_name</replaceable></term> + <term><replaceable class="parameter">procedure_name</replaceable></term> + <term><replaceable class="parameter">routine_name</replaceable></term> + <listitem> + <para> + The name of an object to be added to or removed from the extension. + Names of tables, + aggregates, domains, foreign tables, functions, operators, + operator classes, operator families, procedures, routines, sequences, text search objects, + types, and views can be schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>source_type</replaceable></term> + <listitem> + <para> + The name of the source data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>target_type</replaceable></term> + <listitem> + <para> + The name of the target data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of a function, procedure, or aggregate + argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Note that <command>ALTER EXTENSION</command> does not actually pay + any attention to <literal>OUT</literal> arguments, since only the input + arguments are needed to determine the function's identity. + So it is sufficient to list the <literal>IN</literal>, <literal>INOUT</literal>, + and <literal>VARIADIC</literal> arguments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of a function, procedure, or aggregate argument. + Note that <command>ALTER EXTENSION</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type of a function, procedure, or aggregate argument. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">left_type</replaceable></term> + <term><replaceable class="parameter">right_type</replaceable></term> + <listitem> + <para> + The data type(s) of the operator's arguments (optionally + schema-qualified). Write <literal>NONE</literal> for the missing argument + of a prefix operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROCEDURAL</literal></term> + + <listitem> + <para> + This is a noise word. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>type_name</replaceable></term> + + <listitem> + <para> + The name of the data type of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lang_name</replaceable></term> + + <listitem> + <para> + The name of the language of the transform. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To update the <literal>hstore</literal> extension to version 2.0: +<programlisting> +ALTER EXTENSION hstore UPDATE TO '2.0'; +</programlisting> + </para> + + <para> + To change the schema of the <literal>hstore</literal> extension + to <literal>utils</literal>: +<programlisting> +ALTER EXTENSION hstore SET SCHEMA utils; +</programlisting> + </para> + + <para> + To add an existing function to the <literal>hstore</literal> extension: +<programlisting> +ALTER EXTENSION hstore ADD FUNCTION populate_record(anyelement, hstore); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER EXTENSION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1 id="sql-alterextension-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createextension"/></member> + <member><xref linkend="sql-dropextension"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_foreign_data_wrapper.sgml b/doc/src/sgml/ref/alter_foreign_data_wrapper.sgml new file mode 100644 index 0000000..54f34c2 --- /dev/null +++ b/doc/src/sgml/ref/alter_foreign_data_wrapper.sgml @@ -0,0 +1,188 @@ +<!-- +doc/src/sgml/ref/alter_foreign_data_wrapper.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterforeigndatawrapper"> + <indexterm zone="sql-alterforeigndatawrapper"> + <primary>ALTER FOREIGN DATA WRAPPER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER FOREIGN DATA WRAPPER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER FOREIGN DATA WRAPPER</refname> + <refpurpose>change the definition of a foreign-data wrapper</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER FOREIGN DATA WRAPPER <replaceable class="parameter">name</replaceable> + [ HANDLER <replaceable class="parameter">handler_function</replaceable> | NO HANDLER ] + [ VALIDATOR <replaceable class="parameter">validator_function</replaceable> | NO VALIDATOR ] + [ OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ]) ] +ALTER FOREIGN DATA WRAPPER <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER FOREIGN DATA WRAPPER <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER FOREIGN DATA WRAPPER</command> changes the + definition of a foreign-data wrapper. The first form of the + command changes the support functions or the generic options of the + foreign-data wrapper (at least one clause is required). The second + form changes the owner of the foreign-data wrapper. + </para> + + <para> + Only superusers can alter foreign-data wrappers. Additionally, + only superusers can own foreign-data wrappers. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing foreign-data wrapper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HANDLER <replaceable class="parameter">handler_function</replaceable></literal></term> + <listitem> + <para> + Specifies a new handler function for the foreign-data wrapper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO HANDLER</literal></term> + <listitem> + <para> + This is used to specify that the foreign-data wrapper should no + longer have a handler function. + </para> + <para> + Note that foreign tables that use a foreign-data wrapper with no + handler cannot be accessed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATOR <replaceable class="parameter">validator_function</replaceable></literal></term> + <listitem> + <para> + Specifies a new validator function for the foreign-data wrapper. + </para> + + <para> + Note that it is possible that pre-existing options of the foreign-data + wrapper, or of dependent servers, user mappings, or foreign tables, are + invalid according to the new validator. <productname>PostgreSQL</productname> does + not check for this. It is up to the user to make sure that these + options are correct before using the modified foreign-data wrapper. + However, any options specified in this <command>ALTER FOREIGN DATA + WRAPPER</command> command will be checked using the new validator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO VALIDATOR</literal></term> + <listitem> + <para> + This is used to specify that the foreign-data wrapper should no + longer have a validator function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] )</literal></term> + <listitem> + <para> + Change options for the foreign-data + wrapper. <literal>ADD</literal>, <literal>SET</literal>, and <literal>DROP</literal> + specify the action to be performed. <literal>ADD</literal> is assumed + if no operation is explicitly specified. Option names must be + unique; names and values are also validated using the foreign + data wrapper's validator function, if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the foreign-data wrapper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the foreign-data wrapper. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change a foreign-data wrapper <literal>dbi</literal>, add + option <literal>foo</literal>, drop <literal>bar</literal>: +<programlisting> +ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP 'bar'); +</programlisting> + </para> + + <para> + Change the foreign-data wrapper <literal>dbi</literal> validator + to <literal>bob.myvalidator</literal>: +<programlisting> +ALTER FOREIGN DATA WRAPPER dbi VALIDATOR bob.myvalidator; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER FOREIGN DATA WRAPPER</command> conforms to ISO/IEC + 9075-9 (SQL/MED), except that the <literal>HANDLER</literal>, + <literal>VALIDATOR</literal>, <literal>OWNER TO</literal>, and <literal>RENAME</literal> + clauses are extensions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createforeigndatawrapper"/></member> + <member><xref linkend="sql-dropforeigndatawrapper"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_foreign_table.sgml b/doc/src/sgml/ref/alter_foreign_table.sgml new file mode 100644 index 0000000..5d373ae --- /dev/null +++ b/doc/src/sgml/ref/alter_foreign_table.sgml @@ -0,0 +1,556 @@ +<!-- +doc/src/sgml/rel/alter_foreign_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterforeigntable"> + <indexterm zone="sql-alterforeigntable"> + <primary>ALTER FOREIGN TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER FOREIGN TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER FOREIGN TABLE</refname> + <refpurpose>change the definition of a foreign table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER FOREIGN TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] + <replaceable class="parameter">action</replaceable> [, ... ] +ALTER FOREIGN TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] + RENAME [ COLUMN ] <replaceable class="parameter">column_name</replaceable> TO <replaceable class="parameter">new_column_name</replaceable> +ALTER FOREIGN TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER FOREIGN TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + SET SCHEMA <replaceable class="parameter">new_schema</replaceable> + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + ADD [ COLUMN ] <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + DROP [ COLUMN ] [ IF EXISTS ] <replaceable class="parameter">column_name</replaceable> [ RESTRICT | CASCADE ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> [ SET DATA ] TYPE <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET DEFAULT <replaceable class="parameter">expression</replaceable> + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> DROP DEFAULT + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> { SET | DROP } NOT NULL + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STATISTICS <replaceable class="parameter">integer</replaceable> + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET ( <replaceable class="parameter">attribute_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> RESET ( <replaceable class="parameter">attribute_option</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ]) + ADD <replaceable class="parameter">table_constraint</replaceable> [ NOT VALID ] + VALIDATE CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> + DROP CONSTRAINT [ IF EXISTS ] <replaceable class="parameter">constraint_name</replaceable> [ RESTRICT | CASCADE ] + DISABLE TRIGGER [ <replaceable class="parameter">trigger_name</replaceable> | ALL | USER ] + ENABLE TRIGGER [ <replaceable class="parameter">trigger_name</replaceable> | ALL | USER ] + ENABLE REPLICA TRIGGER <replaceable class="parameter">trigger_name</replaceable> + ENABLE ALWAYS TRIGGER <replaceable class="parameter">trigger_name</replaceable> + SET WITHOUT OIDS + INHERIT <replaceable class="parameter">parent_table</replaceable> + NO INHERIT <replaceable class="parameter">parent_table</replaceable> + OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ]) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER FOREIGN TABLE</command> changes the definition of an + existing foreign table. There are several subforms: + + <variablelist> + <varlistentry> + <term><literal>ADD COLUMN</literal></term> + <listitem> + <para> + This form adds a new column to the foreign table, using the same syntax as + <link linkend="sql-createforeigntable"><command>CREATE FOREIGN TABLE</command></link>. + Unlike the case when adding a column to a regular table, nothing happens + to the underlying storage: this action simply declares that + some new column is now accessible through the foreign table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP COLUMN [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops a column from a foreign table. + You will need to say <literal>CASCADE</literal> if + anything outside the table depends on the column; for example, + views. + If <literal>IF EXISTS</literal> is specified and the column + does not exist, no error is thrown. In this case a notice + is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET DATA TYPE</literal></term> + <listitem> + <para> + This form changes the type of a column of a foreign table. + Again, this has no effect on any underlying storage: this action simply + changes the type that <productname>PostgreSQL</productname> believes the column to + have. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP DEFAULT</literal></term> + <listitem> + <para> + These forms set or remove the default value for a column. + Default values only apply in subsequent <command>INSERT</command> + or <command>UPDATE</command> commands; they do not cause rows already in the + table to change. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP NOT NULL</literal></term> + <listitem> + <para> + Mark a column as allowing, or not allowing, null values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET STATISTICS</literal></term> + <listitem> + <para> + This form + sets the per-column statistics-gathering target for subsequent + <link linkend="sql-analyze"><command>ANALYZE</command></link> operations. + See the similar form of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> + for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">attribute_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] )</literal></term> + <term><literal>RESET ( <replaceable class="parameter">attribute_option</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + This form sets or resets per-attribute options. + See the similar form of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> + for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>SET STORAGE</literal> + </term> + <listitem> + <para> + This form sets the storage mode for a column. + See the similar form of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> + for more details. + Note that the storage mode has no effect unless the table's + foreign-data wrapper chooses to pay attention to it. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD <replaceable class="parameter">table_constraint</replaceable> [ NOT VALID ]</literal></term> + <listitem> + <para> + This form adds a new constraint to a foreign table, using the same + syntax as <link linkend="sql-createforeigntable"><command>CREATE FOREIGN TABLE</command></link>. + Currently only <literal>CHECK</literal> constraints are supported. + </para> + + <para> + Unlike the case when adding a constraint to a regular table, nothing is + done to verify the constraint is correct; rather, this action simply + declares that some new condition should be assumed to hold for all rows + in the foreign table. (See the discussion + in <link linkend="sql-createforeigntable"><command>CREATE FOREIGN TABLE</command></link>.) + If the constraint is marked <literal>NOT VALID</literal>, then it isn't + assumed to hold, but is only recorded for possible future use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATE CONSTRAINT</literal></term> + <listitem> + <para> + This form marks as valid a constraint that was previously marked + as <literal>NOT VALID</literal>. No action is taken to verify the + constraint, but future queries will assume that it holds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP CONSTRAINT [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops the specified constraint on a foreign table. + If <literal>IF EXISTS</literal> is specified and the constraint + does not exist, no error is thrown. + In this case a notice is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] TRIGGER</literal></term> + <listitem> + <para> + These forms configure the firing of trigger(s) belonging to the foreign + table. See the similar form of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> for more + details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET WITHOUT OIDS</literal></term> + <listitem> + <para> + Backward compatibility syntax for removing the <literal>oid</literal> + system column. As <literal>oid</literal> system columns cannot be added + anymore, this never has an effect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INHERIT <replaceable class="parameter">parent_table</replaceable></literal></term> + <listitem> + <para> + This form adds the target foreign table as a new child of the specified + parent table. + See the similar form of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> + for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO INHERIT <replaceable class="parameter">parent_table</replaceable></literal></term> + <listitem> + <para> + This form removes the target foreign table from the list of children of + the specified parent table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OWNER</literal></term> + <listitem> + <para> + This form changes the owner of the foreign table to the + specified user. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] )</literal></term> + <listitem> + <para> + Change options for the foreign table or one of its columns. + <literal>ADD</literal>, <literal>SET</literal>, and <literal>DROP</literal> + specify the action to be performed. <literal>ADD</literal> is assumed + if no operation is explicitly specified. Duplicate option names are not + allowed (although it's OK for a table option and a column option to have + the same name). Option names and values are also validated using the + foreign data wrapper library. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME</literal></term> + <listitem> + <para> + The <literal>RENAME</literal> forms change the name of a foreign table + or the name of an individual column in a foreign table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET SCHEMA</literal></term> + <listitem> + <para> + This form moves the foreign table into another schema. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + All the actions except <literal>RENAME</literal> and <literal>SET SCHEMA</literal> + can be combined into + a list of multiple alterations to apply in parallel. For example, it + is possible to add several columns and/or alter the type of several + columns in a single command. + </para> + + <para> + If the command is written as <literal>ALTER FOREIGN TABLE IF EXISTS ...</literal> + and the foreign table does not exist, no error is thrown. A notice is + issued in this case. + </para> + + <para> + You must own the table to use <command>ALTER FOREIGN TABLE</command>. + To change the schema of a foreign table, you must also have + <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the table's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the table. + However, a superuser can alter ownership of any table anyway.) + To add a column or alter a column type, you must also + have <literal>USAGE</literal> privilege on the data type. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of an existing foreign table to + alter. If <literal>ONLY</literal> is specified before the table name, only + that table is altered. If <literal>ONLY</literal> is not specified, the table + and all its descendant tables (if any) are altered. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + Name of a new or existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_column_name</replaceable></term> + <listitem> + <para> + New name for an existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + New name for the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + Data type of the new column, or new data type for an existing + column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_constraint</replaceable></term> + <listitem> + <para> + New table constraint for the foreign table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">constraint_name</replaceable></term> + <listitem> + <para> + Name of an existing constraint to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the dropped column + or constraint (for example, views referencing the column), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the column or constraint if there are any dependent + objects. This is the default behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">trigger_name</replaceable></term> + <listitem> + <para> + Name of a single trigger to disable or enable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Disable or enable all triggers belonging to the foreign table. (This + requires superuser privilege if any of the triggers are internally + generated triggers. The core system does not add such triggers to + foreign tables, but add-on code could do so.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USER</literal></term> + <listitem> + <para> + Disable or enable all triggers belonging to the foreign table except + for internally generated triggers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">parent_table</replaceable></term> + <listitem> + <para> + A parent table to associate or de-associate with this foreign table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The name of the schema to which the table will be moved. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The key word <literal>COLUMN</literal> is noise and can be omitted. + </para> + + <para> + Consistency with the foreign server is not checked when a column is added + or removed with <literal>ADD COLUMN</literal> or + <literal>DROP COLUMN</literal>, a <literal>NOT NULL</literal> + or <literal>CHECK</literal> constraint is added, or a column type is changed + with <literal>SET DATA TYPE</literal>. It is the user's responsibility to ensure + that the table definition matches the remote side. + </para> + + <para> + Refer to <link linkend="sql-createforeigntable"><command>CREATE FOREIGN TABLE</command></link> for a further description of valid + parameters. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To mark a column as not-null: +<programlisting> +ALTER FOREIGN TABLE distributors ALTER COLUMN street SET NOT NULL; +</programlisting> + </para> + + <para> + To change options of a foreign table: +<programlisting> +ALTER FOREIGN TABLE myschema.distributors OPTIONS (ADD opt1 'value', SET opt2 'value2', DROP opt3); +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The forms <literal>ADD</literal>, <literal>DROP</literal>, + and <literal>SET DATA TYPE</literal> + conform with the SQL standard. The other forms are + <productname>PostgreSQL</productname> extensions of the SQL standard. + Also, the ability to specify more than one manipulation in a single + <command>ALTER FOREIGN TABLE</command> command is an extension. + </para> + + <para> + <command>ALTER FOREIGN TABLE DROP COLUMN</command> can be used to drop the only + column of a foreign table, leaving a zero-column table. This is an + extension of SQL, which disallows zero-column foreign tables. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createforeigntable"/></member> + <member><xref linkend="sql-dropforeigntable"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_function.sgml b/doc/src/sgml/ref/alter_function.sgml new file mode 100644 index 0000000..2e8e116 --- /dev/null +++ b/doc/src/sgml/ref/alter_function.sgml @@ -0,0 +1,392 @@ +<!-- +doc/src/sgml/ref/alter_function.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterfunction"> + <indexterm zone="sql-alterfunction"> + <primary>ALTER FUNCTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER FUNCTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER FUNCTION</refname> + <refpurpose>change the definition of a function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + <replaceable class="parameter">action</replaceable> [ ... ] [ RESTRICT ] +ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + RENAME TO <replaceable>new_name</replaceable> +ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + SET SCHEMA <replaceable>new_schema</replaceable> +ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + [ NO ] DEPENDS ON EXTENSION <replaceable>extension_name</replaceable> + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT + IMMUTABLE | STABLE | VOLATILE + [ NOT ] LEAKPROOF + [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER + PARALLEL { UNSAFE | RESTRICTED | SAFE } + COST <replaceable class="parameter">execution_cost</replaceable> + ROWS <replaceable class="parameter">result_rows</replaceable> + SUPPORT <replaceable class="parameter">support_function</replaceable> + SET <replaceable class="parameter">configuration_parameter</replaceable> { TO | = } { <replaceable class="parameter">value</replaceable> | DEFAULT } + SET <replaceable class="parameter">configuration_parameter</replaceable> FROM CURRENT + RESET <replaceable class="parameter">configuration_parameter</replaceable> + RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER FUNCTION</command> changes the definition of a + function. + </para> + + <para> + You must own the function to use <command>ALTER FUNCTION</command>. + To change a function's schema, you must also have <literal>CREATE</literal> + privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the function's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the function. + However, a superuser can alter ownership of any function anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing function. If no + argument list is specified, the name must be unique in its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Note that <command>ALTER FUNCTION</command> does not actually pay + any attention to <literal>OUT</literal> arguments, since only the input + arguments are needed to determine the function's identity. + So it is sufficient to list the <literal>IN</literal>, <literal>INOUT</literal>, + and <literal>VARIADIC</literal> arguments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>ALTER FUNCTION</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the function's arguments (optionally + schema-qualified), if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the function. Note that if the function is + marked <literal>SECURITY DEFINER</literal>, it will subsequently + execute as the new owner. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable></literal></term> + <term><literal>NO DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable></literal></term> + <listitem> + <para> + This form marks the function as dependent on the extension, or no longer + dependent on that extension if <literal>NO</literal> is specified. + A function that's marked as dependent on an extension is dropped when the + extension is dropped, even if <literal>CASCADE</literal> is not specified. + A function can depend upon multiple extensions, and will be dropped when + any one of those extensions is dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CALLED ON NULL INPUT</literal></term> + <term><literal>RETURNS NULL ON NULL INPUT</literal></term> + <term><literal>STRICT</literal></term> + + <listitem> + <para><literal>CALLED ON NULL INPUT</literal> changes the function so + that it will be invoked when some or all of its arguments are + null. <literal>RETURNS NULL ON NULL INPUT</literal> or + <literal>STRICT</literal> changes the function so that it is not + invoked if any of its arguments are null; instead, a null result + is assumed automatically. See <xref linkend="sql-createfunction"/> + for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IMMUTABLE</literal></term> + <term><literal>STABLE</literal></term> + <term><literal>VOLATILE</literal></term> + + <listitem> + <para> + Change the volatility of the function to the specified setting. + See <xref linkend="sql-createfunction"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><optional> EXTERNAL </optional> SECURITY INVOKER</literal></term> + <term><literal><optional> EXTERNAL </optional> SECURITY DEFINER</literal></term> + + <listitem> + <para> + Change whether the function is a security definer or not. The + key word <literal>EXTERNAL</literal> is ignored for SQL + conformance. See <xref linkend="sql-createfunction"/> for more information about + this capability. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARALLEL</literal></term> + + <listitem> + <para> + Change whether the function is deemed safe for parallelism. + See <xref linkend="sql-createfunction"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LEAKPROOF</literal></term> + <listitem> + <para> + Change whether the function is considered leakproof or not. + See <xref linkend="sql-createfunction"/> for more information about + this capability. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term> + + <listitem> + <para> + Change the estimated execution cost of the function. + See <xref linkend="sql-createfunction"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term> + + <listitem> + <para> + Change the estimated number of rows returned by a set-returning + function. See <xref linkend="sql-createfunction"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SUPPORT</literal> <replaceable class="parameter">support_function</replaceable></term> + + <listitem> + <para> + Set or change the planner support function to use for this function. + See <xref linkend="xfunc-optimization"/> for details. You must be + superuser to use this option. + </para> + + <para> + This option cannot be used to remove the support function altogether, + since it must name a new support function. Use <command>CREATE OR + REPLACE FUNCTION</command> if you need to do that. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + Add or change the assignment to be made to a configuration parameter + when the function is called. If + <replaceable>value</replaceable> is <literal>DEFAULT</literal> + or, equivalently, <literal>RESET</literal> is used, the function-local + setting is removed, so that the function executes with the value + present in its environment. Use <literal>RESET + ALL</literal> to clear all function-local settings. + <literal>SET FROM CURRENT</literal> saves the value of the parameter that + is current when <command>ALTER FUNCTION</command> is executed as the value + to be applied when the function is entered. + </para> + + <para> + See <xref linkend="sql-set"/> and + <xref linkend="runtime-config"/> + for more information about allowed parameter names and values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + Ignored for conformance with the SQL standard. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the function <literal>sqrt</literal> for type + <type>integer</type> to <literal>square_root</literal>: +<programlisting> +ALTER FUNCTION sqrt(integer) RENAME TO square_root; +</programlisting> + </para> + + <para> + To change the owner of the function <literal>sqrt</literal> for type + <type>integer</type> to <literal>joe</literal>: +<programlisting> +ALTER FUNCTION sqrt(integer) OWNER TO joe; +</programlisting> + </para> + + <para> + To change the schema of the function <literal>sqrt</literal> for type + <type>integer</type> to <literal>maths</literal>: +<programlisting> +ALTER FUNCTION sqrt(integer) SET SCHEMA maths; +</programlisting> + </para> + + <para> + To mark the function <literal>sqrt</literal> for type + <type>integer</type> as being dependent on the extension + <literal>mathlib</literal>: +<programlisting> +ALTER FUNCTION sqrt(integer) DEPENDS ON EXTENSION mathlib; +</programlisting> + </para> + + <para> + To adjust the search path that is automatically set for a function: +<programlisting> +ALTER FUNCTION check_password(text) SET search_path = admin, pg_temp; +</programlisting> + </para> + + <para> + To disable automatic setting of <varname>search_path</varname> for a function: +<programlisting> +ALTER FUNCTION check_password(text) RESET search_path; +</programlisting> + The function will now execute with whatever search path is used by its + caller. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This statement is partially compatible with the <command>ALTER + FUNCTION</command> statement in the SQL standard. The standard allows more + properties of a function to be modified, but does not provide the + ability to rename a function, make a function a security definer, + attach configuration parameter values to a function, + or change the owner, schema, or volatility of a function. The standard also + requires the <literal>RESTRICT</literal> key word, which is optional in + <productname>PostgreSQL</productname>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-dropfunction"/></member> + <member><xref linkend="sql-alterprocedure"/></member> + <member><xref linkend="sql-alterroutine"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_group.sgml b/doc/src/sgml/ref/alter_group.sgml new file mode 100644 index 0000000..fa4a8df --- /dev/null +++ b/doc/src/sgml/ref/alter_group.sgml @@ -0,0 +1,135 @@ +<!-- +doc/src/sgml/ref/alter_group.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altergroup"> + <indexterm zone="sql-altergroup"> + <primary>ALTER GROUP</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER GROUP</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER GROUP</refname> + <refpurpose>change role name or membership</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER GROUP <replaceable class="parameter">role_specification</replaceable> ADD USER <replaceable class="parameter">user_name</replaceable> [, ... ] +ALTER GROUP <replaceable class="parameter">role_specification</replaceable> DROP USER <replaceable class="parameter">user_name</replaceable> [, ... ] + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + <replaceable class="parameter">role_name</replaceable> + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER + +ALTER GROUP <replaceable class="parameter">group_name</replaceable> RENAME TO <replaceable>new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER GROUP</command> changes the attributes of a user group. + This is an obsolete command, though still accepted for backwards + compatibility, because groups (and users too) have been superseded by the + more general concept of roles. + </para> + + <para> + The first two variants add users to a group or remove them from a group. + (Any role can play the part of either a <quote>user</quote> or a + <quote>group</quote> for this purpose.) These variants are effectively + equivalent to granting or revoking membership in the role named as the + <quote>group</quote>; so the preferred way to do this is to use + <link linkend="sql-grant"><command>GRANT</command></link> or + <link linkend="sql-revoke"><command>REVOKE</command></link>. + </para> + + <para> + The third variant changes the name of the group. This is exactly + equivalent to renaming the role with + <link linkend="sql-alterrole"><command>ALTER ROLE</command></link>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">group_name</replaceable></term> + <listitem> + <para> + The name of the group (role) to modify. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + Users (roles) that are to be added to or removed from the group. + The users must already exist; <command>ALTER GROUP</command> does not + create or drop users. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_name</replaceable></term> + <listitem> + <para> + The new name of the group. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + <para> + Add users to a group: + +<programlisting> +ALTER GROUP staff ADD USER karl, john; +</programlisting> + + Remove a user from a group: + +<programlisting> +ALTER GROUP workers DROP USER beth; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER GROUP</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-revoke"/></member> + <member><xref linkend="sql-alterrole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_index.sgml b/doc/src/sgml/ref/alter_index.sgml new file mode 100644 index 0000000..e26efec --- /dev/null +++ b/doc/src/sgml/ref/alter_index.sgml @@ -0,0 +1,323 @@ +<!-- +doc/src/sgml/ref/alter_index.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterindex"> + <indexterm zone="sql-alterindex"> + <primary>ALTER INDEX</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER INDEX</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER INDEX</refname> + <refpurpose>change the definition of an index</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER INDEX [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER INDEX [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> +ALTER INDEX <replaceable class="parameter">name</replaceable> ATTACH PARTITION <replaceable class="parameter">index_name</replaceable> +ALTER INDEX <replaceable class="parameter">name</replaceable> [ NO ] DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable> +ALTER INDEX [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) +ALTER INDEX [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] ) +ALTER INDEX [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ALTER [ COLUMN ] <replaceable class="parameter">column_number</replaceable> + SET STATISTICS <replaceable class="parameter">integer</replaceable> +ALTER INDEX ALL IN TABLESPACE <replaceable class="parameter">name</replaceable> [ OWNED BY <replaceable class="parameter">role_name</replaceable> [, ... ] ] + SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> [ NOWAIT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER INDEX</command> changes the definition of an existing index. + There are several subforms described below. Note that the lock level required + may differ for each subform. An <literal>ACCESS EXCLUSIVE</literal> lock is held + unless explicitly noted. When multiple subcommands are listed, the lock + held will be the strictest one required from any subcommand. + + <variablelist> + + <varlistentry> + <term><literal>RENAME</literal></term> + <listitem> + <para> + The <literal>RENAME</literal> form changes the name of the index. + If the index is associated with a table constraint (either + <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, + or <literal>EXCLUDE</literal>), the constraint is renamed as well. + There is no effect on the stored data. + </para> + <para> + Renaming an index acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> + lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET TABLESPACE</literal></term> + <listitem> + <para> + This form changes the index's tablespace to the specified tablespace and + moves the data file(s) associated with the index to the new tablespace. + To change the tablespace of an index, you must own the index and have + <literal>CREATE</literal> privilege on the new tablespace. + All indexes in the current database in a tablespace can be moved by using + the <literal>ALL IN TABLESPACE</literal> form, which will lock all + indexes to be moved and then move each one. This form also supports + <literal>OWNED BY</literal>, which will only move indexes owned by the + roles specified. If the <literal>NOWAIT</literal> option is specified + then the command will fail if it is unable to acquire all of the locks + required immediately. Note that system catalogs will not be moved by + this command, use <command>ALTER DATABASE</command> or explicit + <command>ALTER INDEX</command> invocations instead if desired. + See also + <link linkend="sql-createtablespace"><command>CREATE TABLESPACE</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ATTACH PARTITION</literal></term> + <listitem> + <para> + Causes the named index to become attached to the altered index. + The named index must be on a partition of the table containing the + index being altered, and have an equivalent definition. An attached + index cannot be dropped by itself, and will automatically be dropped + if its parent index is dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable></literal></term> + <term><literal>NO DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable></literal></term> + <listitem> + <para> + This form marks the index as dependent on the extension, or no longer + dependent on that extension if <literal>NO</literal> is specified. + An index that's marked as dependent on an extension is automatically + dropped when the extension is dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This form changes one or more index-method-specific storage parameters + for the index. See + <link linkend="sql-createindex"><command>CREATE INDEX</command></link> + for details on the available parameters. Note that the index contents + will not be modified immediately by this command; depending on the + parameter you might need to rebuild the index with + <link linkend="sql-reindex"><command>REINDEX</command></link> + to get the desired effects. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + This form resets one or more index-method-specific storage parameters to + their defaults. As with <literal>SET</literal>, a <literal>REINDEX</literal> + might be needed to update the index entirely. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALTER [ COLUMN ] <replaceable class="parameter">column_number</replaceable> SET STATISTICS <replaceable class="parameter">integer</replaceable></literal></term> + <listitem> + <para> + This form sets the per-column statistics-gathering target for + subsequent <link linkend="sql-analyze"><command>ANALYZE</command></link> operations, though can + be used only on index columns that are defined as an expression. + Since expressions lack a unique name, we refer to them using the + ordinal number of the index column. + The target can be set in the range 0 to 10000; alternatively, set it + to -1 to revert to using the system default statistics + target (<xref linkend="guc-default-statistics-target"/>). + For more information on the use of statistics by the + <productname>PostgreSQL</productname> query planner, refer to + <xref linkend="planner-stats"/>. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the index does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_number</replaceable></term> + <listitem> + <para> + The ordinal number refers to the ordinal (left-to-right) position + of the index column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of an existing index to + alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the index. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">tablespace_name</replaceable></term> + <listitem> + <para> + The tablespace to which the index will be moved. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">extension_name</replaceable></term> + <listitem> + <para> + The name of the extension that the index is to depend on. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">storage_parameter</replaceable></term> + <listitem> + <para> + The name of an index-method-specific storage parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + The new value for an index-method-specific storage parameter. + This might be a number or a word depending on the parameter. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + These operations are also possible using + <link linkend="sql-altertable"><command>ALTER TABLE</command></link>. + <command>ALTER INDEX</command> is in fact just an alias for the forms + of <command>ALTER TABLE</command> that apply to indexes. + </para> + + <para> + There was formerly an <command>ALTER INDEX OWNER</command> variant, but + this is now ignored (with a warning). An index cannot have an owner + different from its table's owner. Changing the table's owner + automatically changes the index as well. + </para> + + <para> + Changing any part of a system catalog index is not permitted. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + <para> + To rename an existing index: +<programlisting> +ALTER INDEX distributors RENAME TO suppliers; +</programlisting> + </para> + + <para> + To move an index to a different tablespace: +<programlisting> +ALTER INDEX distributors SET TABLESPACE fasttablespace; +</programlisting> + </para> + + <para> + To change an index's fill factor (assuming that the index method + supports it): +<programlisting> +ALTER INDEX distributors SET (fillfactor = 75); +REINDEX INDEX distributors; +</programlisting></para> + + <para> + Set the statistics-gathering target for an expression index: +<programlisting> +CREATE INDEX coord_idx ON measured (x, y, (z + t)); +ALTER INDEX coord_idx ALTER COLUMN 3 SET STATISTICS 1000; +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER INDEX</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createindex"/></member> + <member><xref linkend="sql-reindex"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_language.sgml b/doc/src/sgml/ref/alter_language.sgml new file mode 100644 index 0000000..0b61c18 --- /dev/null +++ b/doc/src/sgml/ref/alter_language.sgml @@ -0,0 +1,91 @@ +<!-- +doc/src/sgml/ref/alter_language.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterlanguage"> + <indexterm zone="sql-alterlanguage"> + <primary>ALTER LANGUAGE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER LANGUAGE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER LANGUAGE</refname> + <refpurpose>change the definition of a procedural language</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER [ PROCEDURAL ] LANGUAGE <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER [ PROCEDURAL ] LANGUAGE <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER LANGUAGE</command> changes the definition of a + procedural language. The only functionality is to rename the language or + assign a new owner. You must be superuser or owner of the language to + use <command>ALTER LANGUAGE</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>name</replaceable></term> + <listitem> + <para> + Name of a language + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_name</replaceable></term> + <listitem> + <para> + The new name of the language + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_owner</replaceable></term> + <listitem> + <para> + The new owner of the language + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER LANGUAGE</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createlanguage"/></member> + <member><xref linkend="sql-droplanguage"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_large_object.sgml b/doc/src/sgml/ref/alter_large_object.sgml new file mode 100644 index 0000000..17ea149 --- /dev/null +++ b/doc/src/sgml/ref/alter_large_object.sgml @@ -0,0 +1,86 @@ +<!-- +doc/src/sgml/ref/alter_large_object.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterlargeobject"> + <indexterm zone="sql-alterlargeobject"> + <primary>ALTER LARGE OBJECT</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER LARGE OBJECT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER LARGE OBJECT</refname> + <refpurpose>change the definition of a large object</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER LARGE OBJECT <replaceable class="parameter">large_object_oid</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER LARGE OBJECT</command> changes the definition of a + large object. + </para> + + <para> + You must own the large object to use <command>ALTER LARGE OBJECT</command>. + To alter the owner, you must also be a direct or indirect member of the new + owning role. (However, a superuser can alter any large object anyway.) + Currently, the only functionality is to assign a new owner, so both + restrictions always apply. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>large_object_oid</replaceable></term> + <listitem> + <para> + OID of the large object to be altered + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_owner</replaceable></term> + <listitem> + <para> + The new owner of the large object + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER LARGE OBJECT</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="largeobjects"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_materialized_view.sgml b/doc/src/sgml/ref/alter_materialized_view.sgml new file mode 100644 index 0000000..cae135c --- /dev/null +++ b/doc/src/sgml/ref/alter_materialized_view.sgml @@ -0,0 +1,186 @@ +<!-- +doc/src/sgml/ref/alter_materialized_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altermaterializedview"> + <indexterm zone="sql-altermaterializedview"> + <primary>ALTER MATERIALIZED VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER MATERIALIZED VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER MATERIALIZED VIEW</refname> + <refpurpose>change the definition of a materialized view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER MATERIALIZED VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + <replaceable class="parameter">action</replaceable> [, ... ] +ALTER MATERIALIZED VIEW <replaceable class="parameter">name</replaceable> + [ NO ] DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable> +ALTER MATERIALIZED VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + RENAME [ COLUMN ] <replaceable class="parameter">column_name</replaceable> TO <replaceable class="parameter">new_column_name</replaceable> +ALTER MATERIALIZED VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER MATERIALIZED VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER MATERIALIZED VIEW ALL IN TABLESPACE <replaceable class="parameter">name</replaceable> [ OWNED BY <replaceable class="parameter">role_name</replaceable> [, ... ] ] + SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> [ NOWAIT ] + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STATISTICS <replaceable class="parameter">integer</replaceable> + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET ( <replaceable class="parameter">attribute_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> RESET ( <replaceable class="parameter">attribute_option</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET COMPRESSION <replaceable class="parameter">compression_method</replaceable> + CLUSTER ON <replaceable class="parameter">index_name</replaceable> + SET WITHOUT CLUSTER + SET ACCESS METHOD <replaceable class="parameter">new_access_method</replaceable> + SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> + SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) + RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] ) + OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER MATERIALIZED VIEW</command> changes various auxiliary + properties of an existing materialized view. + </para> + + <para> + You must own the materialized view to use <command>ALTER MATERIALIZED + VIEW</command>. To change a materialized view's schema, you must also have + <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the materialized view's schema. (These restrictions enforce that altering + the owner doesn't do anything you couldn't do by dropping and recreating the + materialized view. However, a superuser can alter ownership of any view + anyway.) + </para> + + <para> + The statement subforms and actions available for + <command>ALTER MATERIALIZED VIEW</command> are a subset of those available + for <command>ALTER TABLE</command>, and have the same meaning when used for + materialized views. See the descriptions for + <link linkend="sql-altertable"><command>ALTER TABLE</command></link> + for details. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing materialized view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + Name of a new or existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">extension_name</replaceable></term> + <listitem> + <para> + The name of the extension that the materialized view is to depend on (or no longer + dependent on, if <literal>NO</literal> is specified). A materialized view + that's marked as dependent on an extension is automatically dropped when + the extension is dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_column_name</replaceable></term> + <listitem> + <para> + New name for an existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the materialized view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the materialized view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the materialized view. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the materialized view <literal>foo</literal> to + <literal>bar</literal>: +<programlisting> +ALTER MATERIALIZED VIEW foo RENAME TO bar; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER MATERIALIZED VIEW</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-creatematerializedview"/></member> + <member><xref linkend="sql-dropmaterializedview"/></member> + <member><xref linkend="sql-refreshmaterializedview"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_opclass.sgml b/doc/src/sgml/ref/alter_opclass.sgml new file mode 100644 index 0000000..b1db459 --- /dev/null +++ b/doc/src/sgml/ref/alter_opclass.sgml @@ -0,0 +1,124 @@ +<!-- +doc/src/sgml/ref/alter_opclass.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alteropclass"> + <indexterm zone="sql-alteropclass"> + <primary>ALTER OPERATOR CLASS</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER OPERATOR CLASS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER OPERATOR CLASS</refname> + <refpurpose>change the definition of an operator class</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER OPERATOR CLASS <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + RENAME TO <replaceable>new_name</replaceable> + +ALTER OPERATOR CLASS <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + +ALTER OPERATOR CLASS <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER OPERATOR CLASS</command> changes the definition of + an operator class. + </para> + + <para> + You must own the operator class to use <command>ALTER OPERATOR CLASS</command>. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the operator class's schema. (These restrictions enforce that altering the + owner doesn't do anything you couldn't do by dropping and recreating the + operator class. However, a superuser can alter ownership of any operator + class anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator + class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index method this operator class is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the operator class. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER OPERATOR CLASS</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-dropopclass"/></member> + <member><xref linkend="sql-alteropfamily"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_operator.sgml b/doc/src/sgml/ref/alter_operator.sgml new file mode 100644 index 0000000..ad90c13 --- /dev/null +++ b/doc/src/sgml/ref/alter_operator.sgml @@ -0,0 +1,160 @@ +<!-- +doc/src/sgml/ref/alter_operator.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alteroperator"> + <indexterm zone="sql-alteroperator"> + <primary>ALTER OPERATOR</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER OPERATOR</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER OPERATOR</refname> + <refpurpose>change the definition of an operator</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , <replaceable>right_type</replaceable> ) + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + +ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , <replaceable>right_type</replaceable> ) + SET SCHEMA <replaceable>new_schema</replaceable> + +ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , <replaceable>right_type</replaceable> ) + SET ( { RESTRICT = { <replaceable class="parameter">res_proc</replaceable> | NONE } + | JOIN = { <replaceable class="parameter">join_proc</replaceable> | NONE } + } [, ... ] ) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER OPERATOR</command> changes the definition of + an operator. + </para> + + <para> + You must own the operator to use <command>ALTER OPERATOR</command>. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the operator's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the operator. + However, a superuser can alter ownership of any operator anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">left_type</replaceable></term> + <listitem> + <para> + The data type of the operator's left operand; write + <literal>NONE</literal> if the operator has no left operand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">right_type</replaceable></term> + <listitem> + <para> + The data type of the operator's right operand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">res_proc</replaceable></term> + <listitem> + <para> + The restriction selectivity estimator function for this operator; write NONE to remove existing selectivity estimator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">join_proc</replaceable></term> + <listitem> + <para> + The join selectivity estimator function for this operator; write NONE to remove existing selectivity estimator. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change the owner of a custom operator <literal>a @@ b</literal> for type <type>text</type>: +<programlisting> +ALTER OPERATOR @@ (text, text) OWNER TO joe; +</programlisting></para> + + <para> + Change the restriction and join selectivity estimator functions of a custom operator <literal>a && b</literal> for type <type>int[]</type>: +<programlisting> +ALTER OPERATOR && (_int4, _int4) SET (RESTRICT = _int_contsel, JOIN = _int_contjoinsel); +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER OPERATOR</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createoperator"/></member> + <member><xref linkend="sql-dropoperator"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_opfamily.sgml b/doc/src/sgml/ref/alter_opfamily.sgml new file mode 100644 index 0000000..b2e5b9b --- /dev/null +++ b/doc/src/sgml/ref/alter_opfamily.sgml @@ -0,0 +1,360 @@ +<!-- +doc/src/sgml/ref/alter_opfamily.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alteropfamily"> + <indexterm zone="sql-alteropfamily"> + <primary>ALTER OPERATOR FAMILY</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER OPERATOR FAMILY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER OPERATOR FAMILY</refname> + <refpurpose>change the definition of an operator family</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER OPERATOR FAMILY <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> ADD + { OPERATOR <replaceable class="parameter">strategy_number</replaceable> <replaceable class="parameter">operator_name</replaceable> ( <replaceable class="parameter">op_type</replaceable>, <replaceable class="parameter">op_type</replaceable> ) + [ FOR SEARCH | FOR ORDER BY <replaceable class="parameter">sort_family_name</replaceable> ] + | FUNCTION <replaceable class="parameter">support_number</replaceable> [ ( <replaceable class="parameter">op_type</replaceable> [ , <replaceable class="parameter">op_type</replaceable> ] ) ] + <replaceable class="parameter">function_name</replaceable> [ ( <replaceable class="parameter">argument_type</replaceable> [, ...] ) ] + } [, ... ] + +ALTER OPERATOR FAMILY <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> DROP + { OPERATOR <replaceable class="parameter">strategy_number</replaceable> ( <replaceable class="parameter">op_type</replaceable> [ , <replaceable class="parameter">op_type</replaceable> ] ) + | FUNCTION <replaceable class="parameter">support_number</replaceable> ( <replaceable class="parameter">op_type</replaceable> [ , <replaceable class="parameter">op_type</replaceable> ] ) + } [, ... ] + +ALTER OPERATOR FAMILY <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + RENAME TO <replaceable>new_name</replaceable> + +ALTER OPERATOR FAMILY <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + +ALTER OPERATOR FAMILY <replaceable>name</replaceable> USING <replaceable class="parameter">index_method</replaceable> + SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER OPERATOR FAMILY</command> changes the definition of + an operator family. You can add operators and support functions + to the family, remove them from the family, + or change the family's name or owner. + </para> + + <para> + When operators and support functions are added to a family with + <command>ALTER OPERATOR FAMILY</command>, they are not part of any + specific operator class within the family, but are just <quote>loose</quote> + within the family. This indicates that these operators and functions + are compatible with the family's semantics, but are not required for + correct functioning of any specific index. (Operators and functions + that are so required should be declared as part of an operator class, + instead; see <xref linkend="sql-createopclass"/>.) + <productname>PostgreSQL</productname> will allow loose members of a + family to be dropped from the family at any time, but members of an + operator class cannot be dropped without dropping the whole class and + any indexes that depend on it. + Typically, single-data-type operators + and functions are part of operator classes because they are needed to + support an index on that specific data type, while cross-data-type + operators and functions are made loose members of the family. + </para> + + <para> + You must be a superuser to use <command>ALTER OPERATOR FAMILY</command>. + (This restriction is made because an erroneous operator family definition + could confuse or even crash the server.) + </para> + + <para> + <command>ALTER OPERATOR FAMILY</command> does not presently check + whether the operator family definition includes all the operators and + functions required by the index method, nor whether the operators and + functions form a self-consistent set. It is the user's + responsibility to define a valid operator family. + </para> + + <para> + Refer to <xref linkend="xindex"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator + family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index method this operator family is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">strategy_number</replaceable></term> + <listitem> + <para> + The index method's strategy number for an operator + associated with the operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">operator_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an operator associated + with the operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">op_type</replaceable></term> + <listitem> + <para> + In an <literal>OPERATOR</literal> clause, + the operand data type(s) of the operator, or <literal>NONE</literal> to + signify a prefix operator. Unlike the comparable + syntax in <command>CREATE OPERATOR CLASS</command>, the operand data types + must always be specified. + </para> + + <para> + In an <literal>ADD FUNCTION</literal> clause, the operand data type(s) the + function is intended to support, if different from + the input data type(s) of the function. For B-tree comparison functions + and hash functions it is not necessary to specify <replaceable + class="parameter">op_type</replaceable> since the function's input + data type(s) are always the correct ones to use. For B-tree sort + support functions, B-Tree equal image functions, and all + functions in GiST, SP-GiST and GIN operator classes, it is + necessary to specify the operand data type(s) the function is to + be used with. + </para> + + <para> + In a <literal>DROP FUNCTION</literal> clause, the operand data type(s) the + function is intended to support must be specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sort_family_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing <literal>btree</literal> operator + family that describes the sort ordering associated with an ordering + operator. + </para> + + <para> + If neither <literal>FOR SEARCH</literal> nor <literal>FOR ORDER BY</literal> is + specified, <literal>FOR SEARCH</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">support_number</replaceable></term> + <listitem> + <para> + The index method's support function number for a + function associated with the operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a function that is an index + method support function for the operator family. If no argument list + is specified, the name must be unique in its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argument_type</replaceable></term> + <listitem> + <para> + The parameter data type(s) of the function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the operator family. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The <literal>OPERATOR</literal> and <literal>FUNCTION</literal> + clauses can appear in any order. + </para> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Notice that the <literal>DROP</literal> syntax only specifies the <quote>slot</quote> + in the operator family, by strategy or support number and input data + type(s). The name of the operator or function occupying the slot is not + mentioned. Also, for <literal>DROP FUNCTION</literal> the type(s) to specify + are the input data type(s) the function is intended to support; for + GiST, SP-GiST and GIN indexes this might have nothing to do with the actual + input argument types of the function. + </para> + + <para> + Because the index machinery does not check access permissions on functions + before using them, including a function or operator in an operator family + is tantamount to granting public execute permission on it. This is usually + not an issue for the sorts of functions that are useful in an operator + family. + </para> + + <para> + The operators should not be defined by SQL functions. An SQL function + is likely to be inlined into the calling query, which will prevent + the optimizer from recognizing that the query matches an index. + </para> + + <para> + Before <productname>PostgreSQL</productname> 8.4, the <literal>OPERATOR</literal> + clause could include a <literal>RECHECK</literal> option. This is no longer + supported because whether an index operator is <quote>lossy</quote> is now + determined on-the-fly at run time. This allows efficient handling of + cases where an operator might or might not be lossy. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example command adds cross-data-type operators and + support functions to an operator family that already contains B-tree + operator classes for data types <type>int4</type> and <type>int2</type>. + </para> + +<programlisting> +ALTER OPERATOR FAMILY integer_ops USING btree ADD + + -- int4 vs int2 + OPERATOR 1 < (int4, int2) , + OPERATOR 2 <= (int4, int2) , + OPERATOR 3 = (int4, int2) , + OPERATOR 4 >= (int4, int2) , + OPERATOR 5 > (int4, int2) , + FUNCTION 1 btint42cmp(int4, int2) , + + -- int2 vs int4 + OPERATOR 1 < (int2, int4) , + OPERATOR 2 <= (int2, int4) , + OPERATOR 3 = (int2, int4) , + OPERATOR 4 >= (int2, int4) , + OPERATOR 5 > (int2, int4) , + FUNCTION 1 btint24cmp(int2, int4) ; +</programlisting> + + <para> + To remove these entries again: + </para> + +<programlisting> +ALTER OPERATOR FAMILY integer_ops USING btree DROP + + -- int4 vs int2 + OPERATOR 1 (int4, int2) , + OPERATOR 2 (int4, int2) , + OPERATOR 3 (int4, int2) , + OPERATOR 4 (int4, int2) , + OPERATOR 5 (int4, int2) , + FUNCTION 1 (int4, int2) , + + -- int2 vs int4 + OPERATOR 1 (int2, int4) , + OPERATOR 2 (int2, int4) , + OPERATOR 3 (int2, int4) , + OPERATOR 4 (int2, int4) , + OPERATOR 5 (int2, int4) , + FUNCTION 1 (int2, int4) ; +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER OPERATOR FAMILY</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createopfamily"/></member> + <member><xref linkend="sql-dropopfamily"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-alteropclass"/></member> + <member><xref linkend="sql-dropopclass"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_policy.sgml b/doc/src/sgml/ref/alter_policy.sgml new file mode 100644 index 0000000..fbc262b --- /dev/null +++ b/doc/src/sgml/ref/alter_policy.sgml @@ -0,0 +1,143 @@ +<!-- +doc/src/sgml/ref/alter_policy.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterpolicy"> + <indexterm zone="sql-alterpolicy"> + <primary>ALTER POLICY</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER POLICY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER POLICY</refname> + <refpurpose>change the definition of a row-level security policy</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER POLICY <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> + +ALTER POLICY <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> + [ TO { <replaceable class="parameter">role_name</replaceable> | PUBLIC | CURRENT_ROLE | CURRENT_USER | SESSION_USER } [, ...] ] + [ USING ( <replaceable class="parameter">using_expression</replaceable> ) ] + [ WITH CHECK ( <replaceable class="parameter">check_expression</replaceable> ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER POLICY</command> changes the definition of an existing + row-level security policy. Note that <command>ALTER POLICY</command> + only allows the set of roles to which the policy applies and the + <literal>USING</literal> and <literal>WITH CHECK</literal> expressions to + be modified. To change other properties of a policy, such as the command + to which it applies or whether it is permissive or restrictive, the policy + must be dropped and recreated. + </para> + + <para> + To use <command>ALTER POLICY</command>, you must own the table that + the policy applies to. + </para> + + <para> + In the second form of <command>ALTER POLICY</command>, the role list, + <replaceable class="parameter">using_expression</replaceable>, and + <replaceable class="parameter">check_expression</replaceable> are replaced + independently if specified. When one of those clauses is omitted, the + corresponding part of the policy is unchanged. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing policy to alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table that the + policy is on. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the policy. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The role(s) to which the policy applies. Multiple roles can be + specified at one time. To apply the policy to all roles, + use <literal>PUBLIC</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">using_expression</replaceable></term> + <listitem> + <para> + The <literal>USING</literal> expression for the policy. + See <xref linkend="sql-createpolicy"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">check_expression</replaceable></term> + <listitem> + <para> + The <literal>WITH CHECK</literal> expression for the policy. + See <xref linkend="sql-createpolicy"/> for details. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER POLICY</command> is a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createpolicy"/></member> + <member><xref linkend="sql-droppolicy"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_procedure.sgml b/doc/src/sgml/ref/alter_procedure.sgml new file mode 100644 index 0000000..20a6238 --- /dev/null +++ b/doc/src/sgml/ref/alter_procedure.sgml @@ -0,0 +1,289 @@ +<!-- +doc/src/sgml/ref/alter_procedure.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterprocedure"> + <indexterm zone="sql-alterprocedure"> + <primary>ALTER PROCEDURE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER PROCEDURE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER PROCEDURE</refname> + <refpurpose>change the definition of a procedure</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER PROCEDURE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + <replaceable class="parameter">action</replaceable> [ ... ] [ RESTRICT ] +ALTER PROCEDURE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + RENAME TO <replaceable>new_name</replaceable> +ALTER PROCEDURE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER PROCEDURE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + SET SCHEMA <replaceable>new_schema</replaceable> +ALTER PROCEDURE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + [ NO ] DEPENDS ON EXTENSION <replaceable>extension_name</replaceable> + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER + SET <replaceable class="parameter">configuration_parameter</replaceable> { TO | = } { <replaceable class="parameter">value</replaceable> | DEFAULT } + SET <replaceable class="parameter">configuration_parameter</replaceable> FROM CURRENT + RESET <replaceable class="parameter">configuration_parameter</replaceable> + RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER PROCEDURE</command> changes the definition of a + procedure. + </para> + + <para> + You must own the procedure to use <command>ALTER PROCEDURE</command>. + To change a procedure's schema, you must also have <literal>CREATE</literal> + privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the procedure's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the procedure. + However, a superuser can alter ownership of any procedure anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing procedure. If no + argument list is specified, the name must be unique in its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. If omitted, + the default is <literal>IN</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>ALTER PROCEDURE</command> does not actually pay + any attention to argument names, since only the argument data + types are used to determine the procedure's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the procedure's arguments (optionally + schema-qualified), if any. + See <xref linkend="sql-dropprocedure"/> for the details of how + the procedure is looked up using the argument data type(s). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the procedure. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the procedure. Note that if the procedure is + marked <literal>SECURITY DEFINER</literal>, it will subsequently + execute as the new owner. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the procedure. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">extension_name</replaceable></term> + <listitem> + <para> + This form marks the procedure as dependent on the extension, or no longer + dependent on the extension if <literal>NO</literal> is specified. + A procedure that's marked as dependent on an extension is dropped when the + extension is dropped, even if cascade is not specified. + A procedure can depend upon multiple extensions, and will be dropped when + any one of those extensions is dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><optional> EXTERNAL </optional> SECURITY INVOKER</literal></term> + <term><literal><optional> EXTERNAL </optional> SECURITY DEFINER</literal></term> + + <listitem> + <para> + Change whether the procedure is a security definer or not. The + key word <literal>EXTERNAL</literal> is ignored for SQL + conformance. See <xref linkend="sql-createprocedure"/> for more information about + this capability. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + Add or change the assignment to be made to a configuration parameter + when the procedure is called. If + <replaceable>value</replaceable> is <literal>DEFAULT</literal> + or, equivalently, <literal>RESET</literal> is used, the procedure-local + setting is removed, so that the procedure executes with the value + present in its environment. Use <literal>RESET + ALL</literal> to clear all procedure-local settings. + <literal>SET FROM CURRENT</literal> saves the value of the parameter that + is current when <command>ALTER PROCEDURE</command> is executed as the value + to be applied when the procedure is entered. + </para> + + <para> + See <xref linkend="sql-set"/> and + <xref linkend="runtime-config"/> + for more information about allowed parameter names and values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + Ignored for conformance with the SQL standard. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the procedure <literal>insert_data</literal> with two arguments + of type <type>integer</type> to <literal>insert_record</literal>: +<programlisting> +ALTER PROCEDURE insert_data(integer, integer) RENAME TO insert_record; +</programlisting> + </para> + + <para> + To change the owner of the procedure <literal>insert_data</literal> with + two arguments of type <type>integer</type> to <literal>joe</literal>: +<programlisting> +ALTER PROCEDURE insert_data(integer, integer) OWNER TO joe; +</programlisting> + </para> + + <para> + To change the schema of the procedure <literal>insert_data</literal> with + two arguments of type <type>integer</type> + to <literal>accounting</literal>: +<programlisting> +ALTER PROCEDURE insert_data(integer, integer) SET SCHEMA accounting; +</programlisting> + </para> + + <para> + To mark the procedure <literal>insert_data(integer, integer)</literal> as + being dependent on the extension <literal>myext</literal>: +<programlisting> +ALTER PROCEDURE insert_data(integer, integer) DEPENDS ON EXTENSION myext; +</programlisting> + </para> + + <para> + To adjust the search path that is automatically set for a procedure: +<programlisting> +ALTER PROCEDURE check_password(text) SET search_path = admin, pg_temp; +</programlisting> + </para> + + <para> + To disable automatic setting of <varname>search_path</varname> for a procedure: +<programlisting> +ALTER PROCEDURE check_password(text) RESET search_path; +</programlisting> + The procedure will now execute with whatever search path is used by its + caller. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This statement is partially compatible with the <command>ALTER + PROCEDURE</command> statement in the SQL standard. The standard allows more + properties of a procedure to be modified, but does not provide the + ability to rename a procedure, make a procedure a security definer, + attach configuration parameter values to a procedure, + or change the owner, schema, or volatility of a procedure. The standard also + requires the <literal>RESTRICT</literal> key word, which is optional in + <productname>PostgreSQL</productname>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createprocedure"/></member> + <member><xref linkend="sql-dropprocedure"/></member> + <member><xref linkend="sql-alterfunction"/></member> + <member><xref linkend="sql-alterroutine"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_publication.sgml b/doc/src/sgml/ref/alter_publication.sgml new file mode 100644 index 0000000..c84b11f --- /dev/null +++ b/doc/src/sgml/ref/alter_publication.sgml @@ -0,0 +1,235 @@ +<!-- +doc/src/sgml/ref/alter_publication.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterpublication"> + <indexterm zone="sql-alterpublication"> + <primary>ALTER PUBLICATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER PUBLICATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER PUBLICATION</refname> + <refpurpose>change the definition of a publication</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> ADD <replaceable class="parameter">publication_object</replaceable> [, ...] +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> SET <replaceable class="parameter">publication_object</replaceable> [, ...] +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> DROP <replaceable class="parameter">publication_object</replaceable> [, ...] +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER PUBLICATION <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> + +<phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> + + TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + The command <command>ALTER PUBLICATION</command> can change the attributes + of a publication. + </para> + + <para> + The first three variants change which tables/schemas are part of the + publication. The <literal>SET</literal> clause will replace the list of + tables/schemas in the publication with the specified list; the existing + tables/schemas that were present in the publication will be removed. The + <literal>ADD</literal> and <literal>DROP</literal> clauses will add and + remove one or more tables/schemas from the publication. Note that adding + tables/schemas to a publication that is already subscribed to will require an + <literal>ALTER SUBSCRIPTION ... REFRESH PUBLICATION</literal> action on the + subscribing side in order to become effective. Note also that + <literal>DROP TABLES IN SCHEMA</literal> will not drop any schema tables + that were specified using <literal>FOR TABLE</literal>/ + <literal>ADD TABLE</literal>, and the combination of <literal>DROP</literal> + with a <literal>WHERE</literal> clause is not allowed. + </para> + + <para> + The fourth variant of this command listed in the synopsis can change + all of the publication properties specified in + <xref linkend="sql-createpublication"/>. Properties not mentioned in the + command retain their previous settings. + </para> + + <para> + The remaining variants change the owner and the name of the publication. + </para> + + <para> + You must own the publication to use <command>ALTER PUBLICATION</command>. + Adding a table to a publication additionally requires owning that table. + The <literal>ADD TABLES IN SCHEMA</literal> and + <literal>SET TABLES IN SCHEMA</literal> to a publication requires the + invoking user to be a superuser. To alter the owner, you must also be a + direct or indirect member of the new owning role. The new owner must have + <literal>CREATE</literal> privilege on the database. Also, the new owner + of a <literal>FOR ALL TABLES</literal> or <literal>FOR TABLES IN SCHEMA</literal> + publication must be a superuser. However, a superuser can + change the ownership of a publication regardless of these restrictions. + </para> + + <para> + Adding/Setting any schema when the publication also publishes a table with a + column list, and vice versa is not supported. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing publication whose definition is to be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + Name of an existing table. If <literal>ONLY</literal> is specified before the + table name, only that table is affected. If <literal>ONLY</literal> is not + specified, the table and all its descendant tables (if any) are + affected. Optionally, <literal>*</literal> can be specified after the table + name to explicitly indicate that descendant tables are included. + </para> + + <para> + Optionally, a column list can be specified. See <xref + linkend="sql-createpublication"/> for details. Note that a subscription + having several publications in which the same table has been published + with different column lists is not supported. See + <xref linkend="logical-replication-col-list-combining"/> for details of + potential problems when altering column lists. + </para> + + <para> + If the optional <literal>WHERE</literal> clause is specified, rows for + which the <replaceable class="parameter">expression</replaceable> + evaluates to false or null will not be published. Note that parentheses + are required around the expression. The + <replaceable class="parameter">expression</replaceable> is evaluated with + the role used for the replication connection. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">schema_name</replaceable></term> + <listitem> + <para> + Name of an existing schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause alters publication parameters originally set by + <xref linkend="sql-createpublication"/>. See there for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the publication. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the publication. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change the publication to publish only deletes and updates: +<programlisting> +ALTER PUBLICATION noinsert SET (publish = 'update, delete'); +</programlisting> + </para> + + <para> + Add some tables to the publication: +<programlisting> +ALTER PUBLICATION mypublication ADD TABLE users (user_id, firstname), departments; +</programlisting></para> + + <para> + Change the set of columns published for a table: +<programlisting> +ALTER PUBLICATION mypublication SET TABLE users (user_id, firstname, lastname), TABLE departments; +</programlisting></para> + + <para> + Add schemas <structname>marketing</structname> and + <structname>sales</structname> to the publication + <structname>sales_publication</structname>: +<programlisting> +ALTER PUBLICATION sales_publication ADD TABLES IN SCHEMA marketing, sales; +</programlisting> + </para> + + <para> + Add tables <structname>users</structname>, + <structname>departments</structname> and schema + <structname>production</structname> to the publication + <structname>production_publication</structname>: +<programlisting> +ALTER PUBLICATION production_publication ADD TABLE users, departments, TABLES IN SCHEMA production; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER PUBLICATION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createpublication"/></member> + <member><xref linkend="sql-droppublication"/></member> + <member><xref linkend="sql-createsubscription"/></member> + <member><xref linkend="sql-altersubscription"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_role.sgml b/doc/src/sgml/ref/alter_role.sgml new file mode 100644 index 0000000..922686e --- /dev/null +++ b/doc/src/sgml/ref/alter_role.sgml @@ -0,0 +1,354 @@ +<!-- +doc/src/sgml/ref/alter_role.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterrole"> + <indexterm zone="sql-alterrole"> + <primary>ALTER ROLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER ROLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER ROLE</refname> + <refpurpose>change a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER ROLE <replaceable class="parameter">role_specification</replaceable> [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + SUPERUSER | NOSUPERUSER + | CREATEDB | NOCREATEDB + | CREATEROLE | NOCREATEROLE + | INHERIT | NOINHERIT + | LOGIN | NOLOGIN + | REPLICATION | NOREPLICATION + | BYPASSRLS | NOBYPASSRLS + | CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + | [ ENCRYPTED ] PASSWORD '<replaceable class="parameter">password</replaceable>' | PASSWORD NULL + | VALID UNTIL '<replaceable class="parameter">timestamp</replaceable>' + +ALTER ROLE <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> + +ALTER ROLE { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] SET <replaceable>configuration_parameter</replaceable> { TO | = } { <replaceable>value</replaceable> | DEFAULT } +ALTER ROLE { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] SET <replaceable>configuration_parameter</replaceable> FROM CURRENT +ALTER ROLE { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] RESET <replaceable>configuration_parameter</replaceable> +ALTER ROLE { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] RESET ALL + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + <replaceable class="parameter">role_name</replaceable> + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER ROLE</command> changes the attributes of a + <productname>PostgreSQL</productname> role. + </para> + + <para> + The first variant of this command listed in the synopsis can change + many of the role attributes that can be specified in + <link linkend="sql-createrole"><command>CREATE ROLE</command></link>. + (All the possible attributes are covered, + except that there are no options for adding or removing memberships; use + <link linkend="sql-grant"><command>GRANT</command></link> and + <link linkend="sql-revoke"><command>REVOKE</command></link> for that.) + Attributes not mentioned in the command retain their previous settings. + Database superusers can change any of these settings for any role. + Roles having <literal>CREATEROLE</literal> privilege can change any of these + settings except <literal>SUPERUSER</literal>, <literal>REPLICATION</literal>, + and <literal>BYPASSRLS</literal>; but only for non-superuser and + non-replication roles. + Ordinary roles can only change their own password. + </para> + + <para> + The second variant changes the name of the role. + Database superusers can rename any role. + Roles having <literal>CREATEROLE</literal> privilege can rename non-superuser + roles. + The current session user cannot be renamed. + (Connect as a different user if you need to do that.) + Because <literal>MD5</literal>-encrypted passwords use the role name as + cryptographic salt, renaming a role clears its password if the + password is <literal>MD5</literal>-encrypted. + </para> + + <para> + The remaining variants change a role's session default for a configuration + variable, either for all databases or, when the <literal>IN + DATABASE</literal> clause is specified, only for sessions in the named + database. If <literal>ALL</literal> is specified instead of a role name, + this changes the setting for all roles. Using <literal>ALL</literal> + with <literal>IN DATABASE</literal> is effectively the same as using the + command <literal>ALTER DATABASE ... SET ...</literal>. + </para> + + <para> + Whenever the role subsequently + starts a new session, the specified value becomes the session + default, overriding whatever setting is present in + <filename>postgresql.conf</filename> or has been received from the <command>postgres</command> + command line. This only happens at login time; executing + <link linkend="sql-set-role"><command>SET ROLE</command></link> or + <link linkend="sql-set-session-authorization"><command>SET SESSION AUTHORIZATION</command></link> does not cause new + configuration values to be set. + Settings set for all databases are overridden by database-specific settings + attached to a role. Settings for specific databases or specific roles override + settings for all roles. + </para> + + <para> + Superusers can change anyone's session defaults. Roles having + <literal>CREATEROLE</literal> privilege can change defaults for non-superuser + roles. Ordinary roles can only set defaults for themselves. + Certain configuration variables cannot be set this way, or can only be + set if a superuser issues the command. Only superusers can change a setting + for all roles in all databases. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the role whose attributes are to be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CURRENT_ROLE</literal></term> + <term><literal>CURRENT_USER</literal></term> + <listitem> + <para> + Alter the current user instead of an explicitly identified role. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SESSION_USER</literal></term> + <listitem> + <para> + Alter the current session user instead of an explicitly identified + role. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SUPERUSER</literal></term> + <term><literal>NOSUPERUSER</literal></term> + <term><literal>CREATEDB</literal></term> + <term><literal>NOCREATEDB</literal></term> + <term><literal>CREATEROLE</literal></term> + <term><literal>NOCREATEROLE</literal></term> + <term><literal>INHERIT</literal></term> + <term><literal>NOINHERIT</literal></term> + <term><literal>LOGIN</literal></term> + <term><literal>NOLOGIN</literal></term> + <term><literal>REPLICATION</literal></term> + <term><literal>NOREPLICATION</literal></term> + <term><literal>BYPASSRLS</literal></term> + <term><literal>NOBYPASSRLS</literal></term> + <term><literal>CONNECTION LIMIT</literal> <replaceable class="parameter">connlimit</replaceable></term> + <term>[ <literal>ENCRYPTED</literal> ] <literal>PASSWORD</literal> '<replaceable class="parameter">password</replaceable>'</term> + <term><literal>PASSWORD NULL</literal></term> + <term><literal>VALID UNTIL</literal> '<replaceable class="parameter">timestamp</replaceable>'</term> + <listitem> + <para> + These clauses alter attributes originally set by + <link linkend="sql-createrole"><command>CREATE ROLE</command></link>. For more information, see the + <command>CREATE ROLE</command> reference page. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_name</replaceable></term> + <listitem> + <para> + The new name of the role. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>database_name</replaceable></term> + <listitem> + <para> + The name of the database the configuration variable should be set in. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + Set this role's session default for the specified configuration + parameter to the given value. If + <replaceable>value</replaceable> is <literal>DEFAULT</literal> + or, equivalently, <literal>RESET</literal> is used, the + role-specific variable setting is removed, so the role will + inherit the system-wide default setting in new sessions. Use + <literal>RESET ALL</literal> to clear all role-specific settings. + <literal>SET FROM CURRENT</literal> saves the session's current value of + the parameter as the role-specific value. + If <literal>IN DATABASE</literal> is specified, the configuration + parameter is set or removed for the given role and database only. + </para> + + <para> + Role-specific variable settings take effect only at login; + <link linkend="sql-set-role"><command>SET ROLE</command></link> and + <link linkend="sql-set-session-authorization"><command>SET SESSION AUTHORIZATION</command></link> + do not process role-specific variable settings. + </para> + + <para> + See <xref linkend="sql-set"/> and <xref + linkend="runtime-config"/> for more information about allowed + parameter names and values. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-createrole"><command>CREATE ROLE</command></link> + to add new roles, and <link linkend="sql-droprole"><command>DROP ROLE</command></link> to remove a role. + </para> + + <para> + <command>ALTER ROLE</command> cannot change a role's memberships. + Use <link linkend="sql-grant"><command>GRANT</command></link> and + <link linkend="sql-revoke"><command>REVOKE</command></link> + to do that. + </para> + + <para> + Caution must be exercised when specifying an unencrypted password + with this command. The password will be transmitted to the server + in cleartext, and it might also be logged in the client's command + history or the server log. <xref linkend="app-psql"/> + contains a command + <command>\password</command> that can be used to change a + role's password without exposing the cleartext password. + </para> + + <para> + It is also possible to tie a + session default to a specific database rather than to a role; see + <xref linkend="sql-alterdatabase"/>. + If there is a conflict, database-role-specific settings override role-specific + ones, which in turn override database-specific ones. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change a role's password: + +<programlisting> +ALTER ROLE davide WITH PASSWORD 'hu8jmn3'; +</programlisting> + </para> + + <para> + Remove a role's password: + +<programlisting> +ALTER ROLE davide WITH PASSWORD NULL; +</programlisting> + </para> + + <para> + Change a password expiration date, specifying that the password + should expire at midday on 4th May 2015 using + the time zone which is one hour ahead of <acronym>UTC</acronym>: +<programlisting> +ALTER ROLE chris VALID UNTIL 'May 4 12:00:00 2015 +1'; +</programlisting> + </para> + + <para> + Make a password valid forever: +<programlisting> +ALTER ROLE fred VALID UNTIL 'infinity'; +</programlisting> + </para> + + <para> + Give a role the ability to manage other roles and create new databases: + +<programlisting> +ALTER ROLE miriam CREATEROLE CREATEDB; +</programlisting> + </para> + + <para> + Give a role a non-default setting of the + <xref linkend="guc-maintenance-work-mem"/> parameter: + +<programlisting> +ALTER ROLE worker_bee SET maintenance_work_mem = 100000; +</programlisting> + </para> + + <para> + Give a role a non-default, database-specific setting of the + <xref linkend="guc-client-min-messages"/> parameter: + +<programlisting> +ALTER ROLE fred IN DATABASE devel SET client_min_messages = DEBUG; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>ALTER ROLE</command> statement is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrole"/></member> + <member><xref linkend="sql-droprole"/></member> + <member><xref linkend="sql-alterdatabase"/></member> + <member><xref linkend="sql-set"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_routine.sgml b/doc/src/sgml/ref/alter_routine.sgml new file mode 100644 index 0000000..d6c9dea --- /dev/null +++ b/doc/src/sgml/ref/alter_routine.sgml @@ -0,0 +1,103 @@ +<!-- +doc/src/sgml/ref/alter_routine.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterroutine"> + <indexterm zone="sql-alterroutine"> + <primary>ALTER ROUTINE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER ROUTINE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER ROUTINE</refname> + <refpurpose>change the definition of a routine</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER ROUTINE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + <replaceable class="parameter">action</replaceable> [ ... ] [ RESTRICT ] +ALTER ROUTINE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + RENAME TO <replaceable>new_name</replaceable> +ALTER ROUTINE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER ROUTINE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + SET SCHEMA <replaceable>new_schema</replaceable> +ALTER ROUTINE <replaceable>name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] + [ NO ] DEPENDS ON EXTENSION <replaceable>extension_name</replaceable> + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + IMMUTABLE | STABLE | VOLATILE + [ NOT ] LEAKPROOF + [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER + PARALLEL { UNSAFE | RESTRICTED | SAFE } + COST <replaceable class="parameter">execution_cost</replaceable> + ROWS <replaceable class="parameter">result_rows</replaceable> + SET <replaceable class="parameter">configuration_parameter</replaceable> { TO | = } { <replaceable class="parameter">value</replaceable> | DEFAULT } + SET <replaceable class="parameter">configuration_parameter</replaceable> FROM CURRENT + RESET <replaceable class="parameter">configuration_parameter</replaceable> + RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER ROUTINE</command> changes the definition of a routine, which + can be an aggregate function, a normal function, or a procedure. See + under <xref linkend="sql-alteraggregate"/>, <xref linkend="sql-alterfunction"/>, + and <xref linkend="sql-alterprocedure"/> for the description of the + parameters, more examples, and further details. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the routine <literal>foo</literal> for type + <type>integer</type> to <literal>foobar</literal>: +<programlisting> +ALTER ROUTINE foo(integer) RENAME TO foobar; +</programlisting> + This command will work independent of whether <literal>foo</literal> is an + aggregate, function, or procedure. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This statement is partially compatible with the <command>ALTER + ROUTINE</command> statement in the SQL standard. See + under <xref linkend="sql-alterfunction"/> + and <xref linkend="sql-alterprocedure"/> for more details. Allowing + routine names to refer to aggregate functions is + a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteraggregate"/></member> + <member><xref linkend="sql-alterfunction"/></member> + <member><xref linkend="sql-alterprocedure"/></member> + <member><xref linkend="sql-droproutine"/></member> + </simplelist> + + <para> + Note that there is no <literal>CREATE ROUTINE</literal> command. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_rule.sgml b/doc/src/sgml/ref/alter_rule.sgml new file mode 100644 index 0000000..c20bfb3 --- /dev/null +++ b/doc/src/sgml/ref/alter_rule.sgml @@ -0,0 +1,105 @@ +<!-- +doc/src/sgml/ref/alter_rule.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterrule"> + <indexterm zone="sql-alterrule"> + <primary>ALTER RULE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER RULE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER RULE</refname> + <refpurpose>change the definition of a rule</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER RULE <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER RULE</command> changes properties of an existing + rule. Currently, the only available action is to change the rule's name. + </para> + + <para> + To use <command>ALTER RULE</command>, you must own the table or view that + the rule applies to. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing rule to alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table or view that the + rule applies to. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the rule. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename an existing rule: +<programlisting> +ALTER RULE notify_all ON emp RENAME TO notify_me; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER RULE</command> is a + <productname>PostgreSQL</productname> language extension, as is the + entire query rewrite system. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrule"/></member> + <member><xref linkend="sql-droprule"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_schema.sgml b/doc/src/sgml/ref/alter_schema.sgml new file mode 100644 index 0000000..04624c5 --- /dev/null +++ b/doc/src/sgml/ref/alter_schema.sgml @@ -0,0 +1,100 @@ +<!-- +doc/src/sgml/ref/alter_schema.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterschema"> + <indexterm zone="sql-alterschema"> + <primary>ALTER SCHEMA</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER SCHEMA</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER SCHEMA</refname> + <refpurpose>change the definition of a schema</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER SCHEMA <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER SCHEMA <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER SCHEMA</command> changes the definition of a schema. + </para> + + <para> + You must own the schema to use <command>ALTER SCHEMA</command>. + To rename a schema you must also have the + <literal>CREATE</literal> privilege for the database. + To alter the owner, you must also be a direct or + indirect member of the new owning role, and you must have the + <literal>CREATE</literal> privilege for the database. + (Note that superusers have all these privileges automatically.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>name</replaceable></term> + <listitem> + <para> + The name of an existing schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>new_name</replaceable></term> + <listitem> + <para> + The new name of the schema. The new name cannot + begin with <literal>pg_</literal>, as such names + are reserved for system schemas. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the schema. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER SCHEMA</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createschema"/></member> + <member><xref linkend="sql-dropschema"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_sequence.sgml b/doc/src/sgml/ref/alter_sequence.sgml new file mode 100644 index 0000000..148085d --- /dev/null +++ b/doc/src/sgml/ref/alter_sequence.sgml @@ -0,0 +1,363 @@ +<!-- +doc/src/sgml/ref/alter_sequence.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altersequence"> + <indexterm zone="sql-altersequence"> + <primary>ALTER SEQUENCE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER SEQUENCE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER SEQUENCE</refname> + <refpurpose> + change the definition of a sequence generator + </refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + [ AS <replaceable class="parameter">data_type</replaceable> ] + [ INCREMENT [ BY ] <replaceable class="parameter">increment</replaceable> ] + [ MINVALUE <replaceable class="parameter">minvalue</replaceable> | NO MINVALUE ] [ MAXVALUE <replaceable class="parameter">maxvalue</replaceable> | NO MAXVALUE ] + [ START [ WITH ] <replaceable class="parameter">start</replaceable> ] + [ RESTART [ [ WITH ] <replaceable class="parameter">restart</replaceable> ] ] + [ CACHE <replaceable class="parameter">cache</replaceable> ] [ [ NO ] CYCLE ] + [ OWNED BY { <replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable> | NONE } ] +ALTER SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET { LOGGED | UNLOGGED } +ALTER SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER SEQUENCE</command> changes the parameters of an existing + sequence generator. Any parameters not specifically set in the + <command>ALTER SEQUENCE</command> command retain their prior settings. + </para> + + <para> + You must own the sequence to use <command>ALTER SEQUENCE</command>. + To change a sequence's schema, you must also have <literal>CREATE</literal> + privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the sequence's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the sequence. + However, a superuser can alter ownership of any sequence anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a sequence to be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the sequence does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The optional + clause <literal>AS <replaceable class="parameter">data_type</replaceable></literal> + changes the data type of the sequence. Valid types are + <literal>smallint</literal>, <literal>integer</literal>, + and <literal>bigint</literal>. + </para> + + <para> + Changing the data type automatically changes the minimum and maximum + values of the sequence if and only if the previous minimum and maximum + values were the minimum or maximum value of the old data type (in + other words, if the sequence had been created using <literal>NO + MINVALUE</literal> or <literal>NO MAXVALUE</literal>, implicitly or + explicitly). Otherwise, the minimum and maximum values are preserved, + unless new values are given as part of the same command. If the + minimum and maximum values do not fit into the new data type, an error + will be generated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">increment</replaceable></term> + <listitem> + <para> + The clause <literal>INCREMENT BY <replaceable + class="parameter">increment</replaceable></literal> is + optional. A positive value will make an ascending sequence, a + negative one a descending sequence. If unspecified, the old + increment value will be maintained. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">minvalue</replaceable></term> + <term><literal>NO MINVALUE</literal></term> + <listitem> + <para> + The optional clause <literal>MINVALUE <replaceable + class="parameter">minvalue</replaceable></literal> determines + the minimum value a sequence can generate. If <literal>NO + MINVALUE</literal> is specified, the defaults of 1 and + the minimum value of the data type for ascending and descending sequences, + respectively, will be used. If neither option is specified, + the current minimum value will be maintained. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">maxvalue</replaceable></term> + <term><literal>NO MAXVALUE</literal></term> + <listitem> + <para> + The optional clause <literal>MAXVALUE <replaceable + class="parameter">maxvalue</replaceable></literal> determines + the maximum value for the sequence. If <literal>NO + MAXVALUE</literal> is specified, the defaults of + the maximum value of the data type and -1 for ascending and descending + sequences, respectively, will be used. If neither option is + specified, the current maximum value will be maintained. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">start</replaceable></term> + <listitem> + <para> + The optional clause <literal>START WITH <replaceable + class="parameter">start</replaceable></literal> changes the + recorded start value of the sequence. This has no effect on the + <emphasis>current</emphasis> sequence value; it simply sets the value + that future <command>ALTER SEQUENCE RESTART</command> commands will use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">restart</replaceable></term> + <listitem> + <para> + The optional clause <literal>RESTART [ WITH <replaceable + class="parameter">restart</replaceable> ]</literal> changes the + current value of the sequence. This is similar to calling the + <function>setval</function> function with <literal>is_called</literal> = + <literal>false</literal>: the specified value will be returned by the + <emphasis>next</emphasis> call of <function>nextval</function>. + Writing <literal>RESTART</literal> with no <replaceable + class="parameter">restart</replaceable> value is equivalent to supplying + the start value that was recorded by <command>CREATE SEQUENCE</command> + or last set by <command>ALTER SEQUENCE START WITH</command>. + </para> + + <para> + In contrast to a <function>setval</function> call, + a <literal>RESTART</literal> operation on a sequence is transactional + and blocks concurrent transactions from obtaining numbers from the + same sequence. If that's not the desired mode of + operation, <function>setval</function> should be used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">cache</replaceable></term> + <listitem> + <para> + The clause <literal>CACHE <replaceable + class="parameter">cache</replaceable></literal> enables + sequence numbers to be preallocated and stored in memory for + faster access. The minimum value is 1 (only one value can be + generated at a time, i.e., no cache). If unspecified, the old + cache value will be maintained. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CYCLE</literal></term> + <listitem> + <para> + The optional <literal>CYCLE</literal> key word can be used to enable + the sequence to wrap around when the + <replaceable class="parameter">maxvalue</replaceable> or + <replaceable class="parameter">minvalue</replaceable> has been + reached by + an ascending or descending sequence respectively. If the limit is + reached, the next number generated will be the + <replaceable class="parameter">minvalue</replaceable> or + <replaceable class="parameter">maxvalue</replaceable>, + respectively. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO CYCLE</literal></term> + <listitem> + <para> + If the optional <literal>NO CYCLE</literal> key word is + specified, any calls to <function>nextval</function> after the + sequence has reached its maximum value will return an error. + If neither <literal>CYCLE</literal> or <literal>NO + CYCLE</literal> are specified, the old cycle behavior will be + maintained. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET { LOGGED | UNLOGGED }</literal></term> + <listitem> + <para> + This form changes the sequence from unlogged to logged or vice-versa + (see <xref linkend="sql-createsequence"/>). It cannot be applied to a + temporary sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OWNED BY</literal> <replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable></term> + <term><literal>OWNED BY NONE</literal></term> + <listitem> + <para> + The <literal>OWNED BY</literal> option causes the sequence to be + associated with a specific table column, such that if that column + (or its whole table) is dropped, the sequence will be automatically + dropped as well. If specified, this association replaces any + previously specified association for the sequence. The specified + table must have the same owner and be in the same schema as the + sequence. + Specifying <literal>OWNED BY NONE</literal> removes any existing + association, making the sequence <quote>free-standing</quote>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the sequence. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>ALTER SEQUENCE</command> will not immediately affect + <function>nextval</function> results in backends, + other than the current one, that have preallocated (cached) sequence + values. They will use up all cached values prior to noticing the changed + sequence generation parameters. The current backend will be affected + immediately. + </para> + + <para> + <command>ALTER SEQUENCE</command> does not affect the <function>currval</function> + status for the sequence. (Before <productname>PostgreSQL</productname> + 8.3, it sometimes did.) + </para> + + <para> + <command>ALTER SEQUENCE</command> blocks + concurrent <function>nextval</function>, <function>currval</function>, + <function>lastval</function>, and <command>setval</command> calls. + </para> + + <para> + For historical reasons, <command>ALTER TABLE</command> can be used with + sequences too; but the only variants of <command>ALTER TABLE</command> + that are allowed with sequences are equivalent to the forms shown above. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Restart a sequence called <literal>serial</literal>, at 105: +<programlisting> +ALTER SEQUENCE serial RESTART WITH 105; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER SEQUENCE</command> conforms to the <acronym>SQL</acronym> + standard, except for the <literal>AS</literal>, <literal>START WITH</literal>, + <literal>OWNED BY</literal>, <literal>OWNER TO</literal>, <literal>RENAME TO</literal>, and + <literal>SET SCHEMA</literal> clauses, which are + <productname>PostgreSQL</productname> extensions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createsequence"/></member> + <member><xref linkend="sql-dropsequence"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_server.sgml b/doc/src/sgml/ref/alter_server.sgml new file mode 100644 index 0000000..186f38b --- /dev/null +++ b/doc/src/sgml/ref/alter_server.sgml @@ -0,0 +1,144 @@ +<!-- +doc/src/sgml/ref/alter_server.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterserver"> + <indexterm zone="sql-alterserver"> + <primary>ALTER SERVER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER SERVER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER SERVER</refname> + <refpurpose>change the definition of a foreign server</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER SERVER <replaceable class="parameter">name</replaceable> [ VERSION '<replaceable class="parameter">new_version</replaceable>' ] + [ OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] ) ] +ALTER SERVER <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER SERVER <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER SERVER</command> changes the definition of a foreign + server. The first form changes the server version string or the + generic options of the server (at least one clause is required). + The second form changes the owner of the server. + </para> + + <para> + To alter the server you must be the owner of the server. + Additionally to alter the owner, you must own the server and also + be a direct or indirect member of the new owning role, and you must + have <literal>USAGE</literal> privilege on the server's foreign-data + wrapper. (Note that superusers satisfy all these criteria + automatically.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_version</replaceable></term> + <listitem> + <para> + New server version. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] )</literal></term> + <listitem> + <para> + Change options for the + server. <literal>ADD</literal>, <literal>SET</literal>, and <literal>DROP</literal> + specify the action to be performed. <literal>ADD</literal> is assumed + if no operation is explicitly specified. Option names must be + unique; names and values are also validated using the server's + foreign-data wrapper library. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the foreign server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the foreign server. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Alter server <literal>foo</literal>, add connection options: +<programlisting> +ALTER SERVER foo OPTIONS (host 'foo', dbname 'foodb'); +</programlisting> + </para> + + <para> + Alter server <literal>foo</literal>, change version, + change <literal>host</literal> option: +<programlisting> +ALTER SERVER foo VERSION '8.4' OPTIONS (SET host 'baz'); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER SERVER</command> conforms to ISO/IEC 9075-9 (SQL/MED). + The <literal>OWNER TO</literal> and <literal>RENAME</literal> forms are + PostgreSQL extensions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createserver"/></member> + <member><xref linkend="sql-dropserver"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_statistics.sgml b/doc/src/sgml/ref/alter_statistics.sgml new file mode 100644 index 0000000..ce6cdf2 --- /dev/null +++ b/doc/src/sgml/ref/alter_statistics.sgml @@ -0,0 +1,135 @@ +<!-- +doc/src/sgml/ref/alter_statistics.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterstatistics"> + <indexterm zone="sql-alterstatistics"> + <primary>ALTER STATISTICS</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER STATISTICS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER STATISTICS</refname> + <refpurpose> + change the definition of an extended statistics object + </refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER STATISTICS <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER STATISTICS <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER STATISTICS <replaceable class="parameter">name</replaceable> SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER STATISTICS <replaceable class="parameter">name</replaceable> SET STATISTICS <replaceable class="parameter">new_target</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER STATISTICS</command> changes the parameters of an existing + extended statistics object. Any parameters not specifically set in the + <command>ALTER STATISTICS</command> command retain their prior settings. + </para> + + <para> + You must own the statistics object to use <command>ALTER STATISTICS</command>. + To change a statistics object's schema, you must also + have <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the statistics object's schema. (These restrictions enforce that altering + the owner doesn't do anything you couldn't do by dropping and recreating + the statistics object. However, a superuser can alter ownership of any + statistics object anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the statistics object to be + altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the statistics object. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the statistics object. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the statistics object. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_target</replaceable></term> + <listitem> + <para> + The statistic-gathering target for this statistics object for subsequent + <link linkend="sql-analyze"><command>ANALYZE</command></link> operations. + The target can be set in the range 0 to 10000; alternatively, set it + to -1 to revert to using the maximum of the statistics target of the + referenced columns, if set, or the system default statistics + target (<xref linkend="guc-default-statistics-target"/>). + For more information on the use of statistics by the + <productname>PostgreSQL</productname> query planner, refer to + <xref linkend="planner-stats"/>. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER STATISTICS</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createstatistics"/></member> + <member><xref linkend="sql-dropstatistics"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_subscription.sgml b/doc/src/sgml/ref/alter_subscription.sgml new file mode 100644 index 0000000..353ea5d --- /dev/null +++ b/doc/src/sgml/ref/alter_subscription.sgml @@ -0,0 +1,313 @@ +<!-- +doc/src/sgml/ref/alter_subscription.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altersubscription"> + <indexterm zone="sql-altersubscription"> + <primary>ALTER SUBSCRIPTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER SUBSCRIPTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER SUBSCRIPTION</refname> + <refpurpose>change the definition of a subscription</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> CONNECTION '<replaceable>conninfo</replaceable>' +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> SET PUBLICATION <replaceable class="parameter">publication_name</replaceable> [, ...] [ WITH ( <replaceable class="parameter">publication_option</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> ADD PUBLICATION <replaceable class="parameter">publication_name</replaceable> [, ...] [ WITH ( <replaceable class="parameter">publication_option</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> DROP PUBLICATION <replaceable class="parameter">publication_name</replaceable> [, ...] [ WITH ( <replaceable class="parameter">publication_option</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> REFRESH PUBLICATION [ WITH ( <replaceable class="parameter">refresh_option</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> ENABLE +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> DISABLE +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> SET ( <replaceable class="parameter">subscription_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> SKIP ( <replaceable class="parameter">skip_option</replaceable> = <replaceable class="parameter">value</replaceable> ) +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER SUBSCRIPTION</command> can change most of the subscription + properties that can be specified + in <xref linkend="sql-createsubscription"/>. + </para> + + <para> + You must own the subscription to use <command>ALTER SUBSCRIPTION</command>. + To alter the owner, you must also be a direct or indirect member of the + new owning role. The new owner has to be a superuser. + (Currently, all subscription owners must be superusers, so the owner checks + will be bypassed in practice. But this might change in the future.) + </para> + + <para> + When refreshing a publication we remove the relations that are no longer + part of the publication and we also remove the table synchronization slots + if there are any. It is necessary to remove these slots so that the resources + allocated for the subscription on the remote host are released. If due to + network breakdown or some other error, <productname>PostgreSQL</productname> + is unable to remove the slots, an error will be reported. To proceed in this + situation, the user either needs to retry the operation or disassociate the + slot from the subscription and drop the subscription as explained in + <xref linkend="sql-dropsubscription"/>. + </para> + + <para> + Commands <command>ALTER SUBSCRIPTION ... REFRESH PUBLICATION</command> and + <command>ALTER SUBSCRIPTION ... {SET|ADD|DROP} PUBLICATION ...</command> + with <literal>refresh</literal> option as <literal>true</literal> cannot be + executed inside a transaction block. + + These commands also cannot be executed when the subscription has + <literal>two_phase</literal> commit enabled, + unless <literal>copy_data</literal> is <literal>false</literal>. + See column <structfield>subtwophasestate</structfield> of + <link linkend="catalog-pg-subscription"><structname>pg_subscription</structname></link> + to know the actual two-phase state. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a subscription whose properties are to be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONNECTION '<replaceable class="parameter">conninfo</replaceable>'</literal></term> + <listitem> + <para> + This clause replaces the connection string originally set by + <xref linkend="sql-createsubscription"/>. See there for more + information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET PUBLICATION <replaceable class="parameter">publication_name</replaceable></literal></term> + <term><literal>ADD PUBLICATION <replaceable class="parameter">publication_name</replaceable></literal></term> + <term><literal>DROP PUBLICATION <replaceable class="parameter">publication_name</replaceable></literal></term> + <listitem> + <para> + These forms change the list of subscribed publications. + <literal>SET</literal> + replaces the entire list of publications with a new list, + <literal>ADD</literal> adds additional publications to the list of + publications, and <literal>DROP</literal> removes the publications from + the list of publications. We allow non-existent publications to be + specified in <literal>ADD</literal> and <literal>SET</literal> variants + so that users can add those later. See <xref linkend="sql-createsubscription"/> + for more information. By default, this command will also act like + <literal>REFRESH PUBLICATION</literal>. + </para> + + <para> + <replaceable>publication_option</replaceable> specifies additional + options for this operation. The supported options are: + + <variablelist> + <varlistentry> + <term><literal>refresh</literal> (<type>boolean</type>)</term> + <listitem> + <para> + When false, the command will not try to refresh table information. + <literal>REFRESH PUBLICATION</literal> should then be executed separately. + The default is <literal>true</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + Additionally, the options described under + <literal>REFRESH PUBLICATION</literal> may be specified, to control the + implicit refresh operation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REFRESH PUBLICATION</literal></term> + <listitem> + <para> + Fetch missing table information from publisher. This will start + replication of tables that were added to the subscribed-to publications + since <command>CREATE SUBSCRIPTION</command> or + the last invocation of <command>REFRESH PUBLICATION</command>. + </para> + + <para> + <replaceable>refresh_option</replaceable> specifies additional options for the + refresh operation. The supported options are: + + <variablelist> + <varlistentry> + <term><literal>copy_data</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether to copy pre-existing data in the publications + that are being subscribed to when the replication starts. + The default is <literal>true</literal>. + </para> + <para> + Previously subscribed tables are not copied, even if a table's row + filter <literal>WHERE</literal> clause has since been modified. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ENABLE</literal></term> + <listitem> + <para> + Enables a previously disabled subscription, starting the logical + replication worker at the end of the transaction. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal></term> + <listitem> + <para> + Disables a running subscription, stopping the logical replication + worker at the end of the transaction. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">subscription_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause alters parameters originally set by + <xref linkend="sql-createsubscription"/>. See there for more + information. The parameters that can be altered + are <literal>slot_name</literal>, + <literal>synchronous_commit</literal>, + <literal>binary</literal>, <literal>streaming</literal>, and + <literal>disable_on_error</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SKIP ( <replaceable class="parameter">skip_option</replaceable> = <replaceable class="parameter">value</replaceable> )</literal></term> + <listitem> + <para> + Skips applying all changes of the remote transaction. If incoming data + violates any constraints, logical replication will stop until it is + resolved. By using the <command>ALTER SUBSCRIPTION ... SKIP</command> command, + the logical replication worker skips all data modification changes within + the transaction. This option has no effect on the transactions that are + already prepared by enabling <literal>two_phase</literal> on + subscriber. + After the logical replication worker successfully skips the transaction or + finishes a transaction, the LSN (stored in + <structname>pg_subscription</structname>.<structfield>subskiplsn</structfield>) + is cleared. See <xref linkend="logical-replication-conflicts"/> for + the details of logical replication conflicts. Using this command requires + superuser privilege. + </para> + + <para> + <replaceable>skip_option</replaceable> specifies options for this operation. + The supported option is: + + <variablelist> + <varlistentry> + <term><literal>lsn</literal> (<type>pg_lsn</type>)</term> + <listitem> + <para> + Specifies the finish LSN of the remote transaction whose changes + are to be skipped by the logical replication worker. The finish LSN + is the LSN at which the transaction is either committed or prepared. + Skipping individual subtransactions is not supported. Setting + <literal>NONE</literal> resets the LSN. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the subscription. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the subscription. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change the publication subscribed by a subscription to + <literal>insert_only</literal>: +<programlisting> +ALTER SUBSCRIPTION mysub SET PUBLICATION insert_only; +</programlisting> + </para> + + <para> + Disable (stop) the subscription: +<programlisting> +ALTER SUBSCRIPTION mysub DISABLE; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER SUBSCRIPTION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createsubscription"/></member> + <member><xref linkend="sql-dropsubscription"/></member> + <member><xref linkend="sql-createpublication"/></member> + <member><xref linkend="sql-alterpublication"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_system.sgml b/doc/src/sgml/ref/alter_system.sgml new file mode 100644 index 0000000..bea5714 --- /dev/null +++ b/doc/src/sgml/ref/alter_system.sgml @@ -0,0 +1,152 @@ +<!-- +doc/src/sgml/ref/alter_system.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altersystem"> + <indexterm zone="sql-altersystem"> + <primary>ALTER SYSTEM</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER SYSTEM</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER SYSTEM</refname> + <refpurpose>change a server configuration parameter</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER SYSTEM SET <replaceable class="parameter">configuration_parameter</replaceable> { TO | = } { <replaceable class="parameter">value</replaceable> [, ...] | DEFAULT } + +ALTER SYSTEM RESET <replaceable class="parameter">configuration_parameter</replaceable> +ALTER SYSTEM RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER SYSTEM</command> is used for changing server configuration + parameters across the entire database cluster. It can be more convenient + than the traditional method of manually editing + the <filename>postgresql.conf</filename> file. + <command>ALTER SYSTEM</command> writes the given parameter setting to + the <filename>postgresql.auto.conf</filename> file, which is read in + addition to <filename>postgresql.conf</filename>. + Setting a parameter to <literal>DEFAULT</literal>, or using the + <command>RESET</command> variant, removes that configuration entry from the + <filename>postgresql.auto.conf</filename> file. Use <literal>RESET + ALL</literal> to remove all such configuration entries. + </para> + + <para> + Values set with <command>ALTER SYSTEM</command> will be effective after + the next server configuration reload, or after the next server restart + in the case of parameters that can only be changed at server start. + A server configuration reload can be commanded by calling the SQL + function <function>pg_reload_conf()</function>, running <literal>pg_ctl reload</literal>, + or sending a <systemitem>SIGHUP</systemitem> signal to the main server process. + </para> + + <para> + Only superusers and users granted <literal>ALTER SYSTEM</literal> privilege + on a parameter can change it using <command>ALTER SYSTEM</command>. Also, since + this command acts directly on the file system and cannot be rolled back, + it is not allowed inside a transaction block or function. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">configuration_parameter</replaceable></term> + <listitem> + <para> + Name of a settable configuration parameter. Available parameters are + documented in <xref linkend="runtime-config"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + New value of the parameter. Values can be specified as string + constants, identifiers, numbers, or comma-separated lists of + these, as appropriate for the particular parameter. + Values that are neither numbers nor valid identifiers must be quoted. + <literal>DEFAULT</literal> can be written to specify removing the + parameter and its value from <filename>postgresql.auto.conf</filename>. + </para> + + <para> + For some list-accepting parameters, quoted values will produce + double-quoted output to preserve whitespace and commas; for others, + double-quotes must be used inside single-quoted strings to get + this effect. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + This command can't be used to set <xref linkend="guc-data-directory"/>, + nor parameters that are not allowed in <filename>postgresql.conf</filename> + (e.g., <link linkend="runtime-config-preset">preset options</link>). + </para> + + <para> + See <xref linkend="config-setting"/> for other ways to set the parameters. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Set the <literal>wal_level</literal>: +<programlisting> +ALTER SYSTEM SET wal_level = replica; +</programlisting> + </para> + + <para> + Undo that, restoring whatever setting was effective + in <filename>postgresql.conf</filename>: +<programlisting> +ALTER SYSTEM RESET wal_level; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>ALTER SYSTEM</command> statement is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set"/></member> + <member><xref linkend="sql-show"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml new file mode 100644 index 0000000..6fd8faf --- /dev/null +++ b/doc/src/sgml/ref/alter_table.sgml @@ -0,0 +1,1785 @@ +<!-- +doc/src/sgml/ref/alter_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertable"> + <indexterm zone="sql-altertable"> + <primary>ALTER TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TABLE</refname> + <refpurpose>change the definition of a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] + <replaceable class="parameter">action</replaceable> [, ... ] +ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] + RENAME [ COLUMN ] <replaceable class="parameter">column_name</replaceable> TO <replaceable class="parameter">new_column_name</replaceable> +ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] + RENAME CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> TO <replaceable class="parameter">new_constraint_name</replaceable> +ALTER TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER TABLE ALL IN TABLESPACE <replaceable class="parameter">name</replaceable> [ OWNED BY <replaceable class="parameter">role_name</replaceable> [, ... ] ] + SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> [ NOWAIT ] +ALTER TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + ATTACH PARTITION <replaceable class="parameter">partition_name</replaceable> { FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT } +ALTER TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> + DETACH PARTITION <replaceable class="parameter">partition_name</replaceable> [ CONCURRENTLY | FINALIZE ] + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + ADD [ COLUMN ] [ IF NOT EXISTS ] <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + DROP [ COLUMN ] [ IF EXISTS ] <replaceable class="parameter">column_name</replaceable> [ RESTRICT | CASCADE ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> [ SET DATA ] TYPE <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ USING <replaceable class="parameter">expression</replaceable> ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET DEFAULT <replaceable class="parameter">expression</replaceable> + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> DROP DEFAULT + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> { SET | DROP } NOT NULL + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> DROP EXPRESSION [ IF EXISTS ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( <replaceable>sequence_options</replaceable> ) ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> { SET GENERATED { ALWAYS | BY DEFAULT } | SET <replaceable>sequence_option</replaceable> | RESTART [ [ WITH ] <replaceable class="parameter">restart</replaceable> ] } [...] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> DROP IDENTITY [ IF EXISTS ] + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STATISTICS <replaceable class="parameter">integer</replaceable> + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET ( <replaceable class="parameter">attribute_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> RESET ( <replaceable class="parameter">attribute_option</replaceable> [, ... ] ) + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } + ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET COMPRESSION <replaceable class="parameter">compression_method</replaceable> + ADD <replaceable class="parameter">table_constraint</replaceable> [ NOT VALID ] + ADD <replaceable class="parameter">table_constraint_using_index</replaceable> + ALTER CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + VALIDATE CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> + DROP CONSTRAINT [ IF EXISTS ] <replaceable class="parameter">constraint_name</replaceable> [ RESTRICT | CASCADE ] + DISABLE TRIGGER [ <replaceable class="parameter">trigger_name</replaceable> | ALL | USER ] + ENABLE TRIGGER [ <replaceable class="parameter">trigger_name</replaceable> | ALL | USER ] + ENABLE REPLICA TRIGGER <replaceable class="parameter">trigger_name</replaceable> + ENABLE ALWAYS TRIGGER <replaceable class="parameter">trigger_name</replaceable> + DISABLE RULE <replaceable class="parameter">rewrite_rule_name</replaceable> + ENABLE RULE <replaceable class="parameter">rewrite_rule_name</replaceable> + ENABLE REPLICA RULE <replaceable class="parameter">rewrite_rule_name</replaceable> + ENABLE ALWAYS RULE <replaceable class="parameter">rewrite_rule_name</replaceable> + DISABLE ROW LEVEL SECURITY + ENABLE ROW LEVEL SECURITY + FORCE ROW LEVEL SECURITY + NO FORCE ROW LEVEL SECURITY + CLUSTER ON <replaceable class="parameter">index_name</replaceable> + SET WITHOUT CLUSTER + SET WITHOUT OIDS + SET ACCESS METHOD <replaceable class="parameter">new_access_method</replaceable> + SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> + SET { LOGGED | UNLOGGED } + SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) + RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] ) + INHERIT <replaceable class="parameter">parent_table</replaceable> + NO INHERIT <replaceable class="parameter">parent_table</replaceable> + OF <replaceable class="parameter">type_name</replaceable> + NOT OF + OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } + REPLICA IDENTITY { DEFAULT | USING INDEX <replaceable class="parameter">index_name</replaceable> | FULL | NOTHING } + +<phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase> + +IN ( <replaceable class="parameter">partition_bound_expr</replaceable> [, ...] ) | +FROM ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) + TO ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) | +WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REMAINDER <replaceable class="parameter">numeric_literal</replaceable> ) + +<phrase>and <replaceable class="parameter">column_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ NOT NULL | + NULL | + CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] | + DEFAULT <replaceable>default_expr</replaceable> | + GENERATED ALWAYS AS ( <replaceable>generation_expr</replaceable> ) STORED | + GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( <replaceable>sequence_options</replaceable> ) ] | + UNIQUE [ NULLS [ NOT ] DISTINCT ] <replaceable class="parameter">index_parameters</replaceable> | + PRIMARY KEY <replaceable class="parameter">index_parameters</replaceable> | + REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] + [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ] } +[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + +<phrase>and <replaceable class="parameter">table_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] | + UNIQUE [ NULLS [ NOT ] DISTINCT ] ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> | + PRIMARY KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> | + EXCLUDE [ USING <replaceable class="parameter">index_method</replaceable> ] ( <replaceable class="parameter">exclude_element</replaceable> WITH <replaceable class="parameter">operator</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> [ WHERE ( <replaceable class="parameter">predicate</replaceable> ) ] | + FOREIGN KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> [, ... ] ) ] + [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ] } +[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + +<phrase>and <replaceable class="parameter">table_constraint_using_index</replaceable> is:</phrase> + + [ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] + { UNIQUE | PRIMARY KEY } USING INDEX <replaceable class="parameter">index_name</replaceable> + [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + +<phrase><replaceable class="parameter">index_parameters</replaceable> in <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and <literal>EXCLUDE</literal> constraints are:</phrase> + +[ INCLUDE ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] +[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +[ USING INDEX TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + +<phrase><replaceable class="parameter">exclude_element</replaceable> in an <literal>EXCLUDE</literal> constraint is:</phrase> + +{ <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ <replaceable class="parameter">opclass</replaceable> ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] + +<phrase><replaceable class="parameter">referential_action</replaceable> in a <literal>FOREIGN KEY</literal>/<literal>REFERENCES</literal> constraint is:</phrase> + +{ NO ACTION | RESTRICT | CASCADE | SET NULL [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] | SET DEFAULT [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TABLE</command> changes the definition of an existing table. + There are several subforms described below. Note that the lock level required + may differ for each subform. An <literal>ACCESS EXCLUSIVE</literal> lock is + acquired unless explicitly noted. When multiple subcommands are given, the + lock acquired will be the strictest one required by any subcommand. + + <variablelist> + <varlistentry> + <term><literal>ADD COLUMN [ IF NOT EXISTS ]</literal></term> + <listitem> + <para> + This form adds a new column to the table, using the same syntax as + <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. If <literal>IF NOT EXISTS</literal> + is specified and a column already exists with this name, + no error is thrown. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP COLUMN [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops a column from a table. Indexes and + table constraints involving the column will be automatically + dropped as well. + Multivariate statistics referencing the dropped column will also be + removed if the removal of the column would cause the statistics to + contain data for only a single column. + You will need to say <literal>CASCADE</literal> if anything outside the table + depends on the column, for example, foreign key references or views. + If <literal>IF EXISTS</literal> is specified and the column + does not exist, no error is thrown. In this case a notice + is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET DATA TYPE</literal></term> + <listitem> + <para> + This form changes the type of a column of a table. Indexes and + simple table constraints involving the column will be automatically + converted to use the new column type by reparsing the originally + supplied expression. + The optional <literal>COLLATE</literal> clause specifies a collation + for the new column; if omitted, the collation is the default for the + new column type. + The optional <literal>USING</literal> + clause specifies how to compute the new column value from the old; + if omitted, the default conversion is the same as an assignment + cast from old data type to new. A <literal>USING</literal> + clause must be provided if there is no implicit or assignment + cast from old to new type. + </para> + + <para> + When this form is used, the column's statistics are removed, + so running <link linkend="sql-analyze"><command>ANALYZE</command></link> + on the table afterwards is recommended. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP DEFAULT</literal></term> + <listitem> + <para> + These forms set or remove the default value for a column (where + removal is equivalent to setting the default value to NULL). The new + default value will only apply in subsequent <command>INSERT</command> + or <command>UPDATE</command> commands; it does not cause rows already + in the table to change. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP NOT NULL</literal></term> + <listitem> + <para> + These forms change whether a column is marked to allow null + values or to reject null values. + </para> + + <para> + <literal>SET NOT NULL</literal> may only be applied to a column + provided none of the records in the table contain a + <literal>NULL</literal> value for the column. Ordinarily this is + checked during the <literal>ALTER TABLE</literal> by scanning the + entire table; however, if a valid <literal>CHECK</literal> constraint is + found which proves no <literal>NULL</literal> can exist, then the + table scan is skipped. + </para> + + <para> + If this table is a partition, one cannot perform <literal>DROP NOT NULL</literal> + on a column if it is marked <literal>NOT NULL</literal> in the parent + table. To drop the <literal>NOT NULL</literal> constraint from all the + partitions, perform <literal>DROP NOT NULL</literal> on the parent + table. Even if there is no <literal>NOT NULL</literal> constraint on the + parent, such a constraint can still be added to individual partitions, + if desired; that is, the children can disallow nulls even if the parent + allows them, but not the other way around. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP EXPRESSION [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form turns a stored generated column into a normal base column. + Existing data in the columns is retained, but future changes will no + longer apply the generation expression. + </para> + + <para> + If <literal>DROP EXPRESSION IF EXISTS</literal> is specified and the + column is not a stored generated column, no error is thrown. In this + case a notice is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY</literal></term> + <term><literal>SET GENERATED { ALWAYS | BY DEFAULT }</literal></term> + <term><literal>DROP IDENTITY [ IF EXISTS ]</literal></term> + <listitem> + <para> + These forms change whether a column is an identity column or change the + generation attribute of an existing identity column. + See <link linkend="sql-createtable"><command>CREATE TABLE</command></link> for details. + Like <literal>SET DEFAULT</literal>, these forms only affect the + behavior of subsequent <command>INSERT</command> + and <command>UPDATE</command> commands; they do not cause rows + already in the table to change. + </para> + + <para> + If <literal>DROP IDENTITY IF EXISTS</literal> is specified and the + column is not an identity column, no error is thrown. In this case a + notice is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET <replaceable>sequence_option</replaceable></literal></term> + <term><literal>RESTART</literal></term> + <listitem> + <para> + These forms alter the sequence that underlies an existing identity + column. <replaceable>sequence_option</replaceable> is an option + supported by <link linkend="sql-altersequence"><command>ALTER SEQUENCE</command></link> such + as <literal>INCREMENT BY</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET STATISTICS</literal></term> + <listitem> + <para> + This form + sets the per-column statistics-gathering target for subsequent + <link linkend="sql-analyze"><command>ANALYZE</command></link> operations. + The target can be set in the range 0 to 10000; alternatively, set it + to -1 to revert to using the system default statistics + target (<xref linkend="guc-default-statistics-target"/>). + For more information on the use of statistics by the + <productname>PostgreSQL</productname> query planner, refer to + <xref linkend="planner-stats"/>. + </para> + <para> + <literal>SET STATISTICS</literal> acquires a + <literal>SHARE UPDATE EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">attribute_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] )</literal></term> + <term><literal>RESET ( <replaceable class="parameter">attribute_option</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + This form sets or resets per-attribute options. Currently, the only + defined per-attribute options are <literal>n_distinct</literal> and + <literal>n_distinct_inherited</literal>, which override the + number-of-distinct-values estimates made by subsequent + <link linkend="sql-analyze"><command>ANALYZE</command></link> + operations. <literal>n_distinct</literal> affects the statistics for the table + itself, while <literal>n_distinct_inherited</literal> affects the statistics + gathered for the table plus its inheritance children. When set to a + positive value, <command>ANALYZE</command> will assume that the column contains + exactly the specified number of distinct nonnull values. When set to a + negative value, which must be greater + than or equal to -1, <command>ANALYZE</command> will assume that the number of + distinct nonnull values in the column is linear in the size of the + table; the exact count is to be computed by multiplying the estimated + table size by the absolute value of the given number. For example, + a value of -1 implies that all values in the column are distinct, while + a value of -0.5 implies that each value appears twice on the average. + This can be useful when the size of the table changes over time, since + the multiplication by the number of rows in the table is not performed + until query planning time. Specify a value of 0 to revert to estimating + the number of distinct values normally. For more information on the use + of statistics by the <productname>PostgreSQL</productname> query + planner, refer to <xref linkend="planner-stats"/>. + </para> + <para> + Changing per-attribute options acquires a + <literal>SHARE UPDATE EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>SET STORAGE</literal> + <indexterm> + <primary>TOAST</primary> + <secondary>per-column storage settings</secondary> + </indexterm> + </term> + <listitem> + <para> + This form sets the storage mode for a column. This controls whether this + column is held inline or in a secondary <acronym>TOAST</acronym> table, and + whether the data + should be compressed or not. <literal>PLAIN</literal> must be used + for fixed-length values such as <type>integer</type> and is + inline, uncompressed. <literal>MAIN</literal> is for inline, + compressible data. <literal>EXTERNAL</literal> is for external, + uncompressed data, and <literal>EXTENDED</literal> is for external, + compressed data. <literal>EXTENDED</literal> is the default for most + data types that support non-<literal>PLAIN</literal> storage. + Use of <literal>EXTERNAL</literal> will make substring operations on + very large <type>text</type> and <type>bytea</type> values run faster, + at the penalty of increased storage space. Note that + <literal>SET STORAGE</literal> doesn't itself change anything in the table, + it just sets the strategy to be pursued during future table updates. + See <xref linkend="storage-toast"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>SET COMPRESSION <replaceable class="parameter">compression_method</replaceable></literal> + </term> + <listitem> + <para> + This form sets the compression method for a column, determining how + values inserted in future will be compressed (if the storage mode + permits compression at all). + This does not cause the table to be rewritten, so existing data may still + be compressed with other compression methods. If the table is restored + with <application>pg_restore</application>, then all values are rewritten + with the configured compression method. + However, when data is inserted from another relation (for example, + by <command>INSERT ... SELECT</command>), values from the source table are + not necessarily detoasted, so any previously compressed data may retain + its existing compression method, rather than being recompressed with the + compression method of the target column. + The supported compression + methods are <literal>pglz</literal> and <literal>lz4</literal>. + (<literal>lz4</literal> is available only if <option>--with-lz4</option> + was used when building <productname>PostgreSQL</productname>.) In + addition, <replaceable class="parameter">compression_method</replaceable> + can be <literal>default</literal>, which selects the default behavior of + consulting the <xref linkend="guc-default-toast-compression"/> setting + at the time of data insertion to determine the method to use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD <replaceable class="parameter">table_constraint</replaceable> [ NOT VALID ]</literal></term> + <listitem> + <para> + This form adds a new constraint to a table using the same constraint + syntax as <link linkend="sql-createtable"><command>CREATE TABLE</command></link>, plus the option <literal>NOT + VALID</literal>, which is currently only allowed for foreign key + and CHECK constraints. + </para> + + <para> + Normally, this form will cause a scan of the table to verify that all + existing rows in the table satisfy the new constraint. But if + the <literal>NOT VALID</literal> option is used, this + potentially-lengthy scan is skipped. The constraint will still be + enforced against subsequent inserts or updates (that is, they'll fail + unless there is a matching row in the referenced table, in the case + of foreign keys, or they'll fail unless the new row matches the + specified check condition). But the + database will not assume that the constraint holds for all rows in + the table, until it is validated by using the <literal>VALIDATE + CONSTRAINT</literal> option. + See <xref linkend="sql-altertable-notes"/> below for more information + about using the <literal>NOT VALID</literal> option. + </para> + + <para> + Although most forms of <literal>ADD + <replaceable class="parameter">table_constraint</replaceable></literal> + require an <literal>ACCESS EXCLUSIVE</literal> lock, <literal>ADD + FOREIGN KEY</literal> requires only a <literal>SHARE ROW + EXCLUSIVE</literal> lock. Note that <literal>ADD FOREIGN KEY</literal> + also acquires a <literal>SHARE ROW EXCLUSIVE</literal> lock on the + referenced table, in addition to the lock on the table on which the + constraint is declared. + </para> + + <para> + Additional restrictions apply when unique or primary key constraints + are added to partitioned tables; see <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. + Also, foreign key constraints on partitioned + tables may not be declared <literal>NOT VALID</literal> at present. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD <replaceable class="parameter">table_constraint_using_index</replaceable></literal></term> + <listitem> + <para> + This form adds a new <literal>PRIMARY KEY</literal> or <literal>UNIQUE</literal> + constraint to a table based on an existing unique index. All the + columns of the index will be included in the constraint. + </para> + + <para> + The index cannot have expression columns nor be a partial index. + Also, it must be a b-tree index with default sort ordering. These + restrictions ensure that the index is equivalent to one that would be + built by a regular <literal>ADD PRIMARY KEY</literal> or <literal>ADD UNIQUE</literal> + command. + </para> + + <para> + If <literal>PRIMARY KEY</literal> is specified, and the index's columns are not + already marked <literal>NOT NULL</literal>, then this command will attempt to + do <literal>ALTER COLUMN SET NOT NULL</literal> against each such column. + That requires a full table scan to verify the column(s) contain no + nulls. In all other cases, this is a fast operation. + </para> + + <para> + If a constraint name is provided then the index will be renamed to match + the constraint name. Otherwise the constraint will be named the same as + the index. + </para> + + <para> + After this command is executed, the index is <quote>owned</quote> by the + constraint, in the same way as if the index had been built by + a regular <literal>ADD PRIMARY KEY</literal> or <literal>ADD UNIQUE</literal> + command. In particular, dropping the constraint will make the index + disappear too. + </para> + + <para> + This form is not currently supported on partitioned tables. + </para> + + <note> + <para> + Adding a constraint using an existing index can be helpful in + situations where a new constraint needs to be added without blocking + table updates for a long time. To do that, create the index using + <command>CREATE INDEX CONCURRENTLY</command>, and then install it as an + official constraint using this syntax. See the example below. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALTER CONSTRAINT</literal></term> + <listitem> + <para> + This form alters the attributes of a constraint that was previously + created. Currently only foreign key constraints may be altered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATE CONSTRAINT</literal></term> + <listitem> + <para> + This form validates a foreign key or check constraint that was + previously created as <literal>NOT VALID</literal>, by scanning the + table to ensure there are no rows for which the constraint is not + satisfied. Nothing happens if the constraint is already marked valid. + (See <xref linkend="sql-altertable-notes"/> below for an explanation + of the usefulness of this command.) + </para> + <para> + This command acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP CONSTRAINT [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops the specified constraint on a table, along with + any index underlying the constraint. + If <literal>IF EXISTS</literal> is specified and the constraint + does not exist, no error is thrown. In this case a notice is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] TRIGGER</literal></term> + <listitem> + <para> + These forms configure the firing of trigger(s) belonging to the table. + A disabled trigger is still known to the system, but is not executed + when its triggering event occurs. (For a deferred trigger, the enable + status is checked when the event occurs, not when the trigger function + is actually executed.) One can disable or enable a single + trigger specified by name, or all triggers on the table, or only + user triggers (this option excludes internally generated constraint + triggers, such as those that are used to implement foreign key + constraints or deferrable uniqueness and exclusion constraints). + Disabling or enabling internally generated constraint triggers + requires superuser privileges; it should be done with caution since + of course the integrity of the constraint cannot be guaranteed if the + triggers are not executed. + </para> + + <para> + The trigger firing mechanism is also affected by the configuration + variable <xref linkend="guc-session-replication-role"/>. Simply enabled + triggers (the default) will fire when the replication role is <quote>origin</quote> + (the default) or <quote>local</quote>. Triggers configured as <literal>ENABLE + REPLICA</literal> will only fire if the session is in <quote>replica</quote> + mode, and triggers configured as <literal>ENABLE ALWAYS</literal> will + fire regardless of the current replication role. + </para> + + <para> + The effect of this mechanism is that in the default configuration, + triggers do not fire on replicas. This is useful because if a trigger + is used on the origin to propagate data between tables, then the + replication system will also replicate the propagated data; so the + trigger should not fire a second time on the replica, because that would + lead to duplication. However, if a trigger is used for another purpose + such as creating external alerts, then it might be appropriate to set it + to <literal>ENABLE ALWAYS</literal> so that it is also fired on + replicas. + </para> + + <para> + When this command is applied to a partitioned table, the states of + corresponding clone triggers in the partitions are updated too, + unless <literal>ONLY</literal> is specified. + </para> + + <para> + This command acquires a <literal>SHARE ROW EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] RULE</literal></term> + <listitem> + <para> + These forms configure the firing of rewrite rules belonging to the table. + A disabled rule is still known to the system, but is not applied + during query rewriting. The semantics are as for disabled/enabled + triggers. This configuration is ignored for <literal>ON SELECT</literal> rules, which + are always applied in order to keep views working even if the current + session is in a non-default replication role. + </para> + + <para> + The rule firing mechanism is also affected by the configuration variable + <xref linkend="guc-session-replication-role"/>, analogous to triggers as + described above. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE</literal>/<literal>ENABLE ROW LEVEL SECURITY</literal></term> + <listitem> + <para> + These forms control the application of row security policies belonging + to the table. If enabled and no policies exist for the table, then a + default-deny policy is applied. Note that policies can exist for a table + even if row-level security is disabled. In this case, the policies will + <emphasis>not</emphasis> be applied and the policies will be ignored. + See also + <link linkend="sql-createpolicy"><command>CREATE POLICY</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO FORCE</literal>/<literal>FORCE ROW LEVEL SECURITY</literal></term> + <listitem> + <para> + These forms control the application of row security policies belonging + to the table when the user is the table owner. If enabled, row-level + security policies will be applied when the user is the table owner. If + disabled (the default) then row-level security will not be applied when + the user is the table owner. + See also + <link linkend="sql-createpolicy"><command>CREATE POLICY</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CLUSTER ON</literal></term> + <listitem> + <para> + This form selects the default index for future + <link linkend="sql-cluster"><command>CLUSTER</command></link> + operations. It does not actually re-cluster the table. + </para> + <para> + Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET WITHOUT CLUSTER</literal></term> + <listitem> + <para> + This form removes the most recently used + <link linkend="sql-cluster"><command>CLUSTER</command></link> + index specification from the table. This affects + future cluster operations that don't specify an index. + </para> + <para> + Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET WITHOUT OIDS</literal></term> + <listitem> + <para> + Backward-compatible syntax for removing the <literal>oid</literal> + system column. As <literal>oid</literal> system columns cannot be + added anymore, this never has an effect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ACCESS METHOD</literal></term> + <listitem> + <para> + This form changes the access method of the table by rewriting it. See + <xref linkend="tableam"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET TABLESPACE</literal></term> + <listitem> + <para> + This form changes the table's tablespace to the specified tablespace and + moves the data file(s) associated with the table to the new tablespace. + Indexes on the table, if any, are not moved; but they can be moved + separately with additional <literal>SET TABLESPACE</literal> commands. + When applied to a partitioned table, nothing is moved, but any + partitions created afterwards with + <command>CREATE TABLE PARTITION OF</command> will use that tablespace, + unless overridden by a <literal>TABLESPACE</literal> clause. + </para> + + <para> + All tables in the current database in a tablespace can be moved by using + the <literal>ALL IN TABLESPACE</literal> form, which will lock all tables + to be moved first and then move each one. This form also supports + <literal>OWNED BY</literal>, which will only move tables owned by the + roles specified. If the <literal>NOWAIT</literal> option is specified + then the command will fail if it is unable to acquire all of the locks + required immediately. Note that system catalogs are not moved by this + command; use <command>ALTER DATABASE</command> or explicit + <command>ALTER TABLE</command> invocations instead if desired. The + <literal>information_schema</literal> relations are not considered part + of the system catalogs and will be moved. + See also + <link linkend="sql-createtablespace"><command>CREATE TABLESPACE</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET { LOGGED | UNLOGGED }</literal></term> + <listitem> + <para> + This form changes the table from unlogged to logged or vice-versa + (see <xref linkend="sql-createtable-unlogged"/>). It cannot be applied + to a temporary table. + </para> + + <para> + This also changes the persistence of any sequences linked to the table + (for identity or serial columns). However, it is also possible to + change the persistence of such sequences separately. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This form changes one or more storage parameters for the table. See + <xref linkend="sql-createtable-storage-parameters"/> in the + <link linkend="sql-createtable"><command>CREATE TABLE</command></link> documentation + for details on the available parameters. Note that the table contents + will not be modified immediately by this command; depending on the + parameter you might need to rewrite the table to get the desired effects. + That can be done with <link linkend="sql-vacuum"><command>VACUUM + FULL</command></link>, <link linkend="sql-cluster"><command>CLUSTER</command></link> or one of the forms + of <command>ALTER TABLE</command> that forces a table rewrite. + For planner related parameters, changes will take effect from the next + time the table is locked so currently executing queries will not be + affected. + </para> + + <para> + <literal>SHARE UPDATE EXCLUSIVE</literal> lock will be taken for + fillfactor, toast and autovacuum storage parameters, as well as the + planner parameter <varname>parallel_workers</varname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + This form resets one or more storage parameters to their + defaults. As with <literal>SET</literal>, a table rewrite might be + needed to update the table entirely. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INHERIT <replaceable class="parameter">parent_table</replaceable></literal></term> + <listitem> + <para> + This form adds the target table as a new child of the specified parent + table. Subsequently, queries against the parent will include records + of the target table. To be added as a child, the target table must + already contain all the same columns as the parent (it could have + additional columns, too). The columns must have matching data types, + and if they have <literal>NOT NULL</literal> constraints in the parent + then they must also have <literal>NOT NULL</literal> constraints in the + child. + </para> + + <para> + There must also be matching child-table constraints for all + <literal>CHECK</literal> constraints of the parent, except those + marked non-inheritable (that is, created with <literal>ALTER TABLE ... ADD CONSTRAINT ... NO INHERIT</literal>) + in the parent, which are ignored; all child-table constraints matched + must not be marked non-inheritable. + Currently + <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and + <literal>FOREIGN KEY</literal> constraints are not considered, but + this might change in the future. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NO INHERIT <replaceable class="parameter">parent_table</replaceable></literal></term> + <listitem> + <para> + This form removes the target table from the list of children of the + specified parent table. + Queries against the parent table will no longer include records drawn + from the target table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OF <replaceable class="parameter">type_name</replaceable></literal></term> + <listitem> + <para> + This form links the table to a composite type as though <command>CREATE + TABLE OF</command> had formed it. The table's list of column names and types + must precisely match that of the composite type. The table must + not inherit from any other table. These restrictions ensure + that <command>CREATE TABLE OF</command> would permit an equivalent table + definition. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOT OF</literal></term> + <listitem> + <para> + This form dissociates a typed table from its type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OWNER TO</literal></term> + <listitem> + <para> + This form changes the owner of the table, sequence, view, materialized view, + or foreign table to the specified user. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-altertable-replica-identity"> + <term><literal>REPLICA IDENTITY</literal></term> + <listitem> + <para> + This form changes the information which is written to the write-ahead log + to identify rows which are updated or deleted. + In most cases, the old value of each column is only logged if it differs + from the new value; however, if the old value is stored externally, it is + always logged regardless of whether it changed. + This option has no effect except when logical replication is in use. + <variablelist> + <varlistentry> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + Records the old values of the columns of the primary key, if any. + This is the default for non-system tables. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USING INDEX <replaceable class="parameter">index_name</replaceable></literal></term> + <listitem> + <para> + Records the old values of the columns covered by the named index, + that must be unique, not partial, not deferrable, and include only + columns marked <literal>NOT NULL</literal>. If this index is + dropped, the behavior is the same as <literal>NOTHING</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FULL</literal></term> + <listitem> + <para> + Records the old values of all columns in the row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOTHING</literal></term> + <listitem> + <para> + Records no information about the old row. This is the default for + system tables. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME</literal></term> + <listitem> + <para> + The <literal>RENAME</literal> forms change the name of a table + (or an index, sequence, view, materialized view, or foreign table), the + name of an individual column in a table, or the name of a constraint of + the table. When renaming a constraint that has an underlying index, + the index is renamed as well. + There is no effect on the stored data. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET SCHEMA</literal></term> + <listitem> + <para> + This form moves the table into another schema. Associated indexes, + constraints, and sequences owned by table columns are moved as well. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-altertable-attach-partition"> + <term><literal>ATTACH PARTITION <replaceable class="parameter">partition_name</replaceable> { FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT }</literal></term> + <listitem> + <para> + This form attaches an existing table (which might itself be partitioned) + as a partition of the target table. The table can be attached + as a partition for specific values using <literal>FOR VALUES</literal> + or as a default partition by using <literal>DEFAULT</literal>. + For each index in the target table, a corresponding + one will be created in the attached table; or, if an equivalent + index already exists, it will be attached to the target table's index, + as if <command>ALTER INDEX ATTACH PARTITION</command> had been executed. + Note that if the existing table is a foreign table, it is currently not + allowed to attach the table as a partition of the target table if there + are <literal>UNIQUE</literal> indexes on the target table. (See also + <xref linkend="sql-createforeigntable"/>.) For each user-defined + row-level trigger that exists in the target table, a corresponding one + is created in the attached table. + </para> + + <para> + A partition using <literal>FOR VALUES</literal> uses same syntax for + <replaceable class="parameter">partition_bound_spec</replaceable> as + <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. The partition bound specification + must correspond to the partitioning strategy and partition key of the + target table. The table to be attached must have all the same columns + as the target table and no more; moreover, the column types must also + match. Also, it must have all the <literal>NOT NULL</literal> and + <literal>CHECK</literal> constraints of the target table. Currently + <literal>FOREIGN KEY</literal> constraints are not considered. + <literal>UNIQUE</literal> and <literal>PRIMARY KEY</literal> constraints + from the parent table will be created in the partition, if they don't + already exist. + If any of the <literal>CHECK</literal> constraints of the table being + attached are marked <literal>NO INHERIT</literal>, the command will fail; + such constraints must be recreated without the + <literal>NO INHERIT</literal> clause. + </para> + + <para> + If the new partition is a regular table, a full table scan is performed + to check that existing rows in the table do not violate the partition + constraint. It is possible to avoid this scan by adding a valid + <literal>CHECK</literal> constraint to the table that allows only + rows satisfying the desired partition constraint before running this + command. The <literal>CHECK</literal> constraint will be used to + determine that the table need not be scanned to validate the partition + constraint. This does not work, however, if any of the partition keys + is an expression and the partition does not accept + <literal>NULL</literal> values. If attaching a list partition that will + not accept <literal>NULL</literal> values, also add a + <literal>NOT NULL</literal> constraint to the partition key column, + unless it's an expression. + </para> + + <para> + If the new partition is a foreign table, nothing is done to verify + that all the rows in the foreign table obey the partition constraint. + (See the discussion in <xref linkend="sql-createforeigntable"/> about + constraints on the foreign table.) + </para> + + <para> + When a table has a default partition, defining a new partition changes + the partition constraint for the default partition. The default + partition can't contain any rows that would need to be moved to the new + partition, and will be scanned to verify that none are present. This + scan, like the scan of the new partition, can be avoided if an + appropriate <literal>CHECK</literal> constraint is present. Also like + the scan of the new partition, it is always skipped when the default + partition is a foreign table. + </para> + + <para> + Attaching a partition acquires a + <literal>SHARE UPDATE EXCLUSIVE</literal> lock on the parent table, + in addition to the <literal>ACCESS EXCLUSIVE</literal> locks on the table + being attached and on the default partition (if any). + </para> + + <para> + Further locks must also be held on all sub-partitions if the table being + attached is itself a partitioned table. Likewise if the default + partition is itself a partitioned table. The locking of the + sub-partitions can be avoided by adding a <literal>CHECK</literal> + constraint as described in + <xref linkend="ddl-partitioning-declarative-maintenance"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-altertable-detach-partition"> + <term><literal>DETACH PARTITION <replaceable class="parameter">partition_name</replaceable> [ CONCURRENTLY | FINALIZE ]</literal></term> + + <listitem> + <para> + This form detaches the specified partition of the target table. The detached + partition continues to exist as a standalone table, but no longer has any + ties to the table from which it was detached. Any indexes that were + attached to the target table's indexes are detached. Any triggers that + were created as clones of those in the target table are removed. + <literal>SHARE</literal> lock is obtained on any tables that reference + this partitioned table in foreign key constraints. + </para> + <para> + If <literal>CONCURRENTLY</literal> is specified, it runs using a reduced + lock level to avoid blocking other sessions that might be accessing the + partitioned table. In this mode, two transactions are used internally. + During the first transaction, a <literal>SHARE UPDATE EXCLUSIVE</literal> + lock is taken on both parent table and partition, and the partition is + marked as undergoing detach; at that point, the transaction is committed + and all other transactions using the partitioned table are waited for. + Once all those transactions have completed, the second transaction + acquires <literal>SHARE UPDATE EXCLUSIVE</literal> on the partitioned + table and <literal>ACCESS EXCLUSIVE</literal> on the partition, + and the detach process completes. A <literal>CHECK</literal> constraint + that duplicates the partition constraint is added to the partition. + <literal>CONCURRENTLY</literal> cannot be run in a transaction block and + is not allowed if the partitioned table contains a default partition. + </para> + <para> + If <literal>FINALIZE</literal> is specified, a previous + <literal>DETACH CONCURRENTLY</literal> invocation that was canceled or + interrupted is completed. + At most one partition in a partitioned table can be pending detach at + a time. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + All the forms of ALTER TABLE that act on a single table, except + <literal>RENAME</literal>, <literal>SET SCHEMA</literal>, + <literal>ATTACH PARTITION</literal>, and + <literal>DETACH PARTITION</literal> can be combined into + a list of multiple alterations to be applied together. For example, it + is possible to add several columns and/or alter the type of several + columns in a single command. This is particularly useful with large + tables, since only one pass over the table need be made. + </para> + + <para> + You must own the table to use <command>ALTER TABLE</command>. + To change the schema or tablespace of a table, you must also have + <literal>CREATE</literal> privilege on the new schema or tablespace. + To add the table as a new child of a parent table, you must own the parent + table as well. Also, to attach a table as a new partition of the table, + you must own the table being attached. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the table's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the table. + However, a superuser can alter ownership of any table anyway.) + To add a column or alter a column type or use the <literal>OF</literal> + clause, you must also have <literal>USAGE</literal> privilege on the data + type. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the table does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing table to + alter. If <literal>ONLY</literal> is specified before the table name, only + that table is altered. If <literal>ONLY</literal> is not specified, the table + and all its descendant tables (if any) are altered. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + Name of a new or existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_column_name</replaceable></term> + <listitem> + <para> + New name for an existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + New name for the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + Data type of the new column, or new data type for an existing + column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_constraint</replaceable></term> + <listitem> + <para> + New table constraint for the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">constraint_name</replaceable></term> + <listitem> + <para> + Name of a new or existing constraint. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the dropped column + or constraint (for example, views referencing the column), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the column or constraint if there are any dependent + objects. This is the default behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">trigger_name</replaceable></term> + <listitem> + <para> + Name of a single trigger to disable or enable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Disable or enable all triggers belonging to the table. + (This requires superuser privilege if any of the triggers are + internally generated constraint triggers, such as those that are used + to implement foreign key constraints or deferrable uniqueness and + exclusion constraints.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USER</literal></term> + <listitem> + <para> + Disable or enable all triggers belonging to the table except for + internally generated constraint triggers, such as those that are used + to implement foreign key constraints or deferrable uniqueness and + exclusion constraints. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_name</replaceable></term> + <listitem> + <para> + The name of an existing index. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">storage_parameter</replaceable></term> + <listitem> + <para> + The name of a table storage parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + The new value for a table storage parameter. + This might be a number or a word depending on the parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">parent_table</replaceable></term> + <listitem> + <para> + A parent table to associate or de-associate with this table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_access_method</replaceable></term> + <listitem> + <para> + The name of the access method to which the table will be converted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_tablespace</replaceable></term> + <listitem> + <para> + The name of the tablespace to which the table will be moved. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The name of the schema to which the table will be moved. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">partition_name</replaceable></term> + <listitem> + <para> + The name of the table to attach as a new partition or to detach from this table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">partition_bound_spec</replaceable></term> + <listitem> + <para> + The partition bound specification for a new partition. Refer to + <xref linkend="sql-createtable"/> for more details on the syntax of the same. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1 id="sql-altertable-notes" xreflabel="Notes"> + <title>Notes</title> + + <para> + The key word <literal>COLUMN</literal> is noise and can be omitted. + </para> + + <para> + When a column is added with <literal>ADD COLUMN</literal> and a + non-volatile <literal>DEFAULT</literal> is specified, the default is + evaluated at the time of the statement and the result stored in the + table's metadata. That value will be used for the column for all existing + rows. If no <literal>DEFAULT</literal> is specified, NULL is used. In + neither case is a rewrite of the table required. + </para> + + <para> + Adding a column with a volatile <literal>DEFAULT</literal> or + changing the type of an existing column will require the entire table and + its indexes to be rewritten. As an exception, when changing the type of an + existing column, if the <literal>USING</literal> clause does not change + the column contents and the old type is either binary coercible to the new + type or an unconstrained domain over the new type, a table rewrite is not + needed. However, indexes must always be rebuilt unless the system can + verify that the new index would be logically equivalent to the existing + one. For example, if the collation for a column has been changed, an index + rebuild is always required because the new sort order might be different. + However, in the absence of a collation change, a column can be changed + from <type>text</type> to <type>varchar</type> (or vice versa) without + rebuilding the indexes because these data types sort identically. + Table and/or index rebuilds may take a + significant amount of time for a large table; and will temporarily require + as much as double the disk space. + </para> + + <para> + Adding a <literal>CHECK</literal> or <literal>NOT NULL</literal> constraint requires + scanning the table to verify that existing rows meet the constraint, + but does not require a table rewrite. + </para> + + <para> + Similarly, when attaching a new partition it may be scanned to verify that + existing rows meet the partition constraint. + </para> + + <para> + The main reason for providing the option to specify multiple changes + in a single <command>ALTER TABLE</command> is that multiple table scans or + rewrites can thereby be combined into a single pass over the table. + </para> + + <para> + Scanning a large table to verify a new foreign key or check constraint + can take a long time, and other updates to the table are locked out + until the <command>ALTER TABLE ADD CONSTRAINT</command> command is + committed. The main purpose of the <literal>NOT VALID</literal> + constraint option is to reduce the impact of adding a constraint on + concurrent updates. With <literal>NOT VALID</literal>, + the <command>ADD CONSTRAINT</command> command does not scan the table + and can be committed immediately. After that, a <literal>VALIDATE + CONSTRAINT</literal> command can be issued to verify that existing rows + satisfy the constraint. The validation step does not need to lock out + concurrent updates, since it knows that other transactions will be + enforcing the constraint for rows that they insert or update; only + pre-existing rows need to be checked. Hence, validation acquires only + a <literal>SHARE UPDATE EXCLUSIVE</literal> lock on the table being + altered. (If the constraint is a foreign key then a <literal>ROW + SHARE</literal> lock is also required on the table referenced by the + constraint.) In addition to improving concurrency, it can be useful to + use <literal>NOT VALID</literal> and <literal>VALIDATE + CONSTRAINT</literal> in cases where the table is known to contain + pre-existing violations. Once the constraint is in place, no new + violations can be inserted, and the existing problems can be corrected + at leisure until <literal>VALIDATE CONSTRAINT</literal> finally + succeeds. + </para> + + <para> + The <literal>DROP COLUMN</literal> form does not physically remove + the column, but simply makes it invisible to SQL operations. Subsequent + insert and update operations in the table will store a null value for the + column. Thus, dropping a column is quick but it will not immediately + reduce the on-disk size of your table, as the space occupied + by the dropped column is not reclaimed. The space will be + reclaimed over time as existing rows are updated. + </para> + + <para> + To force immediate reclamation of space occupied by a dropped column, + you can execute one of the forms of <command>ALTER TABLE</command> that + performs a rewrite of the whole table. This results in reconstructing + each row with the dropped column replaced by a null value. + </para> + + <para> + The rewriting forms of <command>ALTER TABLE</command> are not MVCC-safe. + After a table rewrite, the table will appear empty to concurrent + transactions, if they are using a snapshot taken before the rewrite + occurred. See <xref linkend="mvcc-caveats"/> for more details. + </para> + + <para> + The <literal>USING</literal> option of <literal>SET DATA TYPE</literal> can actually + specify any expression involving the old values of the row; that is, it + can refer to other columns as well as the one being converted. This allows + very general conversions to be done with the <literal>SET DATA TYPE</literal> + syntax. Because of this flexibility, the <literal>USING</literal> + expression is not applied to the column's default value (if any); the + result might not be a constant expression as required for a default. + This means that when there is no implicit or assignment cast from old to + new type, <literal>SET DATA TYPE</literal> might fail to convert the default even + though a <literal>USING</literal> clause is supplied. In such cases, + drop the default with <literal>DROP DEFAULT</literal>, perform the <literal>ALTER + TYPE</literal>, and then use <literal>SET DEFAULT</literal> to add a suitable new + default. Similar considerations apply to indexes and constraints involving + the column. + </para> + + <para> + If a table has any descendant tables, it is not permitted to add, + rename, or change the type of a column in the parent table without doing + the same to the descendants. This ensures that the descendants always + have columns matching the parent. Similarly, a <literal>CHECK</literal> + constraint cannot be renamed in the parent without also renaming it in + all descendants, so that <literal>CHECK</literal> constraints also match + between the parent and its descendants. (That restriction does not apply + to index-based constraints, however.) + Also, because selecting from the parent also selects from its descendants, + a constraint on the parent cannot be marked valid unless it is also marked + valid for those descendants. In all of these cases, <command>ALTER TABLE + ONLY</command> will be rejected. + </para> + + <para> + A recursive <literal>DROP COLUMN</literal> operation will remove a + descendant table's column only if the descendant does not inherit + that column from any other parents and never had an independent + definition of the column. A nonrecursive <literal>DROP + COLUMN</literal> (i.e., <command>ALTER TABLE ONLY ... DROP + COLUMN</command>) never removes any descendant columns, but + instead marks them as independently defined rather than inherited. + A nonrecursive <literal>DROP COLUMN</literal> command will fail for a + partitioned table, because all partitions of a table must have the same + columns as the partitioning root. + </para> + + <para> + The actions for identity columns (<literal>ADD + GENERATED</literal>, <literal>SET</literal> etc., <literal>DROP + IDENTITY</literal>), as well as the actions + <literal>CLUSTER</literal>, <literal>OWNER</literal>, + and <literal>TABLESPACE</literal> never recurse to descendant tables; + that is, they always act as though <literal>ONLY</literal> were specified. + Actions affecting trigger states recurse to partitions of partitioned + tables (unless <literal>ONLY</literal> is specified), but never to + traditional-inheritance descendants. + Adding a constraint recurses only for <literal>CHECK</literal> constraints + that are not marked <literal>NO INHERIT</literal>. + </para> + + <para> + Changing any part of a system catalog table is not permitted. + </para> + + <para> + Refer to <xref linkend="sql-createtable"/> for a further description of valid + parameters. <xref linkend="ddl"/> has further information on + inheritance. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To add a column of type <type>varchar</type> to a table: +<programlisting> +ALTER TABLE distributors ADD COLUMN address varchar(30); +</programlisting> + That will cause all existing rows in the table to be filled with null + values for the new column. + </para> + + <para> + To add a column with a non-null default: +<programlisting> +ALTER TABLE measurements + ADD COLUMN mtime timestamp with time zone DEFAULT now(); +</programlisting> + Existing rows will be filled with the current time as the value of the + new column, and then new rows will receive the time of their insertion. + </para> + + <para> + To add a column and fill it with a value different from the default to + be used later: +<programlisting> +ALTER TABLE transactions + ADD COLUMN status varchar(30) DEFAULT 'old', + ALTER COLUMN status SET default 'current'; +</programlisting> + Existing rows will be filled with <literal>old</literal>, but then + the default for subsequent commands will be <literal>current</literal>. + The effects are the same as if the two sub-commands had been issued + in separate <command>ALTER TABLE</command> commands. + </para> + + <para> + To drop a column from a table: +<programlisting> +ALTER TABLE distributors DROP COLUMN address RESTRICT; +</programlisting> + </para> + + <para> + To change the types of two existing columns in one operation: +<programlisting> +ALTER TABLE distributors + ALTER COLUMN address TYPE varchar(80), + ALTER COLUMN name TYPE varchar(100); +</programlisting> + </para> + + <para> + To change an integer column containing Unix timestamps to <type>timestamp + with time zone</type> via a <literal>USING</literal> clause: +<programlisting> +ALTER TABLE foo + ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone + USING + timestamp with time zone 'epoch' + foo_timestamp * interval '1 second'; +</programlisting> + </para> + + <para> + The same, when the column has a default expression that won't automatically + cast to the new data type: +<programlisting> +ALTER TABLE foo + ALTER COLUMN foo_timestamp DROP DEFAULT, + ALTER COLUMN foo_timestamp TYPE timestamp with time zone + USING + timestamp with time zone 'epoch' + foo_timestamp * interval '1 second', + ALTER COLUMN foo_timestamp SET DEFAULT now(); +</programlisting> + </para> + + <para> + To rename an existing column: +<programlisting> +ALTER TABLE distributors RENAME COLUMN address TO city; +</programlisting> + </para> + + <para> + To rename an existing table: +<programlisting> +ALTER TABLE distributors RENAME TO suppliers; +</programlisting> + </para> + + <para> + To rename an existing constraint: +<programlisting> +ALTER TABLE distributors RENAME CONSTRAINT zipchk TO zip_check; +</programlisting> + </para> + + <para> + To add a not-null constraint to a column: +<programlisting> +ALTER TABLE distributors ALTER COLUMN street SET NOT NULL; +</programlisting> + To remove a not-null constraint from a column: +<programlisting> +ALTER TABLE distributors ALTER COLUMN street DROP NOT NULL; +</programlisting> + </para> + + <para> + To add a check constraint to a table and all its children: +<programlisting> +ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5); +</programlisting> + </para> + + <para> + To add a check constraint only to a table and not to its children: +<programlisting> +ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT; +</programlisting> + (The check constraint will not be inherited by future children, either.) + </para> + + <para> + To remove a check constraint from a table and all its children: +<programlisting> +ALTER TABLE distributors DROP CONSTRAINT zipchk; +</programlisting> + </para> + + <para> + To remove a check constraint from one table only: +<programlisting> +ALTER TABLE ONLY distributors DROP CONSTRAINT zipchk; +</programlisting> + (The check constraint remains in place for any child tables.) + </para> + + <para> + To add a foreign key constraint to a table: +<programlisting> +ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address); +</programlisting> + </para> + + <para> + To add a foreign key constraint to a table with the least impact on other work: +<programlisting> +ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID; +ALTER TABLE distributors VALIDATE CONSTRAINT distfk; +</programlisting> + </para> + + <para> + To add a (multicolumn) unique constraint to a table: +<programlisting> +ALTER TABLE distributors ADD CONSTRAINT dist_id_zipcode_key UNIQUE (dist_id, zipcode); +</programlisting> + </para> + + <para> + To add an automatically named primary key constraint to a table, noting + that a table can only ever have one primary key: +<programlisting> +ALTER TABLE distributors ADD PRIMARY KEY (dist_id); +</programlisting> + </para> + + <para> + To move a table to a different tablespace: +<programlisting> +ALTER TABLE distributors SET TABLESPACE fasttablespace; +</programlisting> + </para> + + <para> + To move a table to a different schema: +<programlisting> +ALTER TABLE myschema.distributors SET SCHEMA yourschema; +</programlisting> + </para> + + <para> + To recreate a primary key constraint, without blocking updates while the + index is rebuilt: +<programlisting> +CREATE UNIQUE INDEX CONCURRENTLY dist_id_temp_idx ON distributors (dist_id); +ALTER TABLE distributors DROP CONSTRAINT distributors_pkey, + ADD CONSTRAINT distributors_pkey PRIMARY KEY USING INDEX dist_id_temp_idx; +</programlisting></para> + + <para> + To attach a partition to a range-partitioned table: +<programlisting> +ALTER TABLE measurement + ATTACH PARTITION measurement_y2016m07 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); +</programlisting></para> + + <para> + To attach a partition to a list-partitioned table: +<programlisting> +ALTER TABLE cities + ATTACH PARTITION cities_ab FOR VALUES IN ('a', 'b'); +</programlisting></para> + + <para> + To attach a partition to a hash-partitioned table: +<programlisting> +ALTER TABLE orders + ATTACH PARTITION orders_p4 FOR VALUES WITH (MODULUS 4, REMAINDER 3); +</programlisting></para> + + <para> + To attach a default partition to a partitioned table: +<programlisting> +ALTER TABLE cities + ATTACH PARTITION cities_partdef DEFAULT; +</programlisting></para> + + <para> + To detach a partition from a partitioned table: +<programlisting> +ALTER TABLE measurement + DETACH PARTITION measurement_y2015m12; +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The forms <literal>ADD</literal> (without <literal>USING INDEX</literal>), + <literal>DROP [COLUMN]</literal>, <literal>DROP IDENTITY</literal>, <literal>RESTART</literal>, + <literal>SET DEFAULT</literal>, <literal>SET DATA TYPE</literal> (without <literal>USING</literal>), + <literal>SET GENERATED</literal>, and <literal>SET <replaceable>sequence_option</replaceable></literal> + conform with the SQL standard. The other forms are + <productname>PostgreSQL</productname> extensions of the SQL standard. + Also, the ability to specify more than one manipulation in a single + <command>ALTER TABLE</command> command is an extension. + </para> + + <para> + <command>ALTER TABLE DROP COLUMN</command> can be used to drop the only + column of a table, leaving a zero-column table. This is an + extension of SQL, which disallows zero-column tables. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtable"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_tablespace.sgml b/doc/src/sgml/ref/alter_tablespace.sgml new file mode 100644 index 0000000..6de8074 --- /dev/null +++ b/doc/src/sgml/ref/alter_tablespace.sgml @@ -0,0 +1,140 @@ +<!-- +doc/src/sgml/ref/alter_tablespace.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertablespace"> + <indexterm zone="sql-altertablespace"> + <primary>ALTER TABLESPACE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TABLESPACE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TABLESPACE</refname> + <refpurpose>change the definition of a tablespace</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TABLESPACE <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER TABLESPACE <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER TABLESPACE <replaceable>name</replaceable> SET ( <replaceable class="parameter">tablespace_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) +ALTER TABLESPACE <replaceable>name</replaceable> RESET ( <replaceable class="parameter">tablespace_option</replaceable> [, ... ] ) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TABLESPACE</command> can be used to change the definition of + a tablespace. + </para> + + <para> + You must own the tablespace to change the definition of a tablespace. + To alter the owner, you must also be a direct or indirect member of the new + owning role. + (Note that superusers have these privileges automatically.) + </para> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing tablespace. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the tablespace. The new name cannot + begin with <literal>pg_</literal>, as such names + are reserved for system tablespaces. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the tablespace. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">tablespace_option</replaceable></term> + <listitem> + <para> + A tablespace parameter to be set or reset. Currently, the only + available parameters are <varname>seq_page_cost</varname>, + <varname>random_page_cost</varname>, <varname>effective_io_concurrency</varname> + and <varname>maintenance_io_concurrency</varname>. + Setting these values for a particular tablespace will override the + planner's usual estimate of the cost of reading pages from tables in + that tablespace, and the executor's prefetching behavior, as established + by the configuration parameters of the + same name (see <xref linkend="guc-seq-page-cost"/>, + <xref linkend="guc-random-page-cost"/>, + <xref linkend="guc-effective-io-concurrency"/>, + <xref linkend="guc-maintenance-io-concurrency"/>). This may be useful if + one tablespace is located on a disk which is faster or slower than the + remainder of the I/O subsystem. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Rename tablespace <literal>index_space</literal> to <literal>fast_raid</literal>: +<programlisting> +ALTER TABLESPACE index_space RENAME TO fast_raid; +</programlisting> + </para> + + <para> + Change the owner of tablespace <literal>index_space</literal>: +<programlisting> +ALTER TABLESPACE index_space OWNER TO mary; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER TABLESPACE</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtablespace"/></member> + <member><xref linkend="sql-droptablespace"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_trigger.sgml b/doc/src/sgml/ref/alter_trigger.sgml new file mode 100644 index 0000000..ece9cb5 --- /dev/null +++ b/doc/src/sgml/ref/alter_trigger.sgml @@ -0,0 +1,146 @@ +<!-- +doc/src/sgml/ref/alter_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertrigger"> + <indexterm zone="sql-altertrigger"> + <primary>ALTER TRIGGER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TRIGGER</refname> + <refpurpose>change the definition of a trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TRIGGER <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER TRIGGER <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> [ NO ] DEPENDS ON EXTENSION <replaceable class="parameter">extension_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TRIGGER</command> changes properties of an existing + trigger. + </para> + + <para> + The <literal>RENAME</literal> clause changes the name of + the given trigger without otherwise changing the trigger + definition. + If the table that the trigger is on is a partitioned table, + then corresponding clone triggers in the partitions are + renamed too. + </para> + + <para> + The <literal>DEPENDS ON EXTENSION</literal> clause marks + the trigger as dependent on an extension, such that if the extension is + dropped, the trigger will automatically be dropped as well. + </para> + + <para> + You must own the table on which the trigger acts to be allowed to change its properties. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing trigger to alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name of the table on which this trigger acts. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the trigger. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">extension_name</replaceable></term> + <listitem> + <para> + The name of the extension that the trigger is to depend on (or no longer + dependent on, if <literal>NO</literal> is specified). A trigger + that's marked as dependent on an extension is automatically dropped when + the extension is dropped. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The ability to temporarily enable or disable a trigger is provided by + <link linkend="sql-altertable"><command>ALTER TABLE</command></link>, not by + <command>ALTER TRIGGER</command>, because <command>ALTER TRIGGER</command> has no + convenient way to express the option of enabling or disabling all of + a table's triggers at once. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename an existing trigger: +<programlisting> +ALTER TRIGGER emp_stamp ON emp RENAME TO emp_track_chgs; +</programlisting></para> + + <para> + To mark a trigger as being dependent on an extension: +<programlisting> +ALTER TRIGGER emp_stamp ON emp DEPENDS ON EXTENSION emplib; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER TRIGGER</command> is a <productname>PostgreSQL</productname> + extension of the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertable"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_tsconfig.sgml b/doc/src/sgml/ref/alter_tsconfig.sgml new file mode 100644 index 0000000..8fafcd3 --- /dev/null +++ b/doc/src/sgml/ref/alter_tsconfig.sgml @@ -0,0 +1,189 @@ +<!-- +doc/src/sgml/ref/alter_tsconfig.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertsconfig"> + <indexterm zone="sql-altertsconfig"> + <primary>ALTER TEXT SEARCH CONFIGURATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TEXT SEARCH CONFIGURATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TEXT SEARCH CONFIGURATION</refname> + <refpurpose>change the definition of a text search configuration</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> + ADD MAPPING FOR <replaceable class="parameter">token_type</replaceable> [, ... ] WITH <replaceable class="parameter">dictionary_name</replaceable> [, ... ] +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> + ALTER MAPPING FOR <replaceable class="parameter">token_type</replaceable> [, ... ] WITH <replaceable class="parameter">dictionary_name</replaceable> [, ... ] +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> + ALTER MAPPING REPLACE <replaceable class="parameter">old_dictionary</replaceable> WITH <replaceable class="parameter">new_dictionary</replaceable> +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> + ALTER MAPPING FOR <replaceable class="parameter">token_type</replaceable> [, ... ] REPLACE <replaceable class="parameter">old_dictionary</replaceable> WITH <replaceable class="parameter">new_dictionary</replaceable> +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> + DROP MAPPING [ IF EXISTS ] FOR <replaceable class="parameter">token_type</replaceable> [, ... ] +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER TEXT SEARCH CONFIGURATION <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TEXT SEARCH CONFIGURATION</command> changes the definition of + a text search configuration. You can modify + its mappings from token types to dictionaries, + or change the configuration's name or owner. + </para> + + <para> + You must be the owner of the configuration to use + <command>ALTER TEXT SEARCH CONFIGURATION</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search + configuration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">token_type</replaceable></term> + <listitem> + <para> + The name of a token type that is emitted by the configuration's + parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">dictionary_name</replaceable></term> + <listitem> + <para> + The name of a text search dictionary to be consulted for the + specified token type(s). If multiple dictionaries are listed, + they are consulted in the specified order. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">old_dictionary</replaceable></term> + <listitem> + <para> + The name of a text search dictionary to be replaced in the mapping. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_dictionary</replaceable></term> + <listitem> + <para> + The name of a text search dictionary to be substituted for + <replaceable class="parameter">old_dictionary</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the text search configuration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the text search configuration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the text search configuration. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The <literal>ADD MAPPING FOR</literal> form installs a list of dictionaries to be + consulted for the specified token type(s); it is an error if there is + already a mapping for any of the token types. + The <literal>ALTER MAPPING FOR</literal> form does the same, but first removing + any existing mapping for those token types. + The <literal>ALTER MAPPING REPLACE</literal> forms substitute <replaceable + class="parameter">new_dictionary</replaceable> for <replaceable + class="parameter">old_dictionary</replaceable> anywhere the latter appears. + This is done for only the specified token types when <literal>FOR</literal> + appears, or for all mappings of the configuration when it doesn't. + The <literal>DROP MAPPING</literal> form removes all dictionaries for the + specified token type(s), causing tokens of those types to be ignored + by the text search configuration. It is an error if there is no mapping + for the token types, unless <literal>IF EXISTS</literal> appears. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example replaces the <literal>english</literal> dictionary + with the <literal>swedish</literal> dictionary anywhere that <literal>english</literal> + is used within <literal>my_config</literal>. + </para> + +<programlisting> +ALTER TEXT SEARCH CONFIGURATION my_config + ALTER MAPPING REPLACE english WITH swedish; +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER TEXT SEARCH CONFIGURATION</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtsconfig"/></member> + <member><xref linkend="sql-droptsconfig"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_tsdictionary.sgml b/doc/src/sgml/ref/alter_tsdictionary.sgml new file mode 100644 index 0000000..d1923ef --- /dev/null +++ b/doc/src/sgml/ref/alter_tsdictionary.sgml @@ -0,0 +1,170 @@ +<!-- +doc/src/sgml/ref/alter_tsdictionary.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertsdictionary"> + <indexterm zone="sql-altertsdictionary"> + <primary>ALTER TEXT SEARCH DICTIONARY</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TEXT SEARCH DICTIONARY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TEXT SEARCH DICTIONARY</refname> + <refpurpose>change the definition of a text search dictionary</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TEXT SEARCH DICTIONARY <replaceable>name</replaceable> ( + <replaceable class="parameter">option</replaceable> [ = <replaceable class="parameter">value</replaceable> ] [, ... ] +) +ALTER TEXT SEARCH DICTIONARY <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER TEXT SEARCH DICTIONARY <replaceable>name</replaceable> OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER TEXT SEARCH DICTIONARY <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TEXT SEARCH DICTIONARY</command> changes the definition of + a text search dictionary. You can change the dictionary's + template-specific options, or change the dictionary's name or owner. + </para> + + <para> + You must be the owner of the dictionary to use + <command>ALTER TEXT SEARCH DICTIONARY</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search + dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">option</replaceable></term> + <listitem> + <para> + The name of a template-specific option to be set for this dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + The new value to use for a template-specific option. + If the equal sign and value are omitted, then any previous + setting for the option is removed from the dictionary, + allowing the default to be used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the text search dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The new owner of the text search dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the text search dictionary. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + Template-specific options can appear in any order. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example command changes the stopword list + for a Snowball-based dictionary. Other parameters remain unchanged. + </para> + +<programlisting> +ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian ); +</programlisting> + + <para> + The following example command changes the language option to <literal>dutch</literal>, + and removes the stopword option entirely. + </para> + +<programlisting> +ALTER TEXT SEARCH DICTIONARY my_dict ( language = dutch, StopWords ); +</programlisting> + + <para> + The following example command <quote>updates</quote> the dictionary's + definition without actually changing anything. + +<programlisting> +ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ); +</programlisting> + + (The reason this works is that the option removal code doesn't complain + if there is no such option.) This trick is useful when changing + configuration files for the dictionary: the <command>ALTER</command> will + force existing database sessions to re-read the configuration files, + which otherwise they would never do if they had read them earlier. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER TEXT SEARCH DICTIONARY</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtsdictionary"/></member> + <member><xref linkend="sql-droptsdictionary"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_tsparser.sgml b/doc/src/sgml/ref/alter_tsparser.sgml new file mode 100644 index 0000000..9edff4b --- /dev/null +++ b/doc/src/sgml/ref/alter_tsparser.sgml @@ -0,0 +1,93 @@ +<!-- +doc/src/sgml/ref/alter_tsparser.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertsparser"> + <indexterm zone="sql-altertsparser"> + <primary>ALTER TEXT SEARCH PARSER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TEXT SEARCH PARSER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TEXT SEARCH PARSER</refname> + <refpurpose>change the definition of a text search parser</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TEXT SEARCH PARSER <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER TEXT SEARCH PARSER <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TEXT SEARCH PARSER</command> changes the definition of + a text search parser. Currently, the only supported functionality + is to change the parser's name. + </para> + + <para> + You must be a superuser to use <command>ALTER TEXT SEARCH PARSER</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the text search parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the text search parser. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER TEXT SEARCH PARSER</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtsparser"/></member> + <member><xref linkend="sql-droptsparser"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_tstemplate.sgml b/doc/src/sgml/ref/alter_tstemplate.sgml new file mode 100644 index 0000000..5d3c826 --- /dev/null +++ b/doc/src/sgml/ref/alter_tstemplate.sgml @@ -0,0 +1,93 @@ +<!-- +doc/src/sgml/ref/alter_tstemplate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertstemplate"> + <indexterm zone="sql-altertstemplate"> + <primary>ALTER TEXT SEARCH TEMPLATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TEXT SEARCH TEMPLATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TEXT SEARCH TEMPLATE</refname> + <refpurpose>change the definition of a text search template</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TEXT SEARCH TEMPLATE <replaceable>name</replaceable> RENAME TO <replaceable>new_name</replaceable> +ALTER TEXT SEARCH TEMPLATE <replaceable>name</replaceable> SET SCHEMA <replaceable>new_schema</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TEXT SEARCH TEMPLATE</command> changes the definition of + a text search template. Currently, the only supported functionality + is to change the template's name. + </para> + + <para> + You must be a superuser to use <command>ALTER TEXT SEARCH TEMPLATE</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search template. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name of the text search template. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the text search template. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ALTER TEXT SEARCH TEMPLATE</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtstemplate"/></member> + <member><xref linkend="sql-droptstemplate"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_type.sgml b/doc/src/sgml/ref/alter_type.sgml new file mode 100644 index 0000000..1460651 --- /dev/null +++ b/doc/src/sgml/ref/alter_type.sgml @@ -0,0 +1,494 @@ +<!-- +doc/src/sgml/ref/alter_type.sgml +PostgreSQL documentation +--> + +<refentry id="sql-altertype"> + <indexterm zone="sql-altertype"> + <primary>ALTER TYPE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER TYPE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER TYPE</refname> + <refpurpose> + change the definition of a type + </refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER TYPE <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER TYPE <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER TYPE <replaceable class="parameter">name</replaceable> SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER TYPE <replaceable class="parameter">name</replaceable> RENAME ATTRIBUTE <replaceable class="parameter">attribute_name</replaceable> TO <replaceable class="parameter">new_attribute_name</replaceable> [ CASCADE | RESTRICT ] +ALTER TYPE <replaceable class="parameter">name</replaceable> <replaceable class="parameter">action</replaceable> [, ... ] +ALTER TYPE <replaceable class="parameter">name</replaceable> ADD VALUE [ IF NOT EXISTS ] <replaceable class="parameter">new_enum_value</replaceable> [ { BEFORE | AFTER } <replaceable class="parameter">neighbor_enum_value</replaceable> ] +ALTER TYPE <replaceable class="parameter">name</replaceable> RENAME VALUE <replaceable class="parameter">existing_enum_value</replaceable> TO <replaceable class="parameter">new_enum_value</replaceable> +ALTER TYPE <replaceable class="parameter">name</replaceable> SET ( <replaceable class="parameter">property</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) + +<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase> + + ADD ATTRIBUTE <replaceable class="parameter">attribute_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ CASCADE | RESTRICT ] + DROP ATTRIBUTE [ IF EXISTS ] <replaceable class="parameter">attribute_name</replaceable> [ CASCADE | RESTRICT ] + ALTER ATTRIBUTE <replaceable class="parameter">attribute_name</replaceable> [ SET DATA ] TYPE <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER TYPE</command> changes the definition of an existing type. + There are several subforms: + + <variablelist> + <varlistentry> + <term><literal>OWNER</literal></term> + <listitem> + <para> + This form changes the owner of the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME</literal></term> + <listitem> + <para> + This form changes the name of the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET SCHEMA</literal></term> + <listitem> + <para> + This form moves the type into another schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME ATTRIBUTE</literal></term> + <listitem> + <para> + This form is only usable with composite types. + It changes the name of an individual attribute of the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD ATTRIBUTE</literal></term> + <listitem> + <para> + This form adds a new attribute to a composite type, using the same syntax as + <link linkend="sql-createtype"><command>CREATE TYPE</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP ATTRIBUTE [ IF EXISTS ]</literal></term> + <listitem> + <para> + This form drops an attribute from a composite type. + If <literal>IF EXISTS</literal> is specified and the attribute + does not exist, no error is thrown. In this case a notice + is issued instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALTER ATTRIBUTE ... SET DATA TYPE</literal></term> + <listitem> + <para> + This form changes the type of an attribute of a composite type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADD VALUE [ IF NOT EXISTS ] [ BEFORE | AFTER ]</literal></term> + <listitem> + <para> + This form adds a new value to an enum type. The new value's place in + the enum's ordering can be specified as being <literal>BEFORE</literal> + or <literal>AFTER</literal> one of the existing values. Otherwise, + the new item is added at the end of the list of values. + </para> + <para> + If <literal>IF NOT EXISTS</literal> is specified, it is not an error if + the type already contains the new value: a notice is issued but no other + action is taken. Otherwise, an error will occur if the new value is + already present. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RENAME VALUE</literal></term> + <listitem> + <para> + This form renames a value of an enum type. + The value's place in the enum's ordering is not affected. + An error will occur if the specified value is not present or the new + name is already present. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>SET ( <replaceable class="parameter">property</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] )</literal> + </term> + <listitem> + <para> + This form is only applicable to base types. It allows adjustment of a + subset of the base-type properties that can be set in <command>CREATE + TYPE</command>. Specifically, these properties can be changed: + <itemizedlist> + <listitem> + <para> + <literal>RECEIVE</literal> can be set to the name of a binary input + function, or <literal>NONE</literal> to remove the type's binary + input function. Using this option requires superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>SEND</literal> can be set to the name of a binary output + function, or <literal>NONE</literal> to remove the type's binary + output function. Using this option requires superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>TYPMOD_IN</literal> can be set to the name of a type + modifier input function, or <literal>NONE</literal> to remove the + type's type modifier input function. Using this option requires + superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>TYPMOD_OUT</literal> can be set to the name of a type + modifier output function, or <literal>NONE</literal> to remove the + type's type modifier output function. Using this option requires + superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>ANALYZE</literal> can be set to the name of a type-specific + statistics collection function, or <literal>NONE</literal> to remove + the type's statistics collection function. Using this option + requires superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>SUBSCRIPT</literal> can be set to the name of a type-specific + subscripting handler function, or <literal>NONE</literal> to remove + the type's subscripting handler function. Using this option + requires superuser privilege. + </para> + </listitem> + <listitem> + <para> + <literal>STORAGE</literal><indexterm> + <primary>TOAST</primary> + <secondary>per-type storage settings</secondary> + </indexterm> + can be set to <literal>plain</literal>, + <literal>extended</literal>, <literal>external</literal>, + or <literal>main</literal> (see <xref linkend="storage-toast"/> for + more information about what these mean). However, changing + from <literal>plain</literal> to another setting requires superuser + privilege (because it requires that the type's C functions all be + TOAST-ready), and changing to <literal>plain</literal> from another + setting is not allowed at all (since the type may already have + TOASTed values present in the database). Note that changing this + option doesn't by itself change any stored data, it just sets the + default TOAST strategy to be used for table columns created in the + future. See <xref linkend="sql-altertable"/> to change the TOAST + strategy for existing table columns. + </para> + </listitem> + </itemizedlist> + See <xref linkend="sql-createtype"/> for more details about these + type properties. Note that where appropriate, a change in these + properties for a base type will be propagated automatically to domains + based on that type. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The <literal>ADD ATTRIBUTE</literal>, <literal>DROP + ATTRIBUTE</literal>, and <literal>ALTER ATTRIBUTE</literal> actions + can be combined into a list of multiple alterations to apply in + parallel. For example, it is possible to add several attributes + and/or alter the type of several attributes in a single command. + </para> + + <para> + You must own the type to use <command>ALTER TYPE</command>. + To change the schema of a type, you must also have + <literal>CREATE</literal> privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the type's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the type. + However, a superuser can alter ownership of any type anyway.) + To add an attribute or alter an attribute type, you must also + have <literal>USAGE</literal> privilege on the attribute's data type. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of an existing type to + alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">attribute_name</replaceable></term> + <listitem> + <para> + The name of the attribute to add, alter, or drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_attribute_name</replaceable></term> + <listitem> + <para> + The new name of the attribute to be renamed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The data type of the attribute to add, or the new type of the + attribute to alter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_enum_value</replaceable></term> + <listitem> + <para> + The new value to be added to an enum type's list of values, + or the new name to be given to an existing value. + Like all enum literals, it needs to be quoted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">neighbor_enum_value</replaceable></term> + <listitem> + <para> + The existing enum value that the new value should be added immediately + before or after in the enum type's sort ordering. + Like all enum literals, it needs to be quoted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">existing_enum_value</replaceable></term> + <listitem> + <para> + The existing enum value that should be renamed. + Like all enum literals, it needs to be quoted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">property</replaceable></term> + <listitem> + <para> + The name of a base-type property to be modified; see above for + possible values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically propagate the operation to typed tables of the + type being altered, and their descendants. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse the operation if the type being altered is the type of a + typed table. This is the default. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If <command>ALTER TYPE ... ADD VALUE</command> (the form that adds a new + value to an enum type) is executed inside a transaction block, the new + value cannot be used until after the transaction has been committed. + </para> + + <para> + Comparisons involving an added enum value will sometimes be slower than + comparisons involving only original members of the enum type. This will + usually only occur if <literal>BEFORE</literal> or <literal>AFTER</literal> + is used to set the new value's sort position somewhere other than at the + end of the list. However, sometimes it will happen even though the new + value is added at the end (this occurs if the OID counter <quote>wrapped + around</quote> since the original creation of the enum type). The slowdown is + usually insignificant; but if it matters, optimal performance can be + regained by dropping and recreating the enum type, or by dumping and + restoring the database. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename a data type: +<programlisting> +ALTER TYPE electronic_mail RENAME TO email; +</programlisting> + </para> + + <para> + To change the owner of the type <literal>email</literal> + to <literal>joe</literal>: +<programlisting> +ALTER TYPE email OWNER TO joe; +</programlisting> + </para> + + <para> + To change the schema of the type <literal>email</literal> + to <literal>customers</literal>: +<programlisting> +ALTER TYPE email SET SCHEMA customers; +</programlisting> + </para> + + <para> + To add a new attribute to a composite type: +<programlisting> +ALTER TYPE compfoo ADD ATTRIBUTE f3 int; +</programlisting> + </para> + + <para> + To add a new value to an enum type in a particular sort position: +<programlisting> +ALTER TYPE colors ADD VALUE 'orange' AFTER 'red'; +</programlisting> + </para> + + <para> + To rename an enum value: +<programlisting> +ALTER TYPE colors RENAME VALUE 'purple' TO 'mauve'; +</programlisting> + </para> + + <para> + To create binary I/O functions for an existing base type: +<programlisting> +CREATE FUNCTION mytypesend(mytype) RETURNS bytea ...; +CREATE FUNCTION mytyperecv(internal, oid, integer) RETURNS mytype ...; +ALTER TYPE mytype SET ( + SEND = mytypesend, + RECEIVE = mytyperecv +); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The variants to add and drop attributes are part of the SQL + standard; the other variants are PostgreSQL extensions. + </para> + </refsect1> + + <refsect1 id="sql-altertype-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtype"/></member> + <member><xref linkend="sql-droptype"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_user.sgml b/doc/src/sgml/ref/alter_user.sgml new file mode 100644 index 0000000..0ee89f5 --- /dev/null +++ b/doc/src/sgml/ref/alter_user.sgml @@ -0,0 +1,81 @@ +<!-- +doc/src/sgml/ref/alter_user.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alteruser"> + <indexterm zone="sql-alteruser"> + <primary>ALTER USER</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER USER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER USER</refname> + <refpurpose>change a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER USER <replaceable class="parameter">role_specification</replaceable> [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + SUPERUSER | NOSUPERUSER + | CREATEDB | NOCREATEDB + | CREATEROLE | NOCREATEROLE + | INHERIT | NOINHERIT + | LOGIN | NOLOGIN + | REPLICATION | NOREPLICATION + | BYPASSRLS | NOBYPASSRLS + | CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + | [ ENCRYPTED ] PASSWORD '<replaceable class="parameter">password</replaceable>' | PASSWORD NULL + | VALID UNTIL '<replaceable class="parameter">timestamp</replaceable>' + +ALTER USER <replaceable class="parameter">name</replaceable> RENAME TO <replaceable>new_name</replaceable> + +ALTER USER { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] SET <replaceable>configuration_parameter</replaceable> { TO | = } { <replaceable>value</replaceable> | DEFAULT } +ALTER USER { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] SET <replaceable>configuration_parameter</replaceable> FROM CURRENT +ALTER USER { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] RESET <replaceable>configuration_parameter</replaceable> +ALTER USER { <replaceable class="parameter">role_specification</replaceable> | ALL } [ IN DATABASE <replaceable class="parameter">database_name</replaceable> ] RESET ALL + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + <replaceable class="parameter">role_name</replaceable> + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER USER</command> is now an alias for + <link linkend="sql-alterrole"><command>ALTER ROLE</command></link>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>ALTER USER</command> statement is a + <productname>PostgreSQL</productname> extension. The SQL standard + leaves the definition of users to the implementation. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterrole"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/alter_user_mapping.sgml b/doc/src/sgml/ref/alter_user_mapping.sgml new file mode 100644 index 0000000..ee5aee9 --- /dev/null +++ b/doc/src/sgml/ref/alter_user_mapping.sgml @@ -0,0 +1,124 @@ +<!-- +doc/src/sgml/ref/alter_user_mapping.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterusermapping"> + <indexterm zone="sql-alterusermapping"> + <primary>ALTER USER MAPPING</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER USER MAPPING</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER USER MAPPING</refname> + <refpurpose>change the definition of a user mapping</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER USER MAPPING FOR { <replaceable class="parameter">user_name</replaceable> | USER | CURRENT_ROLE | CURRENT_USER | SESSION_USER | PUBLIC } + SERVER <replaceable class="parameter">server_name</replaceable> + OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] ) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER USER MAPPING</command> changes the definition of a + user mapping. + </para> + + <para> + The owner of a foreign server can alter user mappings for that + server for any user. Also, a user can alter a user mapping for + their own user name if <literal>USAGE</literal> privilege on the server has + been granted to the user. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + User name of the mapping. <literal>CURRENT_ROLE</literal>, <literal>CURRENT_USER</literal>, + and <literal>USER</literal> match the name of the current + user. <literal>PUBLIC</literal> is used to match all present and future + user names in the system. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + Server name of the user mapping. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( [ ADD | SET | DROP ] <replaceable class="parameter">option</replaceable> ['<replaceable class="parameter">value</replaceable>'] [, ... ] )</literal></term> + <listitem> + <para> + Change options for the user mapping. The new options override + any previously specified + options. <literal>ADD</literal>, <literal>SET</literal>, and <literal>DROP</literal> + specify the action to be performed. <literal>ADD</literal> is assumed + if no operation is explicitly specified. Option names must be + unique; options are also validated by the server's foreign-data + wrapper. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change the password for user mapping <literal>bob</literal>, server <literal>foo</literal>: +<programlisting> +ALTER USER MAPPING FOR bob SERVER foo OPTIONS (SET password 'public'); +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER USER MAPPING</command> conforms to ISO/IEC 9075-9 + (SQL/MED). There is a subtle syntax issue: The standard omits + the <literal>FOR</literal> key word. Since both <literal>CREATE + USER MAPPING</literal> and <literal>DROP USER MAPPING</literal> use + <literal>FOR</literal> in analogous positions, and IBM DB2 (being + the other major SQL/MED implementation) also requires it + for <literal>ALTER USER MAPPING</literal>, PostgreSQL diverges from + the standard here in the interest of consistency and + interoperability. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createusermapping"/></member> + <member><xref linkend="sql-dropusermapping"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/alter_view.sgml b/doc/src/sgml/ref/alter_view.sgml new file mode 100644 index 0000000..8bdc90a --- /dev/null +++ b/doc/src/sgml/ref/alter_view.sgml @@ -0,0 +1,229 @@ +<!-- +doc/src/sgml/ref/alter_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-alterview"> + <indexterm zone="sql-alterview"> + <primary>ALTER VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>ALTER VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ALTER VIEW</refname> + <refpurpose>change the definition of a view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> SET DEFAULT <replaceable class="parameter">expression</replaceable> +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ALTER [ COLUMN ] <replaceable class="parameter">column_name</replaceable> DROP DEFAULT +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RENAME [ COLUMN ] <replaceable class="parameter">column_name</replaceable> TO <replaceable class="parameter">new_column_name</replaceable> +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RENAME TO <replaceable class="parameter">new_name</replaceable> +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET SCHEMA <replaceable class="parameter">new_schema</replaceable> +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> SET ( <replaceable class="parameter">view_option_name</replaceable> [= <replaceable class="parameter">view_option_value</replaceable>] [, ... ] ) +ALTER VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> RESET ( <replaceable class="parameter">view_option_name</replaceable> [, ... ] ) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ALTER VIEW</command> changes various auxiliary properties + of a view. (If you want to modify the view's defining query, + use <command>CREATE OR REPLACE VIEW</command>.) + </para> + + <para> + You must own the view to use <command>ALTER VIEW</command>. + To change a view's schema, you must also have <literal>CREATE</literal> + privilege on the new schema. + To alter the owner, you must also be a direct or indirect member of the new + owning role, and that role must have <literal>CREATE</literal> privilege on + the view's schema. (These restrictions enforce that altering the owner + doesn't do anything you couldn't do by dropping and recreating the view. + However, a superuser can alter ownership of any view anyway.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + Name of an existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_column_name</replaceable></term> + <listitem> + <para> + New name for an existing column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the view does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET</literal>/<literal>DROP DEFAULT</literal></term> + <listitem> + <para> + These forms set or remove the default value for a column. + A view column's default value is substituted into any + <command>INSERT</command> or <command>UPDATE</command> command whose target is the + view, before applying any rules or triggers for the view. The view's + default will therefore take precedence over any default values from + underlying relations. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_owner</replaceable></term> + <listitem> + <para> + The user name of the new owner of the view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_name</replaceable></term> + <listitem> + <para> + The new name for the view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_schema</replaceable></term> + <listitem> + <para> + The new schema for the view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET ( <replaceable class="parameter">view_option_name</replaceable> [= <replaceable class="parameter">view_option_value</replaceable>] [, ... ] )</literal></term> + <term><literal>RESET ( <replaceable class="parameter">view_option_name</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + Sets or resets a view option. Currently supported options are: + <variablelist> + <varlistentry> + <term><literal>check_option</literal> (<type>enum</type>)</term> + <listitem> + <para> + Changes the check option of the view. The value must + be <literal>local</literal> or <literal>cascaded</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>security_barrier</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Changes the security-barrier property of the view. The value must + be a Boolean value, such as <literal>true</literal> + or <literal>false</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>security_invoker</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Changes the security-invoker property of the view. The value must + be a Boolean value, such as <literal>true</literal> + or <literal>false</literal>. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + For historical reasons, <command>ALTER TABLE</command> can be used with + views too; but the only variants of <command>ALTER TABLE</command> + that are allowed with views are equivalent to the ones shown above. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To rename the view <literal>foo</literal> to + <literal>bar</literal>: +<programlisting> +ALTER VIEW foo RENAME TO bar; +</programlisting> + </para> + + <para> + To attach a default column value to an updatable view: +<programlisting> +CREATE TABLE base_table (id int, ts timestamptz); +CREATE VIEW a_view AS SELECT * FROM base_table; +ALTER VIEW a_view ALTER COLUMN ts SET DEFAULT now(); +INSERT INTO base_table(id) VALUES(1); -- ts will receive a NULL +INSERT INTO a_view(id) VALUES(2); -- ts will receive the current time +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ALTER VIEW</command> is a <productname>PostgreSQL</productname> + extension of the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createview"/></member> + <member><xref linkend="sql-dropview"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/analyze.sgml b/doc/src/sgml/ref/analyze.sgml new file mode 100644 index 0000000..2ba115d --- /dev/null +++ b/doc/src/sgml/ref/analyze.sgml @@ -0,0 +1,321 @@ +<!-- +doc/src/sgml/ref/analyze.sgml +PostgreSQL documentation +--> + +<refentry id="sql-analyze"> + <indexterm zone="sql-analyze"> + <primary>ANALYZE</primary> + </indexterm> + + <refmeta> + <refentrytitle>ANALYZE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ANALYZE</refname> + <refpurpose>collect statistics about a database</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ANALYZE [ ( <replaceable class="parameter">option</replaceable> [, ...] ) ] [ <replaceable class="parameter">table_and_columns</replaceable> [, ...] ] +ANALYZE [ VERBOSE ] [ <replaceable class="parameter">table_and_columns</replaceable> [, ...] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + VERBOSE [ <replaceable class="parameter">boolean</replaceable> ] + SKIP_LOCKED [ <replaceable class="parameter">boolean</replaceable> ] + +<phrase>and <replaceable class="parameter">table_and_columns</replaceable> is:</phrase> + + <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ANALYZE</command> collects statistics about the contents + of tables in the database, and stores the results in the <link + linkend="catalog-pg-statistic"><structname>pg_statistic</structname></link> + system catalog. Subsequently, the query planner uses these + statistics to help determine the most efficient execution plans for + queries. + </para> + + <para> + Without a <replaceable class="parameter">table_and_columns</replaceable> + list, <command>ANALYZE</command> processes every table and materialized view + in the current database that the current user has permission to analyze. + With a list, <command>ANALYZE</command> processes only those table(s). + It is further possible to give a list of column names for a table, + in which case only the statistics for those columns are collected. + </para> + + <para> + When the option list is surrounded by parentheses, the options can be + written in any order. The parenthesized syntax was added in + <productname>PostgreSQL</productname> 11; the unparenthesized syntax + is deprecated. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>VERBOSE</literal></term> + <listitem> + <para> + Enables display of progress messages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SKIP_LOCKED</literal></term> + <listitem> + <para> + Specifies that <command>ANALYZE</command> should not wait for any + conflicting locks to be released when beginning work on a relation: + if a relation cannot be locked immediately without waiting, the relation + is skipped. Note that even with this option, <command>ANALYZE</command> + may still block when opening the relation's indexes or when acquiring + sample rows from partitions, table inheritance children, and some + types of foreign tables. Also, while <command>ANALYZE</command> + ordinarily processes all partitions of specified partitioned tables, + this option will cause <command>ANALYZE</command> to skip all + partitions if there is a conflicting lock on the partitioned table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of a specific table to + analyze. If omitted, all regular tables, partitioned tables, and + materialized views in the current database are analyzed (but not + foreign tables). If the specified table is a partitioned table, both the + inheritance statistics of the partitioned table as a whole and + statistics of the individual partitions are updated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a specific column to analyze. Defaults to all columns. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + When <literal>VERBOSE</literal> is specified, <command>ANALYZE</command> emits + progress messages to indicate which table is currently being + processed. Various statistics about the tables are printed as well. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + To analyze a table, one must ordinarily be the table's owner or a + superuser. However, database owners are allowed to + analyze all tables in their databases, except shared catalogs. + (The restriction for shared catalogs means that a true database-wide + <command>ANALYZE</command> can only be performed by a superuser.) + <command>ANALYZE</command> will skip over any tables that the calling user + does not have permission to analyze. + </para> + + <para> + Foreign tables are analyzed only when explicitly selected. Not all + foreign data wrappers support <command>ANALYZE</command>. If the table's + wrapper does not support <command>ANALYZE</command>, the command prints a + warning and does nothing. + </para> + + <para> + In the default <productname>PostgreSQL</productname> configuration, + the autovacuum daemon (see <xref linkend="autovacuum"/>) + takes care of automatic analyzing of tables when they are first loaded + with data, and as they change throughout regular operation. + When autovacuum is disabled, + it is a good idea to run <command>ANALYZE</command> periodically, or + just after making major changes in the contents of a table. Accurate + statistics will help the planner to choose the most appropriate query + plan, and thereby improve the speed of query processing. A common + strategy for read-mostly databases is to run <link linkend="sql-vacuum"><command>VACUUM</command></link> + and <command>ANALYZE</command> once a day during a low-usage time of day. + (This will not be sufficient if there is heavy update activity.) + </para> + + <para> + <command>ANALYZE</command> + requires only a read lock on the target table, so it can run in + parallel with other activity on the table. + </para> + + <para> + The statistics collected by <command>ANALYZE</command> usually + include a list of some of the most common values in each column and + a histogram showing the approximate data distribution in each + column. One or both of these can be omitted if + <command>ANALYZE</command> deems them uninteresting (for example, + in a unique-key column, there are no common values) or if the + column data type does not support the appropriate operators. There + is more information about the statistics in <xref + linkend="maintenance"/>. + </para> + + <para> + For large tables, <command>ANALYZE</command> takes a random sample + of the table contents, rather than examining every row. This + allows even very large tables to be analyzed in a small amount of + time. Note, however, that the statistics are only approximate, and + will change slightly each time <command>ANALYZE</command> is run, + even if the actual table contents did not change. This might result + in small changes in the planner's estimated costs shown by + <link linkend="sql-explain"><command>EXPLAIN</command></link>. + In rare situations, this non-determinism will cause the planner's + choices of query plans to change after <command>ANALYZE</command> is run. + To avoid this, raise the amount of statistics collected by + <command>ANALYZE</command>, as described below. + </para> + + <para> + The extent of analysis can be controlled by adjusting the + <xref linkend="guc-default-statistics-target"/> configuration variable, or + on a column-by-column basis by setting the per-column statistics + target with <link linkend="sql-altertable"><command>ALTER TABLE ... ALTER COLUMN ... SET + STATISTICS</command></link>. + The target value sets the + maximum number of entries in the most-common-value list and the + maximum number of bins in the histogram. The default target value + is 100, but this can be adjusted up or down to trade off accuracy of + planner estimates against the time taken for + <command>ANALYZE</command> and the amount of space occupied in + <literal>pg_statistic</literal>. In particular, setting the + statistics target to zero disables collection of statistics for + that column. It might be useful to do that for columns that are + never used as part of the <literal>WHERE</literal>, <literal>GROUP BY</literal>, + or <literal>ORDER BY</literal> clauses of queries, since the planner will + have no use for statistics on such columns. + </para> + + <para> + The largest statistics target among the columns being analyzed determines + the number of table rows sampled to prepare the statistics. Increasing + the target causes a proportional increase in the time and space needed + to do <command>ANALYZE</command>. + </para> + + <para> + One of the values estimated by <command>ANALYZE</command> is the number of + distinct values that appear in each column. Because only a subset of the + rows are examined, this estimate can sometimes be quite inaccurate, even + with the largest possible statistics target. If this inaccuracy leads to + bad query plans, a more accurate value can be determined manually and then + installed with + <link linkend="sql-altertable"><command>ALTER TABLE ... ALTER COLUMN ... SET (n_distinct = ...)</command></link>. + </para> + + <para> + If the table being analyzed has inheritance children, + <command>ANALYZE</command> gathers two sets of statistics: one on the rows + of the parent table only, and a second including rows of both the parent + table and all of its children. This second set of statistics is needed when + planning queries that process the inheritance tree as a whole. The child + tables themselves are not individually analyzed in this case. + The autovacuum daemon, however, will only consider inserts or + updates on the parent table itself when deciding whether to trigger an + automatic analyze for that table. If that table is rarely inserted into + or updated, the inheritance statistics will not be up to date unless you + run <command>ANALYZE</command> manually. + </para> + + <para> + For partitioned tables, <command>ANALYZE</command> gathers statistics by + sampling rows from all partitions; in addition, it will recurse into each + partition and update its statistics. Each leaf partition is analyzed only + once, even with multi-level partitioning. No statistics are collected for + only the parent table (without data from its partitions), because with + partitioning it's guaranteed to be empty. + </para> + + <para> + The autovacuum daemon does not process partitioned tables, nor does it + process inheritance parents if only the children are ever modified. + It is usually necessary to periodically run a manual + <command>ANALYZE</command> to keep the statistics of the table hierarchy + up to date. + </para> + + <para> + If any child tables or partitions are foreign tables whose foreign + data wrappers do not support <command>ANALYZE</command>, those tables are + ignored while gathering inheritance statistics. + </para> + + <para> + If the table being analyzed is completely empty, <command>ANALYZE</command> + will not record new statistics for that table. Any existing statistics + will be retained. + </para> + + <para> + Each backend running <command>ANALYZE</command> will report its progress + in the <structname>pg_stat_progress_analyze</structname> view. See + <xref linkend="analyze-progress-reporting"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>ANALYZE</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-vacuum"/></member> + <member><xref linkend="app-vacuumdb"/></member> + <member><xref linkend="runtime-config-resource-vacuum-cost"/></member> + <member><xref linkend="autovacuum"/></member> + <member><xref linkend="analyze-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/begin.sgml b/doc/src/sgml/ref/begin.sgml new file mode 100644 index 0000000..016b021 --- /dev/null +++ b/doc/src/sgml/ref/begin.sgml @@ -0,0 +1,161 @@ +<!-- +doc/src/sgml/ref/begin.sgml +PostgreSQL documentation +--> + +<refentry id="sql-begin"> + <indexterm zone="sql-begin"> + <primary>BEGIN</primary> + </indexterm> + + <refmeta> + <refentrytitle>BEGIN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>BEGIN</refname> + <refpurpose>start a transaction block</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +BEGIN [ WORK | TRANSACTION ] [ <replaceable class="parameter">transaction_mode</replaceable> [, ...] ] + +<phrase>where <replaceable class="parameter">transaction_mode</replaceable> is one of:</phrase> + + ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED } + READ WRITE | READ ONLY + [ NOT ] DEFERRABLE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>BEGIN</command> initiates a transaction block, that is, + all statements after a <command>BEGIN</command> command will be + executed in a single transaction until an explicit <link + linkend="sql-commit"><command>COMMIT</command></link> or <link + linkend="sql-rollback"><command>ROLLBACK</command></link> is given. + By default (without <command>BEGIN</command>), + <productname>PostgreSQL</productname> executes + transactions in <quote>autocommit</quote> mode, that is, each + statement is executed in its own transaction and a commit is + implicitly performed at the end of the statement (if execution was + successful, otherwise a rollback is done). + </para> + + <para> + Statements are executed more quickly in a transaction block, because + transaction start/commit requires significant CPU and disk + activity. Execution of multiple statements inside a transaction is + also useful to ensure consistency when making several related changes: + other sessions will be unable to see the intermediate states + wherein not all the related updates have been done. + </para> + + <para> + If the isolation level, read/write mode, or deferrable mode is specified, the new + transaction has those characteristics, as if + <link linkend="sql-set-transaction"><command>SET TRANSACTION</command></link> + was executed. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>WORK</literal></term> + <term><literal>TRANSACTION</literal></term> + <listitem> + <para> + Optional key words. They have no effect. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + Refer to <xref linkend="sql-set-transaction"/> for information on the meaning + of the other parameters to this statement. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <link linkend="sql-start-transaction"><command>START TRANSACTION</command></link> has the same functionality + as <command>BEGIN</command>. + </para> + + <para> + Use <link linkend="sql-commit"><command>COMMIT</command></link> or + <link linkend="sql-rollback"><command>ROLLBACK</command></link> + to terminate a transaction block. + </para> + + <para> + Issuing <command>BEGIN</command> when already inside a transaction block will + provoke a warning message. The state of the transaction is not affected. + To nest transactions within a transaction block, use savepoints + (see <xref linkend="sql-savepoint"/>). + </para> + + <para> + For reasons of backwards compatibility, the commas between successive + <replaceable class="parameter">transaction_modes</replaceable> can be + omitted. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To begin a transaction block: + +<programlisting> +BEGIN; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>BEGIN</command> is a <productname>PostgreSQL</productname> + language extension. It is equivalent to the SQL-standard command + <link linkend="sql-start-transaction"><command>START TRANSACTION</command></link>, whose reference page + contains additional compatibility information. + </para> + + <para> + The <literal>DEFERRABLE</literal> + <replaceable class="parameter">transaction_mode</replaceable> + is a <productname>PostgreSQL</productname> language extension. + </para> + + <para> + Incidentally, the <literal>BEGIN</literal> key word is used for a + different purpose in embedded SQL. You are advised to be careful + about the transaction semantics when porting database applications. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback"/></member> + <member><xref linkend="sql-start-transaction"/></member> + <member><xref linkend="sql-savepoint"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/call.sgml b/doc/src/sgml/ref/call.sgml new file mode 100644 index 0000000..9e83a77 --- /dev/null +++ b/doc/src/sgml/ref/call.sgml @@ -0,0 +1,133 @@ +<!-- +doc/src/sgml/ref/call.sgml +PostgreSQL documentation +--> + +<refentry id="sql-call"> + <indexterm zone="sql-call"> + <primary>CALL</primary> + </indexterm> + + <refmeta> + <refentrytitle>CALL</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CALL</refname> + <refpurpose>invoke a procedure</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CALL <replaceable class="parameter">name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> ] [, ...] ) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CALL</command> executes a procedure. + </para> + + <para> + If the procedure has any output parameters, then a result row will be + returned, containing the values of those parameters. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the procedure. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argument</replaceable></term> + <listitem> + <para> + An argument expression for the procedure call. + </para> + + <para> + Arguments can include parameter names, using the syntax + <literal><replaceable class="parameter">name</replaceable> => <replaceable class="parameter">value</replaceable></literal>. + This works the same as in ordinary function calls; see + <xref linkend="sql-syntax-calling-funcs"/> for details. + </para> + + <para> + Arguments must be supplied for all procedure parameters that lack + defaults, including <literal>OUT</literal> parameters. However, + arguments matching <literal>OUT</literal> parameters are not evaluated, + so it's customary to just write <literal>NULL</literal> for them. + (Writing something else for an <literal>OUT</literal> parameter + might cause compatibility problems with + future <productname>PostgreSQL</productname> versions.) + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The user must have <literal>EXECUTE</literal> privilege on the procedure in + order to be allowed to invoke it. + </para> + + <para> + To call a function (not a procedure), use <command>SELECT</command> instead. + </para> + + <para> + If <command>CALL</command> is executed in a transaction block, then the + called procedure cannot execute transaction control statements. + Transaction control statements are only allowed if <command>CALL</command> + is executed in its own transaction. + </para> + + <para> + <application>PL/pgSQL</application> handles output parameters + in <command>CALL</command> commands differently; + see <xref linkend="plpgsql-statements-calling-procedure"/>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> +<programlisting> +CALL do_db_maintenance(); +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CALL</command> conforms to the SQL standard, + except for the handling of output parameters. The standard + says that users should write variables to receive the values + of output parameters. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createprocedure"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/checkpoint.sgml b/doc/src/sgml/ref/checkpoint.sgml new file mode 100644 index 0000000..28a1d71 --- /dev/null +++ b/doc/src/sgml/ref/checkpoint.sgml @@ -0,0 +1,69 @@ +<!-- +doc/src/sgml/ref/checkpoint.sgml +PostgreSQL documentation +--> + +<refentry id="sql-checkpoint"> + <indexterm zone="sql-checkpoint"> + <primary>CHECKPOINT</primary> + </indexterm> + + <refmeta> + <refentrytitle>CHECKPOINT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CHECKPOINT</refname> + <refpurpose>force a write-ahead log checkpoint</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CHECKPOINT +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + A checkpoint is a point in the write-ahead log sequence at which + all data files have been updated to reflect the information in the + log. All data files will be flushed to disk. Refer to + <xref linkend="wal-configuration"/> for more details about what happens + during a checkpoint. + </para> + + <para> + The <command>CHECKPOINT</command> command forces an immediate + checkpoint when the command is issued, without waiting for a + regular checkpoint scheduled by the system (controlled by the settings in + <xref linkend="runtime-config-wal-checkpoints"/>). + <command>CHECKPOINT</command> is not intended for use during normal + operation. + </para> + + <para> + If executed during recovery, the <command>CHECKPOINT</command> command + will force a restartpoint (see <xref linkend="wal-configuration"/>) + rather than writing a new checkpoint. + </para> + + <para> + Only superusers or users with the privileges of + the <link linkend="predefined-roles-table"><literal>pg_checkpoint</literal></link> + role can call <command>CHECKPOINT</command>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>CHECKPOINT</command> command is a + <productname>PostgreSQL</productname> language extension. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/close.sgml b/doc/src/sgml/ref/close.sgml new file mode 100644 index 0000000..32d20ed --- /dev/null +++ b/doc/src/sgml/ref/close.sgml @@ -0,0 +1,132 @@ +<!-- +doc/src/sgml/ref/close.sgml +PostgreSQL documentation +--> + +<refentry id="sql-close"> + <indexterm zone="sql-close"> + <primary>CLOSE</primary> + </indexterm> + + <indexterm zone="sql-close"> + <primary>cursor</primary> + <secondary>CLOSE</secondary> + </indexterm> + + <refmeta> + <refentrytitle>CLOSE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CLOSE</refname> + <refpurpose>close a cursor</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CLOSE { <replaceable class="parameter">name</replaceable> | ALL } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CLOSE</command> frees the resources associated with an open cursor. + After the cursor is closed, no subsequent operations + are allowed on it. A cursor should be closed when it is + no longer needed. + </para> + + <para> + Every non-holdable open cursor is implicitly closed when a + transaction is terminated by <command>COMMIT</command> or + <command>ROLLBACK</command>. A holdable cursor is implicitly + closed if the transaction that created it aborts via + <command>ROLLBACK</command>. If the creating transaction + successfully commits, the holdable cursor remains open until an + explicit <command>CLOSE</command> is executed, or the client + disconnects. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an open cursor to close. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Close all open cursors. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <productname>PostgreSQL</productname> does not have an explicit + <command>OPEN</command> cursor statement; a cursor is considered + open when it is declared. Use the + <link linkend="sql-declare"><command>DECLARE</command></link> + statement to declare a cursor. + </para> + + <para> + You can see all available cursors by querying the <link + linkend="view-pg-cursors"><structname>pg_cursors</structname></link> system view. + </para> + + <para> + If a cursor is closed after a savepoint which is later rolled back, + the <command>CLOSE</command> is not rolled back; that is, the cursor + remains closed. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Close the cursor <literal>liahona</literal>: +<programlisting> +CLOSE liahona; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CLOSE</command> is fully conforming with the SQL + standard. <command>CLOSE ALL</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-declare"/></member> + <member><xref linkend="sql-fetch"/></member> + <member><xref linkend="sql-move"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/cluster.sgml b/doc/src/sgml/ref/cluster.sgml new file mode 100644 index 0000000..c37f423 --- /dev/null +++ b/doc/src/sgml/ref/cluster.sgml @@ -0,0 +1,259 @@ +<!-- +doc/src/sgml/ref/cluster.sgml +PostgreSQL documentation +--> + +<refentry id="sql-cluster"> + <indexterm zone="sql-cluster"> + <primary>CLUSTER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CLUSTER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CLUSTER</refname> + <refpurpose>cluster a table according to an index</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CLUSTER [VERBOSE] <replaceable class="parameter">table_name</replaceable> [ USING <replaceable class="parameter">index_name</replaceable> ] +CLUSTER ( <replaceable class="parameter">option</replaceable> [, ...] ) <replaceable class="parameter">table_name</replaceable> [ USING <replaceable class="parameter">index_name</replaceable> ] +CLUSTER [VERBOSE] + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + VERBOSE [ <replaceable class="parameter">boolean</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CLUSTER</command> instructs <productname>PostgreSQL</productname> + to cluster the table specified + by <replaceable class="parameter">table_name</replaceable> + based on the index specified by + <replaceable class="parameter">index_name</replaceable>. The index must + already have been defined on + <replaceable class="parameter">table_name</replaceable>. + </para> + + <para> + When a table is clustered, it is physically reordered + based on the index information. Clustering is a one-time operation: + when the table is subsequently updated, the changes are + not clustered. That is, no attempt is made to store new or + updated rows according to their index order. (If one wishes, one can + periodically recluster by issuing the command again. Also, setting + the table's <literal>fillfactor</literal> storage parameter to less than + 100% can aid in preserving cluster ordering during updates, since updated + rows are kept on the same page if enough space is available there.) + </para> + + <para> + When a table is clustered, <productname>PostgreSQL</productname> + remembers which index it was clustered by. The form + <command>CLUSTER <replaceable class="parameter">table_name</replaceable></command> + reclusters the table using the same index as before. You can also + use the <literal>CLUSTER</literal> or <literal>SET WITHOUT CLUSTER</literal> + forms of <link linkend="sql-altertable"><command>ALTER TABLE</command></link> to set the index to be used for + future cluster operations, or to clear any previous setting. + </para> + + <para> + <command>CLUSTER</command> without any parameter reclusters all the + previously-clustered tables in the current database that the calling user + owns, or all such tables if called by a superuser. This + form of <command>CLUSTER</command> cannot be executed inside a transaction + block. + </para> + + <para> + When a table is being clustered, an <literal>ACCESS + EXCLUSIVE</literal> lock is acquired on it. This prevents any other + database operations (both reads and writes) from operating on the + table until the <command>CLUSTER</command> is finished. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of a table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_name</replaceable></term> + <listitem> + <para> + The name of an index. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VERBOSE</literal></term> + <listitem> + <para> + Prints a progress report as each table is clustered. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + In cases where you are accessing single rows randomly + within a table, the actual order of the data in the + table is unimportant. However, if you tend to access some + data more than others, and there is an index that groups + them together, you will benefit from using <command>CLUSTER</command>. + If you are requesting a range of indexed values from a table, or a + single indexed value that has multiple rows that match, + <command>CLUSTER</command> will help because once the index identifies the + table page for the first row that matches, all other rows + that match are probably already on the same table page, + and so you save disk accesses and speed up the query. + </para> + + <para> + <command>CLUSTER</command> can re-sort the table using either an index scan + on the specified index, or (if the index is a b-tree) a sequential + scan followed by sorting. It will attempt to choose the method that + will be faster, based on planner cost parameters and available statistical + information. + </para> + + <para> + When an index scan is used, a temporary copy of the table is created that + contains the table data in the index order. Temporary copies of each + index on the table are created as well. Therefore, you need free space on + disk at least equal to the sum of the table size and the index sizes. + </para> + + <para> + When a sequential scan and sort is used, a temporary sort file is + also created, so that the peak temporary space requirement is as much + as double the table size, plus the index sizes. This method is often + faster than the index scan method, but if the disk space requirement is + intolerable, you can disable this choice by temporarily setting <xref + linkend="guc-enable-sort"/> to <literal>off</literal>. + </para> + + <para> + It is advisable to set <xref linkend="guc-maintenance-work-mem"/> to + a reasonably large value (but not more than the amount of RAM you can + dedicate to the <command>CLUSTER</command> operation) before clustering. + </para> + + <para> + Because the planner records statistics about the ordering of + tables, it is advisable to run <link linkend="sql-analyze"><command>ANALYZE</command></link> + on the newly clustered table. + Otherwise, the planner might make poor choices of query plans. + </para> + + <para> + Because <command>CLUSTER</command> remembers which indexes are clustered, + one can cluster the tables one wants clustered manually the first time, + then set up a periodic maintenance script that executes + <command>CLUSTER</command> without any parameters, so that the desired tables + are periodically reclustered. + </para> + + <para> + Each backend running <command>CLUSTER</command> will report its progress + in the <structname>pg_stat_progress_cluster</structname> view. See + <xref linkend="cluster-progress-reporting"/> for details. + </para> + + <para> + Clustering a partitioned table clusters each of its partitions using the + partition of the specified partitioned index. When clustering a partitioned + table, the index may not be omitted. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Cluster the table <literal>employees</literal> on the basis of + its index <literal>employees_ind</literal>: +<programlisting> +CLUSTER employees USING employees_ind; +</programlisting> + </para> + + <para> + Cluster the <literal>employees</literal> table using the same + index that was used before: +<programlisting> +CLUSTER employees; +</programlisting> + </para> + + <para> + Cluster all tables in the database that have previously been clustered: +<programlisting> +CLUSTER; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CLUSTER</command> statement in the SQL standard. + </para> + + <para> + The syntax +<synopsis> +CLUSTER <replaceable class="parameter">index_name</replaceable> ON <replaceable class="parameter">table_name</replaceable> +</synopsis> + is also supported for compatibility with pre-8.3 <productname>PostgreSQL</productname> + versions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-clusterdb"/></member> + <member><xref linkend="cluster-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/clusterdb.sgml b/doc/src/sgml/ref/clusterdb.sgml new file mode 100644 index 0000000..c838b22 --- /dev/null +++ b/doc/src/sgml/ref/clusterdb.sgml @@ -0,0 +1,352 @@ +<!-- +doc/src/sgml/ref/clusterdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-clusterdb"> + <indexterm zone="app-clusterdb"> + <primary>clusterdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>clusterdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>clusterdb</refname> + <refpurpose>cluster a <productname>PostgreSQL</productname> database</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>clusterdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <group choice="opt"><arg choice="plain"><option>--verbose</option></arg><arg choice="plain"><option>-v</option></arg></group> + + <arg choice="plain" rep="repeat"> + <arg choice="opt"> + <group choice="plain"> + <arg choice="plain"><option>--table</option></arg> + <arg choice="plain"><option>-t</option></arg> + </group> + <replaceable>table</replaceable> + </arg> + </arg> + + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>clusterdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <group choice="opt"><arg choice="plain"><option>--verbose</option></arg><arg choice="plain"><option>-v</option></arg></group> + <group choice="plain"><arg choice="plain"><option>--all</option></arg><arg choice="plain"><option>-a</option></arg></group> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1> + <title>Description</title> + + <para> + <application>clusterdb</application> is a utility for reclustering tables + in a <productname>PostgreSQL</productname> database. It finds tables + that have previously been clustered, and clusters them again on the same + index that was last used. Tables that have never been clustered are not + affected. + </para> + + <para> + <application>clusterdb</application> is a wrapper around the SQL + command <xref linkend="sql-cluster"/>. + There is no effective difference between clustering databases via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>clusterdb</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--all</option></term> + <listitem> + <para> + Cluster all databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option><optional>-d</optional> <replaceable class="parameter">dbname</replaceable></option></term> + <term><option><optional>--dbname=</optional><replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to be clustered, + when <option>-a</option>/<option>--all</option> is not used. + If this is not specified, the database name is read + from the environment variable <envar>PGDATABASE</envar>. If + that is not set, the user name specified for the connection is + used. The <replaceable>dbname</replaceable> can be a <link + linkend="libpq-connstring">connection string</link>. If so, + connection string parameters will override any conflicting command + line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>clusterdb</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Do not display progress messages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">table</replaceable></option></term> + <term><option>--table=<replaceable class="parameter">table</replaceable></option></term> + <listitem> + <para> + Cluster <replaceable class="parameter">table</replaceable> only. + Multiple tables can be clustered by writing multiple + <option>-t</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Print detailed information during processing. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>clusterdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>clusterdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + <application>clusterdb</application> also accepts + the following command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>clusterdb</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>clusterdb</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>clusterdb</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to to discover which + databases should be clustered, + when <option>-a</option>/<option>--all</option> is used. + If not specified, the <literal>postgres</literal> database will be used, + or if that does not exist, <literal>template1</literal> will be used. + This can be a <link linkend="libpq-connstring">connection + string</link>. If so, connection string parameters will override any + conflicting command line options. Also, connection string parameters + other than the database name itself will be re-used when connecting + to other databases. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-cluster"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To cluster the database <literal>test</literal>: +<screen> +<prompt>$ </prompt><userinput>clusterdb test</userinput> +</screen> + </para> + + <para> + To cluster a single table + <literal>foo</literal> in a database named + <literal>xyzzy</literal>: +<screen> +<prompt>$ </prompt><userinput>clusterdb --table=foo xyzzy</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-cluster"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/comment.sgml b/doc/src/sgml/ref/comment.sgml new file mode 100644 index 0000000..fd3f465 --- /dev/null +++ b/doc/src/sgml/ref/comment.sgml @@ -0,0 +1,374 @@ +<!-- +doc/src/sgml/ref/comment.sgml +PostgreSQL documentation +--> + +<refentry id="sql-comment"> + <indexterm zone="sql-comment"> + <primary>COMMENT</primary> + </indexterm> + + <refmeta> + <refentrytitle>COMMENT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>COMMENT</refname> + <refpurpose>define or change the comment of an object</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +COMMENT ON +{ + ACCESS METHOD <replaceable class="parameter">object_name</replaceable> | + AGGREGATE <replaceable class="parameter">aggregate_name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) | + CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) | + COLLATION <replaceable class="parameter">object_name</replaceable> | + COLUMN <replaceable class="parameter">relation_name</replaceable>.<replaceable class="parameter">column_name</replaceable> | + CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ON <replaceable class="parameter">table_name</replaceable> | + CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ON DOMAIN <replaceable class="parameter">domain_name</replaceable> | + CONVERSION <replaceable class="parameter">object_name</replaceable> | + DATABASE <replaceable class="parameter">object_name</replaceable> | + DOMAIN <replaceable class="parameter">object_name</replaceable> | + EXTENSION <replaceable class="parameter">object_name</replaceable> | + EVENT TRIGGER <replaceable class="parameter">object_name</replaceable> | + FOREIGN DATA WRAPPER <replaceable class="parameter">object_name</replaceable> | + FOREIGN TABLE <replaceable class="parameter">object_name</replaceable> | + FUNCTION <replaceable class="parameter">function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + INDEX <replaceable class="parameter">object_name</replaceable> | + LARGE OBJECT <replaceable class="parameter">large_object_oid</replaceable> | + MATERIALIZED VIEW <replaceable class="parameter">object_name</replaceable> | + OPERATOR <replaceable class="parameter">operator_name</replaceable> (<replaceable class="parameter">left_type</replaceable>, <replaceable class="parameter">right_type</replaceable>) | + OPERATOR CLASS <replaceable class="parameter">object_name</replaceable> USING <replaceable class="parameter">index_method</replaceable> | + OPERATOR FAMILY <replaceable class="parameter">object_name</replaceable> USING <replaceable class="parameter">index_method</replaceable> | + POLICY <replaceable class="parameter">policy_name</replaceable> ON <replaceable class="parameter">table_name</replaceable> | + [ PROCEDURAL ] LANGUAGE <replaceable class="parameter">object_name</replaceable> | + PROCEDURE <replaceable class="parameter">procedure_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + PUBLICATION <replaceable class="parameter">object_name</replaceable> | + ROLE <replaceable class="parameter">object_name</replaceable> | + ROUTINE <replaceable class="parameter">routine_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + RULE <replaceable class="parameter">rule_name</replaceable> ON <replaceable class="parameter">table_name</replaceable> | + SCHEMA <replaceable class="parameter">object_name</replaceable> | + SEQUENCE <replaceable class="parameter">object_name</replaceable> | + SERVER <replaceable class="parameter">object_name</replaceable> | + STATISTICS <replaceable class="parameter">object_name</replaceable> | + SUBSCRIPTION <replaceable class="parameter">object_name</replaceable> | + TABLE <replaceable class="parameter">object_name</replaceable> | + TABLESPACE <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH CONFIGURATION <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH DICTIONARY <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH PARSER <replaceable class="parameter">object_name</replaceable> | + TEXT SEARCH TEMPLATE <replaceable class="parameter">object_name</replaceable> | + TRANSFORM FOR <replaceable>type_name</replaceable> LANGUAGE <replaceable>lang_name</replaceable> | + TRIGGER <replaceable class="parameter">trigger_name</replaceable> ON <replaceable class="parameter">table_name</replaceable> | + TYPE <replaceable class="parameter">object_name</replaceable> | + VIEW <replaceable class="parameter">object_name</replaceable> +} IS { <replaceable class="parameter">string_literal</replaceable> | NULL } + +<phrase>where <replaceable>aggregate_signature</replaceable> is:</phrase> + +* | +[ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] | +[ [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] ] ORDER BY [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>COMMENT</command> stores a comment about a database object. + </para> + + <para> + Only one comment string is stored for each object, so to modify a comment, + issue a new <command>COMMENT</command> command for the same object. To remove a + comment, write <literal>NULL</literal> in place of the text string. + Comments are automatically dropped when their object is dropped. + </para> + + <para> + A <literal>SHARE UPDATE EXCLUSIVE</literal> lock is acquired on the + object to be commented. + </para> + + <para> + For most kinds of object, only the object's owner can set the comment. + Roles don't have owners, so the rule for <literal>COMMENT ON ROLE</literal> is + that you must be superuser to comment on a superuser role, or have the + <literal>CREATEROLE</literal> privilege to comment on non-superuser roles. + Likewise, access methods don't have owners either; you must be superuser + to comment on an access method. + Of course, a superuser can comment on anything. + </para> + + <para> + Comments can be viewed using <application>psql</application>'s + <command>\d</command> family of commands. + Other user interfaces to retrieve comments can be built atop + the same built-in functions that <application>psql</application> uses, namely + <function>obj_description</function>, <function>col_description</function>, + and <function>shobj_description</function> + (see <xref linkend="functions-info-comment-table"/>). + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">object_name</replaceable></term> + <term><replaceable class="parameter">relation_name</replaceable>.<replaceable>column_name</replaceable></term> + <term><replaceable class="parameter">aggregate_name</replaceable></term> + <term><replaceable class="parameter">constraint_name</replaceable></term> + <term><replaceable class="parameter">function_name</replaceable></term> + <term><replaceable class="parameter">operator_name</replaceable></term> + <term><replaceable class="parameter">policy_name</replaceable></term> + <term><replaceable class="parameter">procedure_name</replaceable></term> + <term><replaceable class="parameter">routine_name</replaceable></term> + <term><replaceable class="parameter">rule_name</replaceable></term> + <term><replaceable class="parameter">trigger_name</replaceable></term> + <listitem> + <para> + The name of the object to be commented. Names of objects that reside in + schemas (tables, functions, etc.) can be + schema-qualified. When commenting on a column, + <replaceable class="parameter">relation_name</replaceable> must refer + to a table, view, composite type, or foreign table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <term><replaceable class="parameter">domain_name</replaceable></term> + <listitem> + <para> + When creating a comment on a constraint, a trigger, a rule or + a policy these parameters specify the name of the table or domain on + which that object is defined. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>source_type</replaceable></term> + <listitem> + <para> + The name of the source data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>target_type</replaceable></term> + <listitem> + <para> + The name of the target data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + <listitem> + <para> + The mode of a function, procedure, or aggregate + argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Note that <command>COMMENT</command> does not actually pay + any attention to <literal>OUT</literal> arguments, since only the input + arguments are needed to determine the function's identity. + So it is sufficient to list the <literal>IN</literal>, <literal>INOUT</literal>, + and <literal>VARIADIC</literal> arguments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + <listitem> + <para> + The name of a function, procedure, or aggregate argument. + Note that <command>COMMENT</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + <listitem> + <para> + The data type of a function, procedure, or aggregate argument. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">large_object_oid</replaceable></term> + <listitem> + <para> + The OID of the large object. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">left_type</replaceable></term> + <term><replaceable class="parameter">right_type</replaceable></term> + <listitem> + <para> + The data type(s) of the operator's arguments (optionally + schema-qualified). Write <literal>NONE</literal> for the missing argument + of a prefix operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROCEDURAL</literal></term> + <listitem> + <para> + This is a noise word. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>type_name</replaceable></term> + + <listitem> + <para> + The name of the data type of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lang_name</replaceable></term> + + <listitem> + <para> + The name of the language of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">string_literal</replaceable></term> + <listitem> + <para> + The new comment contents, written as a string literal. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + Write <literal>NULL</literal> to drop the comment. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + There is presently no security mechanism for viewing comments: any user + connected to a database can see all the comments for objects in + that database. For shared objects such as + databases, roles, and tablespaces, comments are stored globally so any + user connected to any database in the cluster can see all the comments + for shared objects. Therefore, don't put security-critical + information in comments. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Attach a comment to the table <literal>mytable</literal>: + +<programlisting> +COMMENT ON TABLE mytable IS 'This is my table.'; +</programlisting> + + Remove it again: + +<programlisting> +COMMENT ON TABLE mytable IS NULL; +</programlisting> + </para> + + <para> + Some more examples: + +<programlisting> +COMMENT ON ACCESS METHOD gin IS 'GIN index access method'; +COMMENT ON AGGREGATE my_aggregate (double precision) IS 'Computes sample variance'; +COMMENT ON CAST (text AS int4) IS 'Allow casts from text to int4'; +COMMENT ON COLLATION "fr_CA" IS 'Canadian French'; +COMMENT ON COLUMN my_table.my_column IS 'Employee ID number'; +COMMENT ON CONVERSION my_conv IS 'Conversion to UTF8'; +COMMENT ON CONSTRAINT bar_col_cons ON bar IS 'Constrains column col'; +COMMENT ON CONSTRAINT dom_col_constr ON DOMAIN dom IS 'Constrains col of domain'; +COMMENT ON DATABASE my_database IS 'Development Database'; +COMMENT ON DOMAIN my_domain IS 'Email Address Domain'; +COMMENT ON EVENT TRIGGER abort_ddl IS 'Aborts all DDL commands'; +COMMENT ON EXTENSION hstore IS 'implements the hstore data type'; +COMMENT ON FOREIGN DATA WRAPPER mywrapper IS 'my foreign data wrapper'; +COMMENT ON FOREIGN TABLE my_foreign_table IS 'Employee Information in other database'; +COMMENT ON FUNCTION my_function (timestamp) IS 'Returns Roman Numeral'; +COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee ID'; +COMMENT ON LANGUAGE plpython IS 'Python support for stored procedures'; +COMMENT ON LARGE OBJECT 346344 IS 'Planning document'; +COMMENT ON MATERIALIZED VIEW my_matview IS 'Summary of order history'; +COMMENT ON OPERATOR ^ (text, text) IS 'Performs intersection of two texts'; +COMMENT ON OPERATOR - (NONE, integer) IS 'Unary minus'; +COMMENT ON OPERATOR CLASS int4ops USING btree IS '4 byte integer operators for btrees'; +COMMENT ON OPERATOR FAMILY integer_ops USING btree IS 'all integer operators for btrees'; +COMMENT ON POLICY my_policy ON mytable IS 'Filter rows by users'; +COMMENT ON PROCEDURE my_proc (integer, integer) IS 'Runs a report'; +COMMENT ON PUBLICATION alltables IS 'Publishes all operations on all tables'; +COMMENT ON ROLE my_role IS 'Administration group for finance tables'; +COMMENT ON ROUTINE my_routine (integer, integer) IS 'Runs a routine (which is a function or procedure)'; +COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records'; +COMMENT ON SCHEMA my_schema IS 'Departmental data'; +COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys'; +COMMENT ON SERVER myserver IS 'my foreign server'; +COMMENT ON STATISTICS my_statistics IS 'Improves planner row estimations'; +COMMENT ON SUBSCRIPTION alltables IS 'Subscription for all operations on all tables'; +COMMENT ON TABLE my_schema.my_table IS 'Employee Information'; +COMMENT ON TABLESPACE my_tablespace IS 'Tablespace for indexes'; +COMMENT ON TEXT SEARCH CONFIGURATION my_config IS 'Special word filtering'; +COMMENT ON TEXT SEARCH DICTIONARY swedish IS 'Snowball stemmer for Swedish language'; +COMMENT ON TEXT SEARCH PARSER my_parser IS 'Splits text into words'; +COMMENT ON TEXT SEARCH TEMPLATE snowball IS 'Snowball stemmer'; +COMMENT ON TRANSFORM FOR hstore LANGUAGE plpython3u IS 'Transform between hstore and Python dict'; +COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for RI'; +COMMENT ON TYPE complex IS 'Complex number data type'; +COMMENT ON VIEW my_view IS 'View of departmental costs'; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>COMMENT</command> command in the SQL standard. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/commit.sgml b/doc/src/sgml/ref/commit.sgml new file mode 100644 index 0000000..5f244cd --- /dev/null +++ b/doc/src/sgml/ref/commit.sgml @@ -0,0 +1,112 @@ +<!-- +doc/src/sgml/ref/commit.sgml +PostgreSQL documentation +--> + +<refentry id="sql-commit"> + <indexterm zone="sql-commit"> + <primary>COMMIT</primary> + </indexterm> + + <refmeta> + <refentrytitle>COMMIT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>COMMIT</refname> + <refpurpose>commit the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +COMMIT [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>COMMIT</command> commits the current transaction. All + changes made by the transaction become visible to others + and are guaranteed to be durable if a crash occurs. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <indexterm zone="sql-commit-chain"> + <primary>chained transactions</primary> + </indexterm> + + <variablelist> + <varlistentry> + <term><literal>WORK</literal></term> + <term><literal>TRANSACTION</literal></term> + <listitem> + <para> + Optional key words. They have no effect. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-commit-chain"> + <term><literal>AND CHAIN</literal></term> + <listitem> + <para> + If <literal>AND CHAIN</literal> is specified, a new transaction is + immediately started with the same transaction characteristics (see <xref + linkend="sql-set-transaction"/>) as the just finished one. Otherwise, + no new transaction is started. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <xref linkend="sql-rollback"/> to + abort a transaction. + </para> + + <para> + Issuing <command>COMMIT</command> when not inside a transaction does + no harm, but it will provoke a warning message. <command>COMMIT AND + CHAIN</command> when not inside a transaction is an error. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To commit the current transaction and make all changes permanent: +<programlisting> +COMMIT; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The command <command>COMMIT</command> conforms to the SQL standard. The + form <literal>COMMIT TRANSACTION</literal> is a PostgreSQL extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-rollback"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/commit_prepared.sgml b/doc/src/sgml/ref/commit_prepared.sgml new file mode 100644 index 0000000..7299f73 --- /dev/null +++ b/doc/src/sgml/ref/commit_prepared.sgml @@ -0,0 +1,107 @@ +<!-- +doc/src/sgml/ref/commit_prepared.sgml +PostgreSQL documentation +--> + +<refentry id="sql-commit-prepared"> + <indexterm zone="sql-commit-prepared"> + <primary>COMMIT PREPARED</primary> + </indexterm> + + <refmeta> + <refentrytitle>COMMIT PREPARED</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>COMMIT PREPARED</refname> + <refpurpose>commit a transaction that was earlier prepared for two-phase commit</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +COMMIT PREPARED <replaceable class="parameter">transaction_id</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>COMMIT PREPARED</command> commits a transaction that is in + prepared state. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">transaction_id</replaceable></term> + <listitem> + <para> + The transaction identifier of the transaction that is to be + committed. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + To commit a prepared transaction, you must be either the same user that + executed the transaction originally, or a superuser. But you do not + have to be in the same session that executed the transaction. + </para> + + <para> + This command cannot be executed inside a transaction block. The prepared + transaction is committed immediately. + </para> + + <para> + All currently available prepared transactions are listed in the + <link linkend="view-pg-prepared-xacts"><structname>pg_prepared_xacts</structname></link> + system view. + </para> + </refsect1> + + <refsect1 id="sql-commit-prepared-examples"> + <title>Examples</title> + <para> + Commit the transaction identified by the transaction + identifier <literal>foobar</literal>: + +<programlisting> +COMMIT PREPARED 'foobar'; +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>COMMIT PREPARED</command> is a + <productname>PostgreSQL</productname> extension. It is intended for use by + external transaction management systems, some of which are covered by + standards (such as X/Open XA), but the SQL side of those systems is not + standardized. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-prepare-transaction"/></member> + <member><xref linkend="sql-rollback-prepared"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgml new file mode 100644 index 0000000..63afa0d --- /dev/null +++ b/doc/src/sgml/ref/copy.sgml @@ -0,0 +1,1081 @@ +<!-- +doc/src/sgml/ref/copy.sgml +PostgreSQL documentation +--> + +<refentry id="sql-copy"> + <indexterm zone="sql-copy"> + <primary>COPY</primary> + </indexterm> + + <refmeta> + <refentrytitle>COPY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>COPY</refname> + <refpurpose>copy data between a file and a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] + FROM { '<replaceable class="parameter">filename</replaceable>' | PROGRAM '<replaceable class="parameter">command</replaceable>' | STDIN } + [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ] + [ WHERE <replaceable class="parameter">condition</replaceable> ] + +COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) } + TO { '<replaceable class="parameter">filename</replaceable>' | PROGRAM '<replaceable class="parameter">command</replaceable>' | STDOUT } + [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + FORMAT <replaceable class="parameter">format_name</replaceable> + FREEZE [ <replaceable class="parameter">boolean</replaceable> ] + DELIMITER '<replaceable class="parameter">delimiter_character</replaceable>' + NULL '<replaceable class="parameter">null_string</replaceable>' + HEADER [ <replaceable class="parameter">boolean</replaceable> | MATCH ] + QUOTE '<replaceable class="parameter">quote_character</replaceable>' + ESCAPE '<replaceable class="parameter">escape_character</replaceable>' + FORCE_QUOTE { ( <replaceable class="parameter">column_name</replaceable> [, ...] ) | * } + FORCE_NOT_NULL ( <replaceable class="parameter">column_name</replaceable> [, ...] ) + FORCE_NULL ( <replaceable class="parameter">column_name</replaceable> [, ...] ) + ENCODING '<replaceable class="parameter">encoding_name</replaceable>' +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>COPY</command> moves data between + <productname>PostgreSQL</productname> tables and standard file-system + files. <command>COPY TO</command> copies the contents of a table + <emphasis>to</emphasis> a file, while <command>COPY FROM</command> copies + data <emphasis>from</emphasis> a file to a table (appending the data to + whatever is in the table already). <command>COPY TO</command> + can also copy the results of a <command>SELECT</command> query. + </para> + + <para> + If a column list is specified, <command>COPY TO</command> copies only + the data in the specified columns to the file. For <command>COPY + FROM</command>, each field in the file is inserted, in order, into the + specified column. Table columns not specified in the <command>COPY + FROM</command> column list will receive their default values. + </para> + + <para> + <command>COPY</command> with a file name instructs the + <productname>PostgreSQL</productname> server to directly read from + or write to a file. The file must be accessible by the + <productname>PostgreSQL</productname> user (the user ID the server + runs as) and the name must be specified from the viewpoint of the + server. When <literal>PROGRAM</literal> is specified, the server + executes the given command and reads from the standard output of the + program, or writes to the standard input of the program. The command + must be specified from the viewpoint of the server, and be executable + by the <productname>PostgreSQL</productname> user. When + <literal>STDIN</literal> or <literal>STDOUT</literal> is + specified, data is transmitted via the connection between the + client and the server. + </para> + + <para> + Each backend running <command>COPY</command> will report its progress + in the <structname>pg_stat_progress_copy</structname> view. See + <xref linkend="copy-progress-reporting"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + An optional list of columns to be copied. If no column list is + specified, all columns of the table except generated columns will be + copied. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">query</replaceable></term> + <listitem> + <para> + A <link linkend="sql-select"><command>SELECT</command></link>, + <link linkend="sql-values"><command>VALUES</command></link>, + <link linkend="sql-insert"><command>INSERT</command></link>, + <link linkend="sql-update"><command>UPDATE</command></link>, or + <link linkend="sql-delete"><command>DELETE</command></link> command whose results are to be + copied. Note that parentheses are required around the query. + </para> + <para> + For <command>INSERT</command>, <command>UPDATE</command> and + <command>DELETE</command> queries a RETURNING clause must be provided, + and the target relation must not have a conditional rule, nor + an <literal>ALSO</literal> rule, nor an <literal>INSTEAD</literal> rule + that expands to multiple statements. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">filename</replaceable></term> + <listitem> + <para> + The path name of the input or output file. An input file name can be + an absolute or relative path, but an output file name must be an absolute + path. Windows users might need to use an <literal>E''</literal> string and + double any backslashes used in the path name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROGRAM</literal></term> + <listitem> + <para> + A command to execute. In <command>COPY FROM</command>, the input is + read from standard output of the command, and in <command>COPY TO</command>, + the output is written to the standard input of the command. + </para> + <para> + Note that the command is invoked by the shell, so if you need to pass + any arguments to shell command that come from an untrusted source, you + must be careful to strip or escape any special characters that might + have a special meaning for the shell. For security reasons, it is best + to use a fixed command string, or at least avoid passing any user input + in it. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>STDIN</literal></term> + <listitem> + <para> + Specifies that input comes from the client application. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>STDOUT</literal></term> + <listitem> + <para> + Specifies that output goes to the client application. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORMAT</literal></term> + <listitem> + <para> + Selects the data format to be read or written: + <literal>text</literal>, + <literal>csv</literal> (Comma Separated Values), + or <literal>binary</literal>. + The default is <literal>text</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FREEZE</literal></term> + <listitem> + <para> + Requests copying the data with rows already frozen, just as they + would be after running the <command>VACUUM FREEZE</command> command. + This is intended as a performance option for initial data loading. + Rows will be frozen only if the table being loaded has been created + or truncated in the current subtransaction, there are no cursors + open and there are no older snapshots held by this transaction. It is + currently not possible to perform a <command>COPY FREEZE</command> on + a partitioned table. + </para> + <para> + Note that all other sessions will immediately be able to see the data + once it has been successfully loaded. This violates the normal rules + of MVCC visibility and users specifying should be aware of the + potential problems this might cause. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DELIMITER</literal></term> + <listitem> + <para> + Specifies the character that separates columns within each row + (line) of the file. The default is a tab character in text format, + a comma in <literal>CSV</literal> format. + This must be a single one-byte character. + This option is not allowed when using <literal>binary</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + Specifies the string that represents a null value. The default is + <literal>\N</literal> (backslash-N) in text format, and an unquoted empty + string in <literal>CSV</literal> format. You might prefer an + empty string even in text format for cases where you don't want to + distinguish nulls from empty strings. + This option is not allowed when using <literal>binary</literal> format. + </para> + + <note> + <para> + When using <command>COPY FROM</command>, any data item that matches + this string will be stored as a null value, so you should make + sure that you use the same string as you used with + <command>COPY TO</command>. + </para> + </note> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HEADER</literal></term> + <listitem> + <para> + Specifies that the file contains a header line with the names of each + column in the file. On output, the first line contains the column + names from the table. On input, the first line is discarded when this + option is set to <literal>true</literal> (or equivalent Boolean value). + If this option is set to <literal>MATCH</literal>, the number and names + of the columns in the header line must match the actual column names of + the table, in order; otherwise an error is raised. + This option is not allowed when using <literal>binary</literal> format. + The <literal>MATCH</literal> option is only valid for <command>COPY + FROM</command> commands. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>QUOTE</literal></term> + <listitem> + <para> + Specifies the quoting character to be used when a data value is quoted. + The default is double-quote. + This must be a single one-byte character. + This option is allowed only when using <literal>CSV</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ESCAPE</literal></term> + <listitem> + <para> + Specifies the character that should appear before a + data character that matches the <literal>QUOTE</literal> value. + The default is the same as the <literal>QUOTE</literal> value (so that + the quoting character is doubled if it appears in the data). + This must be a single one-byte character. + This option is allowed only when using <literal>CSV</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORCE_QUOTE</literal></term> + <listitem> + <para> + Forces quoting to be + used for all non-<literal>NULL</literal> values in each specified column. + <literal>NULL</literal> output is never quoted. If <literal>*</literal> is specified, + non-<literal>NULL</literal> values will be quoted in all columns. + This option is allowed only in <command>COPY TO</command>, and only when + using <literal>CSV</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORCE_NOT_NULL</literal></term> + <listitem> + <para> + Do not match the specified columns' values against the null string. + In the default case where the null string is empty, this means that + empty values will be read as zero-length strings rather than nulls, + even when they are not quoted. + This option is allowed only in <command>COPY FROM</command>, and only when + using <literal>CSV</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORCE_NULL</literal></term> + <listitem> + <para> + Match the specified columns' values against the null string, even + if it has been quoted, and if a match is found set the value to + <literal>NULL</literal>. In the default case where the null string is empty, + this converts a quoted empty string into NULL. + This option is allowed only in <command>COPY FROM</command>, and only when + using <literal>CSV</literal> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ENCODING</literal></term> + <listitem> + <para> + Specifies that the file is encoded in the <replaceable + class="parameter">encoding_name</replaceable>. If this option is + omitted, the current client encoding is used. See the Notes below + for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WHERE</literal></term> + <listitem> + <para> + The optional <literal>WHERE</literal> clause has the general form +<synopsis> +WHERE <replaceable class="parameter">condition</replaceable> +</synopsis> + where <replaceable class="parameter">condition</replaceable> is + any expression that evaluates to a result of type + <type>boolean</type>. Any row that does not satisfy this + condition will not be inserted to the table. A row satisfies the + condition if it returns true when the actual row values are + substituted for any variable references. + </para> + + <para> + Currently, subqueries are not allowed in <literal>WHERE</literal> + expressions, and the evaluation does not see any changes made by the + <command>COPY</command> itself (this matters when the expression + contains calls to <literal>VOLATILE</literal> functions). + </para> + + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, a <command>COPY</command> command returns a command + tag of the form +<screen> +COPY <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number + of rows copied. + </para> + + <note> + <para> + <application>psql</application> will print this command tag only if the command + was not <literal>COPY ... TO STDOUT</literal>, or the + equivalent <application>psql</application> meta-command + <literal>\copy ... to stdout</literal>. This is to prevent confusing the + command tag with the data that was just printed. + </para> + </note> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>COPY TO</command> can be used only with plain + tables, not views, and does not copy rows from child tables + or child partitions. For example, <literal>COPY <replaceable + class="parameter">table</replaceable> TO</literal> copies + the same rows as <literal>SELECT * FROM ONLY <replaceable + class="parameter">table</replaceable></literal>. + The syntax <literal>COPY (SELECT * FROM <replaceable + class="parameter">table</replaceable>) TO ...</literal> can be used to + dump all of the rows in an inheritance hierarchy, partitioned table, + or view. + </para> + + <para> + <command>COPY FROM</command> can be used with plain, foreign, or + partitioned tables or with views that have + <literal>INSTEAD OF INSERT</literal> triggers. + </para> + + <para> + You must have select privilege on the table + whose values are read by <command>COPY TO</command>, and + insert privilege on the table into which values + are inserted by <command>COPY FROM</command>. It is sufficient + to have column privileges on the column(s) listed in the command. + </para> + + <para> + If row-level security is enabled for the table, the relevant + <command>SELECT</command> policies will apply to <literal>COPY + <replaceable class="parameter">table</replaceable> TO</literal> statements. + Currently, <command>COPY FROM</command> is not supported for tables + with row-level security. Use equivalent <command>INSERT</command> + statements instead. + </para> + + <para> + Files named in a <command>COPY</command> command are read or written + directly by the server, not by the client application. Therefore, + they must reside on or be accessible to the database server machine, + not the client. They must be accessible to and readable or writable + by the <productname>PostgreSQL</productname> user (the user ID the + server runs as), not the client. Similarly, + the command specified with <literal>PROGRAM</literal> is executed directly + by the server, not by the client application, must be executable by the + <productname>PostgreSQL</productname> user. + <command>COPY</command> naming a file or command is only allowed to + database superusers or users who are granted one of the roles + <literal>pg_read_server_files</literal>, + <literal>pg_write_server_files</literal>, + or <literal>pg_execute_server_program</literal>, since it allows reading + or writing any file or running a program that the server has privileges to + access. + </para> + + <para> + Do not confuse <command>COPY</command> with the + <application>psql</application> instruction + <command><link linkend="app-psql-meta-commands-copy">\copy</link></command>. <command>\copy</command> invokes + <command>COPY FROM STDIN</command> or <command>COPY TO + STDOUT</command>, and then fetches/stores the data in a file + accessible to the <application>psql</application> client. Thus, + file accessibility and access rights depend on the client rather + than the server when <command>\copy</command> is used. + </para> + + <para> + It is recommended that the file name used in <command>COPY</command> + always be specified as an absolute path. This is enforced by the + server in the case of <command>COPY TO</command>, but for + <command>COPY FROM</command> you do have the option of reading from + a file specified by a relative path. The path will be interpreted + relative to the working directory of the server process (normally + the cluster's data directory), not the client's working directory. + </para> + + <para> + Executing a command with <literal>PROGRAM</literal> might be restricted + by the operating system's access control mechanisms, such as SELinux. + </para> + + <para> + <command>COPY FROM</command> will invoke any triggers and check + constraints on the destination table. However, it will not invoke rules. + </para> + + <para> + For identity columns, the <command>COPY FROM</command> command will always + write the column values provided in the input data, like + the <command>INSERT</command> option <literal>OVERRIDING SYSTEM + VALUE</literal>. + </para> + + <para> + <command>COPY</command> input and output is affected by + <varname>DateStyle</varname>. To ensure portability to other + <productname>PostgreSQL</productname> installations that might use + non-default <varname>DateStyle</varname> settings, + <varname>DateStyle</varname> should be set to <literal>ISO</literal> before + using <command>COPY TO</command>. It is also a good idea to avoid dumping + data with <varname>IntervalStyle</varname> set to + <literal>sql_standard</literal>, because negative interval values might be + misinterpreted by a server that has a different setting for + <varname>IntervalStyle</varname>. + </para> + + <para> + Input data is interpreted according to <literal>ENCODING</literal> + option or the current client encoding, and output data is encoded + in <literal>ENCODING</literal> or the current client encoding, even + if the data does not pass through the client but is read from or + written to a file directly by the server. + </para> + + <para> + <command>COPY</command> stops operation at the first error. This + should not lead to problems in the event of a <command>COPY + TO</command>, but the target table will already have received + earlier rows in a <command>COPY FROM</command>. These rows will not + be visible or accessible, but they still occupy disk space. This might + amount to a considerable amount of wasted disk space if the failure + happened well into a large copy operation. You might wish to invoke + <command>VACUUM</command> to recover the wasted space. + </para> + + <para> + <literal>FORCE_NULL</literal> and <literal>FORCE_NOT_NULL</literal> can be used + simultaneously on the same column. This results in converting quoted + null strings to null values and unquoted null strings to empty strings. + </para> + + </refsect1> + + <refsect1> + <title>File Formats</title> + + <refsect2> + <title>Text Format</title> + + <para> + When the <literal>text</literal> format is used, + the data read or written is a text file with one line per table row. + Columns in a row are separated by the delimiter character. + The column values themselves are strings generated by the + output function, or acceptable to the input function, of each + attribute's data type. The specified null string is used in + place of columns that are null. + <command>COPY FROM</command> will raise an error if any line of the + input file contains more or fewer columns than are expected. + </para> + + <para> + End of data can be represented by a single line containing just + backslash-period (<literal>\.</literal>). An end-of-data marker is + not necessary when reading from a file, since the end of file + serves perfectly well; it is needed only when copying data to or from + client applications using pre-3.0 client protocol. + </para> + + <para> + Backslash characters (<literal>\</literal>) can be used in the + <command>COPY</command> data to quote data characters that might + otherwise be taken as row or column delimiters. In particular, the + following characters <emphasis>must</emphasis> be preceded by a backslash if + they appear as part of a column value: backslash itself, + newline, carriage return, and the current delimiter character. + </para> + + <para> + The specified null string is sent by <command>COPY TO</command> without + adding any backslashes; conversely, <command>COPY FROM</command> matches + the input against the null string before removing backslashes. Therefore, + a null string such as <literal>\N</literal> cannot be confused with + the actual data value <literal>\N</literal> (which would be represented + as <literal>\\N</literal>). + </para> + + <para> + The following special backslash sequences are recognized by + <command>COPY FROM</command>: + + <informaltable> + <tgroup cols="2"> + <thead> + <row> + <entry>Sequence</entry> + <entry>Represents</entry> + </row> + </thead> + + <tbody> + <row> + <entry><literal>\b</literal></entry> + <entry>Backspace (ASCII 8)</entry> + </row> + <row> + <entry><literal>\f</literal></entry> + <entry>Form feed (ASCII 12)</entry> + </row> + <row> + <entry><literal>\n</literal></entry> + <entry>Newline (ASCII 10)</entry> + </row> + <row> + <entry><literal>\r</literal></entry> + <entry>Carriage return (ASCII 13)</entry> + </row> + <row> + <entry><literal>\t</literal></entry> + <entry>Tab (ASCII 9)</entry> + </row> + <row> + <entry><literal>\v</literal></entry> + <entry>Vertical tab (ASCII 11)</entry> + </row> + <row> + <entry><literal>\</literal><replaceable>digits</replaceable></entry> + <entry>Backslash followed by one to three octal digits specifies + the byte with that numeric code</entry> + </row> + <row> + <entry><literal>\x</literal><replaceable>digits</replaceable></entry> + <entry>Backslash <literal>x</literal> followed by one or two hex digits specifies + the byte with that numeric code</entry> + </row> + </tbody> + </tgroup> + </informaltable> + + Presently, <command>COPY TO</command> will never emit an octal or + hex-digits backslash sequence, but it does use the other sequences + listed above for those control characters. + </para> + + <para> + Any other backslashed character that is not mentioned in the above table + will be taken to represent itself. However, beware of adding backslashes + unnecessarily, since that might accidentally produce a string matching the + end-of-data marker (<literal>\.</literal>) or the null string (<literal>\N</literal> by + default). These strings will be recognized before any other backslash + processing is done. + </para> + + <para> + It is strongly recommended that applications generating <command>COPY</command> data convert + data newlines and carriage returns to the <literal>\n</literal> and + <literal>\r</literal> sequences respectively. At present it is + possible to represent a data carriage return by a backslash and carriage + return, and to represent a data newline by a backslash and newline. + However, these representations might not be accepted in future releases. + They are also highly vulnerable to corruption if the <command>COPY</command> file is + transferred across different machines (for example, from Unix to Windows + or vice versa). + </para> + + <para> + All backslash sequences are interpreted after encoding conversion. + The bytes specified with the octal and hex-digit backslash sequences must + form valid characters in the database encoding. + </para> + + <para> + <command>COPY TO</command> will terminate each row with a Unix-style + newline (<quote><literal>\n</literal></quote>). Servers running on Microsoft Windows instead + output carriage return/newline (<quote><literal>\r\n</literal></quote>), but only for + <command>COPY</command> to a server file; for consistency across platforms, + <command>COPY TO STDOUT</command> always sends <quote><literal>\n</literal></quote> + regardless of server platform. + <command>COPY FROM</command> can handle lines ending with newlines, + carriage returns, or carriage return/newlines. To reduce the risk of + error due to un-backslashed newlines or carriage returns that were + meant as data, <command>COPY FROM</command> will complain if the line + endings in the input are not all alike. + </para> + </refsect2> + + <refsect2> + <title>CSV Format</title> + + <para> + This format option is used for importing and exporting the Comma + Separated Value (<literal>CSV</literal>) file format used by many other + programs, such as spreadsheets. Instead of the escaping rules used by + <productname>PostgreSQL</productname>'s standard text format, it + produces and recognizes the common CSV escaping mechanism. + </para> + + <para> + The values in each record are separated by the <literal>DELIMITER</literal> + character. If the value contains the delimiter character, the + <literal>QUOTE</literal> character, the <literal>NULL</literal> string, a carriage + return, or line feed character, then the whole value is prefixed and + suffixed by the <literal>QUOTE</literal> character, and any occurrence + within the value of a <literal>QUOTE</literal> character or the + <literal>ESCAPE</literal> character is preceded by the escape character. + You can also use <literal>FORCE_QUOTE</literal> to force quotes when outputting + non-<literal>NULL</literal> values in specific columns. + </para> + + <para> + The <literal>CSV</literal> format has no standard way to distinguish a + <literal>NULL</literal> value from an empty string. + <productname>PostgreSQL</productname>'s <command>COPY</command> handles this by quoting. + A <literal>NULL</literal> is output as the <literal>NULL</literal> parameter string + and is not quoted, while a non-<literal>NULL</literal> value matching the + <literal>NULL</literal> parameter string is quoted. For example, with the + default settings, a <literal>NULL</literal> is written as an unquoted empty + string, while an empty string data value is written with double quotes + (<literal>""</literal>). Reading values follows similar rules. You can + use <literal>FORCE_NOT_NULL</literal> to prevent <literal>NULL</literal> input + comparisons for specific columns. You can also use + <literal>FORCE_NULL</literal> to convert quoted null string data values to + <literal>NULL</literal>. + </para> + + <para> + Because backslash is not a special character in the <literal>CSV</literal> + format, <literal>\.</literal>, the end-of-data marker, could also appear + as a data value. To avoid any misinterpretation, a <literal>\.</literal> + data value appearing as a lone entry on a line is automatically + quoted on output, and on input, if quoted, is not interpreted as the + end-of-data marker. If you are loading a file created by another + application that has a single unquoted column and might have a + value of <literal>\.</literal>, you might need to quote that value in the + input file. + </para> + + <note> + <para> + In <literal>CSV</literal> format, all characters are significant. A quoted value + surrounded by white space, or any characters other than + <literal>DELIMITER</literal>, will include those characters. This can cause + errors if you import data from a system that pads <literal>CSV</literal> + lines with white space out to some fixed width. If such a situation + arises you might need to preprocess the <literal>CSV</literal> file to remove + the trailing white space, before importing the data into + <productname>PostgreSQL</productname>. + </para> + </note> + + <note> + <para> + CSV format will both recognize and produce CSV files with quoted + values containing embedded carriage returns and line feeds. Thus + the files are not strictly one line per table row like text-format + files. + </para> + </note> + + <note> + <para> + Many programs produce strange and occasionally perverse CSV files, + so the file format is more a convention than a standard. Thus you + might encounter some files that cannot be imported using this + mechanism, and <command>COPY</command> might produce files that other + programs cannot process. + </para> + </note> + + </refsect2> + + <refsect2> + <title>Binary Format</title> + + <para> + The <literal>binary</literal> format option causes all data to be + stored/read as binary format rather than as text. It is + somewhat faster than the text and <literal>CSV</literal> formats, + but a binary-format file is less portable across machine architectures and + <productname>PostgreSQL</productname> versions. + Also, the binary format is very data type specific; for example + it will not work to output binary data from a <type>smallint</type> column + and read it into an <type>integer</type> column, even though that would work + fine in text format. + </para> + + <para> + The <literal>binary</literal> file format consists + of a file header, zero or more tuples containing the row data, and + a file trailer. Headers and data are in network byte order. + </para> + + <note> + <para> + <productname>PostgreSQL</productname> releases before 7.4 used a + different binary file format. + </para> + </note> + + <refsect3> + <title>File Header</title> + + <para> + The file header consists of 15 bytes of fixed fields, followed + by a variable-length header extension area. The fixed fields are: + + <variablelist> + <varlistentry> + <term>Signature</term> + <listitem> + <para> +11-byte sequence <literal>PGCOPY\n\377\r\n\0</literal> — note that the zero byte +is a required part of the signature. (The signature is designed to allow +easy identification of files that have been munged by a non-8-bit-clean +transfer. This signature will be changed by end-of-line-translation +filters, dropped zero bytes, dropped high bits, or parity changes.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Flags field</term> + <listitem> + <para> +32-bit integer bit mask to denote important aspects of the file format. Bits +are numbered from 0 (<acronym>LSB</acronym>) to 31 (<acronym>MSB</acronym>). Note that +this field is stored in network byte order (most significant byte first), +as are all the integer fields used in the file format. Bits +16–31 are reserved to denote critical file format issues; a reader +should abort if it finds an unexpected bit set in this range. Bits 0–15 +are reserved to signal backwards-compatible format issues; a reader +should simply ignore any unexpected bits set in this range. Currently +only one flag bit is defined, and the rest must be zero: + <variablelist> + <varlistentry> + <term>Bit 16</term> + <listitem> + <para> + If 1, OIDs are included in the data; if 0, not. Oid system columns + are not supported in <productname>PostgreSQL</productname> + anymore, but the format still contains the indicator. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Header extension area length</term> + <listitem> + <para> +32-bit integer, length in bytes of remainder of header, not including self. +Currently, this is zero, and the first tuple follows +immediately. Future changes to the format might allow additional data +to be present in the header. A reader should silently skip over any header +extension data it does not know what to do with. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> +The header extension area is envisioned to contain a sequence of +self-identifying chunks. The flags field is not intended to tell readers +what is in the extension area. Specific design of header extension contents +is left for a later release. + </para> + + <para> + This design allows for both backwards-compatible header additions (add + header extension chunks, or set low-order flag bits) and + non-backwards-compatible changes (set high-order flag bits to signal such + changes, and add supporting data to the extension area if needed). + </para> + </refsect3> + + <refsect3> + <title>Tuples</title> + <para> +Each tuple begins with a 16-bit integer count of the number of fields in the +tuple. (Presently, all tuples in a table will have the same count, but that +might not always be true.) Then, repeated for each field in the tuple, there +is a 32-bit length word followed by that many bytes of field data. (The +length word does not include itself, and can be zero.) As a special case, +-1 indicates a NULL field value. No value bytes follow in the NULL case. + </para> + + <para> +There is no alignment padding or any other extra data between fields. + </para> + + <para> +Presently, all data values in a binary-format file are +assumed to be in binary format (format code one). It is anticipated that a +future extension might add a header field that allows per-column format codes +to be specified. + </para> + + <para> +To determine the appropriate binary format for the actual tuple data you +should consult the <productname>PostgreSQL</productname> source, in +particular the <function>*send</function> and <function>*recv</function> functions for +each column's data type (typically these functions are found in the +<filename>src/backend/utils/adt/</filename> directory of the source +distribution). + </para> + + <para> +If OIDs are included in the file, the OID field immediately follows the +field-count word. It is a normal field except that it's not included in the +field-count. Note that oid system columns are not supported in current +versions of <productname>PostgreSQL</productname>. + </para> + </refsect3> + + <refsect3> + <title>File Trailer</title> + + <para> + The file trailer consists of a 16-bit integer word containing -1. This + is easily distinguished from a tuple's field-count word. + </para> + + <para> + A reader should report an error if a field-count word is neither -1 + nor the expected number of columns. This provides an extra + check against somehow getting out of sync with the data. + </para> + </refsect3> + </refsect2> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example copies a table to the client + using the vertical bar (<literal>|</literal>) as the field delimiter: +<programlisting> +COPY country TO STDOUT (DELIMITER '|'); +</programlisting> + </para> + + <para> + To copy data from a file into the <literal>country</literal> table: +<programlisting> +COPY country FROM '/usr1/proj/bray/sql/country_data'; +</programlisting> + </para> + + <para> + To copy into a file just the countries whose names start with 'A': +<programlisting> +COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy'; +</programlisting> + </para> + + <para> + To copy into a compressed file, you can pipe the output through an external + compression program: +<programlisting> +COPY country TO PROGRAM 'gzip > /usr1/proj/bray/sql/country_data.gz'; +</programlisting> + </para> + + <para> + Here is a sample of data suitable for copying into a table from + <literal>STDIN</literal>: +<programlisting> +AF AFGHANISTAN +AL ALBANIA +DZ ALGERIA +ZM ZAMBIA +ZW ZIMBABWE +</programlisting> + Note that the white space on each line is actually a tab character. + </para> + + <para> + The following is the same data, output in binary format. + The data is shown after filtering through the + Unix utility <command>od -c</command>. The table has three columns; + the first has type <type>char(2)</type>, the second has type <type>text</type>, + and the third has type <type>integer</type>. All the rows have a null value + in the third column. +<programlisting> +0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0 +0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A +0000040 F G H A N I S T A N 377 377 377 377 \0 003 +0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I +0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0 +0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0 +0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377 +0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I +0000200 M B A B W E 377 377 377 377 377 377 +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>COPY</command> statement in the SQL standard. + </para> + + <para> + The following syntax was used before <productname>PostgreSQL</productname> + version 9.0 and is still supported: + +<synopsis> +COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] + FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN } + [ [ WITH ] + [ BINARY ] + [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter_character</replaceable>' ] + [ NULL [ AS ] '<replaceable class="parameter">null_string</replaceable>' ] + [ CSV [ HEADER ] + [ QUOTE [ AS ] '<replaceable class="parameter">quote_character</replaceable>' ] + [ ESCAPE [ AS ] '<replaceable class="parameter">escape_character</replaceable>' ] + [ FORCE NOT NULL <replaceable class="parameter">column_name</replaceable> [, ...] ] ] ] + +COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) } + TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT } + [ [ WITH ] + [ BINARY ] + [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter_character</replaceable>' ] + [ NULL [ AS ] '<replaceable class="parameter">null_string</replaceable>' ] + [ CSV [ HEADER ] + [ QUOTE [ AS ] '<replaceable class="parameter">quote_character</replaceable>' ] + [ ESCAPE [ AS ] '<replaceable class="parameter">escape_character</replaceable>' ] + [ FORCE QUOTE { <replaceable class="parameter">column_name</replaceable> [, ...] | * } ] ] ] +</synopsis> + + Note that in this syntax, <literal>BINARY</literal> and <literal>CSV</literal> are + treated as independent keywords, not as arguments of a <literal>FORMAT</literal> + option. + </para> + + <para> + The following syntax was used before <productname>PostgreSQL</productname> + version 7.3 and is still supported: + +<synopsis> +COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> + FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN } + [ [USING] DELIMITERS '<replaceable class="parameter">delimiter_character</replaceable>' ] + [ WITH NULL AS '<replaceable class="parameter">null_string</replaceable>' ] + +COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> + TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT } + [ [USING] DELIMITERS '<replaceable class="parameter">delimiter_character</replaceable>' ] + [ WITH NULL AS '<replaceable class="parameter">null_string</replaceable>' ] +</synopsis></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="copy-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_access_method.sgml b/doc/src/sgml/ref/create_access_method.sgml new file mode 100644 index 0000000..dae43db --- /dev/null +++ b/doc/src/sgml/ref/create_access_method.sgml @@ -0,0 +1,122 @@ +<!-- +doc/src/sgml/ref/create_access_method.sgml +PostgreSQL documentation +--> + +<refentry id="sql-create-access-method"> + <indexterm zone="sql-create-access-method"> + <primary>CREATE ACCESS METHOD</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE ACCESS METHOD</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE ACCESS METHOD</refname> + <refpurpose>define a new access method</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE ACCESS METHOD <replaceable class="parameter">name</replaceable> + TYPE <replaceable class="parameter">access_method_type</replaceable> + HANDLER <replaceable class="parameter">handler_function</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE ACCESS METHOD</command> creates a new access method. + </para> + + <para> + The access method name must be unique within the database. + </para> + + <para> + Only superusers can define new access methods. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the access method to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">access_method_type</replaceable></term> + <listitem> + <para> + This clause specifies the type of access method to define. + Only <literal>TABLE</literal> and <literal>INDEX</literal> + are supported at present. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">handler_function</replaceable></term> + <listitem> + <para> + <replaceable class="parameter">handler_function</replaceable> is the + name (possibly schema-qualified) of a previously registered function + that represents the access method. The handler function must be + declared to take a single argument of type <type>internal</type>, + and its return type depends on the type of access method; + for <literal>TABLE</literal> access methods, it must + be <type>table_am_handler</type> and for <literal>INDEX</literal> + access methods, it must be <type>index_am_handler</type>. + The C-level API that the handler function must implement varies + depending on the type of access method. The table access method API + is described in <xref linkend="tableam"/> and the index access method + API is described in <xref linkend="indexam"/>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create an index access method <literal>heptree</literal> with + handler function <literal>heptree_handler</literal>: +<programlisting> +CREATE ACCESS METHOD heptree TYPE INDEX HANDLER heptree_handler; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE ACCESS METHOD</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-drop-access-method"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-createopfamily"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_aggregate.sgml b/doc/src/sgml/ref/create_aggregate.sgml new file mode 100644 index 0000000..222e0aa --- /dev/null +++ b/doc/src/sgml/ref/create_aggregate.sgml @@ -0,0 +1,805 @@ +<!-- +doc/src/sgml/ref/create_aggregate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createaggregate"> + <indexterm zone="sql-createaggregate"> + <primary>CREATE AGGREGATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE AGGREGATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE AGGREGATE</refname> + <refpurpose>define a new aggregate function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable> ( [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">arg_data_type</replaceable> [ , ... ] ) ( + SFUNC = <replaceable class="parameter">sfunc</replaceable>, + STYPE = <replaceable class="parameter">state_data_type</replaceable> + [ , SSPACE = <replaceable class="parameter">state_data_size</replaceable> ] + [ , FINALFUNC = <replaceable class="parameter">ffunc</replaceable> ] + [ , FINALFUNC_EXTRA ] + [ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ] + [ , COMBINEFUNC = <replaceable class="parameter">combinefunc</replaceable> ] + [ , SERIALFUNC = <replaceable class="parameter">serialfunc</replaceable> ] + [ , DESERIALFUNC = <replaceable class="parameter">deserialfunc</replaceable> ] + [ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ] + [ , MSFUNC = <replaceable class="parameter">msfunc</replaceable> ] + [ , MINVFUNC = <replaceable class="parameter">minvfunc</replaceable> ] + [ , MSTYPE = <replaceable class="parameter">mstate_data_type</replaceable> ] + [ , MSSPACE = <replaceable class="parameter">mstate_data_size</replaceable> ] + [ , MFINALFUNC = <replaceable class="parameter">mffunc</replaceable> ] + [ , MFINALFUNC_EXTRA ] + [ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ] + [ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ] + [ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ] + [ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ] +) + +CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">arg_data_type</replaceable> [ , ... ] ] + ORDER BY [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">arg_data_type</replaceable> [ , ... ] ) ( + SFUNC = <replaceable class="parameter">sfunc</replaceable>, + STYPE = <replaceable class="parameter">state_data_type</replaceable> + [ , SSPACE = <replaceable class="parameter">state_data_size</replaceable> ] + [ , FINALFUNC = <replaceable class="parameter">ffunc</replaceable> ] + [ , FINALFUNC_EXTRA ] + [ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ] + [ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ] + [ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ] + [ , HYPOTHETICAL ] +) + +<phrase>or the old syntax</phrase> + +CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable> ( + BASETYPE = <replaceable class="parameter">base_type</replaceable>, + SFUNC = <replaceable class="parameter">sfunc</replaceable>, + STYPE = <replaceable class="parameter">state_data_type</replaceable> + [ , SSPACE = <replaceable class="parameter">state_data_size</replaceable> ] + [ , FINALFUNC = <replaceable class="parameter">ffunc</replaceable> ] + [ , FINALFUNC_EXTRA ] + [ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ] + [ , COMBINEFUNC = <replaceable class="parameter">combinefunc</replaceable> ] + [ , SERIALFUNC = <replaceable class="parameter">serialfunc</replaceable> ] + [ , DESERIALFUNC = <replaceable class="parameter">deserialfunc</replaceable> ] + [ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ] + [ , MSFUNC = <replaceable class="parameter">msfunc</replaceable> ] + [ , MINVFUNC = <replaceable class="parameter">minvfunc</replaceable> ] + [ , MSTYPE = <replaceable class="parameter">mstate_data_type</replaceable> ] + [ , MSSPACE = <replaceable class="parameter">mstate_data_size</replaceable> ] + [ , MFINALFUNC = <replaceable class="parameter">mffunc</replaceable> ] + [ , MFINALFUNC_EXTRA ] + [ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ] + [ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ] + [ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ] +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE AGGREGATE</command> defines a new aggregate function. + <command>CREATE OR REPLACE AGGREGATE</command> will either define a new + aggregate function or replace an existing definition. Some basic and + commonly-used aggregate functions are included with the distribution; they + are documented in <xref linkend="functions-aggregate"/>. If one defines new + types or needs an aggregate function not already provided, then + <command>CREATE AGGREGATE</command> can be used to provide the desired + features. + </para> + + <para> + When replacing an existing definition, the argument types, result type, + and number of direct arguments may not be changed. Also, the new definition + must be of the same kind (ordinary aggregate, ordered-set aggregate, or + hypothetical-set aggregate) as the old one. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE AGGREGATE + myschema.myagg ...</literal>) then the aggregate function is created in the + specified schema. Otherwise it is created in the current schema. + </para> + + <para> + An aggregate function is identified by its name and input data type(s). + Two aggregates in the same schema can have the same name if they operate on + different input types. The + name and input data type(s) of an aggregate must also be distinct from + the name and input data type(s) of every ordinary function in the same + schema. + This behavior is identical to overloading of ordinary function names + (see <xref linkend="sql-createfunction"/>). + </para> + + <para> + A simple aggregate function is made from one or two ordinary + functions: + a state transition function + <replaceable class="parameter">sfunc</replaceable>, + and an optional final calculation function + <replaceable class="parameter">ffunc</replaceable>. + These are used as follows: +<programlisting> +<replaceable class="parameter">sfunc</replaceable>( internal-state, next-data-values ) ---> next-internal-state +<replaceable class="parameter">ffunc</replaceable>( internal-state ) ---> aggregate-value +</programlisting> + </para> + + <para> + <productname>PostgreSQL</productname> creates a temporary variable + of data type <replaceable class="parameter">stype</replaceable> + to hold the current internal state of the aggregate. At each input row, + the aggregate argument value(s) are calculated and + the state transition function is invoked with the current state value + and the new argument value(s) to calculate a new + internal state value. After all the rows have been processed, + the final function is invoked once to calculate the aggregate's return + value. If there is no final function then the ending state value + is returned as-is. + </para> + + <para> + An aggregate function can provide an initial condition, + that is, an initial value for the internal state value. + This is specified and stored in the database as a value of type + <type>text</type>, but it must be a valid external representation + of a constant of the state value data type. If it is not supplied + then the state value starts out null. + </para> + + <para> + If the state transition function is declared <quote>strict</quote>, + then it cannot be called with null inputs. With such a transition + function, aggregate execution behaves as follows. Rows with any null input + values are ignored (the function is not called and the previous state value + is retained). If the initial state value is null, then at the first row + with all-nonnull input values, the first argument value replaces the state + value, and the transition function is invoked at each subsequent row with + all-nonnull input values. + This is handy for implementing aggregates like <function>max</function>. + Note that this behavior is only available when + <replaceable class="parameter">state_data_type</replaceable> + is the same as the first + <replaceable class="parameter">arg_data_type</replaceable>. + When these types are different, you must supply a nonnull initial + condition or use a nonstrict transition function. + </para> + + <para> + If the state transition function is not strict, then it will be called + unconditionally at each input row, and must deal with null inputs + and null state values for itself. This allows the aggregate + author to have full control over the aggregate's handling of null values. + </para> + + <para> + If the final function is declared <quote>strict</quote>, then it will not + be called when the ending state value is null; instead a null result + will be returned automatically. (Of course this is just the normal + behavior of strict functions.) In any case the final function has + the option of returning a null value. For example, the final function for + <function>avg</function> returns null when it sees there were zero + input rows. + </para> + + <para> + Sometimes it is useful to declare the final function as taking not just + the state value, but extra parameters corresponding to the aggregate's + input values. The main reason for doing this is if the final function + is polymorphic and the state value's data type would be inadequate to + pin down the result type. These extra parameters are always passed as + NULL (and so the final function must not be strict when + the <literal>FINALFUNC_EXTRA</literal> option is used), but nonetheless they + are valid parameters. The final function could for example make use + of <function>get_fn_expr_argtype</function> to identify the actual argument type + in the current call. + </para> + + <para> + An aggregate can optionally support <firstterm>moving-aggregate mode</firstterm>, + as described in <xref linkend="xaggr-moving-aggregates"/>. This requires + specifying the <literal>MSFUNC</literal>, <literal>MINVFUNC</literal>, + and <literal>MSTYPE</literal> parameters, and optionally + the <literal>MSSPACE</literal>, <literal>MFINALFUNC</literal>, + <literal>MFINALFUNC_EXTRA</literal>, <literal>MFINALFUNC_MODIFY</literal>, + and <literal>MINITCOND</literal> parameters. Except for <literal>MINVFUNC</literal>, + these parameters work like the corresponding simple-aggregate parameters + without <literal>M</literal>; they define a separate implementation of the + aggregate that includes an inverse transition function. + </para> + + <para> + The syntax with <literal>ORDER BY</literal> in the parameter list creates + a special type of aggregate called an <firstterm>ordered-set + aggregate</firstterm>; or if <literal>HYPOTHETICAL</literal> is specified, then + a <firstterm>hypothetical-set aggregate</firstterm> is created. These + aggregates operate over groups of sorted values in order-dependent ways, + so that specification of an input sort order is an essential part of a + call. Also, they can have <firstterm>direct</firstterm> arguments, which are + arguments that are evaluated only once per aggregation rather than once + per input row. Hypothetical-set aggregates are a subclass of ordered-set + aggregates in which some of the direct arguments are required to match, + in number and data types, the aggregated argument columns. This allows + the values of those direct arguments to be added to the collection of + aggregate-input rows as an additional <quote>hypothetical</quote> row. + </para> + + <para> + An aggregate can optionally support <firstterm>partial aggregation</firstterm>, + as described in <xref linkend="xaggr-partial-aggregates"/>. + This requires specifying the <literal>COMBINEFUNC</literal> parameter. + If the <replaceable class="parameter">state_data_type</replaceable> + is <type>internal</type>, it's usually also appropriate to provide the + <literal>SERIALFUNC</literal> and <literal>DESERIALFUNC</literal> parameters so that + parallel aggregation is possible. Note that the aggregate must also be + marked <literal>PARALLEL SAFE</literal> to enable parallel aggregation. + </para> + + <para> + Aggregates that behave like <function>MIN</function> or <function>MAX</function> can + sometimes be optimized by looking into an index instead of scanning every + input row. If this aggregate can be so optimized, indicate it by + specifying a <firstterm>sort operator</firstterm>. The basic requirement is that + the aggregate must yield the first element in the sort ordering induced by + the operator; in other words: +<programlisting> +SELECT agg(col) FROM tab; +</programlisting> + must be equivalent to: +<programlisting> +SELECT col FROM tab ORDER BY col USING sortop LIMIT 1; +</programlisting> + Further assumptions are that the aggregate ignores null inputs, and that + it delivers a null result if and only if there were no non-null inputs. + Ordinarily, a data type's <literal><</literal> operator is the proper sort + operator for <function>MIN</function>, and <literal>></literal> is the proper sort + operator for <function>MAX</function>. Note that the optimization will never + actually take effect unless the specified operator is the <quote>less + than</quote> or <quote>greater than</quote> strategy member of a B-tree + index operator class. + </para> + + <para> + To be able to create an aggregate function, you must + have <literal>USAGE</literal> privilege on the argument types, the state + type(s), and the return type, as well as <literal>EXECUTE</literal> + privilege on the supporting functions. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the aggregate function + to create. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal> or <literal>VARIADIC</literal>. + (Aggregate functions do not support <literal>OUT</literal> arguments.) + If omitted, the default is <literal>IN</literal>. Only the last argument + can be marked <literal>VARIADIC</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. This is currently only useful for + documentation purposes. If omitted, the argument has no name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">arg_data_type</replaceable></term> + <listitem> + <para> + An input data type on which this aggregate function operates. + To create a zero-argument aggregate function, write <literal>*</literal> + in place of the list of argument specifications. (An example of such an + aggregate is <function>count(*)</function>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">base_type</replaceable></term> + <listitem> + <para> + In the old syntax for <command>CREATE AGGREGATE</command>, the input data type + is specified by a <literal>basetype</literal> parameter rather than being + written next to the aggregate name. Note that this syntax allows + only one input parameter. To define a zero-argument aggregate function + with this syntax, specify the <literal>basetype</literal> as + <literal>"ANY"</literal> (not <literal>*</literal>). + Ordered-set aggregates cannot be defined with the old syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sfunc</replaceable></term> + <listitem> + <para> + The name of the state transition function to be called for each + input row. For a normal <replaceable class="parameter">N</replaceable>-argument + aggregate function, the <replaceable class="parameter">sfunc</replaceable> + must take <replaceable class="parameter">N</replaceable>+1 arguments, + the first being of type <replaceable + class="parameter">state_data_type</replaceable> and the rest + matching the declared input data type(s) of the aggregate. + The function must return a value of type <replaceable + class="parameter">state_data_type</replaceable>. This function + takes the current state value and the current input data value(s), + and returns the next state value. + </para> + + <para> + For ordered-set (including hypothetical-set) aggregates, the state + transition function receives only the current state value and the + aggregated arguments, not the direct arguments. Otherwise it is the + same. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">state_data_type</replaceable></term> + <listitem> + <para> + The data type for the aggregate's state value. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">state_data_size</replaceable></term> + <listitem> + <para> + The approximate average size (in bytes) of the aggregate's state value. + If this parameter is omitted or is zero, a default estimate is used + based on the <replaceable>state_data_type</replaceable>. + The planner uses this value to estimate the memory required for a + grouped aggregate query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">ffunc</replaceable></term> + <listitem> + <para> + The name of the final function called to compute the aggregate's + result after all input rows have been traversed. + For a normal aggregate, this function + must take a single argument of type <replaceable + class="parameter">state_data_type</replaceable>. The return + data type of the aggregate is defined as the return type of this + function. If <replaceable class="parameter">ffunc</replaceable> + is not specified, then the ending state value is used as the + aggregate's result, and the return type is <replaceable + class="parameter">state_data_type</replaceable>. + </para> + + <para> + For ordered-set (including hypothetical-set) aggregates, the + final function receives not only the final state value, + but also the values of all the direct arguments. + </para> + + <para> + If <literal>FINALFUNC_EXTRA</literal> is specified, then in addition to the + final state value and any direct arguments, the final function + receives extra NULL values corresponding to the aggregate's regular + (aggregated) arguments. This is mainly useful to allow correct + resolution of the aggregate result type when a polymorphic aggregate + is being defined. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FINALFUNC_MODIFY</literal> = { <literal>READ_ONLY</literal> | <literal>SHAREABLE</literal> | <literal>READ_WRITE</literal> }</term> + <listitem> + <para> + This option specifies whether the final function is a pure function + that does not modify its arguments. <literal>READ_ONLY</literal> indicates + it does not; the other two values indicate that it may change the + transition state value. See <xref linkend="sql-createaggregate-notes"/> + below for more detail. The + default is <literal>READ_ONLY</literal>, except for ordered-set aggregates, + for which the default is <literal>READ_WRITE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">combinefunc</replaceable></term> + <listitem> + <para> + The <replaceable class="parameter">combinefunc</replaceable> function + may optionally be specified to allow the aggregate function to support + partial aggregation. If provided, + the <replaceable class="parameter">combinefunc</replaceable> must + combine two <replaceable class="parameter">state_data_type</replaceable> + values, each containing the result of aggregation over some subset of + the input values, to produce a + new <replaceable class="parameter">state_data_type</replaceable> that + represents the result of aggregating over both sets of inputs. This + function can be thought of as + an <replaceable class="parameter">sfunc</replaceable>, where instead of + acting upon an individual input row and adding it to the running + aggregate state, it adds another aggregate state to the running state. + </para> + + <para> + The <replaceable class="parameter">combinefunc</replaceable> must be + declared as taking two arguments of + the <replaceable class="parameter">state_data_type</replaceable> and + returning a value of + the <replaceable class="parameter">state_data_type</replaceable>. + Optionally this function may be <quote>strict</quote>. In this case the + function will not be called when either of the input states are null; + the other state will be taken as the correct result. + </para> + + <para> + For aggregate functions + whose <replaceable class="parameter">state_data_type</replaceable> + is <type>internal</type>, + the <replaceable class="parameter">combinefunc</replaceable> must not + be strict. In this case + the <replaceable class="parameter">combinefunc</replaceable> must + ensure that null states are handled correctly and that the state being + returned is properly stored in the aggregate memory context. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">serialfunc</replaceable></term> + <listitem> + <para> + An aggregate function + whose <replaceable class="parameter">state_data_type</replaceable> + is <type>internal</type> can participate in parallel aggregation only if it + has a <replaceable class="parameter">serialfunc</replaceable> function, + which must serialize the aggregate state into a <type>bytea</type> value for + transmission to another process. This function must take a single + argument of type <type>internal</type> and return type <type>bytea</type>. A + corresponding <replaceable class="parameter">deserialfunc</replaceable> + is also required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">deserialfunc</replaceable></term> + <listitem> + <para> + Deserialize a previously serialized aggregate state back into + <replaceable class="parameter">state_data_type</replaceable>. This + function must take two arguments of types <type>bytea</type> + and <type>internal</type>, and produce a result of type <type>internal</type>. + (Note: the second, <type>internal</type> argument is unused, but is required + for type safety reasons.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">initial_condition</replaceable></term> + <listitem> + <para> + The initial setting for the state value. This must be a string + constant in the form accepted for the data type <replaceable + class="parameter">state_data_type</replaceable>. If not + specified, the state value starts out null. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">msfunc</replaceable></term> + <listitem> + <para> + The name of the forward state transition function to be called for each + input row in moving-aggregate mode. This is exactly like the regular + transition function, except that its first argument and result are of + type <replaceable>mstate_data_type</replaceable>, which might be different + from <replaceable>state_data_type</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">minvfunc</replaceable></term> + <listitem> + <para> + The name of the inverse state transition function to be used in + moving-aggregate mode. This function has the same argument and + result types as <replaceable>msfunc</replaceable>, but it is used to remove + a value from the current aggregate state, rather than add a value to + it. The inverse transition function must have the same strictness + attribute as the forward state transition function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">mstate_data_type</replaceable></term> + <listitem> + <para> + The data type for the aggregate's state value, when using + moving-aggregate mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">mstate_data_size</replaceable></term> + <listitem> + <para> + The approximate average size (in bytes) of the aggregate's state + value, when using moving-aggregate mode. This works the same as + <replaceable>state_data_size</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">mffunc</replaceable></term> + <listitem> + <para> + The name of the final function called to compute the aggregate's + result after all input rows have been traversed, when using + moving-aggregate mode. This works the same as <replaceable>ffunc</replaceable>, + except that its first argument's type + is <replaceable>mstate_data_type</replaceable> and extra dummy arguments are + specified by writing <literal>MFINALFUNC_EXTRA</literal>. + The aggregate result type determined by <replaceable>mffunc</replaceable> + or <replaceable>mstate_data_type</replaceable> must match that determined by the + aggregate's regular implementation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>MFINALFUNC_MODIFY</literal> = { <literal>READ_ONLY</literal> | <literal>SHAREABLE</literal> | <literal>READ_WRITE</literal> }</term> + <listitem> + <para> + This option is like <literal>FINALFUNC_MODIFY</literal>, but it describes + the behavior of the moving-aggregate final function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">minitial_condition</replaceable></term> + <listitem> + <para> + The initial setting for the state value, when using moving-aggregate + mode. This works the same as <replaceable>initial_condition</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sort_operator</replaceable></term> + <listitem> + <para> + The associated sort operator for a <function>MIN</function>- or + <function>MAX</function>-like aggregate. + This is just an operator name (possibly schema-qualified). + The operator is assumed to have the same input data types as + the aggregate (which must be a single-argument normal aggregate). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARALLEL =</literal> { <literal>SAFE</literal> | <literal>RESTRICTED</literal> | <literal>UNSAFE</literal> }</term> + <listitem> + <para> + The meanings of <literal>PARALLEL SAFE</literal>, <literal>PARALLEL + RESTRICTED</literal>, and <literal>PARALLEL UNSAFE</literal> are the same as + in <link linkend="sql-createfunction"><command>CREATE FUNCTION</command></link>. An aggregate will not be + considered for parallelization if it is marked <literal>PARALLEL + UNSAFE</literal> (which is the default!) or <literal>PARALLEL RESTRICTED</literal>. + Note that the parallel-safety markings of the aggregate's support + functions are not consulted by the planner, only the marking of the + aggregate itself. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HYPOTHETICAL</literal></term> + <listitem> + <para> + For ordered-set aggregates only, this flag specifies that the aggregate + arguments are to be processed according to the requirements for + hypothetical-set aggregates: that is, the last few direct arguments must + match the data types of the aggregated (<literal>WITHIN GROUP</literal>) + arguments. The <literal>HYPOTHETICAL</literal> flag has no effect on + run-time behavior, only on parse-time resolution of the data types and + collations of the aggregate's arguments. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The parameters of <command>CREATE AGGREGATE</command> can be + written in any order, not just the order illustrated above. + </para> + </refsect1> + + <refsect1 id="sql-createaggregate-notes" xreflabel="Notes"> + <title>Notes</title> + + <para> + In parameters that specify support function names, you can write + a schema name if needed, for example <literal>SFUNC = public.sum</literal>. + Do not write argument types there, however — the argument types + of the support functions are determined from other parameters. + </para> + + <para> + Ordinarily, PostgreSQL functions are expected to be true functions that + do not modify their input values. However, an aggregate transition + function, <emphasis>when used in the context of an aggregate</emphasis>, + is allowed to cheat and modify its transition-state argument in place. + This can provide substantial performance benefits compared to making + a fresh copy of the transition state each time. + </para> + + <para> + Likewise, while an aggregate final function is normally expected not to + modify its input values, sometimes it is impractical to avoid modifying + the transition-state argument. Such behavior must be declared using + the <literal>FINALFUNC_MODIFY</literal> parameter. + The <literal>READ_WRITE</literal> + value indicates that the final function modifies the transition state in + unspecified ways. This value prevents use of the aggregate as a window + function, and it also prevents merging of transition states for aggregate + calls that share the same input values and transition functions. + The <literal>SHAREABLE</literal> value indicates that the transition function + cannot be applied after the final function, but multiple final-function + calls can be performed on the ending transition state value. This value + prevents use of the aggregate as a window function, but it allows merging + of transition states. (That is, the optimization of interest here is not + applying the same final function repeatedly, but applying different final + functions to the same ending transition state value. This is allowed as + long as none of the final functions are marked <literal>READ_WRITE</literal>.) + </para> + + <para> + If an aggregate supports moving-aggregate mode, it will improve + calculation efficiency when the aggregate is used as a window function + for a window with moving frame start (that is, a frame start mode other + than <literal>UNBOUNDED PRECEDING</literal>). Conceptually, the forward + transition function adds input values to the aggregate's state when + they enter the window frame from the bottom, and the inverse transition + function removes them again when they leave the frame at the top. So, + when values are removed, they are always removed in the same order they + were added. Whenever the inverse transition function is invoked, it will + thus receive the earliest added but not yet removed argument value(s). + The inverse transition function can assume that at least one row will + remain in the current state after it removes the oldest row. (When this + would not be the case, the window function mechanism simply starts a + fresh aggregation, rather than using the inverse transition function.) + </para> + + <para> + The forward transition function for moving-aggregate mode is not + allowed to return NULL as the new state value. If the inverse + transition function returns NULL, this is taken as an indication that + the inverse function cannot reverse the state calculation for this + particular input, and so the aggregate calculation will be redone from + scratch for the current frame starting position. This convention + allows moving-aggregate mode to be used in situations where there are + some infrequent cases that are impractical to reverse out of the + running state value. + </para> + + <para> + If no moving-aggregate implementation is supplied, + the aggregate can still be used with moving frames, + but <productname>PostgreSQL</productname> will recompute the whole + aggregation whenever the start of the frame moves. + Note that whether or not the aggregate supports moving-aggregate + mode, <productname>PostgreSQL</productname> can handle a moving frame + end without recalculation; this is done by continuing to add new values + to the aggregate's state. This is why use of an aggregate as a window + function requires that the final function be read-only: it must + not damage the aggregate's state value, so that the aggregation can be + continued even after an aggregate result value has been obtained for + one set of frame boundaries. + </para> + + <para> + The syntax for ordered-set aggregates allows <literal>VARIADIC</literal> + to be specified for both the last direct parameter and the last + aggregated (<literal>WITHIN GROUP</literal>) parameter. However, the + current implementation restricts use of <literal>VARIADIC</literal> + in two ways. First, ordered-set aggregates can only use + <literal>VARIADIC "any"</literal>, not other variadic array types. + Second, if the last direct parameter is <literal>VARIADIC "any"</literal>, + then there can be only one aggregated parameter and it must also + be <literal>VARIADIC "any"</literal>. (In the representation used in the + system catalogs, these two parameters are merged into a single + <literal>VARIADIC "any"</literal> item, since <structname>pg_proc</structname> cannot + represent functions with more than one <literal>VARIADIC</literal> parameter.) + If the aggregate is a hypothetical-set aggregate, the direct arguments + that match the <literal>VARIADIC "any"</literal> parameter are the hypothetical + ones; any preceding parameters represent additional direct arguments + that are not constrained to match the aggregated arguments. + </para> + + <para> + Currently, ordered-set aggregates do not need to support + moving-aggregate mode, since they cannot be used as window functions. + </para> + + <para> + Partial (including parallel) aggregation is currently not supported for + ordered-set aggregates. Also, it will never be used for aggregate calls + that include <literal>DISTINCT</literal> or <literal>ORDER BY</literal> clauses, since + those semantics cannot be supported during partial aggregation. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + See <xref linkend="xaggr"/>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE AGGREGATE</command> is a + <productname>PostgreSQL</productname> language extension. The SQL + standard does not provide for user-defined aggregate functions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteraggregate"/></member> + <member><xref linkend="sql-dropaggregate"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_cast.sgml b/doc/src/sgml/ref/create_cast.sgml new file mode 100644 index 0000000..bad75bc --- /dev/null +++ b/doc/src/sgml/ref/create_cast.sgml @@ -0,0 +1,424 @@ +<!-- +doc/src/sgml/ref/create_cast.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createcast"> + <indexterm zone="sql-createcast"> + <primary>CREATE CAST</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE CAST</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE CAST</refname> + <refpurpose>define a new cast</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) + WITH FUNCTION <replaceable>function_name</replaceable> [ (<replaceable>argument_type</replaceable> [, ...]) ] + [ AS ASSIGNMENT | AS IMPLICIT ] + +CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) + WITHOUT FUNCTION + [ AS ASSIGNMENT | AS IMPLICIT ] + +CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) + WITH INOUT + [ AS ASSIGNMENT | AS IMPLICIT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createcast-description"> + <title>Description</title> + + <para> + <command>CREATE CAST</command> defines a new cast. A cast + specifies how to perform a conversion between + two data types. For example, +<programlisting> +SELECT CAST(42 AS float8); +</programlisting> + converts the integer constant 42 to type <type>float8</type> by + invoking a previously specified function, in this case + <literal>float8(int4)</literal>. (If no suitable cast has been defined, the + conversion fails.) + </para> + + <para> + Two types can be <firstterm>binary coercible</firstterm>, which + means that the conversion can be performed <quote>for free</quote> + without invoking any function. This requires that corresponding + values use the same internal representation. For instance, the + types <type>text</type> and <type>varchar</type> are binary + coercible both ways. Binary coercibility is not necessarily a + symmetric relationship. For example, the cast + from <type>xml</type> to <type>text</type> can be performed for + free in the present implementation, but the reverse direction + requires a function that performs at least a syntax check. (Two + types that are binary coercible both ways are also referred to as + binary compatible.) + </para> + + <para> + You can define a cast as an <firstterm>I/O conversion cast</firstterm> by using + the <literal>WITH INOUT</literal> syntax. An I/O conversion cast is + performed by invoking the output function of the source data type, and + passing the resulting string to the input function of the target data type. + In many common cases, this feature avoids the need to write a separate + cast function for conversion. An I/O conversion cast acts the same as + a regular function-based cast; only the implementation is different. + </para> + + <para> + By default, a cast can be invoked only by an explicit cast request, + that is an explicit <literal>CAST(<replaceable>x</replaceable> AS + <replaceable>typename</replaceable>)</literal> or + <replaceable>x</replaceable><literal>::</literal><replaceable>typename</replaceable> + construct. + </para> + + <para> + If the cast is marked <literal>AS ASSIGNMENT</literal> then it can be invoked + implicitly when assigning a value to a column of the target data type. + For example, supposing that <literal>foo.f1</literal> is a column of + type <type>text</type>, then: +<programlisting> +INSERT INTO foo (f1) VALUES (42); +</programlisting> + will be allowed if the cast from type <type>integer</type> to type + <type>text</type> is marked <literal>AS ASSIGNMENT</literal>, otherwise not. + (We generally use the term <firstterm>assignment + cast</firstterm> to describe this kind of cast.) + </para> + + <para> + If the cast is marked <literal>AS IMPLICIT</literal> then it can be invoked + implicitly in any context, whether assignment or internally in an + expression. (We generally use the term <firstterm>implicit + cast</firstterm> to describe this kind of cast.) + For example, consider this query: +<programlisting> +SELECT 2 + 4.0; +</programlisting> + The parser initially marks the constants as being of type <type>integer</type> + and <type>numeric</type> respectively. There is no <type>integer</type> + <literal>+</literal> <type>numeric</type> operator in the system catalogs, + but there is a <type>numeric</type> <literal>+</literal> <type>numeric</type> operator. + The query will therefore succeed if a cast from <type>integer</type> to + <type>numeric</type> is available and is marked <literal>AS IMPLICIT</literal> — + which in fact it is. The parser will apply the implicit cast and resolve + the query as if it had been written +<programlisting> +SELECT CAST ( 2 AS numeric ) + 4.0; +</programlisting> + </para> + + <para> + Now, the catalogs also provide a cast from <type>numeric</type> to + <type>integer</type>. If that cast were marked <literal>AS IMPLICIT</literal> — + which it is not — then the parser would be faced with choosing + between the above interpretation and the alternative of casting the + <type>numeric</type> constant to <type>integer</type> and applying the + <type>integer</type> <literal>+</literal> <type>integer</type> operator. Lacking any + knowledge of which choice to prefer, it would give up and declare the + query ambiguous. The fact that only one of the two casts is + implicit is the way in which we teach the parser to prefer resolution + of a mixed <type>numeric</type>-and-<type>integer</type> expression as + <type>numeric</type>; there is no built-in knowledge about that. + </para> + + <para> + It is wise to be conservative about marking casts as implicit. An + overabundance of implicit casting paths can cause + <productname>PostgreSQL</productname> to choose surprising + interpretations of commands, or to be unable to resolve commands at + all because there are multiple possible interpretations. A good + rule of thumb is to make a cast implicitly invokable only for + information-preserving transformations between types in the same + general type category. For example, the cast from <type>int2</type> to + <type>int4</type> can reasonably be implicit, but the cast from + <type>float8</type> to <type>int4</type> should probably be + assignment-only. Cross-type-category casts, such as <type>text</type> + to <type>int4</type>, are best made explicit-only. + </para> + + <note> + <para> + Sometimes it is necessary for usability or standards-compliance reasons + to provide multiple implicit casts among a set of types, resulting in + ambiguity that cannot be avoided as above. The parser has a fallback + heuristic based on <firstterm>type categories</firstterm> and <firstterm>preferred + types</firstterm> that can help to provide desired behavior in such cases. See + <xref linkend="sql-createtype"/> for + more information. + </para> + </note> + + <para> + To be able to create a cast, you must own the source or the target data type + and have <literal>USAGE</literal> privilege on the other type. To create a + binary-coercible cast, you must be superuser. (This restriction is made + because an erroneous binary-coercible cast conversion can easily crash the + server.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>source_type</replaceable></term> + + <listitem> + <para> + The name of the source data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>target_type</replaceable></term> + + <listitem> + <para> + The name of the target data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><replaceable>function_name</replaceable>[(<replaceable>argument_type</replaceable> [, ...])]</literal></term> + + <listitem> + <para> + The function used to perform the cast. The function name can + be schema-qualified. If it is not, the function will be looked + up in the schema search path. The function's result data type must + match the target type of the cast. Its arguments are discussed below. + If no argument list is specified, the function name must be unique in + its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITHOUT FUNCTION</literal></term> + + <listitem> + <para> + Indicates that the source type is binary-coercible to the target type, + so no function is required to perform the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH INOUT</literal></term> + + <listitem> + <para> + Indicates that the cast is an I/O conversion cast, performed by + invoking the output function of the source data type, and passing the + resulting string to the input function of the target data type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>AS ASSIGNMENT</literal></term> + + <listitem> + <para> + Indicates that the cast can be invoked implicitly in assignment + contexts. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>AS IMPLICIT</literal></term> + + <listitem> + <para> + Indicates that the cast can be invoked implicitly in any context. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + Cast implementation functions can have one to three arguments. + The first argument type must be identical to or binary-coercible from + the cast's source type. The second argument, + if present, must be type <type>integer</type>; it receives the type + modifier associated with the destination type, or <literal>-1</literal> + if there is none. The third argument, + if present, must be type <type>boolean</type>; it receives <literal>true</literal> + if the cast is an explicit cast, <literal>false</literal> otherwise. + (Bizarrely, the SQL standard demands different behaviors for explicit and + implicit casts in some cases. This argument is supplied for functions + that must implement such casts. It is not recommended that you design + your own data types so that this matters.) + </para> + + <para> + The return type of a cast function must be identical to or + binary-coercible to the cast's target type. + </para> + + <para> + Ordinarily a cast must have different source and target data types. + However, it is allowed to declare a cast with identical source and + target types if it has a cast implementation function with more than one + argument. This is used to represent type-specific length coercion + functions in the system catalogs. The named function is used to + coerce a value of the type to the type modifier value given by its + second argument. + </para> + + <para> + When a cast has different source and + target types and a function that takes more than one argument, it + supports converting from one type to another and applying a length + coercion in a single step. When no such entry is available, coercion + to a type that uses a type modifier involves two cast steps, one to + convert between data types and a second to apply the modifier. + </para> + + <para> + A cast to or from a domain type currently has no effect. Casting + to or from a domain uses the casts associated with its underlying type. + </para> + + </refsect1> + + <refsect1 id="sql-createcast-notes"> + <title>Notes</title> + + <para> + Use <link linkend="sql-dropcast"><command>DROP CAST</command></link> to remove user-defined casts. + </para> + + <para> + Remember that if you want to be able to convert types both ways you + need to declare casts both ways explicitly. + </para> + + <indexterm zone="sql-createcast"> + <primary>cast</primary> + <secondary>I/O conversion</secondary> + </indexterm> + + <para> + It is normally not necessary to create casts between user-defined types + and the standard string types (<type>text</type>, <type>varchar</type>, and + <type>char(<replaceable>n</replaceable>)</type>, as well as user-defined types that + are defined to be in the string category). <productname>PostgreSQL</productname> + provides automatic I/O conversion casts for that. The automatic casts to + string types are treated as assignment casts, while the automatic casts + from string types are + explicit-only. You can override this behavior by declaring your own + cast to replace an automatic cast, but usually the only reason to + do so is if you want the conversion to be more easily invokable than the + standard assignment-only or explicit-only setting. Another possible + reason is that you want the conversion to behave differently from the + type's I/O function; but that is sufficiently surprising that you + should think twice about whether it's a good idea. (A small number of + the built-in types do indeed have different behaviors for conversions, + mostly because of requirements of the SQL standard.) + </para> + + <para> + While not required, it is recommended that you continue to follow this old + convention of naming cast implementation functions after the target data + type. Many users are used to being able to cast data types using a + function-style notation, that is + <replaceable>typename</replaceable>(<replaceable>x</replaceable>). This notation is in fact + nothing more nor less than a call of the cast implementation function; it + is not specially treated as a cast. If your conversion functions are not + named to support this convention then you will have surprised users. + Since <productname>PostgreSQL</productname> allows overloading of the same function + name with different argument types, there is no difficulty in having + multiple conversion functions from different types that all use the + target type's name. + </para> + + <note> + <para> + Actually the preceding paragraph is an oversimplification: there are + two cases in which a function-call construct will be treated as a cast + request without having matched it to an actual function. + If a function call <replaceable>name</replaceable>(<replaceable>x</replaceable>) does not + exactly match any existing function, but <replaceable>name</replaceable> is the name + of a data type and <structname>pg_cast</structname> provides a binary-coercible cast + to this type from the type of <replaceable>x</replaceable>, then the call will be + construed as a binary-coercible cast. This exception is made so that + binary-coercible casts can be invoked using functional syntax, even + though they lack any function. Likewise, if there is no + <structname>pg_cast</structname> entry but the cast would be to or from a string + type, the call will be construed as an I/O conversion cast. This + exception allows I/O conversion casts to be invoked using functional + syntax. + </para> + </note> + + <note> + <para> + There is also an exception to the exception: I/O conversion casts from + composite types to string types cannot be invoked using functional + syntax, but must be written in explicit cast syntax (either + <literal>CAST</literal> or <literal>::</literal> notation). This exception was added + because after the introduction of automatically-provided I/O conversion + casts, it was found too easy to accidentally invoke such a cast when + a function or column reference was intended. + </para> + </note> + </refsect1> + + + <refsect1 id="sql-createcast-examples"> + <title>Examples</title> + + <para> + To create an assignment cast from type <type>bigint</type> to type + <type>int4</type> using the function <literal>int4(bigint)</literal>: +<programlisting> +CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT; +</programlisting> + (This cast is already predefined in the system.) + </para> + </refsect1> + + <refsect1 id="sql-createcast-compat"> + <title>Compatibility</title> + + <para> + The <command>CREATE CAST</command> command conforms to the + <acronym>SQL</acronym> standard, + except that SQL does not make provisions for binary-coercible + types or extra arguments to implementation functions. + <literal>AS IMPLICIT</literal> is a <productname>PostgreSQL</productname> + extension, too. + </para> + </refsect1> + + + <refsect1 id="sql-createcast-seealso"> + <title>See Also</title> + + <para> + <xref linkend="sql-createfunction"/>, + <xref linkend="sql-createtype"/>, + <xref linkend="sql-dropcast"/> + </para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_collation.sgml b/doc/src/sgml/ref/create_collation.sgml new file mode 100644 index 0000000..58f5f0c --- /dev/null +++ b/doc/src/sgml/ref/create_collation.sgml @@ -0,0 +1,263 @@ +<!-- +doc/src/sgml/ref/create_collation.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createcollation"> + <indexterm zone="sql-createcollation"> + <primary>CREATE COLLATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE COLLATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE COLLATION</refname> + <refpurpose>define a new collation</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE COLLATION [ IF NOT EXISTS ] <replaceable>name</replaceable> ( + [ LOCALE = <replaceable>locale</replaceable>, ] + [ LC_COLLATE = <replaceable>lc_collate</replaceable>, ] + [ LC_CTYPE = <replaceable>lc_ctype</replaceable>, ] + [ PROVIDER = <replaceable>provider</replaceable>, ] + [ DETERMINISTIC = <replaceable>boolean</replaceable>, ] + [ VERSION = <replaceable>version</replaceable> ] +) +CREATE COLLATION [ IF NOT EXISTS ] <replaceable>name</replaceable> FROM <replaceable>existing_collation</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createcollation-description"> + <title>Description</title> + + <para> + <command>CREATE COLLATION</command> defines a new collation using + the specified operating system locale settings, + or by copying an existing collation. + </para> + + <para> + To be able to create a collation, you must + have <literal>CREATE</literal> privilege on the destination schema. + </para> + </refsect1> + + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a collation with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing collation is anything like the one that would have been created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>name</replaceable></term> + + <listitem> + <para> + The name of the collation. The collation name can be + schema-qualified. If it is not, the collation is defined in the + current schema. The collation name must be unique within that + schema. (The system catalogs can contain collations with the + same name for other encodings, but these are ignored if the + database encoding does not match.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>locale</replaceable></term> + + <listitem> + <para> + This is a shortcut for setting <symbol>LC_COLLATE</symbol> + and <symbol>LC_CTYPE</symbol> at once. If you specify this, + you cannot specify either of those parameters. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lc_collate</replaceable></term> + + <listitem> + <para> + Use the specified operating system locale for + the <symbol>LC_COLLATE</symbol> locale category. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lc_ctype</replaceable></term> + + <listitem> + <para> + Use the specified operating system locale for + the <symbol>LC_CTYPE</symbol> locale category. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>provider</replaceable></term> + + <listitem> + <para> + Specifies the provider to use for locale services associated with this + collation. Possible values + are: <literal>icu</literal>,<indexterm><primary>ICU</primary></indexterm> + <literal>libc</literal>. + <literal>libc</literal> is the default. + The available choices depend on the operating system and build options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DETERMINISTIC</literal></term> + + <listitem> + <para> + Specifies whether the collation should use deterministic comparisons. + The default is true. A deterministic comparison considers strings that + are not byte-wise equal to be unequal even if they are considered + logically equal by the comparison. PostgreSQL breaks ties using a + byte-wise comparison. Comparison that is not deterministic can make the + collation be, say, case- or accent-insensitive. For that, you need to + choose an appropriate <literal>LC_COLLATE</literal> setting + <emphasis>and</emphasis> set the collation to not deterministic here. + </para> + + <para> + Nondeterministic collations are only supported with the ICU provider. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>version</replaceable></term> + + <listitem> + <para> + Specifies the version string to store with the collation. Normally, + this should be omitted, which will cause the version to be computed + from the actual version of the collation as provided by the operating + system. This option is intended to be used + by <command>pg_upgrade</command> for copying the version from an + existing installation. + </para> + + <para> + See also <xref linkend="sql-altercollation"/> for how to handle + collation version mismatches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>existing_collation</replaceable></term> + + <listitem> + <para> + The name of an existing collation to copy. The new collation + will have the same properties as the existing one, but it + will be an independent object. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + + <refsect1 id="sql-createcollation-notes"> + <title>Notes</title> + + <para> + <command>CREATE COLLATION</command> takes a <literal>SHARE ROW + EXCLUSIVE</literal> lock, which is self-conflicting, on the + <structname>pg_collation</structname> system catalog, so only one + <command>CREATE COLLATION</command> command can run at a time. + </para> + + <para> + Use <command>DROP COLLATION</command> to remove user-defined collations. + </para> + + <para> + See <xref linkend="collation-create"/> for more information on how to create collations. + </para> + + <para> + When using the <literal>libc</literal> collation provider, the locale must + be applicable to the current database encoding. + See <xref linkend="sql-createdatabase"/> for the precise rules. + </para> + </refsect1> + + <refsect1 id="sql-createcollation-examples"> + <title>Examples</title> + + <para> + To create a collation from the operating system locale + <literal>fr_FR.utf8</literal> + (assuming the current database encoding is <literal>UTF8</literal>): +<programlisting> +CREATE COLLATION french (locale = 'fr_FR.utf8'); +</programlisting> + </para> + + <para> + To create a collation using the ICU provider using German phone book sort order: +<programlisting> +CREATE COLLATION german_phonebook (provider = icu, locale = 'de-u-co-phonebk'); +</programlisting> + </para> + + <para> + To create a collation from an existing collation: +<programlisting> +CREATE COLLATION german FROM "de_DE"; +</programlisting> + This can be convenient to be able to use operating-system-independent + collation names in applications. + </para> + </refsect1> + + + <refsect1 id="sql-createcollation-compat"> + <title>Compatibility</title> + + <para> + There is a <command>CREATE COLLATION</command> statement in the SQL + standard, but it is limited to copying an existing collation. The + syntax to create a new collation is + a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + + <refsect1 id="sql-createcollation-seealso"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altercollation"/></member> + <member><xref linkend="sql-dropcollation"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_conversion.sgml b/doc/src/sgml/ref/create_conversion.sgml new file mode 100644 index 0000000..75d7b00 --- /dev/null +++ b/doc/src/sgml/ref/create_conversion.sgml @@ -0,0 +1,189 @@ +<!-- +doc/src/sgml/ref/create_conversion.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createconversion"> + <indexterm zone="sql-createconversion"> + <primary>CREATE CONVERSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE CONVERSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE CONVERSION</refname> + <refpurpose>define a new encoding conversion</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ DEFAULT ] CONVERSION <replaceable>name</replaceable> + FOR <replaceable>source_encoding</replaceable> TO <replaceable>dest_encoding</replaceable> FROM <replaceable>function_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createconversion-description"> + <title>Description</title> + + <para> + <command>CREATE CONVERSION</command> defines a new conversion between + two character set encodings. + </para> + + <para> + Conversions that are marked <literal>DEFAULT</literal> can be used for + automatic encoding conversion between client and server. To support that + usage, two conversions, from encoding A to B <emphasis>and</emphasis> + from encoding B to A, must be defined. + </para> + + <para> + To be able to create a conversion, you must have <literal>EXECUTE</literal> privilege + on the function and <literal>CREATE</literal> privilege on the destination schema. + </para> + </refsect1> + + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>DEFAULT</literal></term> + + <listitem> + <para> + The <literal>DEFAULT</literal> clause indicates that this conversion + is the default for this particular source to destination + encoding. There should be only one default encoding in a schema + for the encoding pair. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>name</replaceable></term> + + <listitem> + <para> + The name of the conversion. The conversion name can be + schema-qualified. If it is not, the conversion is defined in the + current schema. The conversion name must be unique within a + schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>source_encoding</replaceable></term> + + <listitem> + <para> + The source encoding name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>dest_encoding</replaceable></term> + + <listitem> + <para> + The destination encoding name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>function_name</replaceable></term> + + <listitem> + <para> + The function used to perform the conversion. The function name can + be schema-qualified. If it is not, the function will be looked + up in the path. + </para> + + <para> + The function must have the following signature: + +<programlisting> +conv_proc( + integer, -- source encoding ID + integer, -- destination encoding ID + cstring, -- source string (null terminated C string) + internal, -- destination (fill with a null terminated C string) + integer, -- source string length + boolean -- if true, don't throw an error if conversion fails +) RETURNS integer; +</programlisting> + The return value is the number of source bytes that were successfully + converted. If the last argument is false, the function must throw an + error on invalid input, and the return value is always equal to the + source string length. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createconversion-notes"> + <title>Notes</title> + + <para> + Neither the source nor the destination encoding can + be <literal>SQL_ASCII</literal>, as the server's behavior for cases + involving the <literal>SQL_ASCII</literal> <quote>encoding</quote> is + hard-wired. + </para> + + <para> + Use <command>DROP CONVERSION</command> to remove user-defined conversions. + </para> + + <para> + The privileges required to create a conversion might be changed in a future + release. + </para> + </refsect1> + + <refsect1 id="sql-createconversion-examples"> + <title>Examples</title> + + <para> + To create a conversion from encoding <literal>UTF8</literal> to + <literal>LATIN1</literal> using <function>myfunc</function>: +<programlisting> +CREATE CONVERSION myconv FOR 'UTF8' TO 'LATIN1' FROM myfunc; +</programlisting></para> + </refsect1> + + + <refsect1 id="sql-createconversion-compat"> + <title>Compatibility</title> + + <para> + <command>CREATE CONVERSION</command> + is a <productname>PostgreSQL</productname> extension. + There is no <command>CREATE CONVERSION</command> + statement in the SQL standard, but a <command>CREATE TRANSLATION</command> + statement that is very similar in purpose and syntax. + </para> + </refsect1> + + + <refsect1 id="sql-createconversion-seealso"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterconversion"/></member> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-dropconversion"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_database.sgml b/doc/src/sgml/ref/create_database.sgml new file mode 100644 index 0000000..ea38c64 --- /dev/null +++ b/doc/src/sgml/ref/create_database.sgml @@ -0,0 +1,449 @@ +<!-- +doc/src/sgml/ref/create_database.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createdatabase"> + <indexterm zone="sql-createdatabase"> + <primary>CREATE DATABASE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE DATABASE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE DATABASE</refname> + <refpurpose>create a new database</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE DATABASE <replaceable class="parameter">name</replaceable> + [ WITH ] [ OWNER [=] <replaceable class="parameter">user_name</replaceable> ] + [ TEMPLATE [=] <replaceable class="parameter">template</replaceable> ] + [ ENCODING [=] <replaceable class="parameter">encoding</replaceable> ] + [ STRATEGY [=] <replaceable class="parameter">strategy</replaceable> ] ] + [ LOCALE [=] <replaceable class="parameter">locale</replaceable> ] + [ LC_COLLATE [=] <replaceable class="parameter">lc_collate</replaceable> ] + [ LC_CTYPE [=] <replaceable class="parameter">lc_ctype</replaceable> ] + [ ICU_LOCALE [=] <replaceable class="parameter">icu_locale</replaceable> ] + [ LOCALE_PROVIDER [=] <replaceable class="parameter">locale_provider</replaceable> ] + [ COLLATION_VERSION = <replaceable>collation_version</replaceable> ] + [ TABLESPACE [=] <replaceable class="parameter">tablespace_name</replaceable> ] + [ ALLOW_CONNECTIONS [=] <replaceable class="parameter">allowconn</replaceable> ] + [ CONNECTION LIMIT [=] <replaceable class="parameter">connlimit</replaceable> ] + [ IS_TEMPLATE [=] <replaceable class="parameter">istemplate</replaceable> ] + [ OID [=] <replaceable class="parameter">oid</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE DATABASE</command> creates a new + <productname>PostgreSQL</productname> database. + </para> + + <para> + To create a database, you must be a superuser or have the special + <literal>CREATEDB</literal> privilege. + See <xref linkend="sql-createrole"/>. + </para> + + <para> + By default, the new database will be created by cloning the standard + system database <literal>template1</literal>. A different template can be + specified by writing <literal>TEMPLATE + <replaceable class="parameter">name</replaceable></literal>. In particular, + by writing <literal>TEMPLATE template0</literal>, you can create a pristine + database (one where no user-defined objects exist and where the system + objects have not been altered) + containing only the standard objects predefined by your + version of <productname>PostgreSQL</productname>. This is useful + if you wish to avoid copying + any installation-local objects that might have been added to + <literal>template1</literal>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a database to create. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + The role name of the user who will own the new database, + or <literal>DEFAULT</literal> to use the default (namely, the + user executing the command). To create a database owned by another + role, you must be a direct or indirect member of that role, + or be a superuser. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">template</replaceable></term> + <listitem> + <para> + The name of the template from which to create the new database, + or <literal>DEFAULT</literal> to use the default template + (<literal>template1</literal>). + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">encoding</replaceable></term> + <listitem> + <para> + Character set encoding to use in the new database. Specify + a string constant (e.g., <literal>'SQL_ASCII'</literal>), + or an integer encoding number, or <literal>DEFAULT</literal> + to use the default encoding (namely, the encoding of the + template database). The character sets supported by the + <productname>PostgreSQL</productname> server are described in + <xref linkend="multibyte-charset-supported"/>. See below for + additional restrictions. + </para> + </listitem> + </varlistentry> + <varlistentry id="create-database-strategy" xreflabel="CREATE DATABASE STRATEGY"> + <term><replaceable class="parameter">strategy</replaceable></term> + <listitem> + <para> + Strategy to be used in creating the new database. If + the <literal>WAL_LOG</literal> strategy is used, the database will be + copied block by block and each block will be separately written + to the write-ahead log. This is the most efficient strategy in + cases where the template database is small, and therefore it is the + default. The older <literal>FILE_COPY</literal> strategy is also + available. This strategy writes a small record to the write-ahead log + for each tablespace used by the target database. Each such record + represents copying an entire directory to a new location at the + filesystem level. While this does reduce the write-ahead + log volume substantially, especially if the template database is large, + it also forces the system to perform a checkpoint both before and + after the creation of the new database. In some situations, this may + have a noticeable negative impact on overall system performance. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">locale</replaceable></term> + <listitem> + <para> + This is a shortcut for setting <symbol>LC_COLLATE</symbol> + and <symbol>LC_CTYPE</symbol> at once. + </para> + <tip> + <para> + The other locale settings <xref linkend="guc-lc-messages"/>, <xref + linkend="guc-lc-monetary"/>, <xref linkend="guc-lc-numeric"/>, and + <xref linkend="guc-lc-time"/> are not fixed per database and are not + set by this command. If you want to make them the default for a + specific database, you can use <literal>ALTER DATABASE + ... SET</literal>. + </para> + </tip> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">lc_collate</replaceable></term> + <listitem> + <para> + Collation order (<literal>LC_COLLATE</literal>) to use in the new database. + This affects the sort order applied to strings, e.g., in queries with + ORDER BY, as well as the order used in indexes on text columns. + The default is to use the collation order of the template database. + See below for additional restrictions. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">lc_ctype</replaceable></term> + <listitem> + <para> + Character classification (<literal>LC_CTYPE</literal>) to use in the new + database. This affects the categorization of characters, e.g., lower, + upper and digit. The default is to use the character classification of + the template database. See below for additional restrictions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">icu_locale</replaceable></term> + <listitem> + <para> + Specifies the ICU locale ID if the ICU locale provider is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>locale_provider</replaceable></term> + + <listitem> + <para> + Specifies the provider to use for the default collation in this + database. Possible values are: + <literal>icu</literal>,<indexterm><primary>ICU</primary></indexterm> + <literal>libc</literal>. <literal>libc</literal> is the default. The + available choices depend on the operating system and build options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>collation_version</replaceable></term> + + <listitem> + <para> + Specifies the collation version string to store with the database. + Normally, this should be omitted, which will cause the version to be + computed from the actual version of the database collation as provided + by the operating system. This option is intended to be used by + <command>pg_upgrade</command> for copying the version from an existing + installation. + </para> + + <para> + See also <xref linkend="sql-alterdatabase"/> for how to handle + database collation version mismatches. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">tablespace_name</replaceable></term> + <listitem> + <para> + The name of the tablespace that will be associated with the + new database, or <literal>DEFAULT</literal> to use the + template database's tablespace. This + tablespace will be the default tablespace used for objects + created in this database. See + <xref linkend="sql-createtablespace"/> + for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">allowconn</replaceable></term> + <listitem> + <para> + If false then no one can connect to this database. The default is + true, allowing connections (except as restricted by other mechanisms, + such as <literal>GRANT</literal>/<literal>REVOKE CONNECT</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">connlimit</replaceable></term> + <listitem> + <para> + How many concurrent connections can be made + to this database. -1 (the default) means no limit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">istemplate</replaceable></term> + <listitem> + <para> + If true, then this database can be cloned by any user with <literal>CREATEDB</literal> + privileges; if false (the default), then only superusers or the owner + of the database can clone it. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">oid</replaceable></term> + <listitem> + <para> + The object identifier to be used for the new database. If this + parameter is not specified, <productname>PostgreSQL</productname> + will choose a suitable OID automatically. This parameter is primarily + intended for internal use by <application>pg_upgrade</application>, + and only <application>pg_upgrade</application> can specify a value + less than 16384. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <para> + Optional parameters can be written in any order, not only the order + illustrated above. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>CREATE DATABASE</command> cannot be executed inside a transaction + block. + </para> + + <para> + Errors along the line of <quote>could not initialize database directory</quote> + are most likely related to insufficient permissions on the data + directory, a full disk, or other file system problems. + </para> + + <para> + Use <link linkend="sql-dropdatabase"><command>DROP DATABASE</command></link> to remove a database. + </para> + + <para> + The program <xref linkend="app-createdb"/> is a + wrapper program around this command, provided for convenience. + </para> + + <para> + Database-level configuration parameters (set via <link + linkend="sql-alterdatabase"><command>ALTER DATABASE</command></link>) and database-level permissions (set via + <link linkend="sql-grant"><command>GRANT</command></link>) are not copied from the template database. + </para> + + <para> + Although it is possible to copy a database other than <literal>template1</literal> + by specifying its name as the template, this is not (yet) intended as + a general-purpose <quote><command>COPY DATABASE</command></quote> facility. + The principal limitation is that no other sessions can be connected to + the template database while it is being copied. <command>CREATE + DATABASE</command> will fail if any other connection exists when it starts; + otherwise, new connections to the template database are locked out + until <command>CREATE DATABASE</command> completes. + See <xref linkend="manage-ag-templatedbs"/> for more information. + </para> + + <para> + The character set encoding specified for the new database must be + compatible with the chosen locale settings (<literal>LC_COLLATE</literal> and + <literal>LC_CTYPE</literal>). If the locale is <literal>C</literal> (or equivalently + <literal>POSIX</literal>), then all encodings are allowed, but for other + locale settings there is only one encoding that will work properly. + (On Windows, however, UTF-8 encoding can be used with any locale.) + <command>CREATE DATABASE</command> will allow superusers to specify + <literal>SQL_ASCII</literal> encoding regardless of the locale settings, + but this choice is deprecated and may result in misbehavior of + character-string functions if data that is not encoding-compatible + with the locale is stored in the database. + </para> + + <para> + The encoding and locale settings must match those of the template database, + except when <literal>template0</literal> is used as template. This is because + other databases might contain data that does not match the specified + encoding, or might contain indexes whose sort ordering is affected by + <literal>LC_COLLATE</literal> and <literal>LC_CTYPE</literal>. Copying such data would + result in a database that is corrupt according to the new settings. + <literal>template0</literal>, however, is known to not contain any data or + indexes that would be affected. + </para> + + <para> + There is currently no option to use a database locale with nondeterministic + comparisons (see <link linkend="sql-createcollation"><command>CREATE + COLLATION</command></link> for an explanation). If this is needed, then + per-column collations would need to be used. + </para> + + <para> + The <literal>CONNECTION LIMIT</literal> option is only enforced approximately; + if two new sessions start at about the same time when just one + connection <quote>slot</quote> remains for the database, it is possible that + both will fail. Also, the limit is not enforced against superusers or + background worker processes. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To create a new database: + +<programlisting> +CREATE DATABASE lusiadas; +</programlisting> + </para> + + <para> + To create a database <literal>sales</literal> owned by user <literal>salesapp</literal> + with a default tablespace of <literal>salesspace</literal>: + +<programlisting> +CREATE DATABASE sales OWNER salesapp TABLESPACE salesspace; +</programlisting> + </para> + + <para> + To create a database <literal>music</literal> with a different locale: +<programlisting> +CREATE DATABASE music + LOCALE 'sv_SE.utf8' + TEMPLATE template0; +</programlisting> + In this example, the <literal>TEMPLATE template0</literal> clause is required if + the specified locale is different from the one in <literal>template1</literal>. + (If it is not, then specifying the locale explicitly is redundant.) + </para> + + <para> + To create a database <literal>music2</literal> with a different locale and a + different character set encoding: +<programlisting> +CREATE DATABASE music2 + LOCALE 'sv_SE.iso885915' + ENCODING LATIN9 + TEMPLATE template0; +</programlisting> + The specified locale and encoding settings must match, or an error will be + reported. + </para> + + <para> + Note that locale names are specific to the operating system, so that the + above commands might not work in the same way everywhere. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CREATE DATABASE</command> statement in the SQL + standard. Databases are equivalent to catalogs, whose creation is + implementation-defined. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterdatabase"/></member> + <member><xref linkend="sql-dropdatabase"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_domain.sgml b/doc/src/sgml/ref/create_domain.sgml new file mode 100644 index 0000000..82a0b87 --- /dev/null +++ b/doc/src/sgml/ref/create_domain.sgml @@ -0,0 +1,288 @@ +<!-- +doc/src/sgml/ref/create_domain.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createdomain"> + <indexterm zone="sql-createdomain"> + <primary>CREATE DOMAIN</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE DOMAIN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE DOMAIN</refname> + <refpurpose>define a new domain</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE DOMAIN <replaceable class="parameter">name</replaceable> [ AS ] <replaceable class="parameter">data_type</replaceable> + [ COLLATE <replaceable>collation</replaceable> ] + [ DEFAULT <replaceable>expression</replaceable> ] + [ <replaceable class="parameter">constraint</replaceable> [ ... ] ] + +<phrase>where <replaceable class="parameter">constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ NOT NULL | NULL | CHECK (<replaceable class="parameter">expression</replaceable>) } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE DOMAIN</command> creates a new domain. A domain is + essentially a data type with optional constraints (restrictions on + the allowed set of values). + The user who defines a domain becomes its owner. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE DOMAIN + myschema.mydomain ...</literal>) then the domain is created in the + specified schema. Otherwise it is created in the current schema. + The domain name must be unique among the types and domains existing + in its schema. + </para> + + <para> + Domains are useful for abstracting common constraints on fields into + a single location for maintenance. For example, several tables might + contain email address columns, all requiring the same CHECK constraint + to verify the address syntax. + Define a domain rather than setting up each table's constraint + individually. + </para> + + <para> + To be able to create a domain, you must have <literal>USAGE</literal> + privilege on the underlying type. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a domain to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The underlying data type of the domain. This can include array + specifiers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>collation</replaceable></term> + <listitem> + <para> + An optional collation for the domain. If no collation is + specified, the domain has the same collation behavior as its + underlying data type. + The underlying type must be collatable if <literal>COLLATE</literal> + is specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT <replaceable>expression</replaceable></literal></term> + + <listitem> + <para> + The <literal>DEFAULT</literal> clause specifies a default value for + columns of the domain data type. The value is any + variable-free expression (but subqueries are not allowed). + The data type of the default expression must match the data + type of the domain. If no default value is specified, then + the default value is the null value. + </para> + + <para> + The default expression will be used in any insert operation + that does not specify a value for the column. If a default + value is defined for a particular column, it overrides any + default associated with the domain. In turn, the domain + default overrides any default value associated with the + underlying data type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONSTRAINT <replaceable class="parameter">constraint_name</replaceable></literal></term> + <listitem> + <para> + An optional name for a constraint. If not specified, + the system generates a name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOT NULL</literal></term> + <listitem> + <para> + Values of this domain are prevented from being null + (but see notes below). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + Values of this domain are allowed to be null. This is the default. + </para> + + <para> + This clause is only intended for compatibility with + nonstandard SQL databases. Its use is discouraged in new + applications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CHECK (<replaceable class="parameter">expression</replaceable>)</literal></term> + <listitem> + <para><literal>CHECK</literal> clauses specify integrity constraints or tests + which values of the domain must satisfy. + Each constraint must be an expression + producing a Boolean result. It should use the key word <literal>VALUE</literal> + to refer to the value being tested. Expressions evaluating + to TRUE or UNKNOWN succeed. If the expression produces a FALSE result, + an error is reported and the value is not allowed to be converted + to the domain type. + </para> + + <para> + Currently, <literal>CHECK</literal> expressions cannot contain + subqueries nor refer to variables other than <literal>VALUE</literal>. + </para> + + <para> + When a domain has multiple <literal>CHECK</literal> constraints, + they will be tested in alphabetical order by name. + (<productname>PostgreSQL</productname> versions before 9.5 did not honor any + particular firing order for <literal>CHECK</literal> constraints.) + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Domain constraints, particularly <literal>NOT NULL</literal>, are checked when + converting a value to the domain type. It is possible for a column that + is nominally of the domain type to read as null despite there being such + a constraint. For example, this can happen in an outer-join query, if + the domain column is on the nullable side of the outer join. A more + subtle example is +<programlisting> +INSERT INTO tab (domcol) VALUES ((SELECT domcol FROM tab WHERE false)); +</programlisting> + The empty scalar sub-SELECT will produce a null value that is considered + to be of the domain type, so no further constraint checking is applied + to it, and the insertion will succeed. + </para> + + <para> + It is very difficult to avoid such problems, because of SQL's general + assumption that a null value is a valid value of every data type. Best practice + therefore is to design a domain's constraints so that a null value is allowed, + and then to apply column <literal>NOT NULL</literal> constraints to columns of + the domain type as needed, rather than directly to the domain type. + </para> + + <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 value. This + assumption is what justifies examining <literal>CHECK</literal> + constraints only when a value is first converted to be of a domain type, + and not at other times. (This is essentially the same as the treatment + of table <literal>CHECK</literal> constraints, as described in + <xref linkend="ddl-constraints-check-constraints"/>.) + </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 stored values of the domain type that + now violate the <literal>CHECK</literal> constraint. That would cause a + subsequent database dump and restore to fail. The recommended way to + handle such a change is to drop the constraint (using <command>ALTER + DOMAIN</command>), adjust the function definition, and re-add the + constraint, thereby rechecking it against stored data. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This example creates the <type>us_postal_code</type> data type and + then uses the type in a table definition. A regular expression test + is used to verify that the value looks like a valid US postal code: + +<programlisting> +CREATE DOMAIN us_postal_code AS TEXT +CHECK( + VALUE ~ '^\d{5}$' +OR VALUE ~ '^\d{5}-\d{4}$' +); + +CREATE TABLE us_snail_addy ( + address_id SERIAL PRIMARY KEY, + street1 TEXT NOT NULL, + street2 TEXT, + street3 TEXT, + city TEXT NOT NULL, + postal us_postal_code NOT NULL +); +</programlisting></para> + </refsect1> + + <refsect1 id="sql-createdomain-compatibility"> + <title>Compatibility</title> + + <para> + The command <command>CREATE DOMAIN</command> conforms to the SQL + standard. + </para> + </refsect1> + + <refsect1 id="sql-createdomain-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterdomain"/></member> + <member><xref linkend="sql-dropdomain"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_event_trigger.sgml b/doc/src/sgml/ref/create_event_trigger.sgml new file mode 100644 index 0000000..22c8119 --- /dev/null +++ b/doc/src/sgml/ref/create_event_trigger.sgml @@ -0,0 +1,170 @@ +<!-- +doc/src/sgml/ref/create_event_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createeventtrigger"> + <indexterm zone="sql-createeventtrigger"> + <primary>CREATE EVENT TRIGGER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE EVENT TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE EVENT TRIGGER</refname> + <refpurpose>define a new event trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE EVENT TRIGGER <replaceable class="parameter">name</replaceable> + ON <replaceable class="parameter">event</replaceable> + [ WHEN <replaceable class="parameter">filter_variable</replaceable> IN (<replaceable class="parameter">filter_value</replaceable> [, ... ]) [ AND ... ] ] + EXECUTE { FUNCTION | PROCEDURE } <replaceable class="parameter">function_name</replaceable>() +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE EVENT TRIGGER</command> creates a new event trigger. + Whenever the designated event occurs and the <literal>WHEN</literal> condition + associated with the trigger, if any, is satisfied, the trigger function + will be executed. For a general introduction to event triggers, see + <xref linkend="event-triggers"/>. The user who creates an event trigger + becomes its owner. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name to give the new trigger. This name must be unique within + the database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">event</replaceable></term> + <listitem> + <para> + The name of the event that triggers a call to the given function. + See <xref linkend="event-trigger-definition"/> for more information + on event names. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">filter_variable</replaceable></term> + <listitem> + <para> + The name of a variable used to filter events. This makes it possible + to restrict the firing of the trigger to a subset of the cases in which + it is supported. Currently the only supported + <replaceable class="parameter">filter_variable</replaceable> + is <literal>TAG</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">filter_value</replaceable></term> + <listitem> + <para> + A list of values for the + associated <replaceable class="parameter">filter_variable</replaceable> + for which the trigger should fire. For <literal>TAG</literal>, this means a + list of command tags (e.g., <literal>'DROP FUNCTION'</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + A user-supplied function that is declared as taking no argument and + returning type <literal>event_trigger</literal>. + </para> + + <para> + In the syntax of <literal>CREATE EVENT TRIGGER</literal>, the keywords + <literal>FUNCTION</literal> and <literal>PROCEDURE</literal> are + equivalent, but the referenced function must in any case be a function, + not a procedure. The use of the keyword <literal>PROCEDURE</literal> + here is historical and deprecated. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1 id="sql-createeventtrigger-notes"> + <title>Notes</title> + + <para> + Only superusers can create event triggers. + </para> + + <para> + Event triggers are disabled in single-user mode (see <xref + linkend="app-postgres"/>). If an erroneous event trigger disables the + database so much that you can't even drop the trigger, restart in + single-user mode and you'll be able to do that. + </para> + </refsect1> + + <refsect1 id="sql-createeventtrigger-examples"> + <title>Examples</title> + + <para> + Forbid the execution of any <link linkend="ddl">DDL</link> command: + +<programlisting> +CREATE OR REPLACE FUNCTION abort_any_command() + RETURNS event_trigger + LANGUAGE plpgsql + AS $$ +BEGIN + RAISE EXCEPTION 'command % is disabled', tg_tag; +END; +$$; + +CREATE EVENT TRIGGER abort_ddl ON ddl_command_start + EXECUTE FUNCTION abort_any_command(); +</programlisting></para> + </refsect1> + + <refsect1 id="sql-createeventtrigger-compatibility"> + <title>Compatibility</title> + + <para> + There is no <command>CREATE EVENT TRIGGER</command> statement in the + SQL standard. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altereventtrigger"/></member> + <member><xref linkend="sql-dropeventtrigger"/></member> + <member><xref linkend="sql-createfunction"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_extension.sgml b/doc/src/sgml/ref/create_extension.sgml new file mode 100644 index 0000000..ca2b80d --- /dev/null +++ b/doc/src/sgml/ref/create_extension.sgml @@ -0,0 +1,247 @@ +<!-- +doc/src/sgml/ref/create_extension.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createextension"> + <indexterm zone="sql-createextension"> + <primary>CREATE EXTENSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE EXTENSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE EXTENSION</refname> + <refpurpose>install an extension</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE EXTENSION [ IF NOT EXISTS ] <replaceable class="parameter">extension_name</replaceable> + [ WITH ] [ SCHEMA <replaceable class="parameter">schema_name</replaceable> ] + [ VERSION <replaceable class="parameter">version</replaceable> ] + [ CASCADE ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE EXTENSION</command> loads a new extension into the current + database. There must not be an extension of the same name already loaded. + </para> + + <para> + Loading an extension essentially amounts to running the extension's script + file. The script will typically create new <acronym>SQL</acronym> objects such as + functions, data types, operators and index support methods. + <command>CREATE EXTENSION</command> additionally records the identities + of all the created objects, so that they can be dropped again if + <command>DROP EXTENSION</command> is issued. + </para> + + <para> + The user who runs <command>CREATE EXTENSION</command> becomes the + owner of the extension for purposes of later privilege checks, and + normally also becomes the owner of any objects created by the + extension's script. + </para> + + <para> + Loading an extension ordinarily requires the same privileges that would + be required to create its component objects. For many extensions this + means superuser privileges are needed. + However, if the extension is marked <firstterm>trusted</firstterm> in + its control file, then it can be installed by any user who has + <literal>CREATE</literal> privilege on the current database. + In this case the extension object itself will be owned by the calling + user, but the contained objects will be owned by the bootstrap superuser + (unless the extension's script explicitly assigns them to the calling + user). This configuration gives the calling user the right to drop the + extension, but not to modify individual objects within it. + </para> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if an extension with the same name already + exists. A notice is issued in this case. Note that there is no + guarantee that the existing extension is anything like the one that + would have been created from the currently-available script file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">extension_name</replaceable></term> + <listitem> + <para> + The name of the extension to be + installed. <productname>PostgreSQL</productname> will create the + extension using details from the file + <literal>SHAREDIR/extension/</literal><replaceable class="parameter">extension_name</replaceable><literal>.control</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">schema_name</replaceable></term> + <listitem> + <para> + The name of the schema in which to install the extension's + objects, given that the extension allows its contents to be + relocated. The named schema must already exist. + If not specified, and the extension's control file does not specify a + schema either, the current default object creation schema is used. + </para> + + <para> + If the extension specifies a <literal>schema</literal> parameter in its + control file, then that schema cannot be overridden with + a <literal>SCHEMA</literal> clause. Normally, an error will be raised if + a <literal>SCHEMA</literal> clause is given and it conflicts with the + extension's <literal>schema</literal> parameter. However, if + the <literal>CASCADE</literal> clause is also given, + then <replaceable class="parameter">schema_name</replaceable> is + ignored when it conflicts. The + given <replaceable class="parameter">schema_name</replaceable> will be + used for installation of any needed extensions that do not + specify <literal>schema</literal> in their control files. + </para> + + <para> + Remember that the extension itself is not considered to be within any + schema: extensions have unqualified names that must be unique + database-wide. But objects belonging to the extension can be within + schemas. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">version</replaceable></term> + <listitem> + <para> + The version of the extension to install. This can be written as + either an identifier or a string literal. The default version is + whatever is specified in the extension's control file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically install any extensions that this extension depends on + that are not already installed. Their dependencies are likewise + automatically installed, recursively. The <literal>SCHEMA</literal> clause, + if given, applies to all extensions that get installed this way. + Other options of the statement are not applied to + automatically-installed extensions; in particular, their default + versions are always selected. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Before you can use <command>CREATE EXTENSION</command> to load an extension + into a database, the extension's supporting files must be installed. + Information about installing the extensions supplied with + <productname>PostgreSQL</productname> can be found in + <link linkend="contrib">Additional Supplied Modules</link>. + </para> + + <para> + The extensions currently available for loading can be identified from the + <link linkend="view-pg-available-extensions"><structname>pg_available_extensions</structname></link> + or + <link linkend="view-pg-available-extension-versions"><structname>pg_available_extension_versions</structname></link> + system views. + </para> + + <caution> + <para> + Installing an extension as superuser requires trusting that the + extension's author wrote the extension installation script in a secure + fashion. It is not terribly difficult for a malicious user to create + trojan-horse objects that will compromise later execution of a + carelessly-written extension script, allowing that user to acquire + superuser privileges. However, trojan-horse objects are only hazardous + if they are in the <varname>search_path</varname> during script + execution, meaning that they are in the extension's installation target + schema or in the schema of some extension it depends on. Therefore, a + good rule of thumb when dealing with extensions whose scripts have not + been carefully vetted is to install them only into schemas for which + CREATE privilege has not been and will not be granted to any untrusted + users. Likewise for any extensions they depend on. + </para> + + <para> + The extensions supplied with <productname>PostgreSQL</productname> are + believed to be secure against installation-time attacks of this sort, + except for a few that depend on other extensions. As stated in the + documentation for those extensions, they should be installed into secure + schemas, or installed into the same schemas as the extensions they + depend on, or both. + </para> + </caution> + + <para> + For information about writing new extensions, see + <xref linkend="extend-extensions"/>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Install the <link linkend="hstore">hstore</link> extension into the + current database, placing its objects in schema <literal>addons</literal>: +<programlisting> +CREATE EXTENSION hstore SCHEMA addons; +</programlisting> + Another way to accomplish the same thing: +<programlisting> +SET search_path = addons; +CREATE EXTENSION hstore; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE EXTENSION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterextension"/></member> + <member><xref linkend="sql-dropextension"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_foreign_data_wrapper.sgml b/doc/src/sgml/ref/create_foreign_data_wrapper.sgml new file mode 100644 index 0000000..0fcba18 --- /dev/null +++ b/doc/src/sgml/ref/create_foreign_data_wrapper.sgml @@ -0,0 +1,183 @@ +<!-- +doc/src/sgml/ref/create_foreign_data_wrapper.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createforeigndatawrapper"> + <indexterm zone="sql-createforeigndatawrapper"> + <primary>CREATE FOREIGN DATA WRAPPER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE FOREIGN DATA WRAPPER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE FOREIGN DATA WRAPPER</refname> + <refpurpose>define a new foreign-data wrapper</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE FOREIGN DATA WRAPPER <replaceable class="parameter">name</replaceable> + [ HANDLER <replaceable class="parameter">handler_function</replaceable> | NO HANDLER ] + [ VALIDATOR <replaceable class="parameter">validator_function</replaceable> | NO VALIDATOR ] + [ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE FOREIGN DATA WRAPPER</command> creates a new + foreign-data wrapper. The user who defines a foreign-data wrapper + becomes its owner. + </para> + + <para> + The foreign-data wrapper name must be unique within the database. + </para> + + <para> + Only superusers can create foreign-data wrappers. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the foreign-data wrapper to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HANDLER <replaceable class="parameter">handler_function</replaceable></literal></term> + <listitem> + <para><replaceable class="parameter">handler_function</replaceable> is the + name of a previously registered function that will be called to + retrieve the execution functions for foreign tables. + The handler function must take no arguments, and + its return type must be <type>fdw_handler</type>. + </para> + + <para> + It is possible to create a foreign-data wrapper with no handler + function, but foreign tables using such a wrapper can only be declared, + not accessed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATOR <replaceable class="parameter">validator_function</replaceable></literal></term> + <listitem> + <para><replaceable class="parameter">validator_function</replaceable> + is the name of a previously registered function that will be called to + check the generic options given to the foreign-data wrapper, as + well as options for foreign servers, user mappings and foreign tables + using the foreign-data wrapper. If no validator function or <literal>NO + VALIDATOR</literal> is specified, then options will not be + checked at creation time. (Foreign-data wrappers will possibly + ignore or reject invalid option specifications at run time, + depending on the implementation.) The validator function must + take two arguments: one of type <type>text[]</type>, which will + contain the array of options as stored in the system catalogs, + and one of type <type>oid</type>, which will be the OID of the + system catalog containing the options. The return type is ignored; + the function should report invalid options using the + <function>ereport(ERROR)</function> function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies options for the new foreign-data wrapper. + The allowed option names and values are specific to each foreign + data wrapper and are validated using the foreign-data wrapper's + validator function. Option names must be unique. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <productname>PostgreSQL</productname>'s foreign-data functionality is still under + active development. Optimization of queries is primitive (and mostly left + to the wrapper, too). Thus, there is considerable room for future + performance improvements. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a useless foreign-data wrapper <literal>dummy</literal>: +<programlisting> +CREATE FOREIGN DATA WRAPPER dummy; +</programlisting> + </para> + + <para> + Create a foreign-data wrapper <literal>file</literal> with + handler function <literal>file_fdw_handler</literal>: +<programlisting> +CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler; +</programlisting> + </para> + + <para> + Create a foreign-data wrapper <literal>mywrapper</literal> with some + options: +<programlisting> +CREATE FOREIGN DATA WRAPPER mywrapper + OPTIONS (debug 'true'); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE FOREIGN DATA WRAPPER</command> conforms to ISO/IEC + 9075-9 (SQL/MED), with the exception that the <literal>HANDLER</literal> + and <literal>VALIDATOR</literal> clauses are extensions and the standard + clauses <literal>LIBRARY</literal> and <literal>LANGUAGE</literal> + are not implemented in <productname>PostgreSQL</productname>. + </para> + + <para> + Note, however, that the SQL/MED functionality as a whole is not yet + conforming. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterforeigndatawrapper"/></member> + <member><xref linkend="sql-dropforeigndatawrapper"/></member> + <member><xref linkend="sql-createserver"/></member> + <member><xref linkend="sql-createusermapping"/></member> + <member><xref linkend="sql-createforeigntable"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_foreign_table.sgml b/doc/src/sgml/ref/create_foreign_table.sgml new file mode 100644 index 0000000..dc4b907 --- /dev/null +++ b/doc/src/sgml/ref/create_foreign_table.sgml @@ -0,0 +1,455 @@ +<!-- +doc/src/sgml/ref/create_foreign_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createforeigntable"> + <indexterm zone="sql-createforeigntable"> + <primary>CREATE FOREIGN TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE FOREIGN TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE FOREIGN TABLE</refname> + <refpurpose>define a new foreign table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE FOREIGN TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name</replaceable> ( [ + { <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] [ COLLATE <replaceable>collation</replaceable> ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + | <replaceable>table_constraint</replaceable> } + [, ... ] +] ) +[ INHERITS ( <replaceable>parent_table</replaceable> [, ... ] ) ] + SERVER <replaceable class="parameter">server_name</replaceable> +[ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] + +CREATE FOREIGN TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name</replaceable> + PARTITION OF <replaceable class="parameter">parent_table</replaceable> [ ( + { <replaceable class="parameter">column_name</replaceable> [ WITH OPTIONS ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + | <replaceable>table_constraint</replaceable> } + [, ... ] +) ] +{ FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT } + SERVER <replaceable class="parameter">server_name</replaceable> +[ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] + +<phrase>where <replaceable class="parameter">column_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ NOT NULL | + NULL | + CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] | + DEFAULT <replaceable>default_expr</replaceable> | + GENERATED ALWAYS AS ( <replaceable>generation_expr</replaceable> ) STORED } + +<phrase>and <replaceable class="parameter">table_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] + +<phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase> + +IN ( <replaceable class="parameter">partition_bound_expr</replaceable> [, ...] ) | +FROM ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) + TO ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) | +WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REMAINDER <replaceable class="parameter">numeric_literal</replaceable> ) +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createforeigntable-description"> + <title>Description</title> + + <para> + <command>CREATE FOREIGN TABLE</command> creates a new foreign table + in the current database. The table will be owned by the user issuing the + command. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE FOREIGN TABLE + myschema.mytable ...</literal>) then the table is created in the specified + schema. Otherwise it is created in the current schema. + The name of the foreign table must be + distinct from the name of any other relation (table, sequence, index, view, + materialized view, or foreign table) in the same schema. + </para> + + <para> + <command>CREATE FOREIGN TABLE</command> also automatically creates a data + type that represents the composite type corresponding to one row of + the foreign table. Therefore, foreign tables cannot have the same + name as any existing data type in the same schema. + </para> + + <para> + If <literal>PARTITION OF</literal> clause is specified then the table is + created as a partition of <literal>parent_table</literal> with specified + bounds. + </para> + + <para> + To be able to create a foreign table, you must have <literal>USAGE</literal> + privilege on the foreign server, as well as <literal>USAGE</literal> + privilege on all column types used in the table. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a relation with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing relation is anything like the one that would have been + created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column to be created in the new table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The data type of the column. This can include array + specifiers. For more information on the data types supported by + <productname>PostgreSQL</productname>, refer to <xref + linkend="datatype"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COLLATE <replaceable>collation</replaceable></literal></term> + <listitem> + <para> + The <literal>COLLATE</literal> clause assigns a collation to + the column (which must be of a collatable data type). + If not specified, the column data type's default collation is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INHERITS ( <replaceable>parent_table</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + The optional <literal>INHERITS</literal> clause specifies a list of + tables from which the new foreign table automatically inherits + all columns. Parent tables can be plain tables or foreign tables. + See the similar form of + <link linkend="sql-createtable"><command>CREATE TABLE</command></link> for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARTITION OF <replaceable>parent_table</replaceable> { FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT }</literal></term> + <listitem> + <para> + This form can be used to create the foreign table as partition of + the given parent table with specified partition bound values. + See the similar form of + <link linkend="sql-createtable"><command>CREATE TABLE</command></link> for more details. + Note that it is currently not allowed to create the foreign table as a + partition of the parent table if there are <literal>UNIQUE</literal> + indexes on the parent table. (See also + <link linkend="sql-altertable"><command>ALTER TABLE ATTACH PARTITION</command></link>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONSTRAINT <replaceable class="parameter">constraint_name</replaceable></literal></term> + <listitem> + <para> + An optional name for a column or table constraint. If the + constraint is violated, the constraint name is present in error messages, + so constraint names like <literal>col must be positive</literal> can be used + to communicate helpful constraint information to client applications. + (Double-quotes are needed to specify constraint names that contain spaces.) + If a constraint name is not specified, the system generates a name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOT NULL</literal></term> + <listitem> + <para> + The column is not allowed to contain null values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + The column is allowed to contain null values. This is the default. + </para> + + <para> + This clause is only provided for compatibility with + non-standard SQL databases. Its use is discouraged in new + applications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] </literal></term> + <listitem> + <para> + The <literal>CHECK</literal> clause specifies an expression producing a + Boolean result which each row in the foreign table is expected + to satisfy; that is, the expression should produce TRUE or UNKNOWN, + never FALSE, for all rows in the foreign table. + A check constraint specified as a column constraint should + reference that column's value only, while an expression + appearing in a table constraint can reference multiple columns. + </para> + + <para> + Currently, <literal>CHECK</literal> expressions cannot contain + subqueries nor refer to variables other than columns of the + current row. The system column <literal>tableoid</literal> + may be referenced, but not any other system column. + </para> + + <para> + A constraint marked with <literal>NO INHERIT</literal> will not propagate to + child tables. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT + <replaceable>default_expr</replaceable></literal></term> + <listitem> + <para> + The <literal>DEFAULT</literal> clause assigns a default data value for + the column whose column definition it appears within. The value + is any variable-free expression (subqueries and cross-references + to other columns in the current table are not allowed). The + data type of the default expression must match the data type of the + column. + </para> + + <para> + The default expression will be used in any insert operation that + does not specify a value for the column. If there is no default + for a column, then the default is null. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>GENERATED ALWAYS AS ( <replaceable>generation_expr</replaceable> ) STORED</literal><indexterm><primary>generated column</primary></indexterm></term> + <listitem> + <para> + This clause creates the column as a <firstterm>generated + column</firstterm>. The column cannot be written to, and when read the + result of the specified expression will be returned. + </para> + + <para> + The keyword <literal>STORED</literal> is required to signify that the + column will be computed on write. (The computed value will be presented + to the foreign-data wrapper for storage and must be returned on + reading.) + </para> + + <para> + The generation expression can refer to other columns in the table, but + not other generated columns. Any functions and operators used must be + immutable. References to other tables are not allowed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + The name of an existing foreign server to use for the foreign table. + For details on defining a server, see <xref + linkend="sql-createserver"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ...] )</literal></term> + <listitem> + <para> + Options to be associated with the new foreign table or one of its + columns. + The allowed option names and values are specific to each foreign + data wrapper and are validated using the foreign-data wrapper's + validator function. Duplicate option names are not allowed (although + it's OK for a table option and a column option to have the same name). + </para> + </listitem> + </varlistentry> + + </variablelist> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Constraints on foreign tables (such as <literal>CHECK</literal> + or <literal>NOT NULL</literal> clauses) are not enforced by the + core <productname>PostgreSQL</productname> system, and most foreign data wrappers + do not attempt to enforce them either; that is, the constraint is + simply assumed to hold true. There would be little point in such + enforcement since it would only apply to rows inserted or updated via + the foreign table, and not to rows modified by other means, such as + directly on the remote server. Instead, a constraint attached to a + foreign table should represent a constraint that is being enforced by + the remote server. + </para> + + <para> + Some special-purpose foreign data wrappers might be the only access + mechanism for the data they access, and in that case it might be + appropriate for the foreign data wrapper itself to perform constraint + enforcement. But you should not assume that a wrapper does that + unless its documentation says so. + </para> + + <para> + Although <productname>PostgreSQL</productname> does not attempt to enforce + constraints on foreign tables, it does assume that they are correct + for purposes of query optimization. If there are rows visible in the + foreign table that do not satisfy a declared constraint, queries on + the table might produce errors or incorrect answers. It is the user's + responsibility to ensure that the constraint definition matches + reality. + </para> + + <caution> + <para> + When a foreign table is used as a partition of a partitioned table, + there is an implicit constraint that its contents must satisfy the + partitioning rule. Again, it is the user's responsibility to ensure + that that is true, which is best done by installing a matching + constraint on the remote server. + </para> + </caution> + + <para> + Within a partitioned table containing foreign-table partitions, + an <command>UPDATE</command> that changes the partition key value can + cause a row to be moved from a local partition to a foreign-table + partition, provided the foreign data wrapper supports tuple routing. + However, it is not currently possible to move a row from a + foreign-table partition to another partition. + An <command>UPDATE</command> that would require doing that will fail + due to the partitioning constraint, assuming that that is properly + enforced by the remote server. + </para> + + <para> + Similar considerations apply to generated columns. Stored generated + columns are computed on insert or update on the local + <productname>PostgreSQL</productname> server and handed to the + foreign-data wrapper for writing out to the foreign data store, but it is + not enforced that a query of the foreign table returns values for stored + generated columns that are consistent with the generation expression. + Again, this might result in incorrect query results. + </para> + </refsect1> + + <refsect1 id="sql-createforeigntable-examples"> + <title>Examples</title> + + <para> + Create foreign table <structname>films</structname>, which will be accessed through + the server <structname>film_server</structname>: + +<programlisting> +CREATE FOREIGN TABLE films ( + code char(5) NOT NULL, + title varchar(40) NOT NULL, + did integer NOT NULL, + date_prod date, + kind varchar(10), + len interval hour to minute +) +SERVER film_server; +</programlisting></para> + + <para> + Create foreign table <structname>measurement_y2016m07</structname>, which will be + accessed through the server <structname>server_07</structname>, as a partition + of the range partitioned table <structname>measurement</structname>: + +<programlisting> +CREATE FOREIGN TABLE measurement_y2016m07 + PARTITION OF measurement FOR VALUES FROM ('2016-07-01') TO ('2016-08-01') + SERVER server_07; +</programlisting></para> + + </refsect1> + + <refsect1 id="sql-createforeigntable-compatibility"> + <title>Compatibility</title> + + <para> + The <command>CREATE FOREIGN TABLE</command> command largely conforms to the + <acronym>SQL</acronym> standard; however, much as with + <link linkend="sql-createtable"><command>CREATE TABLE</command></link>, + <literal>NULL</literal> constraints and zero-column foreign tables are permitted. + The ability to specify column default values is also + a <productname>PostgreSQL</productname> extension. Table inheritance, in the form + defined by <productname>PostgreSQL</productname>, is nonstandard. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterforeigntable"/></member> + <member><xref linkend="sql-dropforeigntable"/></member> + <member><xref linkend="sql-createtable"/></member> + <member><xref linkend="sql-createserver"/></member> + <member><xref linkend="sql-importforeignschema"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_function.sgml b/doc/src/sgml/ref/create_function.sgml new file mode 100644 index 0000000..7e6d52c --- /dev/null +++ b/doc/src/sgml/ref/create_function.sgml @@ -0,0 +1,935 @@ +<!-- +doc/src/sgml/ref/create_function.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createfunction"> + <indexterm zone="sql-createfunction"> + <primary>CREATE FUNCTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE FUNCTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE FUNCTION</refname> + <refpurpose>define a new function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] FUNCTION + <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [ { DEFAULT | = } <replaceable class="parameter">default_expr</replaceable> ] [, ...] ] ) + [ RETURNS <replaceable class="parameter">rettype</replaceable> + | RETURNS TABLE ( <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">column_type</replaceable> [, ...] ) ] + { LANGUAGE <replaceable class="parameter">lang_name</replaceable> + | TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ] + | WINDOW + | { IMMUTABLE | STABLE | VOLATILE } + | [ NOT ] LEAKPROOF + | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } + | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } + | PARALLEL { UNSAFE | RESTRICTED | SAFE } + | COST <replaceable class="parameter">execution_cost</replaceable> + | ROWS <replaceable class="parameter">result_rows</replaceable> + | SUPPORT <replaceable class="parameter">support_function</replaceable> + | SET <replaceable class="parameter">configuration_parameter</replaceable> { TO <replaceable class="parameter">value</replaceable> | = <replaceable class="parameter">value</replaceable> | FROM CURRENT } + | AS '<replaceable class="parameter">definition</replaceable>' + | AS '<replaceable class="parameter">obj_file</replaceable>', '<replaceable class="parameter">link_symbol</replaceable>' + | <replaceable class="parameter">sql_body</replaceable> + } ... +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createfunction-description"> + <title>Description</title> + + <para> + <command>CREATE FUNCTION</command> defines a new function. + <command>CREATE OR REPLACE FUNCTION</command> will either create a + new function, or replace an existing definition. + To be able to define a function, the user must have the + <literal>USAGE</literal> privilege on the language. + </para> + + <para> + If a schema name is included, then the function is created in the + specified schema. Otherwise it is created in the current schema. + The name of the new function must not match any existing function or procedure + with the same input argument types in the same schema. However, + functions and procedures of different argument types can share a name (this is + called <firstterm>overloading</firstterm>). + </para> + + <para> + To replace the current definition of an existing function, use + <command>CREATE OR REPLACE FUNCTION</command>. It is not possible + to change the name or argument types of a function this way (if you + tried, you would actually be creating a new, distinct function). + Also, <command>CREATE OR REPLACE FUNCTION</command> will not let + you change the return type of an existing function. To do that, + you must drop and recreate the function. (When using <literal>OUT</literal> + parameters, that means you cannot change the types of any + <literal>OUT</literal> parameters except by dropping the function.) + </para> + + <para> + When <command>CREATE OR REPLACE FUNCTION</command> is used to replace an + existing function, the ownership and permissions of the function + do not change. All other function properties are assigned the + values specified or implied in the command. You must own the function + to replace it (this includes being a member of the owning role). + </para> + + <para> + If you drop and then recreate a function, the new function is not + the same entity as the old; you will have to drop existing rules, views, + triggers, etc. that refer to the old function. Use + <command>CREATE OR REPLACE FUNCTION</command> to change a function + definition without breaking objects that refer to the function. + Also, <command>ALTER FUNCTION</command> can be used to change most of the + auxiliary properties of an existing function. + </para> + + <para> + The user that creates the function becomes the owner of the function. + </para> + + <para> + To be able to create a function, you must have <literal>USAGE</literal> + privilege on the argument types and the return type. + </para> + + <para> + Refer to <xref linkend="xfunc"/> for further information on writing + functions. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + + <listitem> + <para> + The name (optionally schema-qualified) of the function to create. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Only <literal>OUT</literal> arguments can follow a <literal>VARIADIC</literal> one. + Also, <literal>OUT</literal> and <literal>INOUT</literal> arguments cannot be used + together with the <literal>RETURNS TABLE</literal> notation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. Some languages (including SQL and PL/pgSQL) + let you use the name in the function body. For other languages the + name of an input argument is just extra documentation, so far as + the function itself is concerned; but you can use input argument names + when calling a function to improve readability (see <xref + linkend="sql-syntax-calling-funcs"/>). In any case, the name + of an output argument is significant, because it defines the column + name in the result row type. (If you omit the name for an output + argument, the system will choose a default column name.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the function's arguments (optionally + schema-qualified), if any. The argument types can be base, composite, + or domain types, or can reference the type of a table column. + </para> + <para> + Depending on the implementation language it might also be allowed + to specify <quote>pseudo-types</quote> such as <type>cstring</type>. + Pseudo-types indicate that the actual argument type is either + incompletely specified, or outside the set of ordinary SQL data types. + </para> + <para> + The type of a column is referenced by writing + <literal><replaceable + class="parameter">table_name</replaceable>.<replaceable + class="parameter">column_name</replaceable>%TYPE</literal>. + Using this feature can sometimes help make a function independent of + changes to the definition of a table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">default_expr</replaceable></term> + + <listitem> + <para> + An expression to be used as default value if the parameter is + not specified. The expression has to be coercible to the + argument type of the parameter. + Only input (including <literal>INOUT</literal>) parameters can have a default + value. All input parameters following a + parameter with a default value must have default values as well. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">rettype</replaceable></term> + + <listitem> + <para> + The return data type (optionally schema-qualified). The return type + can be a base, composite, or domain type, + or can reference the type of a table column. + Depending on the implementation language it might also be allowed + to specify <quote>pseudo-types</quote> such as <type>cstring</type>. + If the function is not supposed to return a value, specify + <type>void</type> as the return type. + </para> + <para> + When there are <literal>OUT</literal> or <literal>INOUT</literal> parameters, + the <literal>RETURNS</literal> clause can be omitted. If present, it + must agree with the result type implied by the output parameters: + <literal>RECORD</literal> if there are multiple output parameters, or + the same type as the single output parameter. + </para> + <para> + The <literal>SETOF</literal> + modifier indicates that the function will return a set of + items, rather than a single item. + </para> + <para> + The type of a column is referenced by writing + <literal><replaceable + class="parameter">table_name</replaceable>.<replaceable + class="parameter">column_name</replaceable>%TYPE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + + <listitem> + <para> + The name of an output column in the <literal>RETURNS TABLE</literal> + syntax. This is effectively another way of declaring a named + <literal>OUT</literal> parameter, except that <literal>RETURNS TABLE</literal> + also implies <literal>RETURNS SETOF</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_type</replaceable></term> + + <listitem> + <para> + The data type of an output column in the <literal>RETURNS TABLE</literal> + syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lang_name</replaceable></term> + + <listitem> + <para> + The name of the language that the function is implemented in. + It can be <literal>sql</literal>, <literal>c</literal>, + <literal>internal</literal>, or the name of a user-defined + procedural language, e.g., <literal>plpgsql</literal>. The default is + <literal>sql</literal> if <replaceable + class="parameter">sql_body</replaceable> is specified. Enclosing the + name in single quotes is deprecated and requires matching case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ] }</literal></term> + + <listitem> + <para> + Lists which transforms a call to the function should apply. Transforms + convert between SQL types and language-specific data types; + see <xref linkend="sql-createtransform"/>. Procedural language + implementations usually have hardcoded knowledge of the built-in types, + so those don't need to be listed here. If a procedural language + implementation does not know how to handle a type and no transform is + supplied, it will fall back to a default behavior for converting data + types, but this depends on the implementation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WINDOW</literal></term> + + <listitem> + <para><literal>WINDOW</literal> indicates that the function is a + <firstterm>window function</firstterm> rather than a plain function. + This is currently only useful for functions written in C. + The <literal>WINDOW</literal> attribute cannot be changed when + replacing an existing function definition. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IMMUTABLE</literal></term> + <term><literal>STABLE</literal></term> + <term><literal>VOLATILE</literal></term> + + <listitem> + <para> + These attributes inform the query optimizer about the behavior + of the function. At most one choice + can be specified. If none of these appear, + <literal>VOLATILE</literal> is the default assumption. + </para> + + <para><literal>IMMUTABLE</literal> indicates that the function + cannot modify the database and always + returns the same result when given the same argument values; that + is, it does not do database lookups or otherwise use information not + directly present in its argument list. If this option is given, + any call of the function with all-constant arguments can be + immediately replaced with the function value. + </para> + + <para><literal>STABLE</literal> indicates that the function + cannot modify the database, + and that within a single table scan it will consistently + return the same result for the same argument values, but that its + result could change across SQL statements. This is the appropriate + selection for functions whose results depend on database lookups, + parameter variables (such as the current time zone), etc. (It is + inappropriate for <literal>AFTER</literal> triggers that wish to + query rows modified by the current command.) Also note + that the <function>current_timestamp</function> family of functions qualify + as stable, since their values do not change within a transaction. + </para> + + <para><literal>VOLATILE</literal> indicates that the function value can + change even within a single table scan, so no optimizations can be + made. Relatively few database functions are volatile in this sense; + some examples are <literal>random()</literal>, <literal>currval()</literal>, + <literal>timeofday()</literal>. But note that any function that has + side-effects must be classified volatile, even if its result is quite + predictable, to prevent calls from being optimized away; an example is + <literal>setval()</literal>. + </para> + + <para> + For additional details see <xref linkend="xfunc-volatility"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LEAKPROOF</literal></term> + <listitem> + <para> + <literal>LEAKPROOF</literal> indicates that the function has no side + effects. It reveals no information about its arguments other than by + its return value. For example, a function which throws an error message + for some argument values but not others, or which includes the argument + values in any error message, is not leakproof. This affects how the + system executes queries against views created with the + <literal>security_barrier</literal> option or tables with row level + security enabled. The system will enforce conditions from security + policies and security barrier views before any user-supplied conditions + from the query itself that contain non-leakproof functions, in order to + prevent the inadvertent exposure of data. Functions and operators + marked as leakproof are assumed to be trustworthy, and may be executed + before conditions from security policies and security barrier views. + In addition, functions which do not take arguments or which are not + passed any arguments from the security barrier view or table do not have + to be marked as leakproof to be executed before security conditions. See + <xref linkend="sql-createview"/> and <xref linkend="rules-privileges"/>. + This option can only be set by the superuser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CALLED ON NULL INPUT</literal></term> + <term><literal>RETURNS NULL ON NULL INPUT</literal></term> + <term><literal>STRICT</literal></term> + + <listitem> + <para><literal>CALLED ON NULL INPUT</literal> (the default) indicates + that the function will be called normally when some of its + arguments are null. It is then the function author's + responsibility to check for null values if necessary and respond + appropriately. + </para> + + <para><literal>RETURNS NULL ON NULL INPUT</literal> or + <literal>STRICT</literal> indicates that the function always + returns null whenever any of its arguments are null. If this + parameter is specified, the function is not executed when there + are null arguments; instead a null result is assumed + automatically. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><optional>EXTERNAL</optional> SECURITY INVOKER</literal></term> + <term><literal><optional>EXTERNAL</optional> SECURITY DEFINER</literal></term> + + <listitem> + <para><literal>SECURITY INVOKER</literal> indicates that the function + is to be executed with the privileges of the user that calls it. + That is the default. <literal>SECURITY DEFINER</literal> + specifies that the function is to be executed with the + privileges of the user that owns it. + </para> + + <para> + The key word <literal>EXTERNAL</literal> is allowed for SQL + conformance, but it is optional since, unlike in SQL, this feature + applies to all functions not only external ones. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARALLEL</literal></term> + + <listitem> + <para><literal>PARALLEL UNSAFE</literal> indicates that the function + can't be executed in parallel mode and the presence of such a + function in an SQL statement forces a serial execution plan. This is + the default. <literal>PARALLEL RESTRICTED</literal> indicates that + the function can be executed in parallel mode, but the execution is + restricted to parallel group leader. <literal>PARALLEL SAFE</literal> + indicates that the function is safe to run in parallel mode without + restriction. + </para> + + <para> + Functions should be labeled parallel unsafe if they modify any database + state, or if they make changes to the transaction such as using + sub-transactions, or if they access sequences or attempt to make + persistent changes to settings (e.g., <literal>setval</literal>). They should + be labeled as parallel restricted if they access temporary tables, + client connection state, cursors, prepared statements, or miscellaneous + backend-local state which the system cannot synchronize in parallel mode + (e.g., <literal>setseed</literal> cannot be executed other than by the group + leader because a change made by another process would not be reflected + in the leader). In general, if a function is labeled as being safe when + it is restricted or unsafe, or if it is labeled as being restricted when + it is in fact unsafe, it may throw errors or produce wrong answers + when used in a parallel query. C-language functions could in theory + exhibit totally undefined behavior if mislabeled, since there is no way + for the system to protect itself against arbitrary C code, but in most + likely cases the result will be no worse than for any other function. + If in doubt, functions should be labeled as <literal>UNSAFE</literal>, which is + the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term> + + <listitem> + <para> + A positive number giving the estimated execution cost for the function, + in units of <xref linkend="guc-cpu-operator-cost"/>. If the function + returns a set, this is the cost per returned row. If the cost is + not specified, 1 unit is assumed for C-language and internal functions, + and 100 units for functions in all other languages. Larger values + cause the planner to try to avoid evaluating the function more often + than necessary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term> + + <listitem> + <para> + A positive number giving the estimated number of rows that the planner + should expect the function to return. This is only allowed when the + function is declared to return a set. The default assumption is + 1000 rows. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SUPPORT</literal> <replaceable class="parameter">support_function</replaceable></term> + + <listitem> + <para> + The name (optionally schema-qualified) of a <firstterm>planner support + function</firstterm> to use for this function. See + <xref linkend="xfunc-optimization"/> for details. + You must be superuser to use this option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + The <literal>SET</literal> clause causes the specified configuration + parameter to be set to the specified value when the function is + entered, and then restored to its prior value when the function exits. + <literal>SET FROM CURRENT</literal> saves the value of the parameter that + is current when <command>CREATE FUNCTION</command> is executed as the value + to be applied when the function is entered. + </para> + + <para> + If a <literal>SET</literal> clause is attached to a function, then + the effects of a <command>SET LOCAL</command> command executed inside the + function for the same variable are restricted to the function: the + configuration parameter's prior value is still restored at function exit. + However, an ordinary + <command>SET</command> command (without <literal>LOCAL</literal>) overrides the + <literal>SET</literal> clause, much as it would do for a previous <command>SET + LOCAL</command> command: the effects of such a command will persist after + function exit, unless the current transaction is rolled back. + </para> + + <para> + See <xref linkend="sql-set"/> and + <xref linkend="runtime-config"/> + for more information about allowed parameter names and values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">definition</replaceable></term> + + <listitem> + <para> + A string constant defining the function; the meaning depends on the + language. It can be an internal function name, the path to an + object file, an SQL command, or text in a procedural language. + </para> + + <para> + It is often helpful to use dollar quoting (see <xref + linkend="sql-syntax-dollar-quoting"/>) to write the function definition + string, rather than the normal single quote syntax. Without dollar + quoting, any single quotes or backslashes in the function definition must + be escaped by doubling them. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></literal></term> + + <listitem> + <para> + This form of the <literal>AS</literal> clause is used for + dynamically loadable C language functions when the function name + in the C language source code is not the same as the name of + the SQL function. The string <replaceable + class="parameter">obj_file</replaceable> is the name of the shared + library file containing the compiled C function, and is interpreted + as for the <link linkend="sql-load"><command>LOAD</command></link> command. The string + <replaceable class="parameter">link_symbol</replaceable> is the + function's link symbol, that is, the name of the function in the C + language source code. If the link symbol is omitted, it is assumed to + be the same as the name of the SQL function being defined. The C names + of all functions must be different, so you must give overloaded C + functions different C names (for example, use the argument types as + part of the C names). + </para> + + <para> + When repeated <command>CREATE FUNCTION</command> calls refer to + the same object file, the file is only loaded once per session. + To unload and + reload the file (perhaps during development), start a new session. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sql_body</replaceable></term> + + <listitem> + <para> + The body of a <literal>LANGUAGE SQL</literal> function. This can + either be a single statement +<programlisting> +RETURN <replaceable>expression</replaceable> +</programlisting> + or a block +<programlisting> +BEGIN ATOMIC + <replaceable>statement</replaceable>; + <replaceable>statement</replaceable>; + ... + <replaceable>statement</replaceable>; +END +</programlisting> + </para> + + <para> + This is similar to writing the text of the function body as a string + constant (see <replaceable>definition</replaceable> above), but there + are some differences: This form only works for <literal>LANGUAGE + SQL</literal>, the string constant form works for all languages. This + form is parsed at function definition time, the string constant form is + parsed at execution time; therefore this form cannot support + polymorphic argument types and other constructs that are not resolvable + at function definition time. This form tracks dependencies between the + function and objects used in the function body, so <literal>DROP + ... CASCADE</literal> will work correctly, whereas the form using + string literals may leave dangling functions. Finally, this form is + more compatible with the SQL standard and other SQL implementations. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1 id="sql-createfunction-overloading"> + <title>Overloading</title> + + <para> + <productname>PostgreSQL</productname> allows function + <firstterm>overloading</firstterm>; that is, the same name can be + used for several different functions so long as they have distinct + input argument types. Whether or not you use it, this capability entails + security precautions when calling functions in databases where some users + mistrust other users; see <xref linkend="typeconv-func"/>. + </para> + + <para> + Two functions are considered the same if they have the same names and + <emphasis>input</emphasis> argument types, ignoring any <literal>OUT</literal> + parameters. Thus for example these declarations conflict: +<programlisting> +CREATE FUNCTION foo(int) ... +CREATE FUNCTION foo(int, out text) ... +</programlisting> + </para> + + <para> + Functions that have different argument type lists will not be considered + to conflict at creation time, but if defaults are provided they might + conflict in use. For example, consider +<programlisting> +CREATE FUNCTION foo(int) ... +CREATE FUNCTION foo(int, int default 42) ... +</programlisting> + A call <literal>foo(10)</literal> will fail due to the ambiguity about which + function should be called. + </para> + + </refsect1> + + <refsect1 id="sql-createfunction-notes"> + <title>Notes</title> + + <para> + The full <acronym>SQL</acronym> type syntax is allowed for + declaring a function's arguments and return value. However, + parenthesized type modifiers (e.g., the precision field for + type <type>numeric</type>) are discarded by <command>CREATE FUNCTION</command>. + Thus for example + <literal>CREATE FUNCTION foo (varchar(10)) ...</literal> + is exactly the same as + <literal>CREATE FUNCTION foo (varchar) ...</literal>. + </para> + + <para> + When replacing an existing function with <command>CREATE OR REPLACE + FUNCTION</command>, there are restrictions on changing parameter names. + You cannot change the name already assigned to any input parameter + (although you can add names to parameters that had none before). + If there is more than one output parameter, you cannot change the + names of the output parameters, because that would change the + column names of the anonymous composite type that describes the + function's result. These restrictions are made to ensure that + existing calls of the function do not stop working when it is replaced. + </para> + + <para> + If a function is declared <literal>STRICT</literal> with a <literal>VARIADIC</literal> + argument, the strictness check tests that the variadic array <emphasis>as + a whole</emphasis> is non-null. The function will still be called if the + array has null elements. + </para> + + </refsect1> + + <refsect1 id="sql-createfunction-examples"> + <title>Examples</title> + + <para> + Add two integers using an SQL function: +<programlisting> +CREATE FUNCTION add(integer, integer) RETURNS integer + AS 'select $1 + $2;' + LANGUAGE SQL + IMMUTABLE + RETURNS NULL ON NULL INPUT; +</programlisting> + The same function written in a more SQL-conforming style, using argument + names and an unquoted body: +<programlisting> +CREATE FUNCTION add(a integer, b integer) RETURNS integer + LANGUAGE SQL + IMMUTABLE + RETURNS NULL ON NULL INPUT + RETURN a + b; +</programlisting> + </para> + + <para> + Increment an integer, making use of an argument name, in + <application>PL/pgSQL</application>: +<programlisting> +CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$ + BEGIN + RETURN i + 1; + END; +$$ LANGUAGE plpgsql; +</programlisting> + </para> + + <para> + Return a record containing multiple output parameters: +<programlisting> +CREATE FUNCTION dup(in int, out f1 int, out f2 text) + AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ + LANGUAGE SQL; + +SELECT * FROM dup(42); +</programlisting> + You can do the same thing more verbosely with an explicitly named + composite type: +<programlisting> +CREATE TYPE dup_result AS (f1 int, f2 text); + +CREATE FUNCTION dup(int) RETURNS dup_result + AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ + LANGUAGE SQL; + +SELECT * FROM dup(42); +</programlisting> + Another way to return multiple columns is to use a <literal>TABLE</literal> + function: +<programlisting> +CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text) + AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ + LANGUAGE SQL; + +SELECT * FROM dup(42); +</programlisting> + However, a <literal>TABLE</literal> function is different from the + preceding examples, because it actually returns a <emphasis>set</emphasis> + of records, not just one record. + </para> + </refsect1> + + <refsect1 id="sql-createfunction-security"> + <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title> + + <indexterm> + <primary><varname>search_path</varname> configuration parameter</primary> + <secondary>use in securing functions</secondary> + </indexterm> + + <para> + Because a <literal>SECURITY DEFINER</literal> function is executed + with the privileges of the user that owns it, care is needed to + ensure that the function cannot be misused. For security, + <xref linkend="guc-search-path"/> should be set to exclude any schemas + writable by untrusted users. This prevents + malicious users from creating objects (e.g., tables, functions, and + operators) that mask objects intended to be used by the function. + Particularly important in this regard is the + temporary-table schema, which is searched first by default, and + is normally writable by anyone. A secure arrangement can be obtained + by forcing the temporary schema to be searched last. To do this, + write <literal>pg_temp</literal><indexterm><primary>pg_temp</primary><secondary>securing functions</secondary></indexterm> as the last entry in <varname>search_path</varname>. + This function illustrates safe usage: + +<programlisting> +CREATE FUNCTION check_password(uname TEXT, pass TEXT) +RETURNS BOOLEAN AS $$ +DECLARE passed BOOLEAN; +BEGIN + SELECT (pwd = $2) INTO passed + FROM pwds + WHERE username = $1; + + RETURN passed; +END; +$$ LANGUAGE plpgsql + SECURITY DEFINER + -- Set a secure search_path: trusted schema(s), then 'pg_temp'. + SET search_path = admin, pg_temp; +</programlisting> + + This function's intention is to access a table <literal>admin.pwds</literal>. + But without the <literal>SET</literal> clause, or with a <literal>SET</literal> clause + mentioning only <literal>admin</literal>, the function could be subverted by + creating a temporary table named <literal>pwds</literal>. + </para> + + <para> + Before <productname>PostgreSQL</productname> version 8.3, the + <literal>SET</literal> clause was not available, and so older functions may + contain rather complicated logic to save, set, and restore + <varname>search_path</varname>. The <literal>SET</literal> clause is far easier + to use for this purpose. + </para> + + <para> + Another point to keep in mind is that by default, execute privilege + is granted to <literal>PUBLIC</literal> for newly created functions + (see <xref linkend="ddl-priv"/> for more + information). Frequently you will wish to restrict use of a security + definer function to only some users. To do that, you must revoke + the default <literal>PUBLIC</literal> privileges and then grant execute + privilege selectively. To avoid having a window where the new function + is accessible to all, create it and set the privileges within a single + transaction. For example: + </para> + +<programlisting> +BEGIN; +CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER; +REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins; +COMMIT; +</programlisting> + + </refsect1> + + <refsect1 id="sql-createfunction-compat"> + <title>Compatibility</title> + + <para> + A <command>CREATE FUNCTION</command> command is defined in the SQL + standard. The <productname>PostgreSQL</productname> implementation can be + used in a compatible way but has many extensions. Conversely, the SQL + standard specifies a number of optional features that are not implemented + in <productname>PostgreSQL</productname>. + </para> + + <para> + The following are important compatibility issues: + + <itemizedlist> + <listitem> + <para> + <literal>OR REPLACE</literal> is a PostgreSQL extension. + </para> + </listitem> + + <listitem> + <para> + For compatibility with some other database systems, <replaceable + class="parameter">argmode</replaceable> can be written either before or + after <replaceable class="parameter">argname</replaceable>. But only + the first way is standard-compliant. + </para> + </listitem> + + <listitem> + <para> + For parameter defaults, the SQL standard specifies only the syntax with + the <literal>DEFAULT</literal> key word. The syntax with + <literal>=</literal> is used in T-SQL and Firebird. + </para> + </listitem> + + <listitem> + <para> + The <literal>SETOF</literal> modifier is a PostgreSQL extension. + </para> + </listitem> + + <listitem> + <para> + Only <literal>SQL</literal> is standardized as a language. + </para> + </listitem> + + <listitem> + <para> + All other attributes except <literal>CALLED ON NULL INPUT</literal> and + <literal>RETURNS NULL ON NULL INPUT</literal> are not standardized. + </para> + </listitem> + + <listitem> + <para> + For the body of <literal>LANGUAGE SQL</literal> functions, the SQL + standard only specifies the <replaceable>sql_body</replaceable> form. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + Simple <literal>LANGUAGE SQL</literal> functions can be written in a way + that is both standard-conforming and portable to other implementations. + More complex functions using advanced features, optimization attributes, or + other languages will necessarily be specific to PostgreSQL in a significant + way. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterfunction"/></member> + <member><xref linkend="sql-dropfunction"/></member> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-load"/></member> + <member><xref linkend="sql-revoke"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_group.sgml b/doc/src/sgml/ref/create_group.sgml new file mode 100644 index 0000000..d124c98 --- /dev/null +++ b/doc/src/sgml/ref/create_group.sgml @@ -0,0 +1,72 @@ +<!-- +doc/src/sgml/ref/create_group.sgml +PostgreSQL documentation +--> + +<refentry id="sql-creategroup"> + <indexterm zone="sql-creategroup"> + <primary>CREATE GROUP</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE GROUP</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE GROUP</refname> + <refpurpose>define a new database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE GROUP <replaceable class="parameter">name</replaceable> [ [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + SUPERUSER | NOSUPERUSER + | CREATEDB | NOCREATEDB + | CREATEROLE | NOCREATEROLE + | INHERIT | NOINHERIT + | LOGIN | NOLOGIN + | REPLICATION | NOREPLICATION + | BYPASSRLS | NOBYPASSRLS + | CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + | [ ENCRYPTED ] PASSWORD '<replaceable class="parameter">password</replaceable>' | PASSWORD NULL + | VALID UNTIL '<replaceable class="parameter">timestamp</replaceable>' + | IN ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | IN GROUP <replaceable class="parameter">role_name</replaceable> [, ...] + | ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | ADMIN <replaceable class="parameter">role_name</replaceable> [, ...] + | USER <replaceable class="parameter">role_name</replaceable> [, ...] + | SYSID <replaceable class="parameter">uid</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE GROUP</command> is now an alias for + <xref linkend="sql-createrole"/>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CREATE GROUP</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrole"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_index.sgml b/doc/src/sgml/ref/create_index.sgml new file mode 100644 index 0000000..40986aa --- /dev/null +++ b/doc/src/sgml/ref/create_index.sgml @@ -0,0 +1,999 @@ +<!-- +doc/src/sgml/ref/create_index.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createindex"> + <indexterm zone="sql-createindex"> + <primary>CREATE INDEX</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE INDEX</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE INDEX</refname> + <refpurpose>define a new index</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] <replaceable class="parameter">name</replaceable> ] ON [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ USING <replaceable class="parameter">method</replaceable> ] + ( { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">opclass</replaceable> [ ( <replaceable class="parameter">opclass_parameter</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ) + [ INCLUDE ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] + [ NULLS [ NOT ] DISTINCT ] + [ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] + [ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + [ WHERE <replaceable class="parameter">predicate</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE INDEX</command> constructs an index on the specified column(s) + of the specified relation, which can be a table or a materialized view. + Indexes are primarily used to enhance database performance (though + inappropriate use can result in slower performance). + </para> + + <para> + The key field(s) for the index are specified as column names, + or alternatively as expressions written in parentheses. + Multiple fields can be specified if the index method supports + multicolumn indexes. + </para> + + <para> + An index field can be an expression computed from the values of + one or more columns of the table row. This feature can be used + to obtain fast access to data based on some transformation of + the basic data. For example, an index computed on + <literal>upper(col)</literal> would allow the clause + <literal>WHERE upper(col) = 'JIM'</literal> to use an index. + </para> + + <para> + <productname>PostgreSQL</productname> provides the index methods + B-tree, hash, GiST, SP-GiST, GIN, and BRIN. Users can also define their own + index methods, but that is fairly complicated. + </para> + + <para> + When the <literal>WHERE</literal> clause is present, a + <firstterm>partial index</firstterm> is created. + A partial index is an index that contains entries for only a portion of + a table, usually a portion that is more useful for indexing than the + rest of the table. For example, if you have a table that contains both + billed and unbilled orders where the unbilled orders take up a small + fraction of the total table and yet that is an often used section, you + can improve performance by creating an index on just that portion. + Another possible application is to use <literal>WHERE</literal> with + <literal>UNIQUE</literal> to enforce uniqueness over a subset of a + table. See <xref linkend="indexes-partial"/> for more discussion. + </para> + + <para> + The expression used in the <literal>WHERE</literal> clause can refer + only to columns of the underlying table, but it can use all columns, + not just the ones being indexed. Presently, subqueries and + aggregate expressions are also forbidden in <literal>WHERE</literal>. + The same restrictions apply to index fields that are expressions. + </para> + + <para> + All functions and operators used in an index definition must be + <quote>immutable</quote>, that is, their results must depend only on + their arguments and never on any outside influence (such as + the contents of another table or the current time). This restriction + ensures that the behavior of the index is well-defined. To use a + user-defined function in an index expression or <literal>WHERE</literal> + clause, remember to mark the function immutable when you create it. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>UNIQUE</literal></term> + <listitem> + <para> + Causes the system to check for + duplicate values in the table when the index is created (if data + already exist) and each time data is added. Attempts to + insert or update data which would result in duplicate entries + will generate an error. + </para> + + <para> + Additional restrictions apply when unique indexes are applied to + partitioned tables; see <xref linkend="sql-createtable" />. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONCURRENTLY</literal></term> + <listitem> + <para> + When this option is used, <productname>PostgreSQL</productname> will build the + index without taking any locks that prevent concurrent inserts, + updates, or deletes on the table; whereas a standard index build + locks out writes (but not reads) on the table until it's done. + There are several caveats to be aware of when using this option + — see <xref linkend="sql-createindex-concurrently"/> below. + </para> + <para> + For temporary tables, <command>CREATE INDEX</command> is always + non-concurrent, as no other session can access them, and + non-concurrent index creation is cheaper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a relation with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing index is anything like the one that would have been created. + Index name is required when <literal>IF NOT EXISTS</literal> is specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDE</literal></term> + <listitem> + <para> + The optional <literal>INCLUDE</literal> clause specifies a + list of columns which will be included in the index + as <firstterm>non-key</firstterm> columns. A non-key column cannot + be used in an index scan search qualification, and it is disregarded + for purposes of any uniqueness or exclusion constraint enforced by + the index. However, an index-only scan can return the contents of + non-key columns without having to visit the index's table, since + they are available directly from the index entry. Thus, addition of + non-key columns allows index-only scans to be used for queries that + otherwise could not use them. + </para> + + <para> + It's wise to be conservative about adding non-key columns to an + index, especially wide columns. If an index tuple exceeds the + maximum size allowed for the index type, data insertion will fail. + In any case, non-key columns duplicate data from the index's table + and bloat the size of the index, thus potentially slowing searches. + Furthermore, B-tree deduplication is never used with indexes + that have a non-key column. + </para> + + <para> + Columns listed in the <literal>INCLUDE</literal> clause don't need + appropriate operator classes; the clause can include + columns whose data types don't have operator classes defined for + a given access method. + </para> + + <para> + Expressions are not supported as included columns since they cannot be + used in index-only scans. + </para> + + <para> + Currently, the B-tree, GiST and SP-GiST index access methods support + this feature. In these indexes, the values of columns listed + in the <literal>INCLUDE</literal> clause are included in leaf tuples + which correspond to heap tuples, but are not included in upper-level + index entries used for tree navigation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the index to be created. No schema name can be included + here; the index is always created in the same schema as its parent + table. The name of the index must be distinct from the name of any + other relation (table, sequence, index, view, materialized view, or + foreign table) in that schema. + If the name is omitted, <productname>PostgreSQL</productname> chooses a + suitable name based on the parent table's name and the indexed column + name(s). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ONLY</literal></term> + <listitem> + <para> + Indicates not to recurse creating indexes on partitions, if the + table is partitioned. The default is to recurse. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (possibly schema-qualified) of the table to be indexed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">method</replaceable></term> + <listitem> + <para> + The name of the index method to be used. Choices are + <literal>btree</literal>, <literal>hash</literal>, + <literal>gist</literal>, <literal>spgist</literal>, <literal>gin</literal>, + <literal>brin</literal>, or user-installed access methods like + <link linkend="bloom">bloom</link>. + The default method is <literal>btree</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column of the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + An expression based on one or more columns of the table. The + expression usually must be written with surrounding parentheses, + as shown in the syntax. However, the parentheses can be omitted + if the expression has the form of a function call. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">collation</replaceable></term> + <listitem> + <para> + The name of the collation to use for the index. By default, + the index uses the collation declared for the column to be + indexed or the result collation of the expression to be + indexed. Indexes with non-default collations can be useful for + queries that involve expressions using non-default collations. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">opclass</replaceable></term> + <listitem> + <para> + The name of an operator class. See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">opclass_parameter</replaceable></term> + <listitem> + <para> + The name of an operator class parameter. See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ASC</literal></term> + <listitem> + <para> + Specifies ascending sort order (which is the default). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DESC</literal></term> + <listitem> + <para> + Specifies descending sort order. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULLS FIRST</literal></term> + <listitem> + <para> + Specifies that nulls sort before non-nulls. This is the default + when <literal>DESC</literal> is specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULLS LAST</literal></term> + <listitem> + <para> + Specifies that nulls sort after non-nulls. This is the default + when <literal>DESC</literal> is not specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULLS DISTINCT</literal></term> + <term><literal>NULLS NOT DISTINCT</literal></term> + <listitem> + <para> + Specifies whether for a unique index, null values should be considered + distinct (not equal). The default is that they are distinct, so that + a unique index could contain multiple null values in a column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">storage_parameter</replaceable></term> + <listitem> + <para> + The name of an index-method-specific storage parameter. See + <xref linkend="sql-createindex-storage-parameters"/> below + for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">tablespace_name</replaceable></term> + <listitem> + <para> + The tablespace in which to create the index. If not specified, + <xref linkend="guc-default-tablespace"/> is consulted, or + <xref linkend="guc-temp-tablespaces"/> for indexes on temporary + tables. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">predicate</replaceable></term> + <listitem> + <para> + The constraint expression for a partial index. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <refsect2 id="sql-createindex-storage-parameters" xreflabel="Index Storage Parameters"> + <title>Index Storage Parameters</title> + + <para> + The optional <literal>WITH</literal> clause specifies <firstterm>storage + parameters</firstterm> for the index. Each index method has its own set of allowed + storage parameters. The B-tree, hash, GiST and SP-GiST index methods all + accept this parameter: + </para> + + <variablelist> + <varlistentry id="index-reloption-fillfactor" xreflabel="fillfactor"> + <term><literal>fillfactor</literal> (<type>integer</type>) + <indexterm> + <primary><varname>fillfactor</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + The fillfactor for an index is a percentage that determines how full + the index method will try to pack index pages. For B-trees, leaf pages + are filled to this percentage during initial index builds, and also + when extending the index at the right (adding new largest key values). + If pages + subsequently become completely full, they will be split, leading to + fragmentation of the on-disk index structure. B-trees use a default + fillfactor of 90, but any integer value from 10 to 100 can be selected. + </para> + <para> + B-tree indexes on tables where many inserts and/or updates are + anticipated can benefit from lower fillfactor settings at + <command>CREATE INDEX</command> time (following bulk loading into the + table). Values in the range of 50 - 90 can usefully <quote>smooth + out</quote> the <emphasis>rate</emphasis> of page splits during the + early life of the B-tree index (lowering fillfactor like this may even + lower the absolute number of page splits, though this effect is highly + workload dependent). The B-tree bottom-up index deletion technique + described in <xref linkend="btree-deletion"/> is dependent on having + some <quote>extra</quote> space on pages to store <quote>extra</quote> + tuple versions, and so can be affected by fillfactor (though the effect + is usually not significant). + </para> + <para> + In other specific cases it might be useful to increase fillfactor to + 100 at <command>CREATE INDEX</command> time as a way of maximizing + space utilization. You should only consider this when you are + completely sure that the table is static (i.e. that it will never be + affected by either inserts or updates). A fillfactor setting of 100 + otherwise risks <emphasis>harming</emphasis> performance: even a few + updates or inserts will cause a sudden flood of page splits. + </para> + <para> + The other index methods use fillfactor in different but roughly + analogous ways; the default fillfactor varies between methods. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + B-tree indexes additionally accept this parameter: + </para> + + <variablelist> + <varlistentry id="index-reloption-deduplicate-items" xreflabel="deduplicate_items"> + <term><literal>deduplicate_items</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>deduplicate_items</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Controls usage of the B-tree deduplication technique described + in <xref linkend="btree-deduplication"/>. Set to + <literal>ON</literal> or <literal>OFF</literal> to enable or + disable the optimization. (Alternative spellings of + <literal>ON</literal> and <literal>OFF</literal> are allowed as + described in <xref linkend="config-setting"/>.) The default is + <literal>ON</literal>. + </para> + + <note> + <para> + Turning <literal>deduplicate_items</literal> off via + <command>ALTER INDEX</command> prevents future insertions from + triggering deduplication, but does not in itself make existing + posting list tuples use the standard tuple representation. + </para> + </note> + </listitem> + </varlistentry> + </variablelist> + + <para> + GiST indexes additionally accept this parameter: + </para> + + <variablelist> + <varlistentry id="index-reloption-buffering" xreflabel="buffering"> + <term><literal>buffering</literal> (<type>enum</type>) + <indexterm> + <primary><varname>buffering</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Determines whether the buffered build technique described in + <xref linkend="gist-buffering-build"/> is used to build the index. With + <literal>OFF</literal> buffering is disabled, with <literal>ON</literal> + it is enabled, and with <literal>AUTO</literal> it is initially disabled, + but is turned on on-the-fly once the index size reaches + <xref linkend="guc-effective-cache-size"/>. The default + is <literal>AUTO</literal>. + Note that if sorted build is possible, it will be used instead of + buffered build unless <literal>buffering=ON</literal> is specified. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + GIN indexes accept different parameters: + </para> + + <variablelist> + <varlistentry id="index-reloption-fastupdate" xreflabel="fastupdate"> + <term><literal>fastupdate</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>fastupdate</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + This setting controls usage of the fast update technique described in + <xref linkend="gin-fast-update"/>. It is a Boolean parameter: + <literal>ON</literal> enables fast update, <literal>OFF</literal> disables it. + The default is <literal>ON</literal>. + </para> + + <note> + <para> + Turning <literal>fastupdate</literal> off via <command>ALTER INDEX</command> prevents + future insertions from going into the list of pending index entries, + but does not in itself flush previous entries. You might want to + <command>VACUUM</command> the table or call <function>gin_clean_pending_list</function> + function afterward to ensure the pending list is emptied. + </para> + </note> + </listitem> + </varlistentry> + </variablelist> + + <variablelist> + <varlistentry id="index-reloption-gin-pending-list-limit" xreflabel="gin_pending_list_limit"> + <term><literal>gin_pending_list_limit</literal> (<type>integer</type>) + <indexterm> + <primary><varname>gin_pending_list_limit</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Custom <xref linkend="guc-gin-pending-list-limit"/> parameter. + This value is specified in kilobytes. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + <acronym>BRIN</acronym> indexes accept different parameters: + </para> + + <variablelist> + <varlistentry id="index-reloption-pages-per-range" xreflabel="pages_per_range"> + <term><literal>pages_per_range</literal> (<type>integer</type>) + <indexterm> + <primary><varname>pages_per_range</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Defines the number of table blocks that make up one block range for + each entry of a <acronym>BRIN</acronym> index (see <xref linkend="brin-intro"/> + for more details). The default is <literal>128</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="index-reloption-autosummarize" xreflabel="autosummarize"> + <term><literal>autosummarize</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>autosummarize</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Defines whether a summarization run is queued for the previous page + range whenever an insertion is detected on the next one. + See <xref linkend="brin-operation"/> for more details. + The default is <literal>off</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + + <refsect2 id="sql-createindex-concurrently" xreflabel="Building Indexes Concurrently"> + <title>Building Indexes Concurrently</title> + + <indexterm zone="sql-createindex-concurrently"> + <primary>index</primary> + <secondary>building concurrently</secondary> + </indexterm> + + <para> + Creating an index can interfere with regular operation of a database. + Normally <productname>PostgreSQL</productname> locks the table to be indexed against + writes and performs the entire index build with a single scan of the + table. Other transactions can still read the table, but if they try to + insert, update, or delete rows in the table they will block until the + index build is finished. This could have a severe effect if the system is + a live production database. Very large tables can take many hours to be + indexed, and even for smaller tables, an index build can lock out writers + for periods that are unacceptably long for a production system. + </para> + + <para> + <productname>PostgreSQL</productname> supports building indexes without locking + out writes. This method is invoked by specifying the + <literal>CONCURRENTLY</literal> option of <command>CREATE INDEX</command>. + When this option is used, + <productname>PostgreSQL</productname> must perform two scans of the table, and in + addition it must wait for all existing transactions that could potentially + modify or use the index to terminate. Thus + this method requires more total work than a standard index build and takes + significantly longer to complete. However, since it allows normal + operations to continue while the index is built, this method is useful for + adding new indexes in a production environment. Of course, the extra CPU + and I/O load imposed by the index creation might slow other operations. + </para> + + <para> + In a concurrent index build, the index is actually entered as an + <quote>invalid</quote> index into + the system catalogs in one transaction, then two table scans occur in + two more transactions. Before each table scan, the index build must + wait for existing transactions that have modified the table to terminate. + After the second scan, the index build must wait for any transactions + that have a snapshot (see <xref linkend="mvcc"/>) predating the second + scan to terminate, including transactions used by any phase of concurrent + index builds on other tables, if the indexes involved are partial or have + columns that are not simple column references. + Then finally the index can be marked <quote>valid</quote> and ready for use, + and the <command>CREATE INDEX</command> command terminates. + Even then, however, the index may not be immediately usable for queries: + in the worst case, it cannot be used as long as transactions exist that + predate the start of the index build. + </para> + + <para> + If a problem arises while scanning the table, such as a deadlock or a + uniqueness violation in a unique index, the <command>CREATE INDEX</command> + command will fail but leave behind an <quote>invalid</quote> index. This index + will be ignored for querying purposes because it might be incomplete; + however it will still consume update overhead. The <application>psql</application> + <command>\d</command> command will report such an index as <literal>INVALID</literal>: + +<programlisting> +postgres=# \d tab + Table "public.tab" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + col | integer | | | +Indexes: + "idx" btree (col) INVALID +</programlisting> + + The recommended recovery + method in such cases is to drop the index and try again to perform + <command>CREATE INDEX CONCURRENTLY</command>. (Another possibility is + to rebuild the index with <command>REINDEX INDEX CONCURRENTLY</command>). + </para> + + <para> + Another caveat when building a unique index concurrently is that the + uniqueness constraint is already being enforced against other transactions + when the second table scan begins. This means that constraint violations + could be reported in other queries prior to the index becoming available + for use, or even in cases where the index build eventually fails. Also, + if a failure does occur in the second scan, the <quote>invalid</quote> index + continues to enforce its uniqueness constraint afterwards. + </para> + + <para> + Concurrent builds of expression indexes and partial indexes are supported. + Errors occurring in the evaluation of these expressions could cause + behavior similar to that described above for unique constraint violations. + </para> + + <para> + Regular index builds permit other regular index builds on the + same table to occur simultaneously, but only one concurrent index build + can occur on a table at a time. In either case, schema modification of the + table is not allowed while the index is being built. Another difference is + that a regular <command>CREATE INDEX</command> command can be performed + within a transaction block, but <command>CREATE INDEX CONCURRENTLY</command> + cannot. + </para> + + <para> + Concurrent builds for indexes on partitioned tables are currently not + supported. However, you may concurrently build the index on each + partition individually and then finally create the partitioned index + non-concurrently in order to reduce the time where writes to the + partitioned table will be locked out. In this case, building the + partitioned index is a metadata only operation. + </para> + + </refsect2> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + See <xref linkend="indexes"/> for information about when indexes can + be used, when they are not used, and in which particular situations + they can be useful. + </para> + + <para> + Currently, only the B-tree, GiST, GIN, and BRIN index methods support + multiple-key-column indexes. Whether there can be multiple key + columns is independent of whether <literal>INCLUDE</literal> columns + can be added to the index. Indexes can have up to 32 columns, + including <literal>INCLUDE</literal> columns. + (This limit can be altered when building + <productname>PostgreSQL</productname>.) Only B-tree currently + supports unique indexes. + </para> + + <para> + An <firstterm>operator class</firstterm> with optional parameters + can be specified for each column of an index. + The operator class identifies the operators to be + used by the index for that column. For example, a B-tree index on + four-byte integers would use the <literal>int4_ops</literal> class; + this operator class includes comparison functions for four-byte + integers. In practice the default operator class for the column's data + type is usually sufficient. The main point of having operator classes + is that for some data types, there could be more than one meaningful + ordering. For example, we might want to sort a complex-number data + type either by absolute value or by real part. We could do this by + defining two operator classes for the data type and then selecting + the proper class when creating an index. More information about + operator classes is in <xref linkend="indexes-opclass"/> and in <xref + linkend="xindex"/>. + </para> + + <para> + When <literal>CREATE INDEX</literal> is invoked on a partitioned + table, the default behavior is to recurse to all partitions to ensure + they all have matching indexes. + Each partition is first checked to determine whether an equivalent + index already exists, and if so, that index will become attached as a + partition index to the index being created, which will become its + parent index. + If no matching index exists, a new index will be created and + automatically attached; the name of the new index in each partition + will be determined as if no index name had been specified in the + command. + If the <literal>ONLY</literal> option is specified, no recursion + is done, and the index is marked invalid. + (<command>ALTER INDEX ... ATTACH PARTITION</command> marks the index + valid, once all partitions acquire matching indexes.) Note, however, + that any partition that is created in the future using + <command>CREATE TABLE ... PARTITION OF</command> will automatically + have a matching index, regardless of whether <literal>ONLY</literal> is + specified. + </para> + + <para> + For index methods that support ordered scans (currently, only B-tree), + the optional clauses <literal>ASC</literal>, <literal>DESC</literal>, <literal>NULLS + FIRST</literal>, and/or <literal>NULLS LAST</literal> can be specified to modify + the sort ordering of the index. Since an ordered index can be + scanned either forward or backward, it is not normally useful to create a + single-column <literal>DESC</literal> index — that sort ordering is already + available with a regular index. The value of these options is that + multicolumn indexes can be created that match the sort ordering requested + by a mixed-ordering query, such as <literal>SELECT ... ORDER BY x ASC, y + DESC</literal>. The <literal>NULLS</literal> options are useful if you need to support + <quote>nulls sort low</quote> behavior, rather than the default <quote>nulls + sort high</quote>, in queries that depend on indexes to avoid sorting steps. + </para> + + <para> + The system regularly collects statistics on all of a table's + columns. Newly-created non-expression indexes can immediately + use these statistics to determine an index's usefulness. + For new expression indexes, it is necessary to run <link + linkend="sql-analyze"><command>ANALYZE</command></link> or wait for + the <link linkend="autovacuum">autovacuum daemon</link> to analyze + the table to generate statistics for these indexes. + </para> + + <para> + For most index methods, the speed of creating an index is + dependent on the setting of <xref linkend="guc-maintenance-work-mem"/>. + Larger values will reduce the time needed for index creation, so long + as you don't make it larger than the amount of memory really available, + which would drive the machine into swapping. + </para> + + <para> + <productname>PostgreSQL</productname> can build indexes while + leveraging multiple CPUs in order to process the table rows faster. + This feature is known as <firstterm>parallel index + build</firstterm>. For index methods that support building indexes + in parallel (currently, only B-tree), + <varname>maintenance_work_mem</varname> specifies the maximum + amount of memory that can be used by each index build operation as + a whole, regardless of how many worker processes were started. + Generally, a cost model automatically determines how many worker + processes should be requested, if any. + </para> + + <para> + Parallel index builds may benefit from increasing + <varname>maintenance_work_mem</varname> where an equivalent serial + index build will see little or no benefit. Note that + <varname>maintenance_work_mem</varname> may influence the number of + worker processes requested, since parallel workers must have at + least a <literal>32MB</literal> share of the total + <varname>maintenance_work_mem</varname> budget. There must also be + a remaining <literal>32MB</literal> share for the leader process. + Increasing <xref linkend="guc-max-parallel-maintenance-workers"/> + may allow more workers to be used, which will reduce the time + needed for index creation, so long as the index build is not + already I/O bound. Of course, there should also be sufficient + CPU capacity that would otherwise lie idle. + </para> + + <para> + Setting a value for <literal>parallel_workers</literal> via <link + linkend="sql-altertable"><command>ALTER TABLE</command></link> directly controls how many parallel + worker processes will be requested by a <command>CREATE + INDEX</command> against the table. This bypasses the cost model + completely, and prevents <varname>maintenance_work_mem</varname> + from affecting how many parallel workers are requested. Setting + <literal>parallel_workers</literal> to 0 via <command>ALTER + TABLE</command> will disable parallel index builds on the table in + all cases. + </para> + + <tip> + <para> + You might want to reset <literal>parallel_workers</literal> after + setting it as part of tuning an index build. This avoids + inadvertent changes to query plans, since + <literal>parallel_workers</literal> affects + <emphasis>all</emphasis> parallel table scans. + </para> + </tip> + + <para> + While <command>CREATE INDEX</command> with the + <literal>CONCURRENTLY</literal> option supports parallel builds + without special restrictions, only the first table scan is actually + performed in parallel. + </para> + + <para> + Use <link linkend="sql-dropindex"><command>DROP INDEX</command></link> + to remove an index. + </para> + + <para> + Like any long-running transaction, <command>CREATE INDEX</command> on a + table can affect which tuples can be removed by concurrent + <command>VACUUM</command> on any other table. + </para> + + <para> + Prior releases of <productname>PostgreSQL</productname> also had an + R-tree index method. This method has been removed because + it had no significant advantages over the GiST method. + If <literal>USING rtree</literal> is specified, <command>CREATE INDEX</command> + will interpret it as <literal>USING gist</literal>, to simplify conversion + of old databases to GiST. + </para> + + <para> + Each backend running <command>CREATE INDEX</command> will report its + progress in the <structname>pg_stat_progress_create_index</structname> + view. See <xref linkend="create-index-progress-reporting"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To create a unique B-tree index on the column <literal>title</literal> in + the table <literal>films</literal>: +<programlisting> +CREATE UNIQUE INDEX title_idx ON films (title); +</programlisting> + </para> + + <para> + To create a unique B-tree index on the column <literal>title</literal> + with included columns <literal>director</literal> + and <literal>rating</literal> in the table <literal>films</literal>: +<programlisting> +CREATE UNIQUE INDEX title_idx ON films (title) INCLUDE (director, rating); +</programlisting> + </para> + + <para> + To create a B-Tree index with deduplication disabled: +<programlisting> +CREATE INDEX title_idx ON films (title) WITH (deduplicate_items = off); +</programlisting> + </para> + + <para> + To create an index on the expression <literal>lower(title)</literal>, + allowing efficient case-insensitive searches: +<programlisting> +CREATE INDEX ON films ((lower(title))); +</programlisting> + (In this example we have chosen to omit the index name, so the system + will choose a name, typically <literal>films_lower_idx</literal>.) + </para> + + <para> + To create an index with non-default collation: +<programlisting> +CREATE INDEX title_idx_german ON films (title COLLATE "de_DE"); +</programlisting> + </para> + + <para> + To create an index with non-default sort ordering of nulls: +<programlisting> +CREATE INDEX title_idx_nulls_low ON films (title NULLS FIRST); +</programlisting> + </para> + + <para> + To create an index with non-default fill factor: +<programlisting> +CREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70); +</programlisting> + </para> + + <para> + To create a <acronym>GIN</acronym> index with fast updates disabled: +<programlisting> +CREATE INDEX gin_idx ON documents_table USING GIN (locations) WITH (fastupdate = off); +</programlisting> + </para> + + <para> + To create an index on the column <literal>code</literal> in the table + <literal>films</literal> and have the index reside in the tablespace + <literal>indexspace</literal>: +<programlisting> +CREATE INDEX code_idx ON films (code) TABLESPACE indexspace; +</programlisting> + </para> + + <para> + To create a GiST index on a point attribute so that we + can efficiently use box operators on the result of the + conversion function: +<programlisting> +CREATE INDEX pointloc + ON points USING gist (box(location,location)); +SELECT * FROM points + WHERE box(location,location) && '(0,0),(1,1)'::box; +</programlisting> + </para> + + <para> + To create an index without locking out writes to the table: +<programlisting> +CREATE INDEX CONCURRENTLY sales_quantity_index ON sales_table (quantity); +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE INDEX</command> is a + <productname>PostgreSQL</productname> language extension. There + are no provisions for indexes in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterindex"/></member> + <member><xref linkend="sql-dropindex"/></member> + <member><xref linkend="sql-reindex"/></member> + <member><xref linkend="create-index-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_language.sgml b/doc/src/sgml/ref/create_language.sgml new file mode 100644 index 0000000..102efe5 --- /dev/null +++ b/doc/src/sgml/ref/create_language.sgml @@ -0,0 +1,250 @@ +<!-- +doc/src/sgml/ref/create_language.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createlanguage"> + <indexterm zone="sql-createlanguage"> + <primary>CREATE LANGUAGE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE LANGUAGE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE LANGUAGE</refname> + <refpurpose>define a new procedural language</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE <replaceable class="parameter">name</replaceable> + HANDLER <replaceable class="parameter">call_handler</replaceable> [ INLINE <replaceable class="parameter">inline_handler</replaceable> ] [ VALIDATOR <replaceable>valfunction</replaceable> ] +CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE <replaceable class="parameter">name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createlanguage-description"> + <title>Description</title> + + <para> + <command>CREATE LANGUAGE</command> registers a new + procedural language with a <productname>PostgreSQL</productname> + database. Subsequently, functions and procedures can be + defined in this new language. + </para> + + <para> + <command>CREATE LANGUAGE</command> effectively associates the + language name with handler function(s) that are responsible for executing + functions written in the language. Refer to <xref linkend="plhandler"/> + for more information about language handlers. + </para> + + <para> + <command>CREATE OR REPLACE LANGUAGE</command> will either create a + new language, or replace an existing definition. If the language + already exists, its parameters are updated according to the command, + but the language's ownership and permissions settings do not change, + and any existing functions written in the language are assumed to still + be valid. + </para> + + <para> + One must have the + <productname>PostgreSQL</productname> superuser privilege to + register a new language or change an existing language's parameters. + However, once the language is created it is valid to assign ownership of + it to a non-superuser, who may then drop it, change its permissions, + rename it, or assign it to a new owner. (Do not, however, assign + ownership of the underlying C functions to a non-superuser; that would + create a privilege escalation path for that user.) + </para> + + <para> + The form of <command>CREATE LANGUAGE</command> that does not supply + any handler function is obsolete. For backwards compatibility with + old dump files, it is interpreted as <command>CREATE EXTENSION</command>. + That will work if the language has been packaged into an extension of + the same name, which is the conventional way to set up procedural + languages. + </para> + </refsect1> + + <refsect1 id="sql-createlanguage-parameters"> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>TRUSTED</literal></term> + + <listitem> + <para><literal>TRUSTED</literal> specifies that the language does + not grant access to data that the user would not otherwise + have. If this key word is omitted + when registering the language, only users with the + <productname>PostgreSQL</productname> superuser privilege can + use this language to create new functions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROCEDURAL</literal></term> + + <listitem> + <para> + This is a noise word. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + + <listitem> + <para> + The name of the new procedural language. + The name must be unique among the languages in the database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HANDLER</literal> <replaceable class="parameter">call_handler</replaceable></term> + + <listitem> + <para><replaceable class="parameter">call_handler</replaceable> is + the name of a previously registered function that will be + called to execute the procedural language's functions. The call + handler for a procedural language must be written in a compiled + language such as C with version 1 call convention and + registered with <productname>PostgreSQL</productname> as a + function taking no arguments and returning the + <type>language_handler</type> type, a placeholder type that is + simply used to identify the function as a call handler. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INLINE</literal> <replaceable class="parameter">inline_handler</replaceable></term> + + <listitem> + <para><replaceable class="parameter">inline_handler</replaceable> is the + name of a previously registered function that will be called + to execute an anonymous code block + (<link linkend="sql-do"><command>DO</command></link> command) + in this language. + If no <replaceable class="parameter">inline_handler</replaceable> + function is specified, the language does not support anonymous code + blocks. + The handler function must take one argument of + type <type>internal</type>, which will be the <command>DO</command> command's + internal representation, and it will typically return + <type>void</type>. The return value of the handler is ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALIDATOR</literal> <replaceable class="parameter">valfunction</replaceable></term> + + <listitem> + <para><replaceable class="parameter">valfunction</replaceable> is the + name of a previously registered function that will be called + when a new function in the language is created, to validate the + new function. + If no + validator function is specified, then a new function will not + be checked when it is created. + The validator function must take one argument of + type <type>oid</type>, which will be the OID of the + to-be-created function, and will typically return <type>void</type>. + </para> + + <para> + A validator function would typically inspect the function body + for syntactical correctness, but it can also look at other + properties of the function, for example if the language cannot + handle certain argument types. To signal an error, the + validator function should use the <function>ereport()</function> + function. The return value of the function is ignored. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createlanguage-notes"> + <title>Notes</title> + + <para> + Use <link linkend="sql-droplanguage"><command>DROP LANGUAGE</command></link> to drop procedural languages. + </para> + + <para> + The system catalog <classname>pg_language</classname> (see <xref + linkend="catalog-pg-language"/>) records information about the + currently installed languages. Also, the <application>psql</application> + command <command>\dL</command> lists the installed languages. + </para> + + <para> + To create functions in a procedural language, a user must have the + <literal>USAGE</literal> privilege for the language. By default, + <literal>USAGE</literal> is granted to <literal>PUBLIC</literal> (i.e., everyone) + for trusted languages. This can be revoked if desired. + </para> + + <para> + Procedural languages are local to individual databases. + However, a language can be installed into the <literal>template1</literal> + database, which will cause it to be available automatically in + all subsequently-created databases. + </para> + </refsect1> + + <refsect1 id="sql-createlanguage-examples"> + <title>Examples</title> + + <para> + A minimal sequence for creating a new procedural language is: +<programlisting> +CREATE FUNCTION plsample_call_handler() RETURNS language_handler + AS '$libdir/plsample' + LANGUAGE C; +CREATE LANGUAGE plsample + HANDLER plsample_call_handler; +</programlisting> + Typically that would be written in an extension's creation script, + and users would do this to install the extension: +<programlisting> +CREATE EXTENSION plsample; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-createlanguage-compat"> + <title>Compatibility</title> + + <para> + <command>CREATE LANGUAGE</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterlanguage"/></member> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-droplanguage"/></member> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-revoke"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_materialized_view.sgml b/doc/src/sgml/ref/create_materialized_view.sgml new file mode 100644 index 0000000..0d2fea2 --- /dev/null +++ b/doc/src/sgml/ref/create_materialized_view.sgml @@ -0,0 +1,187 @@ +<!-- +doc/src/sgml/ref/create_materialized_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-creatematerializedview"> + <indexterm zone="sql-creatematerializedview"> + <primary>CREATE MATERIALIZED VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE MATERIALIZED VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE MATERIALIZED VIEW</refname> + <refpurpose>define a new materialized view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable> + [ (<replaceable>column_name</replaceable> [, ...] ) ] + [ USING <replaceable class="parameter">method</replaceable> ] + [ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] + [ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + AS <replaceable>query</replaceable> + [ WITH [ NO ] DATA ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE MATERIALIZED VIEW</command> defines a materialized view of + a query. The query is executed and used to populate the view at the time + the command is issued (unless <command>WITH NO DATA</command> is used) and may be + refreshed later using <command>REFRESH MATERIALIZED VIEW</command>. + </para> + + <para> + <command>CREATE MATERIALIZED VIEW</command> is similar to + <command>CREATE TABLE AS</command>, except that it also remembers the query used + to initialize the view, so that it can be refreshed later upon demand. + A materialized view has many of the same properties as a table, but there + is no support for temporary materialized views. + </para> + + <para> + <command>CREATE MATERIALIZED VIEW</command> requires + <literal>CREATE</literal> privilege on the schema used for the materialized + view. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a materialized view with the same name already + exists. A notice is issued in this case. Note that there is no guarantee + that the existing materialized view is anything like the one that would + have been created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the materialized view to be + created. The name must be distinct from the name of any other relation + (table, sequence, index, view, materialized view, or foreign table) in + the same schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>column_name</replaceable></term> + <listitem> + <para> + The name of a column in the new materialized view. If column names are + not provided, they are taken from the output column names of the query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USING <replaceable class="parameter">method</replaceable></literal></term> + <listitem> + <para> + This optional clause specifies the table access method to use to store + the contents for the new materialized view; the method needs be an + access method of type <literal>TABLE</literal>. See <xref + linkend="tableam"/> for more information. If this option is not + specified, the default table access method is chosen for the new + materialized view. See <xref linkend="guc-default-table-access-method"/> + for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional storage parameters for the new + materialized view; see + <xref linkend="sql-createtable-storage-parameters"/> in the + <xref linkend="sql-createtable"/> documentation for more + information. All parameters supported for <literal>CREATE + TABLE</literal> are also supported for <literal>CREATE MATERIALIZED + VIEW</literal>. + See <xref linkend="sql-createtable"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TABLESPACE <replaceable class="parameter">tablespace_name</replaceable></literal></term> + <listitem> + <para> + The <replaceable class="parameter">tablespace_name</replaceable> is the name + of the tablespace in which the new materialized view is to be created. + If not specified, <xref linkend="guc-default-tablespace"/> is consulted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>query</replaceable></term> + <listitem> + <para> + A <link linkend="sql-select"><command>SELECT</command></link>, <link linkend="sql-table"><command>TABLE</command></link>, + or <link linkend="sql-values"><command>VALUES</command></link> command. This query will run within a + security-restricted operation; in particular, calls to functions that + themselves create temporary tables will fail. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH [ NO ] DATA</literal></term> + <listitem> + <para> + This clause specifies whether or not the materialized view should be + populated at creation time. If not, the materialized view will be + flagged as unscannable and cannot be queried until <command>REFRESH + MATERIALIZED VIEW</command> is used. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE MATERIALIZED VIEW</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altermaterializedview"/></member> + <member><xref linkend="sql-createtableas"/></member> + <member><xref linkend="sql-createview"/></member> + <member><xref linkend="sql-dropmaterializedview"/></member> + <member><xref linkend="sql-refreshmaterializedview"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_opclass.sgml b/doc/src/sgml/ref/create_opclass.sgml new file mode 100644 index 0000000..f1d6a4c --- /dev/null +++ b/doc/src/sgml/ref/create_opclass.sgml @@ -0,0 +1,330 @@ +<!-- +doc/src/sgml/ref/create_opclass.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createopclass"> + <indexterm zone="sql-createopclass"> + <primary>CREATE OPERATOR CLASS</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE OPERATOR CLASS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE OPERATOR CLASS</refname> + <refpurpose>define a new operator class</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE OPERATOR CLASS <replaceable class="parameter">name</replaceable> [ DEFAULT ] FOR TYPE <replaceable class="parameter">data_type</replaceable> + USING <replaceable class="parameter">index_method</replaceable> [ FAMILY <replaceable class="parameter">family_name</replaceable> ] AS + { OPERATOR <replaceable class="parameter">strategy_number</replaceable> <replaceable class="parameter">operator_name</replaceable> [ ( <replaceable class="parameter">op_type</replaceable>, <replaceable class="parameter">op_type</replaceable> ) ] [ FOR SEARCH | FOR ORDER BY <replaceable class="parameter">sort_family_name</replaceable> ] + | FUNCTION <replaceable class="parameter">support_number</replaceable> [ ( <replaceable class="parameter">op_type</replaceable> [ , <replaceable class="parameter">op_type</replaceable> ] ) ] <replaceable class="parameter">function_name</replaceable> ( <replaceable class="parameter">argument_type</replaceable> [, ...] ) + | STORAGE <replaceable class="parameter">storage_type</replaceable> + } [, ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE OPERATOR CLASS</command> creates a new operator class. + An operator class defines how a particular data type can be used with + an index. The operator class specifies that certain operators will fill + particular roles or <quote>strategies</quote> for this data type and this + index method. The operator class also specifies the support functions to + be used by + the index method when the operator class is selected for an + index column. All the operators and functions used by an operator + class must be defined before the operator class can be created. + </para> + + <para> + If a schema name is given then the operator class is created in the + specified schema. Otherwise it is created in the current schema. + Two operator classes in the same schema can have the same name only if they + are for different index methods. + </para> + + <para> + The user who defines an operator class becomes its owner. Presently, + the creating user must be a superuser. (This restriction is made because + an erroneous operator class definition could confuse or even crash the + server.) + </para> + + <para> + <command>CREATE OPERATOR CLASS</command> does not presently check + whether the operator class definition includes all the operators and + functions required by the index method, nor whether the operators and + functions form a self-consistent set. It is the user's + responsibility to define a valid operator class. + </para> + + <para> + Related operator classes can be grouped into <firstterm>operator + families</firstterm>. To add a new operator class to an existing family, + specify the <literal>FAMILY</literal> option in <command>CREATE OPERATOR + CLASS</command>. Without this option, the new class is placed into + a family named the same as the new class (creating that family if + it doesn't already exist). + </para> + + <para> + Refer to <xref linkend="xindex"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the operator class to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + If present, the operator class will become the default + operator class for its data type. At most one operator class + can be the default for a specific data type and index method. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The column data type that this operator class is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index method this operator class is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">family_name</replaceable></term> + <listitem> + <para> + The name of the existing operator family to add this operator class to. + If not specified, a family named the same as the operator class is + used (creating it, if it doesn't already exist). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">strategy_number</replaceable></term> + <listitem> + <para> + The index method's strategy number for an operator + associated with the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">operator_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an operator associated + with the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">op_type</replaceable></term> + <listitem> + <para> + In an <literal>OPERATOR</literal> clause, + the operand data type(s) of the operator, or <literal>NONE</literal> to + signify a prefix operator. The operand data + types can be omitted in the normal case where they are the same + as the operator class's data type. + </para> + + <para> + In a <literal>FUNCTION</literal> clause, the operand data type(s) the + function is intended to support, if different from + the input data type(s) of the function (for B-tree comparison functions + and hash functions) + or the class's data type (for B-tree sort support functions, + B-tree equal image functions, and all functions in GiST, + SP-GiST, GIN and BRIN operator classes). These defaults are + correct, and so <replaceable + class="parameter">op_type</replaceable> need not be specified + in <literal>FUNCTION</literal> clauses, except for the case of a + B-tree sort support function that is meant to support + cross-data-type comparisons. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sort_family_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing <literal>btree</literal> operator + family that describes the sort ordering associated with an ordering + operator. + </para> + + <para> + If neither <literal>FOR SEARCH</literal> nor <literal>FOR ORDER BY</literal> is + specified, <literal>FOR SEARCH</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">support_number</replaceable></term> + <listitem> + <para> + The index method's support function number for a + function associated with the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a function that is an + index method support function for the operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argument_type</replaceable></term> + <listitem> + <para> + The parameter data type(s) of the function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">storage_type</replaceable></term> + <listitem> + <para> + The data type actually stored in the index. Normally this is + the same as the column data type, but some index methods + (currently GiST, GIN, SP-GiST and BRIN) allow it to be different. The + <literal>STORAGE</literal> clause must be omitted unless the index + method allows a different type to be used. + If the column <replaceable class="parameter">data_type</replaceable> is specified + as <type>anyarray</type>, the <replaceable class="parameter">storage_type</replaceable> + can be declared as <type>anyelement</type> to indicate that the index + entries are members of the element type belonging to the actual array + type that each particular index is created for. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The <literal>OPERATOR</literal>, <literal>FUNCTION</literal>, and <literal>STORAGE</literal> + clauses can appear in any order. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Because the index machinery does not check access permissions on functions + before using them, including a function or operator in an operator class + is tantamount to granting public execute permission on it. This is usually + not an issue for the sorts of functions that are useful in an operator + class. + </para> + + <para> + The operators should not be defined by SQL functions. An SQL function + is likely to be inlined into the calling query, which will prevent + the optimizer from recognizing that the query matches an index. + </para> + + <para> + Before <productname>PostgreSQL</productname> 8.4, the <literal>OPERATOR</literal> + clause could include a <literal>RECHECK</literal> option. This is no longer + supported because whether an index operator is <quote>lossy</quote> is now + determined on-the-fly at run time. This allows efficient handling of + cases where an operator might or might not be lossy. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example command defines a GiST index operator class + for the data type <literal>_int4</literal> (array of <type>int4</type>). See the + <xref linkend="intarray"/> module for the complete example. + </para> + +<programlisting> +CREATE OPERATOR CLASS gist__int_ops + DEFAULT FOR TYPE _int4 USING gist AS + OPERATOR 3 &&, + OPERATOR 6 = (anyarray, anyarray), + OPERATOR 7 @>, + OPERATOR 8 <@, + OPERATOR 20 @@ (_int4, query_int), + FUNCTION 1 g_int_consistent (internal, _int4, smallint, oid, internal), + FUNCTION 2 g_int_union (internal, internal), + FUNCTION 3 g_int_compress (internal), + FUNCTION 4 g_int_decompress (internal), + FUNCTION 5 g_int_penalty (internal, internal, internal), + FUNCTION 6 g_int_picksplit (internal, internal), + FUNCTION 7 g_int_same (_int4, _int4, internal); +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE OPERATOR CLASS</command> is a + <productname>PostgreSQL</productname> extension. There is no + <command>CREATE OPERATOR CLASS</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteropclass"/></member> + <member><xref linkend="sql-dropopclass"/></member> + <member><xref linkend="sql-createopfamily"/></member> + <member><xref linkend="sql-alteropfamily"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_operator.sgml b/doc/src/sgml/ref/create_operator.sgml new file mode 100644 index 0000000..d4d45ec --- /dev/null +++ b/doc/src/sgml/ref/create_operator.sgml @@ -0,0 +1,300 @@ +<!-- +doc/src/sgml/ref/create_operator.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createoperator"> + <indexterm zone="sql-createoperator"> + <primary>CREATE OPERATOR</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE OPERATOR</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE OPERATOR</refname> + <refpurpose>define a new operator</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE OPERATOR <replaceable>name</replaceable> ( + {FUNCTION|PROCEDURE} = <replaceable class="parameter">function_name</replaceable> + [, LEFTARG = <replaceable class="parameter">left_type</replaceable> ] [, RIGHTARG = <replaceable class="parameter">right_type</replaceable> ] + [, COMMUTATOR = <replaceable class="parameter">com_op</replaceable> ] [, NEGATOR = <replaceable class="parameter">neg_op</replaceable> ] + [, RESTRICT = <replaceable class="parameter">res_proc</replaceable> ] [, JOIN = <replaceable class="parameter">join_proc</replaceable> ] + [, HASHES ] [, MERGES ] +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE OPERATOR</command> defines a new operator, + <replaceable class="parameter">name</replaceable>. The user who + defines an operator becomes its owner. If a schema name is given + then the operator is created in the specified schema. Otherwise it + is created in the current schema. + </para> + + <para> + The operator name is a sequence of up to <symbol>NAMEDATALEN</symbol>-1 + (63 by default) characters from the following list: +<literallayout> ++ - * / < > = ~ ! @ # % ^ & | ` ? +</literallayout> + + There are a few restrictions on your choice of name: + <itemizedlist> + <listitem> + <para> + <literal>--</literal> and <literal>/*</literal> cannot appear anywhere in an operator name, + since they will be taken as the start of a comment. + </para> + </listitem> + <listitem> + <para> + A multicharacter operator name cannot end in <literal>+</literal> or + <literal>-</literal>, + unless the name also contains at least one of these characters: +<literallayout> +~ ! @ # % ^ & | ` ? +</literallayout> + For example, <literal>@-</literal> is an allowed operator name, + but <literal>*-</literal> is not. + This restriction allows <productname>PostgreSQL</productname> to + parse SQL-compliant commands without requiring spaces between tokens. + </para> + </listitem> + <listitem> + <para> + The symbol <literal>=></literal> is reserved by the SQL grammar, + so it cannot be used as an operator name. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + The operator <literal>!=</literal> is mapped to + <literal><></literal> on input, so these two names are always + equivalent. + </para> + + <para> + For binary operators, both <literal>LEFTARG</literal> and + <literal>RIGHTARG</literal> must be defined. For prefix operators only + <literal>RIGHTARG</literal> should be defined. + The <replaceable class="parameter">function_name</replaceable> + function must have been previously defined using <command>CREATE + FUNCTION</command> and must be defined to accept the correct number + of arguments (either one or two) of the indicated types. + </para> + + <para> + In the syntax of <literal>CREATE OPERATOR</literal>, the keywords + <literal>FUNCTION</literal> and <literal>PROCEDURE</literal> are + equivalent, but the referenced function must in any case be a function, not + a procedure. The use of the keyword <literal>PROCEDURE</literal> here is + historical and deprecated. + </para> + + <para> + The other clauses specify optional operator optimization clauses. + Their meaning is detailed in <xref linkend="xoper-optimization"/>. + </para> + + <para> + To be able to create an operator, you must have <literal>USAGE</literal> + privilege on the argument types and the return type, as well + as <literal>EXECUTE</literal> privilege on the underlying function. If a + commutator or negator operator is specified, you must own these operators. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the operator to be defined. See above for allowable + characters. The name can be schema-qualified, for example + <literal>CREATE OPERATOR myschema.+ (...)</literal>. If not, then + the operator is created in the current schema. Two operators + in the same schema can have the same name if they operate on + different data types. This is called + <firstterm>overloading</firstterm>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + The function used to implement this operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">left_type</replaceable></term> + <listitem> + <para> + The data type of the operator's left operand, if any. + This option would be omitted for a prefix operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">right_type</replaceable></term> + <listitem> + <para> + The data type of the operator's right operand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">com_op</replaceable></term> + <listitem> + <para> + The commutator of this operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">neg_op</replaceable></term> + <listitem> + <para> + The negator of this operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">res_proc</replaceable></term> + <listitem> + <para> + The restriction selectivity estimator function for this operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">join_proc</replaceable></term> + <listitem> + <para> + The join selectivity estimator function for this operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>HASHES</literal></term> + <listitem> + <para> + Indicates this operator can support a hash join. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>MERGES</literal></term> + <listitem> + <para> + Indicates this operator can support a merge join. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + To give a schema-qualified operator name in <replaceable + class="parameter">com_op</replaceable> or the other optional + arguments, use the <literal>OPERATOR()</literal> syntax, for example: +<programlisting> +COMMUTATOR = OPERATOR(myschema.===) , +</programlisting></para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Refer to <xref linkend="xoper"/> for further information. + </para> + + <para> + It is not possible to specify an operator's lexical precedence in + <command>CREATE OPERATOR</command>, because the parser's precedence behavior + is hard-wired. See <xref linkend="sql-precedence"/> for precedence details. + </para> + + <para> + The obsolete options <literal>SORT1</literal>, <literal>SORT2</literal>, + <literal>LTCMP</literal>, and <literal>GTCMP</literal> were formerly used to + specify the names of sort operators associated with a merge-joinable + operator. This is no longer necessary, since information about + associated operators is found by looking at B-tree operator families + instead. If one of these options is given, it is ignored except + for implicitly setting <literal>MERGES</literal> true. + </para> + + <para> + Use <link linkend="sql-dropoperator"><command>DROP OPERATOR</command></link> to delete user-defined operators + from a database. Use <link linkend="sql-alteroperator"><command>ALTER OPERATOR</command></link> to modify operators in a + database. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following command defines a new operator, area-equality, for + the data type <type>box</type>: +<programlisting> +CREATE OPERATOR === ( + LEFTARG = box, + RIGHTARG = box, + FUNCTION = area_equal_function, + COMMUTATOR = ===, + NEGATOR = !==, + RESTRICT = area_restriction_function, + JOIN = area_join_function, + HASHES, MERGES +); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE OPERATOR</command> is a + <productname>PostgreSQL</productname> extension. There are no + provisions for user-defined operators in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteroperator"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-dropoperator"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_opfamily.sgml b/doc/src/sgml/ref/create_opfamily.sgml new file mode 100644 index 0000000..ba612c2 --- /dev/null +++ b/doc/src/sgml/ref/create_opfamily.sgml @@ -0,0 +1,118 @@ +<!-- +doc/src/sgml/ref/create_opfamily.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createopfamily"> + <indexterm zone="sql-createopfamily"> + <primary>CREATE OPERATOR FAMILY</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE OPERATOR FAMILY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE OPERATOR FAMILY</refname> + <refpurpose>define a new operator family</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE OPERATOR FAMILY <replaceable class="parameter">name</replaceable> USING <replaceable class="parameter">index_method</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE OPERATOR FAMILY</command> creates a new operator family. + An operator family defines a collection of related operator classes, + and perhaps some additional operators and support functions that are + compatible with these operator classes but not essential for the + functioning of any individual index. (Operators and functions that + are essential to indexes should be grouped within the relevant operator + class, rather than being <quote>loose</quote> in the operator family. + Typically, single-data-type operators are bound to operator classes, + while cross-data-type operators can be loose in an operator family + containing operator classes for both data types.) + </para> + + <para> + The new operator family is initially empty. It should be populated + by issuing subsequent <command>CREATE OPERATOR CLASS</command> commands + to add contained operator classes, and optionally + <command>ALTER OPERATOR FAMILY</command> commands to add <quote>loose</quote> + operators and their corresponding support functions. + </para> + + <para> + If a schema name is given then the operator family is created in the + specified schema. Otherwise it is created in the current schema. + Two operator families in the same schema can have the same name only if they + are for different index methods. + </para> + + <para> + The user who defines an operator family becomes its owner. Presently, + the creating user must be a superuser. (This restriction is made because + an erroneous operator family definition could confuse or even crash the + server.) + </para> + + <para> + Refer to <xref linkend="xindex"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the operator family to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index method this operator family is for. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE OPERATOR FAMILY</command> is a + <productname>PostgreSQL</productname> extension. There is no + <command>CREATE OPERATOR FAMILY</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteropfamily"/></member> + <member><xref linkend="sql-dropopfamily"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-alteropclass"/></member> + <member><xref linkend="sql-dropopclass"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_policy.sgml b/doc/src/sgml/ref/create_policy.sgml new file mode 100644 index 0000000..e76c342 --- /dev/null +++ b/doc/src/sgml/ref/create_policy.sgml @@ -0,0 +1,655 @@ +<!-- +doc/src/sgml/ref/create_policy.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createpolicy"> + <indexterm zone="sql-createpolicy"> + <primary>CREATE POLICY</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE POLICY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE POLICY</refname> + <refpurpose>define a new row-level security policy for a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE POLICY <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> + [ AS { PERMISSIVE | RESTRICTIVE } ] + [ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ] + [ TO { <replaceable class="parameter">role_name</replaceable> | PUBLIC | CURRENT_ROLE | CURRENT_USER | SESSION_USER } [, ...] ] + [ USING ( <replaceable class="parameter">using_expression</replaceable> ) ] + [ WITH CHECK ( <replaceable class="parameter">check_expression</replaceable> ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + The <command>CREATE POLICY</command> command defines a new row-level + security policy for a table. Note that row-level security must be + enabled on the table (using <command>ALTER TABLE ... ENABLE ROW LEVEL + SECURITY</command>) in order for created policies to be applied. + </para> + + <para> + A policy grants the permission to select, insert, update, or delete rows + that match the relevant policy expression. Existing table rows are + checked against the expression specified in <literal>USING</literal>, + while new rows that would be created via <literal>INSERT</literal> + or <literal>UPDATE</literal> are checked against the expression specified + in <literal>WITH CHECK</literal>. When a <literal>USING</literal> + expression returns true for a given row then that row is visible to the + user, while if false or null is returned then the row is not visible. + When a <literal>WITH CHECK</literal> expression returns true for a row + then that row is inserted or updated, while if false or null is returned + then an error occurs. + </para> + + <para> + For <command>INSERT</command>, <command>UPDATE</command>, and + <command>MERGE</command> statements, + <literal>WITH CHECK</literal> expressions are enforced after + <literal>BEFORE</literal> triggers are fired, and before any actual data + modifications are made. Thus a <literal>BEFORE ROW</literal> trigger may + modify the data to be inserted, affecting the result of the security + policy check. <literal>WITH CHECK</literal> expressions are enforced + before any other constraints. + </para> + + <para> + Policy names are per-table. Therefore, one policy name can be used for many + different tables and have a definition for each table which is appropriate to + that table. + </para> + + <para> + Policies can be applied for specific commands or for specific roles. The + default for newly created policies is that they apply for all commands and + roles, unless otherwise specified. Multiple policies may apply to a single + command; see below for more details. + <xref linkend="sql-createpolicy-summary"/> summarizes how the different types + of policy apply to specific commands. + </para> + + <para> + For policies that can have both <literal>USING</literal> + and <literal>WITH CHECK</literal> expressions (<literal>ALL</literal> + and <literal>UPDATE</literal>), if no <literal>WITH CHECK</literal> + expression is defined, then the <literal>USING</literal> expression will be + used both to determine which rows are visible (normal + <literal>USING</literal> case) and which new rows will be allowed to be + added (<literal>WITH CHECK</literal> case). + </para> + + <para> + If row-level security is enabled for a table, but no applicable policies + exist, a <quote>default deny</quote> policy is assumed, so that no rows will + be visible or updatable. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the policy to be created. This must be distinct from the + name of any other policy for the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table the + policy applies to. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PERMISSIVE</literal></term> + <listitem> + <para> + Specify that the policy is to be created as a permissive policy. + All permissive policies which are applicable to a given query will + be combined together using the Boolean <quote>OR</quote> operator. By creating + permissive policies, administrators can add to the set of records + which can be accessed. Policies are permissive by default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICTIVE</literal></term> + <listitem> + <para> + Specify that the policy is to be created as a restrictive policy. + All restrictive policies which are applicable to a given query will + be combined together using the Boolean <quote>AND</quote> operator. By creating + restrictive policies, administrators can reduce the set of records + which can be accessed as all restrictive policies must be passed for + each record. + </para> + + <para> + Note that there needs to be at least one permissive policy to grant + access to records before restrictive policies can be usefully used to + reduce that access. If only restrictive policies exist, then no records + will be accessible. When a mix of permissive and restrictive policies + are present, a record is only accessible if at least one of the + permissive policies passes, in addition to all the restrictive + policies. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">command</replaceable></term> + <listitem> + <para> + The command to which the policy applies. Valid options are + <command>ALL</command>, <command>SELECT</command>, + <command>INSERT</command>, <command>UPDATE</command>, + and <command>DELETE</command>. + <command>ALL</command> is the default. + See below for specifics regarding how these are applied. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The role(s) to which the policy is to be applied. The default is + <literal>PUBLIC</literal>, which will apply the policy to all roles. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">using_expression</replaceable></term> + <listitem> + <para> + Any <acronym>SQL</acronym> conditional expression (returning + <type>boolean</type>). The conditional expression cannot contain + any aggregate or window functions. This expression will be added + to queries that refer to the table if row-level security is enabled. + Rows for which the expression returns true will be visible. Any + rows for which the expression returns false or null will not be + visible to the user (in a <command>SELECT</command>), and will not be + available for modification (in an <command>UPDATE</command> + or <command>DELETE</command>). Such rows are silently suppressed; no error + is reported. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">check_expression</replaceable></term> + <listitem> + <para> + Any <acronym>SQL</acronym> conditional expression (returning + <type>boolean</type>). The conditional expression cannot contain + any aggregate or window functions. This expression will be used in + <command>INSERT</command> and <command>UPDATE</command> queries against + the table if row-level security is enabled. Only rows for which the + expression evaluates to true will be allowed. An error will be thrown + if the expression evaluates to false or null for any of the records + inserted or any of the records that result from the update. Note that + the <replaceable class="parameter">check_expression</replaceable> is + evaluated against the proposed new contents of the row, not the + original contents. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <refsect2> + <title>Per-Command Policies</title> + + <variablelist> + + <varlistentry id="sql-createpolicy-all"> + <term><literal>ALL</literal></term> + <listitem> + <para> + Using <literal>ALL</literal> for a policy means that it will apply + to all commands, regardless of the type of command. If an + <literal>ALL</literal> policy exists and more specific policies + exist, then both the <literal>ALL</literal> policy and the more + specific policy (or policies) will be applied. + Additionally, <literal>ALL</literal> policies will be applied to + both the selection side of a query and the modification side, using + the <literal>USING</literal> expression for both cases if only + a <literal>USING</literal> expression has been defined. + </para> + <para> + As an example, if an <literal>UPDATE</literal> is issued, then the + <literal>ALL</literal> policy will be applicable both to what the + <literal>UPDATE</literal> will be able to select as rows to be + updated (applying the <literal>USING</literal> expression), + and to the resulting updated rows, to check if they are permitted + to be added to the table (applying the <literal>WITH CHECK</literal> + expression, if defined, and the <literal>USING</literal> expression + otherwise). If an <command>INSERT</command> + or <command>UPDATE</command> command attempts to add rows to the + table that do not pass the <literal>ALL</literal> + policy's <literal>WITH CHECK</literal> expression, the entire + command will be aborted. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createpolicy-select"> + <term><literal>SELECT</literal></term> + <listitem> + <para> + Using <literal>SELECT</literal> for a policy means that it will apply + to <literal>SELECT</literal> queries and whenever + <literal>SELECT</literal> permissions are required on the relation the + policy is defined for. The result is that only those records from the + relation that pass the <literal>SELECT</literal> policy will be + returned during a <literal>SELECT</literal> query, and that queries + that require <literal>SELECT</literal> permissions, such as + <literal>UPDATE</literal>, will also only see those records + that are allowed by the <literal>SELECT</literal> policy. + A <literal>SELECT</literal> policy cannot have a <literal>WITH + CHECK</literal> expression, as it only applies in cases where + records are being retrieved from the relation. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createpolicy-insert"> + <term><literal>INSERT</literal></term> + <listitem> + <para> + Using <literal>INSERT</literal> for a policy means that it will apply + to <literal>INSERT</literal> commands and <literal>MERGE</literal> + commands that contain <literal>INSERT</literal> actions. + Rows being inserted that do + not pass this policy will result in a policy violation error, and the + entire <literal>INSERT</literal> command will be aborted. + An <literal>INSERT</literal> policy cannot have + a <literal>USING</literal> expression, as it only applies in cases + where records are being added to the relation. + </para> + <para> + Note that <literal>INSERT</literal> with <literal>ON CONFLICT DO + UPDATE</literal> checks <literal>INSERT</literal> policies' + <literal>WITH CHECK</literal> expressions only for rows appended + to the relation by the <literal>INSERT</literal> path. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createpolicy-update"> + <term><literal>UPDATE</literal></term> + <listitem> + <para> + Using <literal>UPDATE</literal> for a policy means that it will apply + to <literal>UPDATE</literal>, <literal>SELECT FOR UPDATE</literal> + and <literal>SELECT FOR SHARE</literal> commands, as well as + auxiliary <literal>ON CONFLICT DO UPDATE</literal> clauses of + <literal>INSERT</literal> commands. + <literal>MERGE</literal> commands containing <literal>UPDATE</literal> + actions are affected as well. Since <literal>UPDATE</literal> + involves pulling an existing record and replacing it with a new + modified record, <literal>UPDATE</literal> + policies accept both a <literal>USING</literal> expression and + a <literal>WITH CHECK</literal> expression. + The <literal>USING</literal> expression determines which records + the <literal>UPDATE</literal> command will see to operate against, + while the <literal>WITH CHECK</literal> expression defines which + modified rows are allowed to be stored back into the relation. + </para> + + <para> + Any rows whose updated values do not pass the + <literal>WITH CHECK</literal> expression will cause an error, and the + entire command will be aborted. If only a <literal>USING</literal> + clause is specified, then that clause will be used for both + <literal>USING</literal> and <literal>WITH CHECK</literal> cases. + </para> + + <para> + Typically an <literal>UPDATE</literal> command also needs to read + data from columns in the relation being updated (e.g., in a + <literal>WHERE</literal> clause or a <literal>RETURNING</literal> + clause, or in an expression on the right hand side of the + <literal>SET</literal> clause). In this case, + <literal>SELECT</literal> rights are also required on the relation + being updated, and the appropriate <literal>SELECT</literal> or + <literal>ALL</literal> policies will be applied in addition to + the <literal>UPDATE</literal> policies. Thus the user must have + access to the row(s) being updated through a <literal>SELECT</literal> + or <literal>ALL</literal> policy in addition to being granted + permission to update the row(s) via an <literal>UPDATE</literal> + or <literal>ALL</literal> policy. + </para> + + <para> + When an <literal>INSERT</literal> command has an auxiliary + <literal>ON CONFLICT DO UPDATE</literal> clause, if the + <literal>UPDATE</literal> path is taken, the row to be updated is + first checked against the <literal>USING</literal> expressions of + any <literal>UPDATE</literal> policies, and then the new updated row + is checked against the <literal>WITH CHECK</literal> expressions. + Note, however, that unlike a standalone <literal>UPDATE</literal> + command, if the existing row does not pass the + <literal>USING</literal> expressions, an error will be thrown (the + <literal>UPDATE</literal> path will <emphasis>never</emphasis> be silently + avoided). + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createpolicy-delete"> + <term><literal>DELETE</literal></term> + <listitem> + <para> + Using <literal>DELETE</literal> for a policy means that it will apply + to <literal>DELETE</literal> commands. Only rows that pass this + policy will be seen by a <literal>DELETE</literal> command. There can + be rows that are visible through a <literal>SELECT</literal> that are + not available for deletion, if they do not pass the + <literal>USING</literal> expression for + the <literal>DELETE</literal> policy. + </para> + + <para> + In most cases a <literal>DELETE</literal> command also needs to read + data from columns in the relation that it is deleting from (e.g., + in a <literal>WHERE</literal> clause or a + <literal>RETURNING</literal> clause). In this case, + <literal>SELECT</literal> rights are also required on the relation, + and the appropriate <literal>SELECT</literal> or + <literal>ALL</literal> policies will be applied in addition to + the <literal>DELETE</literal> policies. Thus the user must have + access to the row(s) being deleted through a <literal>SELECT</literal> + or <literal>ALL</literal> policy in addition to being granted + permission to delete the row(s) via a <literal>DELETE</literal> or + <literal>ALL</literal> policy. + </para> + + <para> + A <literal>DELETE</literal> policy cannot have a <literal>WITH + CHECK</literal> expression, as it only applies in cases where + records are being deleted from the relation, so that there is no + new row to check. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <table id="sql-createpolicy-summary"> + <title>Policies Applied by Command Type</title> + <tgroup cols="6"> + <colspec colnum="4" colname="update-using"/> + <colspec colnum="5" colname="update-check"/> + <spanspec namest="update-using" nameend="update-check" spanname="update"/> + <thead> + <row> + <entry morerows="1">Command</entry> + <entry><literal>SELECT/ALL policy</literal></entry> + <entry><literal>INSERT/ALL policy</literal></entry> + <entry spanname="update"><literal>UPDATE/ALL policy</literal></entry> + <entry><literal>DELETE/ALL policy</literal></entry> + </row> + <row> + <entry><literal>USING expression</literal></entry> + <entry><literal>WITH CHECK expression</literal></entry> + <entry><literal>USING expression</literal></entry> + <entry><literal>WITH CHECK expression</literal></entry> + <entry><literal>USING expression</literal></entry> + </row> + </thead> + <tbody> + <row> + <entry><command>SELECT</command></entry> + <entry>Existing row</entry> + <entry>—</entry> + <entry>—</entry> + <entry>—</entry> + <entry>—</entry> + </row> + <row> + <entry><command>SELECT FOR UPDATE/SHARE</command></entry> + <entry>Existing row</entry> + <entry>—</entry> + <entry>Existing row</entry> + <entry>—</entry> + <entry>—</entry> + </row> + <row> + <entry><command>INSERT</command> / <command>MERGE ... THEN INSERT</command></entry> + <entry>—</entry> + <entry>New row</entry> + <entry>—</entry> + <entry>—</entry> + <entry>—</entry> + </row> + <row> + <entry><command>INSERT ... RETURNING</command></entry> + <entry> + New row <footnote id="rls-select-priv"> + <para> + If read access is required to the existing or new row (for example, + a <literal>WHERE</literal> or <literal>RETURNING</literal> clause + that refers to columns from the relation). + </para> + </footnote> + </entry> + <entry>New row</entry> + <entry>—</entry> + <entry>—</entry> + <entry>—</entry> + </row> + <row> + <entry><command>UPDATE</command> / <command>MERGE ... THEN UPDATE</command></entry> + <entry> + Existing & new rows <footnoteref linkend="rls-select-priv"/> + </entry> + <entry>—</entry> + <entry>Existing row</entry> + <entry>New row</entry> + <entry>—</entry> + </row> + <row> + <entry><command>DELETE</command></entry> + <entry> + Existing row <footnoteref linkend="rls-select-priv"/> + </entry> + <entry>—</entry> + <entry>—</entry> + <entry>—</entry> + <entry>Existing row</entry> + </row> + <row> + <entry><command>ON CONFLICT DO UPDATE</command></entry> + <entry>Existing & new rows</entry> + <entry>—</entry> + <entry>Existing row</entry> + <entry>New row</entry> + <entry>—</entry> + </row> + </tbody> + </tgroup> + </table> + + </refsect2> + + <refsect2> + <title>Application of Multiple Policies</title> + + <para> + When multiple policies of different command types apply to the same command + (for example, <literal>SELECT</literal> and <literal>UPDATE</literal> + policies applied to an <literal>UPDATE</literal> command), then the user + must have both types of permissions (for example, permission to select rows + from the relation as well as permission to update them). Thus the + expressions for one type of policy are combined with the expressions for + the other type of policy using the <literal>AND</literal> operator. + </para> + + <para> + When multiple policies of the same command type apply to the same command, + then there must be at least one <literal>PERMISSIVE</literal> policy + granting access to the relation, and all of the + <literal>RESTRICTIVE</literal> policies must pass. Thus all the + <literal>PERMISSIVE</literal> policy expressions are combined using + <literal>OR</literal>, all the <literal>RESTRICTIVE</literal> policy + expressions are combined using <literal>AND</literal>, and the results are + combined using <literal>AND</literal>. If there are no + <literal>PERMISSIVE</literal> policies, then access is denied. + </para> + + <para> + Note that, for the purposes of combining multiple policies, + <literal>ALL</literal> policies are treated as having the same type as + whichever other type of policy is being applied. + </para> + + <para> + For example, in an <literal>UPDATE</literal> command requiring both + <literal>SELECT</literal> and <literal>UPDATE</literal> permissions, if + there are multiple applicable policies of each type, they will be combined + as follows: + +<programlisting> +<replaceable>expression</replaceable> from RESTRICTIVE SELECT/ALL policy 1 +AND +<replaceable>expression</replaceable> from RESTRICTIVE SELECT/ALL policy 2 +AND +... +AND +( + <replaceable>expression</replaceable> from PERMISSIVE SELECT/ALL policy 1 + OR + <replaceable>expression</replaceable> from PERMISSIVE SELECT/ALL policy 2 + OR + ... +) +AND +<replaceable>expression</replaceable> from RESTRICTIVE UPDATE/ALL policy 1 +AND +<replaceable>expression</replaceable> from RESTRICTIVE UPDATE/ALL policy 2 +AND +... +AND +( + <replaceable>expression</replaceable> from PERMISSIVE UPDATE/ALL policy 1 + OR + <replaceable>expression</replaceable> from PERMISSIVE UPDATE/ALL policy 2 + OR + ... +) +</programlisting></para> + + </refsect2> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + You must be the owner of a table to create or change policies for it. + </para> + + <para> + While policies will be applied for explicit queries against tables + in the database, they are not applied when the system is performing internal + referential integrity checks or validating constraints. This means there are + indirect ways to determine that a given value exists. An example of this is + attempting to insert a duplicate value into a column that is a primary key + or has a unique constraint. If the insert fails then the user can infer that + the value already exists. (This example assumes that the user is permitted by + policy to insert records which they are not allowed to see.) Another example + is where a user is allowed to insert into a table which references another, + otherwise hidden table. Existence can be determined by the user inserting + values into the referencing table, where success would indicate that the + value exists in the referenced table. These issues can be addressed by + carefully crafting policies to prevent users from being able to insert, + delete, or update records at all which might possibly indicate a value they + are not otherwise able to see, or by using generated values (e.g., surrogate + keys) instead of keys with external meanings. + </para> + + <para> + Generally, the system will enforce filter conditions imposed using + security policies prior to qualifications that appear in user queries, + in order to prevent inadvertent exposure of the protected data to + user-defined functions which might not be trustworthy. However, + functions and operators marked by the system (or the system + administrator) as <literal>LEAKPROOF</literal> may be evaluated before + policy expressions, as they are assumed to be trustworthy. + </para> + + <para> + Since policy expressions + are added to the user's query directly, they will be run with the rights of + the user running the overall query. Therefore, users who are using a given + policy must be able to access any tables or functions referenced in the + expression or they will simply receive a permission denied error when + attempting to query the table that has row-level security enabled. + This does not change how views + work, however. As with normal queries and views, permission checks and + policies for the tables which are referenced by a view will use the view + owner's rights and any policies which apply to the view owner, except if + the view is defined using the <literal>security_invoker</literal> option + (see <link linkend="sql-createview"><command>CREATE VIEW</command></link>). + </para> + + <para> + No separate policy exists for <command>MERGE</command>. Instead, the policies + defined for <command>SELECT</command>, <command>INSERT</command>, + <command>UPDATE</command>, and <command>DELETE</command> are applied + while executing <command>MERGE</command>, depending on the actions that are + performed. + </para> + + <para> + Additional discussion and practical examples can be found + in <xref linkend="ddl-rowsecurity"/>. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE POLICY</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterpolicy"/></member> + <member><xref linkend="sql-droppolicy"/></member> + <member><xref linkend="sql-altertable"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_procedure.sgml b/doc/src/sgml/ref/create_procedure.sgml new file mode 100644 index 0000000..03a14c8 --- /dev/null +++ b/doc/src/sgml/ref/create_procedure.sgml @@ -0,0 +1,411 @@ +<!-- +doc/src/sgml/ref/create_procedure.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createprocedure"> + <indexterm zone="sql-createprocedure"> + <primary>CREATE PROCEDURE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE PROCEDURE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE PROCEDURE</refname> + <refpurpose>define a new procedure</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] PROCEDURE + <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [ { DEFAULT | = } <replaceable class="parameter">default_expr</replaceable> ] [, ...] ] ) + { LANGUAGE <replaceable class="parameter">lang_name</replaceable> + | TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ] + | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER + | SET <replaceable class="parameter">configuration_parameter</replaceable> { TO <replaceable class="parameter">value</replaceable> | = <replaceable class="parameter">value</replaceable> | FROM CURRENT } + | AS '<replaceable class="parameter">definition</replaceable>' + | AS '<replaceable class="parameter">obj_file</replaceable>', '<replaceable class="parameter">link_symbol</replaceable>' + | <replaceable class="parameter">sql_body</replaceable> + } ... +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createprocedure-description"> + <title>Description</title> + + <para> + <command>CREATE PROCEDURE</command> defines a new procedure. + <command>CREATE OR REPLACE PROCEDURE</command> will either create a + new procedure, or replace an existing definition. + To be able to define a procedure, the user must have the + <literal>USAGE</literal> privilege on the language. + </para> + + <para> + If a schema name is included, then the procedure is created in the + specified schema. Otherwise it is created in the current schema. + The name of the new procedure must not match any existing procedure or function + with the same input argument types in the same schema. However, + procedures and functions of different argument types can share a name (this is + called <firstterm>overloading</firstterm>). + </para> + + <para> + To replace the current definition of an existing procedure, use + <command>CREATE OR REPLACE PROCEDURE</command>. It is not possible + to change the name or argument types of a procedure this way (if you + tried, you would actually be creating a new, distinct procedure). + </para> + + <para> + When <command>CREATE OR REPLACE PROCEDURE</command> is used to replace an + existing procedure, the ownership and permissions of the procedure + do not change. All other procedure properties are assigned the + values specified or implied in the command. You must own the procedure + to replace it (this includes being a member of the owning role). + </para> + + <para> + The user that creates the procedure becomes the owner of the procedure. + </para> + + <para> + To be able to create a procedure, you must have <literal>USAGE</literal> + privilege on the argument types. + </para> + + <para> + Refer to <xref linkend="xproc"/> for further information on writing + procedures. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + + <listitem> + <para> + The name (optionally schema-qualified) of the procedure to create. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. If omitted, + the default is <literal>IN</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the procedure's arguments (optionally + schema-qualified), if any. The argument types can be base, composite, + or domain types, or can reference the type of a table column. + </para> + <para> + Depending on the implementation language it might also be allowed + to specify <quote>pseudo-types</quote> such as <type>cstring</type>. + Pseudo-types indicate that the actual argument type is either + incompletely specified, or outside the set of ordinary SQL data types. + </para> + <para> + The type of a column is referenced by writing + <literal><replaceable + class="parameter">table_name</replaceable>.<replaceable + class="parameter">column_name</replaceable>%TYPE</literal>. + Using this feature can sometimes help make a procedure independent of + changes to the definition of a table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">default_expr</replaceable></term> + + <listitem> + <para> + An expression to be used as default value if the parameter is + not specified. The expression has to be coercible to the + argument type of the parameter. + All input parameters following a + parameter with a default value must have default values as well. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lang_name</replaceable></term> + + <listitem> + <para> + The name of the language that the procedure is implemented in. + It can be <literal>sql</literal>, <literal>c</literal>, + <literal>internal</literal>, or the name of a user-defined + procedural language, e.g., <literal>plpgsql</literal>. The default is + <literal>sql</literal> if <replaceable + class="parameter">sql_body</replaceable> is specified. Enclosing the + name in single quotes is deprecated and requires matching case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ] }</literal></term> + + <listitem> + <para> + Lists which transforms a call to the procedure should apply. Transforms + convert between SQL types and language-specific data types; + see <xref linkend="sql-createtransform"/>. Procedural language + implementations usually have hardcoded knowledge of the built-in types, + so those don't need to be listed here. If a procedural language + implementation does not know how to handle a type and no transform is + supplied, it will fall back to a default behavior for converting data + types, but this depends on the implementation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><optional>EXTERNAL</optional> SECURITY INVOKER</literal></term> + <term><literal><optional>EXTERNAL</optional> SECURITY DEFINER</literal></term> + + <listitem> + <para><literal>SECURITY INVOKER</literal> indicates that the procedure + is to be executed with the privileges of the user that calls it. + That is the default. <literal>SECURITY DEFINER</literal> + specifies that the procedure is to be executed with the + privileges of the user that owns it. + </para> + + <para> + The key word <literal>EXTERNAL</literal> is allowed for SQL + conformance, but it is optional since, unlike in SQL, this feature + applies to all procedures not only external ones. + </para> + + <para> + A <literal>SECURITY DEFINER</literal> procedure cannot execute + transaction control statements (for example, <command>COMMIT</command> + and <command>ROLLBACK</command>, depending on the language). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>configuration_parameter</replaceable></term> + <term><replaceable>value</replaceable></term> + <listitem> + <para> + The <literal>SET</literal> clause causes the specified configuration + parameter to be set to the specified value when the procedure is + entered, and then restored to its prior value when the procedure exits. + <literal>SET FROM CURRENT</literal> saves the value of the parameter that + is current when <command>CREATE PROCEDURE</command> is executed as the value + to be applied when the procedure is entered. + </para> + + <para> + If a <literal>SET</literal> clause is attached to a procedure, then + the effects of a <command>SET LOCAL</command> command executed inside the + procedure for the same variable are restricted to the procedure: the + configuration parameter's prior value is still restored at procedure exit. + However, an ordinary + <command>SET</command> command (without <literal>LOCAL</literal>) overrides the + <literal>SET</literal> clause, much as it would do for a previous <command>SET + LOCAL</command> command: the effects of such a command will persist after + procedure exit, unless the current transaction is rolled back. + </para> + + <para> + If a <literal>SET</literal> clause is attached to a procedure, then + that procedure cannot execute transaction control statements (for + example, <command>COMMIT</command> and <command>ROLLBACK</command>, + depending on the language). + </para> + + <para> + See <xref linkend="sql-set"/> and + <xref linkend="runtime-config"/> + for more information about allowed parameter names and values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">definition</replaceable></term> + + <listitem> + <para> + A string constant defining the procedure; the meaning depends on the + language. It can be an internal procedure name, the path to an + object file, an SQL command, or text in a procedural language. + </para> + + <para> + It is often helpful to use dollar quoting (see <xref + linkend="sql-syntax-dollar-quoting"/>) to write the procedure definition + string, rather than the normal single quote syntax. Without dollar + quoting, any single quotes or backslashes in the procedure definition must + be escaped by doubling them. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></literal></term> + + <listitem> + <para> + This form of the <literal>AS</literal> clause is used for + dynamically loadable C language procedures when the procedure name + in the C language source code is not the same as the name of + the SQL procedure. The string <replaceable + class="parameter">obj_file</replaceable> is the name of the shared + library file containing the compiled C procedure, and is interpreted + as for the <link linkend="sql-load"><command>LOAD</command></link> command. The string + <replaceable class="parameter">link_symbol</replaceable> is the + procedure's link symbol, that is, the name of the procedure in the C + language source code. If the link symbol is omitted, it is assumed + to be the same as the name of the SQL procedure being defined. + </para> + + <para> + When repeated <command>CREATE PROCEDURE</command> calls refer to + the same object file, the file is only loaded once per session. + To unload and + reload the file (perhaps during development), start a new session. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sql_body</replaceable></term> + + <listitem> + <para> + The body of a <literal>LANGUAGE SQL</literal> procedure. This should + be a block +<programlisting> +BEGIN ATOMIC + <replaceable>statement</replaceable>; + <replaceable>statement</replaceable>; + ... + <replaceable>statement</replaceable>; +END +</programlisting> + </para> + + <para> + This is similar to writing the text of the procedure body as a string + constant (see <replaceable>definition</replaceable> above), but there + are some differences: This form only works for <literal>LANGUAGE + SQL</literal>, the string constant form works for all languages. This + form is parsed at procedure definition time, the string constant form is + parsed at execution time; therefore this form cannot support + polymorphic argument types and other constructs that are not resolvable + at procedure definition time. This form tracks dependencies between the + procedure and objects used in the procedure body, so <literal>DROP + ... CASCADE</literal> will work correctly, whereas the form using + string literals may leave dangling procedures. Finally, this form is + more compatible with the SQL standard and other SQL implementations. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1 id="sql-createprocedure-notes"> + <title>Notes</title> + + <para> + See <xref linkend="sql-createfunction"/> for more details on function + creation that also apply to procedures. + </para> + + <para> + Use <xref linkend="sql-call"/> to execute a procedure. + </para> + </refsect1> + + <refsect1 id="sql-createprocedure-examples"> + <title>Examples</title> + + <para> +<programlisting> +CREATE PROCEDURE insert_data(a integer, b integer) +LANGUAGE SQL +AS $$ +INSERT INTO tbl VALUES (a); +INSERT INTO tbl VALUES (b); +$$; +</programlisting> + or +<programlisting> +CREATE PROCEDURE insert_data(a integer, b integer) +LANGUAGE SQL +BEGIN ATOMIC + INSERT INTO tbl VALUES (a); + INSERT INTO tbl VALUES (b); +END; +</programlisting> + and call like this: +<programlisting> +CALL insert_data(1, 2); +</programlisting></para> + </refsect1> + + <refsect1 id="sql-createprocedure-compat"> + <title>Compatibility</title> + + <para> + A <command>CREATE PROCEDURE</command> command is defined in the SQL + standard. The <productname>PostgreSQL</productname> implementation can be + used in a compatible way but has many extensions. For details see also + <xref linkend="sql-createfunction"/>. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterprocedure"/></member> + <member><xref linkend="sql-dropprocedure"/></member> + <member><xref linkend="sql-call"/></member> + <member><xref linkend="sql-createfunction"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_publication.sgml b/doc/src/sgml/ref/create_publication.sgml new file mode 100644 index 0000000..7ab7e77 --- /dev/null +++ b/doc/src/sgml/ref/create_publication.sgml @@ -0,0 +1,409 @@ +<!-- +doc/src/sgml/ref/create_publication.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createpublication"> + <indexterm zone="sql-createpublication"> + <primary>CREATE PUBLICATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE PUBLICATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE PUBLICATION</refname> + <refpurpose>define a new publication</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE PUBLICATION <replaceable class="parameter">name</replaceable> + [ FOR ALL TABLES + | FOR <replaceable class="parameter">publication_object</replaceable> [, ... ] ] + [ WITH ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] + +<phrase>where <replaceable class="parameter">publication_object</replaceable> is one of:</phrase> + + TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] [ WHERE ( <replaceable class="parameter">expression</replaceable> ) ] [, ... ] + TABLES IN SCHEMA { <replaceable class="parameter">schema_name</replaceable> | CURRENT_SCHEMA } [, ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE PUBLICATION</command> adds a new publication + into the current database. The publication name must be distinct from + the name of any existing publication in the current database. + </para> + + <para> + A publication is essentially a group of tables whose data changes are + intended to be replicated through logical replication. See + <xref linkend="logical-replication-publication"/> for details about how + publications fit into the logical replication setup. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the new publication. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FOR TABLE</literal></term> + <listitem> + <para> + Specifies a list of tables to add to the publication. If + <literal>ONLY</literal> is specified before the table name, only + that table is added to the publication. If <literal>ONLY</literal> is not + specified, the table and all its descendant tables (if any) are added. + Optionally, <literal>*</literal> can be specified after the table name to + explicitly indicate that descendant tables are included. + This does not apply to a partitioned table, however. The partitions of + a partitioned table are always implicitly considered part of the + publication, so they are never explicitly added to the publication. + </para> + + <para> + If the optional <literal>WHERE</literal> clause is specified, it defines a + <firstterm>row filter</firstterm> expression. Rows for + which the <replaceable class="parameter">expression</replaceable> + evaluates to false or null will not be published. Note that parentheses + are required around the expression. It has no effect on + <literal>TRUNCATE</literal> commands. + </para> + + <para> + When a column list is specified, only the named columns are replicated. + If no column list is specified, all columns of the table are replicated + through this publication, including any columns added later. It has no + effect on <literal>TRUNCATE</literal> commands. See + <xref linkend="logical-replication-col-lists"/> for details about column + lists. + </para> + + <para> + Only persistent base tables and partitioned tables can be part of a + publication. Temporary tables, unlogged tables, foreign tables, + materialized views, and regular views cannot be part of a publication. + </para> + + <para> + Specifying a column list when the publication also publishes + <literal>FOR TABLES IN SCHEMA</literal> is not supported. + </para> + + <para> + When a partitioned table is added to a publication, all of its existing + and future partitions are implicitly considered to be part of the + publication. So, even operations that are performed directly on a + partition are also published via publications that its ancestors are + part of. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FOR ALL TABLES</literal></term> + <listitem> + <para> + Marks the publication as one that replicates changes for all tables in + the database, including tables created in the future. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FOR TABLES IN SCHEMA</literal></term> + <listitem> + <para> + Marks the publication as one that replicates changes for all tables in + the specified list of schemas, including tables created in the future. + </para> + + <para> + Specifying a schema when the publication also publishes a table with a + column list is not supported. + </para> + + <para> + Only persistent base tables and partitioned tables present in the schema + will be included as part of the publication. Temporary tables, unlogged + tables, foreign tables, materialized views, and regular views from the + schema will not be part of the publication. + </para> + + <para> + When a partitioned table is published via schema level publication, all + of its existing and future partitions are implicitly considered to be part of the + publication, regardless of whether they are from the publication schema or not. + So, even operations that are performed directly on a + partition are also published via publications that its ancestors are + part of. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">publication_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional parameters for a publication. The + following parameters are supported: + + <variablelist> + <varlistentry> + <term><literal>publish</literal> (<type>string</type>)</term> + <listitem> + <para> + This parameter determines which DML operations will be published by + the new publication to the subscribers. The value is + comma-separated list of operations. The allowed operations are + <literal>insert</literal>, <literal>update</literal>, + <literal>delete</literal>, and <literal>truncate</literal>. + The default is to publish all actions, + and so the default value for this option is + <literal>'insert, update, delete, truncate'</literal>. + </para> + <para> + This parameter only affects DML operations. In particular, the initial + data synchronization (see <xref linkend="logical-replication-snapshot"/>) + for logical replication does not take this parameter into account when + copying existing table data. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>publish_via_partition_root</literal> (<type>boolean</type>)</term> + <listitem> + <para> + This parameter determines whether changes in a partitioned table (or + on its partitions) contained in the publication will be published + using the identity and schema of the partitioned table rather than + that of the individual partitions that are actually changed; the + latter is the default. Enabling this allows the changes to be + replicated into a non-partitioned table or a partitioned table + consisting of a different set of partitions. + </para> + + <para> + This parameter also affects how row filters and column lists are + chosen for partitions; see below for details. + </para> + + <para> + If this is enabled, <literal>TRUNCATE</literal> operations performed + directly on partitions are not replicated. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If <literal>FOR TABLE</literal>, <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal> are not specified, then the + publication starts out with an empty set of tables. That is useful if + tables or schemas are to be added later. + </para> + + <para> + The creation of a publication does not start replication. It only defines + a grouping and filtering logic for future subscribers. + </para> + + <para> + To create a publication, the invoking user must have the + <literal>CREATE</literal> privilege for the current database. + (Of course, superusers bypass this check.) + </para> + + <para> + To add a table to a publication, the invoking user must have ownership + rights on the table. The <command>FOR ALL TABLES</command> and + <command>FOR TABLES IN SCHEMA</command> clauses require the invoking + user to be a superuser. + </para> + + <para> + The tables added to a publication that publishes <command>UPDATE</command> + and/or <command>DELETE</command> operations must have + <literal>REPLICA IDENTITY</literal> defined. Otherwise those operations will be + disallowed on those tables. + </para> + + <para> + Any column list must include the <literal>REPLICA IDENTITY</literal> columns + in order for <command>UPDATE</command> or <command>DELETE</command> + operations to be published. There are no column list restrictions if the + publication publishes only <command>INSERT</command> operations. + </para> + + <para> + A row filter expression (i.e., the <literal>WHERE</literal> clause) must contain only + columns that are covered by the <literal>REPLICA IDENTITY</literal>, in + order for <command>UPDATE</command> and <command>DELETE</command> operations + to be published. For publication of <command>INSERT</command> operations, + any column may be used in the <literal>WHERE</literal> expression. The + row filter allows simple expressions that don't have + user-defined functions, user-defined operators, user-defined types, + user-defined collations, non-immutable built-in functions, or references to + system columns. + </para> + + <para> + The row filter on a table becomes redundant if + <literal>FOR TABLES IN SCHEMA</literal> is specified and the table + belongs to the referred schema. + </para> + + <para> + For published partitioned tables, the row filter for each + partition is taken from the published partitioned table if the + publication parameter <literal>publish_via_partition_root</literal> is true, + or from the partition itself if it is false (the default). + See <xref linkend="logical-replication-row-filter"/> for details about row + filters. + Similarly, for published partitioned tables, the column list for each + partition is taken from the published partitioned table if the + publication parameter <literal>publish_via_partition_root</literal> is true, + or from the partition itself if it is false. + </para> + + <para> + For an <command>INSERT ... ON CONFLICT</command> command, the publication will + publish the operation that results from the command. Depending + on the outcome, it may be published as either <command>INSERT</command> or + <command>UPDATE</command>, or it may not be published at all. + </para> + + <para> + For a <command>MERGE</command> command, the publication will publish an + <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> + for each row inserted, updated, or deleted. + </para> + + <para> + <command>ATTACH</command>ing a table into a partition tree whose root is + published using a publication with <literal>publish_via_partition_root</literal> + set to <literal>true</literal> does not result in the table's existing contents + being replicated. + </para> + + <para> + <command>COPY ... FROM</command> commands are published + as <command>INSERT</command> operations. + </para> + + <para> + <acronym>DDL</acronym> operations are not published. + </para> + + <para> + The <literal>WHERE</literal> clause expression is executed with the role used + for the replication connection. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a publication that publishes all changes in two tables: +<programlisting> +CREATE PUBLICATION mypublication FOR TABLE users, departments; +</programlisting> + </para> + + <para> + Create a publication that publishes all changes from active departments: +<programlisting> +CREATE PUBLICATION active_departments FOR TABLE departments WHERE (active IS TRUE); +</programlisting> + </para> + + <para> + Create a publication that publishes all changes in all tables: +<programlisting> +CREATE PUBLICATION alltables FOR ALL TABLES; +</programlisting> + </para> + + <para> + Create a publication that only publishes <command>INSERT</command> + operations in one table: +<programlisting> +CREATE PUBLICATION insert_only FOR TABLE mydata + WITH (publish = 'insert'); +</programlisting> + </para> + + <para> + Create a publication that publishes all changes for tables + <structname>users</structname>, <structname>departments</structname> and + all changes for all the tables present in the schema + <structname>production</structname>: +<programlisting> +CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES IN SCHEMA production; +</programlisting> + </para> + + <para> + Create a publication that publishes all changes for all the tables present in + the schemas <structname>marketing</structname> and + <structname>sales</structname>: +<programlisting> +CREATE PUBLICATION sales_publication FOR TABLES IN SCHEMA marketing, sales; +</programlisting></para> + + <para> + Create a publication that publishes all changes for table <structname>users</structname>, + but replicates only columns <structname>user_id</structname> and + <structname>firstname</structname>: +<programlisting> +CREATE PUBLICATION users_filtered FOR TABLE users (user_id, firstname); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE PUBLICATION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterpublication"/></member> + <member><xref linkend="sql-droppublication"/></member> + <member><xref linkend="sql-createsubscription"/></member> + <member><xref linkend="sql-altersubscription"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_role.sgml b/doc/src/sgml/ref/create_role.sgml new file mode 100644 index 0000000..89df6db --- /dev/null +++ b/doc/src/sgml/ref/create_role.sgml @@ -0,0 +1,504 @@ +<!-- +doc/src/sgml/ref/create_role.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createrole"> + <indexterm zone="sql-createrole"> + <primary>CREATE ROLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE ROLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE ROLE</refname> + <refpurpose>define a new database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE ROLE <replaceable class="parameter">name</replaceable> [ [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + SUPERUSER | NOSUPERUSER + | CREATEDB | NOCREATEDB + | CREATEROLE | NOCREATEROLE + | INHERIT | NOINHERIT + | LOGIN | NOLOGIN + | REPLICATION | NOREPLICATION + | BYPASSRLS | NOBYPASSRLS + | CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + | [ ENCRYPTED ] PASSWORD '<replaceable class="parameter">password</replaceable>' | PASSWORD NULL + | VALID UNTIL '<replaceable class="parameter">timestamp</replaceable>' + | IN ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | IN GROUP <replaceable class="parameter">role_name</replaceable> [, ...] + | ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | ADMIN <replaceable class="parameter">role_name</replaceable> [, ...] + | USER <replaceable class="parameter">role_name</replaceable> [, ...] + | SYSID <replaceable class="parameter">uid</replaceable> +</synopsis> + </refsynopsisdiv> + +<!-- +CAUTION: remember to keep create_user.sgml and create_group.sgml +in sync when changing the above synopsis! +--> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE ROLE</command> adds a new role to a + <productname>PostgreSQL</productname> database cluster. A role is + an entity that can own database objects and have database privileges; + a role can be considered a <quote>user</quote>, a <quote>group</quote>, or both + depending on how it is used. Refer to + <xref linkend="user-manag"/> and <xref + linkend="client-authentication"/> for information about managing + users and authentication. You must have <literal>CREATEROLE</literal> + privilege or be a database superuser to use this command. + </para> + + <para> + Note that roles are defined at the database cluster + level, and so are valid in all databases in the cluster. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the new role. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SUPERUSER</literal></term> + <term><literal>NOSUPERUSER</literal></term> + <listitem> + <para> + These clauses determine whether the new role is a <quote>superuser</quote>, + who can override all access restrictions within the database. + Superuser status is dangerous and should be used only when really + needed. You must yourself be a superuser to create a new superuser. + If not specified, + <literal>NOSUPERUSER</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CREATEDB</literal></term> + <term><literal>NOCREATEDB</literal></term> + <listitem> + <para> + These clauses define a role's ability to create databases. If + <literal>CREATEDB</literal> is specified, the role being + defined will be allowed to create new databases. Specifying + <literal>NOCREATEDB</literal> will deny a role the ability to + create databases. If not specified, + <literal>NOCREATEDB</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CREATEROLE</literal></term> + <term><literal>NOCREATEROLE</literal></term> + <listitem> + <para> + These clauses determine whether a role will be permitted to + create, alter, drop, comment on, change the security label for, + and grant or revoke membership in other roles. + See <xref linkend='role-creation' /> for more details about what + capabilities are conferred by this privilege. + If not specified, <literal>NOCREATEROLE</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INHERIT</literal></term> + <term><literal>NOINHERIT</literal></term> + <listitem> + <para> + These clauses determine whether a role <quote>inherits</quote> the + privileges of roles it is a member of. + A role with the <literal>INHERIT</literal> attribute can automatically + use whatever database privileges have been granted to all roles + it is directly or indirectly a member of. + Without <literal>INHERIT</literal>, membership in another role + only grants the ability to <command>SET ROLE</command> to that other role; + the privileges of the other role are only available after having + done so. + If not specified, + <literal>INHERIT</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LOGIN</literal></term> + <term><literal>NOLOGIN</literal></term> + <listitem> + <para> + These clauses determine whether a role is allowed to log in; + that is, whether the role can be given as the initial session + authorization name during client connection. A role having + the <literal>LOGIN</literal> attribute can be thought of as a user. + Roles without this attribute are useful for managing database + privileges, but are not users in the usual sense of the word. + If not specified, + <literal>NOLOGIN</literal> is the default, except when + <command>CREATE ROLE</command> is invoked through its alternative spelling + <link linkend="sql-createuser"><command>CREATE USER</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REPLICATION</literal></term> + <term><literal>NOREPLICATION</literal></term> + <listitem> + <para> + These clauses determine whether a role is a replication role. A role + must have this attribute (or be a superuser) in order to be able to + connect to the server in replication mode (physical or logical + replication) and in order to be able to create or drop replication + slots. + A role having the <literal>REPLICATION</literal> attribute is a very + highly privileged role, and should only be used on roles actually + used for replication. If not specified, + <literal>NOREPLICATION</literal> is the default. + You must be a superuser to create a new role having the + <literal>REPLICATION</literal> attribute. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BYPASSRLS</literal></term> + <term><literal>NOBYPASSRLS</literal></term> + <listitem> + <para> + These clauses determine whether a role bypasses every row-level + security (RLS) policy. <literal>NOBYPASSRLS</literal> is the default. + You must be a superuser to create a new role having + the <literal>BYPASSRLS</literal> attribute. + </para> + + <para> + Note that pg_dump will set <literal>row_security</literal> to + <literal>OFF</literal> by default, to ensure all contents of a table are + dumped out. If the user running pg_dump does not have appropriate + permissions, an error will be returned. However, superusers and the + owner of the table being dumped always bypass RLS. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONNECTION LIMIT</literal> <replaceable class="parameter">connlimit</replaceable></term> + <listitem> + <para> + If role can log in, this specifies how many concurrent connections + the role can make. -1 (the default) means no limit. Note that only + normal connections are counted towards this limit. Neither prepared + transactions nor background worker connections are counted towards + this limit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>[ <literal>ENCRYPTED</literal> ] <literal>PASSWORD</literal> '<replaceable class="parameter">password</replaceable>'</term> + <term><literal>PASSWORD NULL</literal></term> + <listitem> + <para> + Sets the role's password. (A password is only of use for + roles having the <literal>LOGIN</literal> attribute, but you + can nonetheless define one for roles without it.) If you do + not plan to use password authentication you can omit this + option. If no password is specified, the password will be set + to null and password authentication will always fail for that + user. A null password can optionally be written explicitly as + <literal>PASSWORD NULL</literal>. + </para> + <note> + <para> + Specifying an empty string will also set the password to null, + but that was not the case before <productname>PostgreSQL</productname> + version 10. In earlier versions, an empty string could be used, + or not, depending on the authentication method and the exact + version, and libpq would refuse to use it in any case. + To avoid the ambiguity, specifying an empty string should be + avoided. + </para> + </note> + <para> + The password is always stored encrypted in the system catalogs. The + <literal>ENCRYPTED</literal> keyword has no effect, but is accepted for + backwards compatibility. The method of encryption is determined + by the configuration parameter <xref linkend="guc-password-encryption"/>. + If the presented password string is already in MD5-encrypted or + SCRAM-encrypted format, then it is stored as-is regardless of + <varname>password_encryption</varname> (since the system cannot decrypt + the specified encrypted password string, to encrypt it in a + different format). This allows reloading of encrypted passwords + during dump/restore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VALID UNTIL</literal> '<replaceable class="parameter">timestamp</replaceable>'</term> + <listitem> + <para> + The <literal>VALID UNTIL</literal> clause sets a date and + time after which the role's password is no longer valid. If + this clause is omitted the password will be valid for all time. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IN ROLE</literal> <replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The <literal>IN ROLE</literal> clause lists one or more existing + roles to which the new role will be immediately added as a new + member. (Note that there is no option to add the new role as an + administrator; use a separate <command>GRANT</command> command to do that.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IN GROUP</literal> <replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para><literal>IN GROUP</literal> is an obsolete spelling of + <literal>IN ROLE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ROLE</literal> <replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The <literal>ROLE</literal> clause lists one or more existing + roles which are automatically added as members of the new role. + (This in effect makes the new role a <quote>group</quote>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ADMIN</literal> <replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The <literal>ADMIN</literal> clause is like <literal>ROLE</literal>, + but the named roles are added to the new role <literal>WITH ADMIN + OPTION</literal>, giving them the right to grant membership in this role + to others. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USER</literal> <replaceable class="parameter">role_name</replaceable></term> + <listitem> + <para> + The <literal>USER</literal> clause is an obsolete spelling of + the <literal>ROLE</literal> clause. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SYSID</literal> <replaceable class="parameter">uid</replaceable></term> + <listitem> + <para> + The <literal>SYSID</literal> clause is ignored, but is accepted + for backwards compatibility. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-alterrole"><command>ALTER ROLE</command></link> to + change the attributes of a role, and <link linkend="sql-droprole"><command>DROP ROLE</command></link> + to remove a role. All the attributes + specified by <command>CREATE ROLE</command> can be modified by later + <command>ALTER ROLE</command> commands. + </para> + + <para> + The preferred way to add and remove members of roles that are being + used as groups is to use + <link linkend="sql-grant"><command>GRANT</command></link> and + <link linkend="sql-revoke"><command>REVOKE</command></link>. + </para> + + <para> + The <literal>VALID UNTIL</literal> clause defines an expiration time for a + password only, not for the role per se. In + particular, the expiration time is not enforced when logging in using + a non-password-based authentication method. + </para> + + <para> + The <literal>INHERIT</literal> attribute governs inheritance of grantable + privileges (that is, access privileges for database objects and role + memberships). It does not apply to the special role attributes set by + <command>CREATE ROLE</command> and <command>ALTER ROLE</command>. For example, being + a member of a role with <literal>CREATEDB</literal> privilege does not immediately + grant the ability to create databases, even if <literal>INHERIT</literal> is set; + it would be necessary to become that role via + <link linkend="sql-set-role"><command>SET ROLE</command></link> before + creating a database. + </para> + + <para> + The <literal>INHERIT</literal> attribute is the default for reasons of backwards + compatibility: in prior releases of <productname>PostgreSQL</productname>, + users always had access to all privileges of groups they were members of. + However, <literal>NOINHERIT</literal> provides a closer match to the semantics + specified in the SQL standard. + </para> + + <para> + Be careful with the <literal>CREATEROLE</literal> privilege. There is no concept of + inheritance for the privileges of a <literal>CREATEROLE</literal>-role. That + means that even if a role does not have a certain privilege but is allowed + to create other roles, it can easily create another role with different + privileges than its own (except for creating roles with superuser + privileges). For example, if the role <quote>user</quote> has the + <literal>CREATEROLE</literal> privilege but not the <literal>CREATEDB</literal> privilege, + nonetheless it can create a new role with the <literal>CREATEDB</literal> + privilege. Therefore, regard roles that have the <literal>CREATEROLE</literal> + privilege as almost-superuser-roles. + </para> + + <para> + <productname>PostgreSQL</productname> includes a program <xref + linkend="app-createuser"/> that has + the same functionality as <command>CREATE ROLE</command> (in fact, + it calls this command) but can be run from the command shell. + </para> + + <para> + The <literal>CONNECTION LIMIT</literal> option is only enforced approximately; + if two new sessions start at about the same time when just one + connection <quote>slot</quote> remains for the role, it is possible that + both will fail. Also, the limit is never enforced for superusers. + </para> + + <para> + Caution must be exercised when specifying an unencrypted password + with this command. The password will be transmitted to the server + in cleartext, and it might also be logged in the client's command + history or the server log. The command <xref + linkend="app-createuser"/>, however, transmits + the password encrypted. Also, <xref linkend="app-psql"/> + contains a command + <command>\password</command> that can be used to safely change the + password later. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a role that can log in, but don't give it a password: +<programlisting> +CREATE ROLE jonathan LOGIN; +</programlisting> + </para> + + <para> + Create a role with a password: +<programlisting> +CREATE USER davide WITH PASSWORD 'jw8s0F4'; +</programlisting> + (<command>CREATE USER</command> is the same as <command>CREATE ROLE</command> except + that it implies <literal>LOGIN</literal>.) + </para> + + <para> + Create a role with a password that is valid until the end of 2004. + After one second has ticked in 2005, the password is no longer + valid. + +<programlisting> +CREATE ROLE miriam WITH LOGIN PASSWORD 'jw8s0F4' VALID UNTIL '2005-01-01'; +</programlisting> + </para> + + <para> + Create a role that can create databases and manage roles: +<programlisting> +CREATE ROLE admin WITH CREATEDB CREATEROLE; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>CREATE ROLE</command> statement is in the SQL standard, + but the standard only requires the syntax +<synopsis> +CREATE ROLE <replaceable class="parameter">name</replaceable> [ WITH ADMIN <replaceable class="parameter">role_name</replaceable> ] +</synopsis> + Multiple initial administrators, and all the other options of + <command>CREATE ROLE</command>, are + <productname>PostgreSQL</productname> extensions. + </para> + + <para> + The SQL standard defines the concepts of users and roles, but it + regards them as distinct concepts and leaves all commands defining + users to be specified by each database implementation. In + <productname>PostgreSQL</productname> we have chosen to unify + users and roles into a single kind of entity. Roles therefore + have many more optional attributes than they do in the standard. + </para> + + <para> + The behavior specified by the SQL standard is most closely approximated + by giving users the <literal>NOINHERIT</literal> attribute, while roles are + given the <literal>INHERIT</literal> attribute. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set-role"/></member> + <member><xref linkend="sql-alterrole"/></member> + <member><xref linkend="sql-droprole"/></member> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-revoke"/></member> + <member><xref linkend="app-createuser"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_rule.sgml b/doc/src/sgml/ref/create_rule.sgml new file mode 100644 index 0000000..76029ab --- /dev/null +++ b/doc/src/sgml/ref/create_rule.sgml @@ -0,0 +1,307 @@ +<!-- +doc/src/sgml/ref/create_rule.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createrule"> + <indexterm zone="sql-createrule"> + <primary>CREATE RULE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE RULE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE RULE</refname> + <refpurpose>define a new rewrite rule</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] RULE <replaceable class="parameter">name</replaceable> AS ON <replaceable class="parameter">event</replaceable> + TO <replaceable class="parameter">table_name</replaceable> [ WHERE <replaceable class="parameter">condition</replaceable> ] + DO [ ALSO | INSTEAD ] { NOTHING | <replaceable class="parameter">command</replaceable> | ( <replaceable class="parameter">command</replaceable> ; <replaceable class="parameter">command</replaceable> ... ) } + +<phrase>where <replaceable class="parameter">event</replaceable> can be one of:</phrase> + + SELECT | INSERT | UPDATE | DELETE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE RULE</command> defines a new rule applying to a specified + table or view. + <command>CREATE OR REPLACE RULE</command> will either create a + new rule, or replace an existing rule of the same name for the same + table. + </para> + + <para> + The <productname>PostgreSQL</productname> rule system allows one to + define an alternative action to be performed on insertions, updates, + or deletions in database tables. Roughly speaking, a rule causes + additional commands to be executed when a given command on a given + table is executed. Alternatively, an <literal>INSTEAD</literal> + rule can replace a given command by another, or cause a command + not to be executed at all. Rules are used to implement SQL + views as well. It is important to realize that a rule is really + a command transformation mechanism, or command macro. The + transformation happens before the execution of the command starts. + If you actually want an operation that fires independently for each + physical row, you probably want to use a trigger, not a rule. + More information about the rules system is in <xref linkend="rules"/>. + </para> + + <para> + Presently, <literal>ON SELECT</literal> rules can only be attached + to views. (Attaching one to a table converts the table into a view.) + Such a rule must be named <literal>"_RETURN"</literal>, + must be an unconditional <literal>INSTEAD</literal> rule, and must have + an action that consists of a single <command>SELECT</command> command. + This command defines the visible contents of the view. (The view + itself is basically a dummy table with no storage.) It's best to + regard such a rule as an implementation detail. While a view can be + redefined via <literal>CREATE OR REPLACE RULE "_RETURN" AS + ...</literal>, it's better style to use <literal>CREATE OR REPLACE + VIEW</literal>. + </para> + + <para> + You can create the illusion of an updatable view by defining + <literal>ON INSERT</literal>, <literal>ON UPDATE</literal>, and + <literal>ON DELETE</literal> rules (or any subset of those that's + sufficient for your purposes) to replace update actions on the view + with appropriate updates on other tables. If you want to support + <command>INSERT RETURNING</command> and so on, then be sure to put a suitable + <literal>RETURNING</literal> clause into each of these rules. + </para> + + <para> + There is a catch if you try to use conditional rules for complex view + updates: there <emphasis>must</emphasis> be an unconditional + <literal>INSTEAD</literal> rule for each action you wish to allow + on the view. If the rule is conditional, or is not + <literal>INSTEAD</literal>, then the system will still reject + attempts to perform the update action, because it thinks it might + end up trying to perform the action on the dummy table of the view + in some cases. If you want to handle all the useful cases in + conditional rules, add an unconditional <literal>DO + INSTEAD NOTHING</literal> rule to ensure that the system + understands it will never be called on to update the dummy table. + Then make the conditional rules non-<literal>INSTEAD</literal>; in + the cases where they are applied, they add to the default + <literal>INSTEAD NOTHING</literal> action. (This method does not + currently work to support <literal>RETURNING</literal> queries, however.) + </para> + + <note> + <para> + A view that is simple enough to be automatically updatable (see <xref + linkend="sql-createview"/>) does not require a user-created rule in + order to be updatable. While you can create an explicit rule anyway, + the automatic update transformation will generally outperform an + explicit rule. + </para> + + <para> + Another alternative worth considering is to use <literal>INSTEAD OF</literal> + triggers (see <xref linkend="sql-createtrigger"/>) in place of rules. + </para> + </note> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a rule to create. This must be distinct from the + name of any other rule for the same table. Multiple rules on + the same table and same event type are applied in alphabetical + name order. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">event</replaceable></term> + <listitem> + <para> + The event is one of <literal>SELECT</literal>, + <literal>INSERT</literal>, <literal>UPDATE</literal>, or + <literal>DELETE</literal>. Note that an + <command>INSERT</command> containing an <literal>ON + CONFLICT</literal> clause cannot be used on tables that have + either <literal>INSERT</literal> or <literal>UPDATE</literal> + rules. Consider using an updatable view instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table or view the + rule applies to. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + Any <acronym>SQL</acronym> conditional expression (returning + <type>boolean</type>). The condition expression cannot refer + to any tables except <literal>NEW</literal> and <literal>OLD</literal>, and + cannot contain aggregate functions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>INSTEAD</option></term> + <listitem> + <para><literal>INSTEAD</literal> indicates that the commands should be + executed <emphasis>instead of</emphasis> the original command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>ALSO</option></term> + <listitem> + <para><literal>ALSO</literal> indicates that the commands should be + executed <emphasis>in addition to</emphasis> the original + command. + </para> + + <para> + If neither <literal>ALSO</literal> nor + <literal>INSTEAD</literal> is specified, <literal>ALSO</literal> + is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">command</replaceable></term> + <listitem> + <para> + The command or commands that make up the rule action. Valid + commands are <command>SELECT</command>, + <command>INSERT</command>, <command>UPDATE</command>, + <command>DELETE</command>, or <command>NOTIFY</command>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + Within <replaceable class="parameter">condition</replaceable> and + <replaceable class="parameter">command</replaceable>, the special + table names <literal>NEW</literal> and <literal>OLD</literal> can + be used to refer to values in the referenced table. + <literal>NEW</literal> is valid in <literal>ON INSERT</literal> and + <literal>ON UPDATE</literal> rules to refer to the new row being + inserted or updated. <literal>OLD</literal> is valid in + <literal>ON UPDATE</literal> and <literal>ON DELETE</literal> rules + to refer to the existing row being updated or deleted. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + You must be the owner of a table to create or change rules for it. + </para> + + <para> + In a rule for <literal>INSERT</literal>, <literal>UPDATE</literal>, or + <literal>DELETE</literal> on a view, you can add a <literal>RETURNING</literal> + clause that emits the view's columns. This clause will be used to compute + the outputs if the rule is triggered by an <command>INSERT RETURNING</command>, + <command>UPDATE RETURNING</command>, or <command>DELETE RETURNING</command> command + respectively. When the rule is triggered by a command without + <literal>RETURNING</literal>, the rule's <literal>RETURNING</literal> clause will be + ignored. The current implementation allows only unconditional + <literal>INSTEAD</literal> rules to contain <literal>RETURNING</literal>; furthermore + there can be at most one <literal>RETURNING</literal> clause among all the rules + for the same event. (This ensures that there is only one candidate + <literal>RETURNING</literal> clause to be used to compute the results.) + <literal>RETURNING</literal> queries on the view will be rejected if + there is no <literal>RETURNING</literal> clause in any available rule. + </para> + + <para> + It is very important to take care to avoid circular rules. For + example, though each of the following two rule definitions are + accepted by <productname>PostgreSQL</productname>, the + <command>SELECT</command> command would cause + <productname>PostgreSQL</productname> to report an error because + of recursive expansion of a rule: + +<programlisting> +CREATE RULE "_RETURN" AS + ON SELECT TO t1 + DO INSTEAD + SELECT * FROM t2; + +CREATE RULE "_RETURN" AS + ON SELECT TO t2 + DO INSTEAD + SELECT * FROM t1; + +SELECT * FROM t1; +</programlisting> + </para> + + <para> + Presently, if a rule action contains a <command>NOTIFY</command> + command, the <command>NOTIFY</command> command will be executed + unconditionally, that is, the <command>NOTIFY</command> will be + issued even if there are not any rows that the rule should apply + to. For example, in: +<programlisting> +CREATE RULE notify_me AS ON UPDATE TO mytable DO ALSO NOTIFY mytable; + +UPDATE mytable SET name = 'foo' WHERE id = 42; +</programlisting> + one <command>NOTIFY</command> event will be sent during the + <command>UPDATE</command>, whether or not there are any rows that + match the condition <literal>id = 42</literal>. This is an + implementation restriction that might be fixed in future releases. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE RULE</command> is a + <productname>PostgreSQL</productname> language extension, as is the + entire query rewrite system. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterrule"/></member> + <member><xref linkend="sql-droprule"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_schema.sgml b/doc/src/sgml/ref/create_schema.sgml new file mode 100644 index 0000000..3c2dddb --- /dev/null +++ b/doc/src/sgml/ref/create_schema.sgml @@ -0,0 +1,228 @@ +<!-- +doc/src/sgml/ref/create_schema.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createschema"> + <indexterm zone="sql-createschema"> + <primary>CREATE SCHEMA</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE SCHEMA</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE SCHEMA</refname> + <refpurpose>define a new schema</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE SCHEMA <replaceable class="parameter">schema_name</replaceable> [ AUTHORIZATION <replaceable class="parameter">role_specification</replaceable> ] [ <replaceable class="parameter">schema_element</replaceable> [ ... ] ] +CREATE SCHEMA AUTHORIZATION <replaceable class="parameter">role_specification</replaceable> [ <replaceable class="parameter">schema_element</replaceable> [ ... ] ] +CREATE SCHEMA IF NOT EXISTS <replaceable class="parameter">schema_name</replaceable> [ AUTHORIZATION <replaceable class="parameter">role_specification</replaceable> ] +CREATE SCHEMA IF NOT EXISTS AUTHORIZATION <replaceable class="parameter">role_specification</replaceable> + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + <replaceable class="parameter">user_name</replaceable> + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE SCHEMA</command> enters a new schema + into the current database. + The schema name must be distinct from the name of any existing schema + in the current database. + </para> + + <para> + A schema is essentially a namespace: + it contains named objects (tables, data types, functions, and operators) + whose names can duplicate those of other objects existing in other + schemas. Named objects are accessed either by <quote>qualifying</quote> + their names with the schema name as a prefix, or by setting a search + path that includes the desired schema(s). A <literal>CREATE</literal> command + specifying an unqualified object name creates the object + in the current schema (the one at the front of the search path, + which can be determined with the function <function>current_schema</function>). + </para> + + <para> + Optionally, <command>CREATE SCHEMA</command> can include subcommands + to create objects within the new schema. The subcommands are treated + essentially the same as separate commands issued after creating the + schema, except that if the <literal>AUTHORIZATION</literal> clause is used, + all the created objects will be owned by that user. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">schema_name</replaceable></term> + <listitem> + <para> + The name of a schema to be created. If this is omitted, the + <replaceable class="parameter">user_name</replaceable> + is used as the schema name. The name cannot + begin with <literal>pg_</literal>, as such names + are reserved for system schemas. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + The role name of the user who will own the new schema. If omitted, + defaults to the user executing the command. To create a schema + owned by another role, you must be a direct or indirect member of + that role, or be a superuser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">schema_element</replaceable></term> + <listitem> + <para> + An SQL statement defining an object to be created within the + schema. Currently, only <command>CREATE + TABLE</command>, <command>CREATE VIEW</command>, <command>CREATE + INDEX</command>, <command>CREATE SEQUENCE</command>, <command>CREATE + TRIGGER</command> and <command>GRANT</command> are accepted as clauses + within <command>CREATE SCHEMA</command>. Other kinds of objects may + be created in separate commands after the schema is created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do nothing (except issuing a notice) if a schema with the same name + already exists. <replaceable class="parameter">schema_element</replaceable> + subcommands cannot be included when this option is used. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + To create a schema, the invoking user must have the + <literal>CREATE</literal> privilege for the current database. + (Of course, superusers bypass this check.) + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a schema: +<programlisting> +CREATE SCHEMA myschema; +</programlisting> + </para> + + <para> + Create a schema for user <literal>joe</literal>; the schema will also be + named <literal>joe</literal>: +<programlisting> +CREATE SCHEMA AUTHORIZATION joe; +</programlisting> + </para> + + <para> + Create a schema named <literal>test</literal> that will be owned by user + <literal>joe</literal>, unless there already is a schema named <literal>test</literal>. + (It does not matter whether <literal>joe</literal> owns the pre-existing schema.) +<programlisting> +CREATE SCHEMA IF NOT EXISTS test AUTHORIZATION joe; +</programlisting> + </para> + + <para> + Create a schema and create a table and view within it: +<programlisting> +CREATE SCHEMA hollywood + CREATE TABLE films (title text, release date, awards text[]) + CREATE VIEW winners AS + SELECT title, release FROM films WHERE awards IS NOT NULL; +</programlisting> + Notice that the individual subcommands do not end with semicolons. + </para> + + <para> + The following is an equivalent way of accomplishing the same result: +<programlisting> +CREATE SCHEMA hollywood; +CREATE TABLE hollywood.films (title text, release date, awards text[]); +CREATE VIEW hollywood.winners AS + SELECT title, release FROM hollywood.films WHERE awards IS NOT NULL; +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard allows a <literal>DEFAULT CHARACTER SET</literal> clause + in <command>CREATE SCHEMA</command>, as well as more subcommand + types than are presently accepted by + <productname>PostgreSQL</productname>. + </para> + + <para> + The SQL standard specifies that the subcommands in <command>CREATE + SCHEMA</command> can appear in any order. The present + <productname>PostgreSQL</productname> implementation does not + handle all cases of forward references in subcommands; it might + sometimes be necessary to reorder the subcommands in order to avoid + forward references. + </para> + + <para> + According to the SQL standard, the owner of a schema always owns + all objects within it. <productname>PostgreSQL</productname> + allows schemas to contain objects owned by users other than the + schema owner. This can happen only if the schema owner grants the + <literal>CREATE</literal> privilege on their schema to someone else, or a + superuser chooses to create objects in it. + </para> + + <para> + The <literal>IF NOT EXISTS</literal> option is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterschema"/></member> + <member><xref linkend="sql-dropschema"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_sequence.sgml b/doc/src/sgml/ref/create_sequence.sgml new file mode 100644 index 0000000..34e9084 --- /dev/null +++ b/doc/src/sgml/ref/create_sequence.sgml @@ -0,0 +1,413 @@ +<!-- +doc/src/sgml/ref/create_sequence.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createsequence"> + <indexterm zone="sql-createsequence"> + <primary>CREATE SEQUENCE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE SEQUENCE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE SEQUENCE</refname> + <refpurpose>define a new sequence generator</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ { TEMPORARY | TEMP } | UNLOGGED ] SEQUENCE [ IF NOT EXISTS ] <replaceable class="parameter">name</replaceable> + [ AS <replaceable class="parameter">data_type</replaceable> ] + [ INCREMENT [ BY ] <replaceable class="parameter">increment</replaceable> ] + [ MINVALUE <replaceable class="parameter">minvalue</replaceable> | NO MINVALUE ] [ MAXVALUE <replaceable class="parameter">maxvalue</replaceable> | NO MAXVALUE ] + [ START [ WITH ] <replaceable class="parameter">start</replaceable> ] [ CACHE <replaceable class="parameter">cache</replaceable> ] [ [ NO ] CYCLE ] + [ OWNED BY { <replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable> | NONE } ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE SEQUENCE</command> creates a new sequence number + generator. This involves creating and initializing a new special + single-row table with the name <replaceable + class="parameter">name</replaceable>. The generator will be + owned by the user issuing the command. + </para> + + <para> + If a schema name is given then the sequence is created in the + specified schema. Otherwise it is created in the current schema. + Temporary sequences exist in a special schema, so a schema name cannot be + given when creating a temporary sequence. + The sequence name must be distinct from the name of any other relation + (table, sequence, index, view, materialized view, or foreign table) in + the same schema. + </para> + + <para> + After a sequence is created, you use the functions + <function>nextval</function>, + <function>currval</function>, and + <function>setval</function> + to operate on the sequence. These functions are documented in + <xref linkend="functions-sequence"/>. + </para> + + <para> + Although you cannot update a sequence directly, you can use a query like: + +<programlisting> +SELECT * FROM <replaceable>name</replaceable>; +</programlisting> + + to examine the parameters and current state of a sequence. In particular, + the <literal>last_value</literal> field of the sequence shows the last value + allocated by any session. (Of course, this value might be obsolete + by the time it's printed, if other sessions are actively doing + <function>nextval</function> calls.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + If specified, the sequence object is created only for this + session, and is automatically dropped on session exit. Existing + permanent sequences with the same name are not visible (in this + session) while the temporary sequence exists, unless they are + referenced with schema-qualified names. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>UNLOGGED</literal></term> + <listitem> + <para> + If specified, the sequence is created as an unlogged sequence. Changes + to unlogged sequences are not written to the write-ahead log. They are + not crash-safe: an unlogged sequence is automatically reset to its + initial state after a crash or unclean shutdown. Unlogged sequences are + also not replicated to standby servers. + </para> + + <para> + Unlike unlogged tables, unlogged sequences do not offer a significant + performance advantage. This option is mainly intended for sequences + associated with unlogged tables via identity columns or serial columns. + In those cases, it usually wouldn't make sense to have the sequence + WAL-logged and replicated but not its associated table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a relation with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing relation is anything like the sequence that would have + been created — it might not even be a sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the sequence to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The optional + clause <literal>AS <replaceable class="parameter">data_type</replaceable></literal> + specifies the data type of the sequence. Valid types are + <literal>smallint</literal>, <literal>integer</literal>, + and <literal>bigint</literal>. <literal>bigint</literal> is the + default. The data type determines the default minimum and maximum + values of the sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">increment</replaceable></term> + <listitem> + <para> + The optional clause <literal>INCREMENT BY <replaceable + class="parameter">increment</replaceable></literal> specifies + which value is added to the current sequence value to create a + new value. A positive value will make an ascending sequence, a + negative one a descending sequence. The default value is 1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">minvalue</replaceable></term> + <term><literal>NO MINVALUE</literal></term> + <listitem> + <para> + The optional clause <literal>MINVALUE <replaceable + class="parameter">minvalue</replaceable></literal> determines + the minimum value a sequence can generate. If this clause is not + supplied or <option>NO MINVALUE</option> is specified, then + defaults will be used. The default for an ascending sequence is 1. The + default for a descending sequence is the minimum value of the data type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">maxvalue</replaceable></term> + <term><literal>NO MAXVALUE</literal></term> + <listitem> + <para> + The optional clause <literal>MAXVALUE <replaceable + class="parameter">maxvalue</replaceable></literal> determines + the maximum value for the sequence. If this clause is not + supplied or <option>NO MAXVALUE</option> is specified, then + default values will be used. The default for an ascending sequence is + the maximum value of the data type. The default for a descending + sequence is -1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">start</replaceable></term> + <listitem> + <para> + The optional clause <literal>START WITH <replaceable + class="parameter">start</replaceable> </literal> allows the + sequence to begin anywhere. The default starting value is + <replaceable class="parameter">minvalue</replaceable> for + ascending sequences and <replaceable + class="parameter">maxvalue</replaceable> for descending ones. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">cache</replaceable></term> + <listitem> + <para> + The optional clause <literal>CACHE <replaceable + class="parameter">cache</replaceable></literal> specifies how + many sequence numbers are to be preallocated and stored in + memory for faster access. The minimum value is 1 (only one value + can be generated at a time, i.e., no cache), and this is also the + default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CYCLE</literal></term> + <term><literal>NO CYCLE</literal></term> + <listitem> + <para> + The <literal>CYCLE</literal> option allows the sequence to wrap + around when the <replaceable + class="parameter">maxvalue</replaceable> or <replaceable + class="parameter">minvalue</replaceable> has been reached by an + ascending or descending sequence respectively. If the limit is + reached, the next number generated will be the <replaceable + class="parameter">minvalue</replaceable> or <replaceable + class="parameter">maxvalue</replaceable>, respectively. + </para> + + <para> + If <literal>NO CYCLE</literal> is specified, any calls to + <function>nextval</function> after the sequence has reached its + maximum value will return an error. If neither + <literal>CYCLE</literal> or <literal>NO CYCLE</literal> are + specified, <literal>NO CYCLE</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OWNED BY</literal> <replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable></term> + <term><literal>OWNED BY NONE</literal></term> + <listitem> + <para> + The <literal>OWNED BY</literal> option causes the sequence to be + associated with a specific table column, such that if that column + (or its whole table) is dropped, the sequence will be automatically + dropped as well. The specified table must have the same owner and be in + the same schema as the sequence. + <literal>OWNED BY NONE</literal>, the default, specifies that there + is no such association. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <command>DROP SEQUENCE</command> to remove a sequence. + </para> + + <para> + Sequences are based on <type>bigint</type> arithmetic, so the range + cannot exceed the range of an eight-byte integer + (-9223372036854775808 to 9223372036854775807). + </para> + + <para> + Because <function>nextval</function> and <function>setval</function> calls are never + rolled back, sequence objects cannot be used if <quote>gapless</quote> + assignment of sequence numbers is needed. It is possible to build + gapless assignment by using exclusive locking of a table containing a + counter; but this solution is much more expensive than sequence + objects, especially if many transactions need sequence numbers + concurrently. + </para> + + <para> + Unexpected results might be obtained if a <replaceable + class="parameter">cache</replaceable> setting greater than one is + used for a sequence object that will be used concurrently by + multiple sessions. Each session will allocate and cache successive + sequence values during one access to the sequence object and + increase the sequence object's <literal>last_value</literal> accordingly. + Then, the next <replaceable class="parameter">cache</replaceable>-1 + uses of <function>nextval</function> within that session simply return the + preallocated values without touching the sequence object. So, any + numbers allocated but not used within a session will be lost when + that session ends, resulting in <quote>holes</quote> in the + sequence. + </para> + + <para> + Furthermore, although multiple sessions are guaranteed to allocate + distinct sequence values, the values might be generated out of + sequence when all the sessions are considered. For example, with + a <replaceable class="parameter">cache</replaceable> setting of 10, + session A might reserve values 1..10 and return + <function>nextval</function>=1, then session B might reserve values + 11..20 and return <function>nextval</function>=11 before session A + has generated <function>nextval</function>=2. Thus, with a + <replaceable class="parameter">cache</replaceable> setting of one + it is safe to assume that <function>nextval</function> values are generated + sequentially; with a <replaceable + class="parameter">cache</replaceable> setting greater than one you + should only assume that the <function>nextval</function> values are all + distinct, not that they are generated purely sequentially. Also, + <literal>last_value</literal> will reflect the latest value reserved by + any session, whether or not it has yet been returned by + <function>nextval</function>. + </para> + + <para> + Another consideration is that a <function>setval</function> executed on + such a sequence will not be noticed by other sessions until they + have used up any preallocated values they have cached. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create an ascending sequence called <literal>serial</literal>, starting at 101: +<programlisting> +CREATE SEQUENCE serial START 101; +</programlisting> + </para> + + <para> + Select the next number from this sequence: +<programlisting> +SELECT nextval('serial'); + + nextval +--------- + 101 +</programlisting> + </para> + + <para> + Select the next number from this sequence: +<programlisting> +SELECT nextval('serial'); + + nextval +--------- + 102 +</programlisting> + </para> + + <para> + Use this sequence in an <command>INSERT</command> command: +<programlisting> +INSERT INTO distributors VALUES (nextval('serial'), 'nothing'); +</programlisting> + </para> + + <para> + Update the sequence value after a <command>COPY FROM</command>: +<programlisting> +BEGIN; +COPY distributors FROM 'input_file'; +SELECT setval('serial', max(id)) FROM distributors; +END; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE SEQUENCE</command> conforms to the <acronym>SQL</acronym> + standard, with the following exceptions: + <itemizedlist> + <listitem> + <para> + Obtaining the next value is done using the <function>nextval()</function> + function instead of the standard's <command>NEXT VALUE FOR</command> + expression. + </para> + </listitem> + <listitem> + <para> + The <literal>OWNED BY</literal> clause is a <productname>PostgreSQL</productname> + extension. + </para> + </listitem> + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altersequence"/></member> + <member><xref linkend="sql-dropsequence"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_server.sgml b/doc/src/sgml/ref/create_server.sgml new file mode 100644 index 0000000..05f4019 --- /dev/null +++ b/doc/src/sgml/ref/create_server.sgml @@ -0,0 +1,172 @@ +<!-- +doc/src/sgml/ref/create_server.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createserver"> + <indexterm zone="sql-createserver"> + <primary>CREATE SERVER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE SERVER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE SERVER</refname> + <refpurpose>define a new foreign server</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE SERVER [ IF NOT EXISTS ] <replaceable class="parameter">server_name</replaceable> [ TYPE '<replaceable class="parameter">server_type</replaceable>' ] [ VERSION '<replaceable class="parameter">server_version</replaceable>' ] + FOREIGN DATA WRAPPER <replaceable class="parameter">fdw_name</replaceable> + [ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE SERVER</command> defines a new foreign server. The + user who defines the server becomes its owner. + </para> + + <para> + A foreign server typically encapsulates connection information that + a foreign-data wrapper uses to access an external data resource. + Additional user-specific connection information may be specified by + means of user mappings. + </para> + + <para> + The server name must be unique within the database. + </para> + + <para> + Creating a server requires <literal>USAGE</literal> privilege on the + foreign-data wrapper being used. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a server with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing server is anything like the one that would have been + created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + The name of the foreign server to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_type</replaceable></term> + <listitem> + <para> + Optional server type, potentially useful to foreign-data wrappers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_version</replaceable></term> + <listitem> + <para> + Optional server version, potentially useful to foreign-data wrappers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">fdw_name</replaceable></term> + <listitem> + <para> + The name of the foreign-data wrapper that manages the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies the options for the server. The options + typically define the connection details of the server, but the + actual names and values are dependent on the server's + foreign-data wrapper. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + When using the <xref linkend="dblink"/> module, + a foreign server's name can be used + as an argument of the <xref linkend="contrib-dblink-connect"/> + function to indicate the connection parameters. It is necessary to have + the <literal>USAGE</literal> privilege on the foreign server to be + able to use it in this way. + </para> + + <para> + If the foreign server supports sort pushdown, it is necessary for it + to have the same sort ordering as the local server. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a server <literal>myserver</literal> that uses the + foreign-data wrapper <literal>postgres_fdw</literal>: +<programlisting> +CREATE SERVER myserver FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'foo', dbname 'foodb', port '5432'); +</programlisting> + See <xref linkend="postgres-fdw"/> for more details. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE SERVER</command> conforms to ISO/IEC 9075-9 (SQL/MED). + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterserver"/></member> + <member><xref linkend="sql-dropserver"/></member> + <member><xref linkend="sql-createforeigndatawrapper"/></member> + <member><xref linkend="sql-createforeigntable"/></member> + <member><xref linkend="sql-createusermapping"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_statistics.sgml b/doc/src/sgml/ref/create_statistics.sgml new file mode 100644 index 0000000..a145c41 --- /dev/null +++ b/doc/src/sgml/ref/create_statistics.sgml @@ -0,0 +1,331 @@ +<!-- +doc/src/sgml/ref/create_statistics.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createstatistics"> + <indexterm zone="sql-createstatistics"> + <primary>CREATE STATISTICS</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE STATISTICS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE STATISTICS</refname> + <refpurpose>define extended statistics</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE STATISTICS [ IF NOT EXISTS ] <replaceable class="parameter">statistics_name</replaceable> + ON ( <replaceable class="parameter">expression</replaceable> ) + FROM <replaceable class="parameter">table_name</replaceable> + +CREATE STATISTICS [ IF NOT EXISTS ] <replaceable class="parameter">statistics_name</replaceable> + [ ( <replaceable class="parameter">statistics_kind</replaceable> [, ... ] ) ] + ON { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) }, { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [, ...] + FROM <replaceable class="parameter">table_name</replaceable> +</synopsis> + + </refsynopsisdiv> + + <refsect1 id="sql-createstatistics-description"> + <title>Description</title> + + <para> + <command>CREATE STATISTICS</command> will create a new extended statistics + object tracking data about the specified table, foreign table or + materialized view. The statistics object will be created in the current + database and will be owned by the user issuing the command. + </para> + + <para> + The <command>CREATE STATISTICS</command> command has two basic forms. The + first form allows univariate statistics for a single expression to be + collected, providing benefits similar to an expression index without the + overhead of index maintenance. This form does not allow the statistics + kind to be specified, since the various statistics kinds refer only to + multivariate statistics. The second form of the command allows + multivariate statistics on multiple columns and/or expressions to be + collected, optionally specifying which statistics kinds to include. This + form will also automatically cause univariate statistics to be collected on + any expressions included in the list. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE STATISTICS + myschema.mystat ...</literal>) then the statistics object is created in the + specified schema. Otherwise it is created in the current schema. + The name of the statistics object must be distinct from the name of any + other statistics object in the same schema. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a statistics object with the same name already + exists. A notice is issued in this case. Note that only the name of + the statistics object is considered here, not the details of its + definition. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">statistics_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the statistics object to be + created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">statistics_kind</replaceable></term> + <listitem> + <para> + A multivariate statistics kind to be computed in this statistics object. + Currently supported kinds are + <literal>ndistinct</literal>, which enables n-distinct statistics, + <literal>dependencies</literal>, which enables functional + dependency statistics, and <literal>mcv</literal> which enables + most-common values lists. + If this clause is omitted, all supported statistics kinds are + included in the statistics object. Univariate expression statistics are + built automatically if the statistics definition includes any complex + expressions rather than just simple column references. + For more information, see <xref linkend="planner-stats-extended"/> + and <xref linkend="multivariate-statistics-examples"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a table column to be covered by the computed statistics. + This is only allowed when building multivariate statistics. At least + two column names or expressions must be specified, and their order is + not significant. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + An expression to be covered by the computed statistics. This may be + used to build univariate statistics on a single expression, or as part + of a list of multiple column names and/or expressions to build + multivariate statistics. In the latter case, separate univariate + statistics are built automatically for each expression in the list. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table containing the + column(s) the statistics are computed on; see <xref + linkend="sql-analyze"/> for an explanation of the handling of + inheritance and partitions. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + You must be the owner of a table to create a statistics object + reading it. Once created, however, the ownership of the statistics + object is independent of the underlying table(s). + </para> + + <para> + Expression statistics are per-expression and are similar to creating an + index on the expression, except that they avoid the overhead of index + maintenance. Expression statistics are built automatically for each + expression in the statistics object definition. + </para> + + <para> + Extended statistics are not currently used by the planner for selectivity + estimations made for table joins. This limitation will likely be removed + in a future version of <productname>PostgreSQL</productname>. + </para> + </refsect1> + + <refsect1 id="sql-createstatistics-examples"> + <title>Examples</title> + + <para> + Create table <structname>t1</structname> with two functionally dependent columns, i.e., + knowledge of a value in the first column is sufficient for determining the + value in the other column. Then functional dependency statistics are built + on those columns: + +<programlisting> +CREATE TABLE t1 ( + a int, + b int +); + +INSERT INTO t1 SELECT i/100, i/500 + FROM generate_series(1,1000000) s(i); + +ANALYZE t1; + +-- the number of matching rows will be drastically underestimated: +EXPLAIN ANALYZE SELECT * FROM t1 WHERE (a = 1) AND (b = 0); + +CREATE STATISTICS s1 (dependencies) ON a, b FROM t1; + +ANALYZE t1; + +-- now the row count estimate is more accurate: +EXPLAIN ANALYZE SELECT * FROM t1 WHERE (a = 1) AND (b = 0); +</programlisting> + + Without functional-dependency statistics, the planner would assume + that the two <literal>WHERE</literal> conditions are independent, and would + multiply their selectivities together to arrive at a much-too-small + row count estimate. + With such statistics, the planner recognizes that the <literal>WHERE</literal> + conditions are redundant and does not underestimate the row count. + </para> + + <para> + Create table <structname>t2</structname> with two perfectly correlated columns + (containing identical data), and an MCV list on those columns: + +<programlisting> +CREATE TABLE t2 ( + a int, + b int +); + +INSERT INTO t2 SELECT mod(i,100), mod(i,100) + FROM generate_series(1,1000000) s(i); + +CREATE STATISTICS s2 (mcv) ON a, b FROM t2; + +ANALYZE t2; + +-- valid combination (found in MCV) +EXPLAIN ANALYZE SELECT * FROM t2 WHERE (a = 1) AND (b = 1); + +-- invalid combination (not found in MCV) +EXPLAIN ANALYZE SELECT * FROM t2 WHERE (a = 1) AND (b = 2); +</programlisting> + + The MCV list gives the planner more detailed information about the + specific values that commonly appear in the table, as well as an upper + bound on the selectivities of combinations of values that do not appear + in the table, allowing it to generate better estimates in both cases. + </para> + + <para> + Create table <structname>t3</structname> with a single timestamp column, + and run queries using expressions on that column. Without extended + statistics, the planner has no information about the data distribution for + the expressions, and uses default estimates. The planner also does not + realize that the value of the date truncated to the month is fully + determined by the value of the date truncated to the day. Then expression + and ndistinct statistics are built on those two expressions: + +<programlisting> +CREATE TABLE t3 ( + a timestamp +); + +INSERT INTO t3 SELECT i FROM generate_series('2020-01-01'::timestamp, + '2020-12-31'::timestamp, + '1 minute'::interval) s(i); + +ANALYZE t3; + +-- the number of matching rows will be drastically underestimated: +EXPLAIN ANALYZE SELECT * FROM t3 + WHERE date_trunc('month', a) = '2020-01-01'::timestamp; + +EXPLAIN ANALYZE SELECT * FROM t3 + WHERE date_trunc('day', a) BETWEEN '2020-01-01'::timestamp + AND '2020-06-30'::timestamp; + +EXPLAIN ANALYZE SELECT date_trunc('month', a), date_trunc('day', a) + FROM t3 GROUP BY 1, 2; + +-- build ndistinct statistics on the pair of expressions (per-expression +-- statistics are built automatically) +CREATE STATISTICS s3 (ndistinct) ON date_trunc('month', a), date_trunc('day', a) FROM t3; + +ANALYZE t3; + +-- now the row count estimates are more accurate: +EXPLAIN ANALYZE SELECT * FROM t3 + WHERE date_trunc('month', a) = '2020-01-01'::timestamp; + +EXPLAIN ANALYZE SELECT * FROM t3 + WHERE date_trunc('day', a) BETWEEN '2020-01-01'::timestamp + AND '2020-06-30'::timestamp; + +EXPLAIN ANALYZE SELECT date_trunc('month', a), date_trunc('day', a) + FROM t3 GROUP BY 1, 2; +</programlisting> + + Without expression and ndistinct statistics, the planner has no information + about the number of distinct values for the expressions, and has to rely + on default estimates. The equality and range conditions are assumed to have + 0.5% selectivity, and the number of distinct values in the expression is + assumed to be the same as for the column (i.e. unique). This results in a + significant underestimate of the row count in the first two queries. Moreover, + the planner has no information about the relationship between the expressions, + so it assumes the two <literal>WHERE</literal> and <literal>GROUP BY</literal> + conditions are independent, and multiplies their selectivities together to + arrive at a severe overestimate of the group count in the aggregate query. + This is further exacerbated by the lack of accurate statistics for the + expressions, forcing the planner to use a default ndistinct estimate for the + expression derived from ndistinct for the column. With such statistics, the + planner recognizes that the conditions are correlated, and arrives at much + more accurate estimates. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CREATE STATISTICS</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterstatistics"/></member> + <member><xref linkend="sql-dropstatistics"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_subscription.sgml b/doc/src/sgml/ref/create_subscription.sgml new file mode 100644 index 0000000..3eb1ead --- /dev/null +++ b/doc/src/sgml/ref/create_subscription.sgml @@ -0,0 +1,422 @@ +<!-- +doc/src/sgml/ref/create_subscription.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createsubscription"> + <indexterm zone="sql-createsubscription"> + <primary>CREATE SUBSCRIPTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE SUBSCRIPTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE SUBSCRIPTION</refname> + <refpurpose>define a new subscription</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE SUBSCRIPTION <replaceable class="parameter">subscription_name</replaceable> + CONNECTION '<replaceable class="parameter">conninfo</replaceable>' + PUBLICATION <replaceable class="parameter">publication_name</replaceable> [, ...] + [ WITH ( <replaceable class="parameter">subscription_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE SUBSCRIPTION</command> adds a new logical-replication + subscription. The subscription name must be distinct from the name of + any existing subscription in the current database. + </para> + + <para> + A subscription represents a replication connection to the publisher. + Hence, in addition to adding definitions in the local catalogs, this + command normally creates a replication slot on the publisher. + </para> + + <para> + A logical replication worker will be started to replicate data for the new + subscription at the commit of the transaction where this command is run, + unless the subscription is initially disabled. + </para> + + <para> + Additional information about subscriptions and logical replication as a + whole is available at <xref linkend="logical-replication-subscription"/> and + <xref linkend="logical-replication"/>. + </para> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">subscription_name</replaceable></term> + <listitem> + <para> + The name of the new subscription. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONNECTION '<replaceable class="parameter">conninfo</replaceable>'</literal></term> + <listitem> + <para> + The <application>libpq</application> connection string defining how + to connect to the publisher database. For details see + <xref linkend="libpq-connstring"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PUBLICATION <replaceable class="parameter">publication_name</replaceable> [, ...]</literal></term> + <listitem> + <para> + Names of the publications on the publisher to subscribe to. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">subscription_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional parameters for a subscription. + </para> + + <para> + The following parameters control what happens during subscription creation: + + <variablelist> + + <varlistentry> + <term><literal>connect</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether the <command>CREATE SUBSCRIPTION</command> + command should connect to the publisher at all. The default + is <literal>true</literal>. Setting this to + <literal>false</literal> will force the values of + <literal>create_slot</literal>, <literal>enabled</literal> and + <literal>copy_data</literal> to <literal>false</literal>. + (You cannot combine setting <literal>connect</literal> + to <literal>false</literal> with + setting <literal>create_slot</literal>, <literal>enabled</literal>, + or <literal>copy_data</literal> to <literal>true</literal>.) + </para> + + <para> + Since no connection is made when this option is + <literal>false</literal>, no tables are subscribed, and so + after you enable the subscription nothing will be replicated. + You will need to then run + <literal>ALTER SUBSCRIPTION ... REFRESH PUBLICATION</literal> + for tables to be subscribed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>create_slot</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether the command should create the replication slot on + the publisher. The default is <literal>true</literal>. + If set to <literal>false</literal>, you are responsible for + creating the publisher's slot in some other way. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>enabled</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether the subscription should be actively replicating + or whether it should just be set up but not started yet. The default + is <literal>true</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>slot_name</literal> (<type>string</type>)</term> + <listitem> + <para> + Name of the publisher's replication slot to use. The default is + to use the name of the subscription for the slot name. + </para> + + <para> + Setting <literal>slot_name</literal> to <literal>NONE</literal> + means there will be no replication slot + associated with the subscription. Use this when you will be + creating the replication slot later manually. Such + subscriptions must also have both <literal>enabled</literal> and + <literal>create_slot</literal> set to <literal>false</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following parameters control the subscription's replication + behavior after it has been created: + + <variablelist> + + <varlistentry> + <term><literal>binary</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether the subscription will request the publisher to + send the data in binary format (as opposed to text). + The default is <literal>false</literal>. + Even when this option is enabled, only data types having + binary send and receive functions will be transferred in binary. + </para> + + <para> + When doing cross-version replication, it could be that the + publisher has a binary send function for some data type, but the + subscriber lacks a binary receive function for that type. In + such a case, data transfer will fail, and + the <literal>binary</literal> option cannot be used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>copy_data</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether to copy pre-existing data in the publications + that are being subscribed to when the replication starts. + The default is <literal>true</literal>. + </para> + <para> + If the publications contain <literal>WHERE</literal> clauses, it + will affect what data is copied. Refer to the + <xref linkend="sql-createsubscription-notes" /> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>streaming</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether to enable streaming of in-progress transactions + for this subscription. By default, all transactions + are fully decoded on the publisher and only then sent to the + subscriber as a whole. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>synchronous_commit</literal> (<type>enum</type>)</term> + <listitem> + <para> + The value of this parameter overrides the + <xref linkend="guc-synchronous-commit"/> setting within this + subscription's apply worker processes. The default value + is <literal>off</literal>. + </para> + + <para> + It is safe to use <literal>off</literal> for logical replication: + If the subscriber loses transactions because of missing + synchronization, the data will be sent again from the publisher. + </para> + + <para> + A different setting might be appropriate when doing synchronous + logical replication. The logical replication workers report the + positions of writes and flushes to the publisher, and when using + synchronous replication, the publisher will wait for the actual + flush. This means that setting + <literal>synchronous_commit</literal> for the subscriber to + <literal>off</literal> when the subscription is used for + synchronous replication might increase the latency for + <command>COMMIT</command> on the publisher. In this scenario, it + can be advantageous to set <literal>synchronous_commit</literal> + to <literal>local</literal> or higher. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>two_phase</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether two-phase commit is enabled for this subscription. + The default is <literal>false</literal>. + </para> + + <para> + When two-phase commit is enabled, prepared transactions are sent + to the subscriber at the time of <command>PREPARE + TRANSACTION</command>, and are processed as two-phase + transactions on the subscriber too. Otherwise, prepared + transactions are sent to the subscriber only when committed, and + are then processed immediately by the subscriber. + </para> + + <para> + The implementation of two-phase commit requires that replication + has successfully finished the initial table synchronization + phase. So even when <literal>two_phase</literal> is enabled for a + subscription, the internal two-phase state remains + temporarily <quote>pending</quote> until the initialization phase + completes. See column <structfield>subtwophasestate</structfield> + of <link linkend="catalog-pg-subscription"><structname>pg_subscription</structname></link> + to know the actual two-phase state. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>disable_on_error</literal> (<type>boolean</type>)</term> + <listitem> + <para> + Specifies whether the subscription should be automatically disabled + if any errors are detected by subscription workers during data + replication from the publisher. The default is + <literal>false</literal>. + </para> + </listitem> + </varlistentry> + </variablelist></para> + + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createsubscription-notes" xreflabel="Notes"> + <title>Notes</title> + + <para> + See <xref linkend="logical-replication-security"/> for details on + how to configure access control between the subscription and the + publication instance. + </para> + + <para> + When creating a replication slot (the default behavior), <command>CREATE + SUBSCRIPTION</command> cannot be executed inside a transaction block. + </para> + + <para> + Creating a subscription that connects to the same database cluster (for + example, to replicate between databases in the same cluster or to replicate + within the same database) will only succeed if the replication slot is not + created as part of the same command. Otherwise, the <command>CREATE + SUBSCRIPTION</command> call will hang. To make this work, create the + replication slot separately (using the + function <function>pg_create_logical_replication_slot</function> with the + plugin name <literal>pgoutput</literal>) and create the subscription using + the parameter <literal>create_slot = false</literal>. This is an + implementation restriction that might be lifted in a future release. + </para> + + <para> + If any table in the publication has a <literal>WHERE</literal> clause, rows + for which the <replaceable class="parameter">expression</replaceable> + evaluates to false or null will not be published. If the subscription has + several publications in which the same table has been published with + different <literal>WHERE</literal> clauses, a row will be published if any + of the expressions (referring to that publish operation) are satisfied. In + the case of different <literal>WHERE</literal> clauses, if one of the + publications has no <literal>WHERE</literal> clause (referring to that + publish operation) or the publication is declared as + <literal>FOR ALL TABLES</literal> or + <literal>FOR TABLES IN SCHEMA</literal>, rows are always published + regardless of the definition of the other expressions. + If the subscriber is a <productname>PostgreSQL</productname> version before + 15, then any row filtering is ignored during the initial data synchronization + phase. For this case, the user might want to consider deleting any initially + copied data that would be incompatible with subsequent filtering. + Because initial data synchronization does not take into account the publication + <literal>publish</literal> parameter when copying existing table data, some rows + may be copied that would not be replicated using DML. See + <xref linkend="logical-replication-subscription-examples"/> for examples. + </para> + + <para> + Subscriptions having several publications in which the same table has been + published with different column lists are not supported. + </para> + + <para> + We allow non-existent publications to be specified so that users can add + those later. This means + <link linkend="catalog-pg-subscription"><structname>pg_subscription</structname></link> + can have non-existent publications. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a subscription to a remote server that replicates tables in + the publications <literal>mypublication</literal> and + <literal>insert_only</literal> and starts replicating immediately on + commit: +<programlisting> +CREATE SUBSCRIPTION mysub + CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb' + PUBLICATION mypublication, insert_only; +</programlisting> + </para> + + <para> + Create a subscription to a remote server that replicates tables in + the <literal>insert_only</literal> publication and does not start replicating + until enabled at a later time. +<programlisting> +CREATE SUBSCRIPTION mysub + CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb' + PUBLICATION insert_only + WITH (enabled = false); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE SUBSCRIPTION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altersubscription"/></member> + <member><xref linkend="sql-dropsubscription"/></member> + <member><xref linkend="sql-createpublication"/></member> + <member><xref linkend="sql-alterpublication"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml new file mode 100644 index 0000000..c1b6beb --- /dev/null +++ b/doc/src/sgml/ref/create_table.sgml @@ -0,0 +1,2422 @@ +<!-- +doc/src/sgml/ref/create_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtable"> + <indexterm zone="sql-createtable"> + <primary>CREATE TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TABLE</refname> + <refpurpose>define a new table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name</replaceable> ( [ + { <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ COMPRESSION <replaceable>compression_method</replaceable> ] [ COLLATE <replaceable>collation</replaceable> ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + | <replaceable>table_constraint</replaceable> + | LIKE <replaceable>source_table</replaceable> [ <replaceable>like_option</replaceable> ... ] } + [, ... ] +] ) +[ INHERITS ( <replaceable>parent_table</replaceable> [, ... ] ) ] +[ PARTITION BY { RANGE | LIST | HASH } ( { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">opclass</replaceable> ] [, ... ] ) ] +[ USING <replaceable class="parameter">method</replaceable> ] +[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) | WITHOUT OIDS ] +[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] +[ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + +CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name</replaceable> + OF <replaceable class="parameter">type_name</replaceable> [ ( + { <replaceable class="parameter">column_name</replaceable> [ WITH OPTIONS ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + | <replaceable>table_constraint</replaceable> } + [, ... ] +) ] +[ PARTITION BY { RANGE | LIST | HASH } ( { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">opclass</replaceable> ] [, ... ] ) ] +[ USING <replaceable class="parameter">method</replaceable> ] +[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) | WITHOUT OIDS ] +[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] +[ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + +CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name</replaceable> + PARTITION OF <replaceable class="parameter">parent_table</replaceable> [ ( + { <replaceable class="parameter">column_name</replaceable> [ WITH OPTIONS ] [ <replaceable class="parameter">column_constraint</replaceable> [ ... ] ] + | <replaceable>table_constraint</replaceable> } + [, ... ] +) ] { FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT } +[ PARTITION BY { RANGE | LIST | HASH } ( { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">opclass</replaceable> ] [, ... ] ) ] +[ USING <replaceable class="parameter">method</replaceable> ] +[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) | WITHOUT OIDS ] +[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] +[ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + +<phrase>where <replaceable class="parameter">column_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ NOT NULL | + NULL | + CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] | + DEFAULT <replaceable>default_expr</replaceable> | + GENERATED ALWAYS AS ( <replaceable>generation_expr</replaceable> ) STORED | + GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( <replaceable>sequence_options</replaceable> ) ] | + UNIQUE [ NULLS [ NOT ] DISTINCT ] <replaceable class="parameter">index_parameters</replaceable> | + PRIMARY KEY <replaceable class="parameter">index_parameters</replaceable> | + REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] + [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ] } +[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + +<phrase>and <replaceable class="parameter">table_constraint</replaceable> is:</phrase> + +[ CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> ] +{ CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] | + UNIQUE [ NULLS [ NOT ] DISTINCT ] ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> | + PRIMARY KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> | + EXCLUDE [ USING <replaceable class="parameter">index_method</replaceable> ] ( <replaceable class="parameter">exclude_element</replaceable> WITH <replaceable class="parameter">operator</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> [ WHERE ( <replaceable class="parameter">predicate</replaceable> ) ] | + FOREIGN KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> [, ... ] ) ] + [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE <replaceable +class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ] } +[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] + +<phrase>and <replaceable class="parameter">like_option</replaceable> is:</phrase> + +{ INCLUDING | EXCLUDING } { COMMENTS | COMPRESSION | CONSTRAINTS | DEFAULTS | GENERATED | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL } + +<phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase> + +IN ( <replaceable class="parameter">partition_bound_expr</replaceable> [, ...] ) | +FROM ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) + TO ( { <replaceable class="parameter">partition_bound_expr</replaceable> | MINVALUE | MAXVALUE } [, ...] ) | +WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REMAINDER <replaceable class="parameter">numeric_literal</replaceable> ) + +<phrase><replaceable class="parameter">index_parameters</replaceable> in <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and <literal>EXCLUDE</literal> constraints are:</phrase> + +[ INCLUDE ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] +[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ] +[ USING INDEX TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + +<phrase><replaceable class="parameter">exclude_element</replaceable> in an <literal>EXCLUDE</literal> constraint is:</phrase> + +{ <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ <replaceable class="parameter">opclass</replaceable> ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] + +<phrase><replaceable class="parameter">referential_action</replaceable> in a <literal>FOREIGN KEY</literal>/<literal>REFERENCES</literal> constraint is:</phrase> + +{ NO ACTION | RESTRICT | CASCADE | SET NULL [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] | SET DEFAULT [ ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) ] } +</synopsis> + + </refsynopsisdiv> + + <refsect1 id="sql-createtable-description"> + <title>Description</title> + + <para> + <command>CREATE TABLE</command> will create a new, initially empty table + in the current database. The table will be owned by the user issuing the + command. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE TABLE + myschema.mytable ...</literal>) then the table is created in the specified + schema. Otherwise it is created in the current schema. Temporary + tables exist in a special schema, so a schema name cannot be given + when creating a temporary table. The name of the table must be + distinct from the name of any other relation (table, sequence, index, view, + materialized view, or foreign table) in the same schema. + </para> + + <para> + <command>CREATE TABLE</command> also automatically creates a data + type that represents the composite type corresponding + to one row of the table. Therefore, tables cannot have the same + name as any existing data type in the same schema. + </para> + + <para> + The optional constraint clauses specify constraints (tests) that + new or updated rows must satisfy for an insert or update operation + to succeed. A constraint is an SQL object that helps define the + set of valid values in the table in various ways. + </para> + + <para> + There are two ways to define constraints: table constraints and + column constraints. A column constraint is defined as part of a + column definition. A table constraint definition is not tied to a + particular column, and it can encompass more than one column. + Every column constraint can also be written as a table constraint; + a column constraint is only a notational convenience for use when the + constraint only affects one column. + </para> + + <para> + To be able to create a table, you must have <literal>USAGE</literal> + privilege on all column types or the type in the <literal>OF</literal> + clause, respectively. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry id="sql-createtable-temporary"> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + If specified, the table is created as a temporary table. + Temporary tables are automatically dropped at the end of a + session, or optionally at the end of the current transaction + (see <literal>ON COMMIT</literal> below). The default + search_path includes the temporary schema first and so identically + named existing permanent tables are not chosen for new plans + while the temporary table exists, unless they are referenced + with schema-qualified names. Any indexes created on a temporary + table are automatically temporary as well. + </para> + + <para> + The <link linkend="autovacuum">autovacuum daemon</link> cannot + access and therefore cannot vacuum or analyze temporary tables. + For this reason, appropriate vacuum and analyze operations should be + performed via session SQL commands. For example, if a temporary + table is going to be used in complex queries, it is wise to run + <command>ANALYZE</command> on the temporary table after it is populated. + </para> + + <para> + Optionally, <literal>GLOBAL</literal> or <literal>LOCAL</literal> + can be written before <literal>TEMPORARY</literal> or <literal>TEMP</literal>. + This presently makes no difference in <productname>PostgreSQL</productname> + and is deprecated; see + <xref linkend="sql-createtable-compatibility"/> below. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createtable-unlogged"> + <term><literal>UNLOGGED</literal></term> + <listitem> + <para> + If specified, the table is created as an unlogged table. Data written + to unlogged tables is not written to the write-ahead log (see <xref + linkend="wal"/>), which makes them considerably faster than ordinary + tables. However, they are not crash-safe: an unlogged table is + automatically truncated after a crash or unclean shutdown. The contents + of an unlogged table are also not replicated to standby servers. + Any indexes created on an unlogged table are automatically unlogged as + well. + </para> + + <para> + If this is specified, any sequences created together with the unlogged + table (for identity or serial columns) are also created as unlogged. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a relation with the same name already exists. + A notice is issued in this case. Note that there is no guarantee that + the existing relation is anything like the one that would have been + created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OF <replaceable class="parameter">type_name</replaceable></literal></term> + <listitem> + <para> + Creates a <firstterm>typed table</firstterm>, which takes its + structure from the specified composite type (name optionally + schema-qualified). A typed table is tied to its type; for + example the table will be dropped if the type is dropped + (with <literal>DROP TYPE ... CASCADE</literal>). + </para> + + <para> + When a typed table is created, then the data types of the + columns are determined by the underlying composite type and are + not specified by the <literal>CREATE TABLE</literal> command. + But the <literal>CREATE TABLE</literal> command can add defaults + and constraints to the table and can specify storage parameters. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column to be created in the new table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The data type of the column. This can include array + specifiers. For more information on the data types supported by + <productname>PostgreSQL</productname>, refer to <xref + linkend="datatype"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COLLATE <replaceable>collation</replaceable></literal></term> + <listitem> + <para> + The <literal>COLLATE</literal> clause assigns a collation to + the column (which must be of a collatable data type). + If not specified, the column data type's default collation is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COMPRESSION <replaceable class="parameter">compression_method</replaceable></literal></term> + <listitem> + <para> + The <literal>COMPRESSION</literal> clause sets the compression method + for the column. Compression is supported only for variable-width data + types, and is used only when the column's storage mode + is <literal>main</literal> or <literal>extended</literal>. + (See <xref linkend="sql-altertable"/> for information on + column storage modes.) Setting this property for a partitioned table + has no direct effect, because such tables have no storage of their own, + but the configured value will be inherited by newly-created partitions. + The supported compression methods are <literal>pglz</literal> and + <literal>lz4</literal>. (<literal>lz4</literal> is available only if + <option>--with-lz4</option> was used when building + <productname>PostgreSQL</productname>.) In addition, + <replaceable class="parameter">compression_method</replaceable> + can be <literal>default</literal> to explicitly specify the default + behavior, which is to consult the + <xref linkend="guc-default-toast-compression"/> setting at the time of + data insertion to determine the method to use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INHERITS ( <replaceable>parent_table</replaceable> [, ... ] )</literal></term> + <listitem> + <para> + The optional <literal>INHERITS</literal> clause specifies a list of + tables from which the new table automatically inherits all + columns. Parent tables can be plain tables or foreign tables. + </para> + + <para> + Use of <literal>INHERITS</literal> creates a persistent relationship + between the new child table and its parent table(s). Schema + modifications to the parent(s) normally propagate to children + as well, and by default the data of the child table is included in + scans of the parent(s). + </para> + + <para> + If the same column name exists in more than one parent + table, an error is reported unless the data types of the columns + match in each of the parent tables. If there is no conflict, + then the duplicate columns are merged to form a single column in + the new table. If the column name list of the new table + contains a column name that is also inherited, the data type must + likewise match the inherited column(s), and the column + definitions are merged into one. If the + new table explicitly specifies a default value for the column, + this default overrides any defaults from inherited declarations + of the column. Otherwise, any parents that specify default + values for the column must all specify the same default, or an + error will be reported. + </para> + + <para> + <literal>CHECK</literal> constraints are merged in essentially the same way as + columns: if multiple parent tables and/or the new table definition + contain identically-named <literal>CHECK</literal> constraints, these + constraints must all have the same check expression, or an error will be + reported. Constraints having the same name and expression will + be merged into one copy. A constraint marked <literal>NO INHERIT</literal> in a + parent will not be considered. Notice that an unnamed <literal>CHECK</literal> + constraint in the new table will never be merged, since a unique name + will always be chosen for it. + </para> + + <para> + Column <literal>STORAGE</literal> settings are also copied from parent tables. + </para> + + <para> + If a column in the parent table is an identity column, that property is + not inherited. A column in the child table can be declared identity + column if desired. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARTITION BY { RANGE | LIST | HASH } ( { <replaceable class="parameter">column_name</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ <replaceable class="parameter">opclass</replaceable> ] [, ...] ) </literal></term> + <listitem> + <para> + The optional <literal>PARTITION BY</literal> clause specifies a strategy + of partitioning the table. The table thus created is called a + <firstterm>partitioned</firstterm> table. The parenthesized list of + columns or expressions forms the <firstterm>partition key</firstterm> + for the table. When using range or hash partitioning, the partition key + can include multiple columns or expressions (up to 32, but this limit can + be altered when building <productname>PostgreSQL</productname>), but for + list partitioning, the partition key must consist of a single column or + expression. + </para> + + <para> + Range and list partitioning require a btree operator class, while hash + partitioning requires a hash operator class. If no operator class is + specified explicitly, the default operator class of the appropriate + type will be used; if no default operator class exists, an error will + be raised. When hash partitioning is used, the operator class used + must implement support function 2 (see <xref linkend="xindex-support"/> + for details). + </para> + + <para> + A partitioned table is divided into sub-tables (called partitions), + which are created using separate <literal>CREATE TABLE</literal> commands. + The partitioned table is itself empty. A data row inserted into the + table is routed to a partition based on the value of columns or + expressions in the partition key. If no existing partition matches + the values in the new row, an error will be reported. + </para> + + <para> + Partitioned tables do not support <literal>EXCLUDE</literal> constraints; + however, you can define these constraints on individual partitions. + </para> + + <para> + See <xref linkend="ddl-partitioning"/> for more discussion on table + partitioning. + </para> + + </listitem> + </varlistentry> + + <varlistentry id="sql-createtable-partition"> + <term><literal>PARTITION OF <replaceable class="parameter">parent_table</replaceable> { FOR VALUES <replaceable class="parameter">partition_bound_spec</replaceable> | DEFAULT }</literal></term> + <listitem> + <para> + Creates the table as a <firstterm>partition</firstterm> of the specified + parent table. The table can be created either as a partition for specific + values using <literal>FOR VALUES</literal> or as a default partition + using <literal>DEFAULT</literal>. Any indexes, constraints and + user-defined row-level triggers that exist in the parent table are cloned + on the new partition. + </para> + + <para> + The <replaceable class="parameter">partition_bound_spec</replaceable> + must correspond to the partitioning method and partition key of the + parent table, and must not overlap with any existing partition of that + parent. The form with <literal>IN</literal> is used for list partitioning, + the form with <literal>FROM</literal> and <literal>TO</literal> is used + for range partitioning, and the form with <literal>WITH</literal> is used + for hash partitioning. + </para> + + <para> + <replaceable class="parameter">partition_bound_expr</replaceable> is + any variable-free expression (subqueries, window functions, aggregate + functions, and set-returning functions are not allowed). Its data type + must match the data type of the corresponding partition key column. + The expression is evaluated once at table creation time, so it can + even contain volatile expressions such as + <literal><function>CURRENT_TIMESTAMP</function></literal>. + </para> + + <para> + When creating a list partition, <literal>NULL</literal> can be + specified to signify that the partition allows the partition key + column to be null. However, there cannot be more than one such + list partition for a given parent table. <literal>NULL</literal> + cannot be specified for range partitions. + </para> + + <para> + When creating a range partition, the lower bound specified with + <literal>FROM</literal> is an inclusive bound, whereas the upper + bound specified with <literal>TO</literal> is an exclusive bound. + That is, the values specified in the <literal>FROM</literal> list + are valid values of the corresponding partition key columns for this + partition, whereas those in the <literal>TO</literal> list are + not. Note that this statement must be understood according to the + rules of row-wise comparison (<xref linkend="row-wise-comparison"/>). + For example, given <literal>PARTITION BY RANGE (x,y)</literal>, a partition + bound <literal>FROM (1, 2) TO (3, 4)</literal> + allows <literal>x=1</literal> with any <literal>y>=2</literal>, + <literal>x=2</literal> with any non-null <literal>y</literal>, + and <literal>x=3</literal> with any <literal>y<4</literal>. + </para> + + <para> + The special values <literal>MINVALUE</literal> and <literal>MAXVALUE</literal> + may be used when creating a range partition to indicate that there + is no lower or upper bound on the column's value. For example, a + partition defined using <literal>FROM (MINVALUE) TO (10)</literal> allows + any values less than 10, and a partition defined using + <literal>FROM (10) TO (MAXVALUE)</literal> allows any values greater than + or equal to 10. + </para> + + <para> + When creating a range partition involving more than one column, it + can also make sense to use <literal>MAXVALUE</literal> as part of the lower + bound, and <literal>MINVALUE</literal> as part of the upper bound. For + example, a partition defined using + <literal>FROM (0, MAXVALUE) TO (10, MAXVALUE)</literal> allows any rows + where the first partition key column is greater than 0 and less than + or equal to 10. Similarly, a partition defined using + <literal>FROM ('a', MINVALUE) TO ('b', MINVALUE)</literal> allows any rows + where the first partition key column starts with "a". + </para> + + <para> + Note that if <literal>MINVALUE</literal> or <literal>MAXVALUE</literal> is used for + one column of a partitioning bound, the same value must be used for all + subsequent columns. For example, <literal>(10, MINVALUE, 0)</literal> is not + a valid bound; you should write <literal>(10, MINVALUE, MINVALUE)</literal>. + </para> + + <para> + Also note that some element types, such as <literal>timestamp</literal>, + have a notion of "infinity", which is just another value that can + be stored. This is different from <literal>MINVALUE</literal> and + <literal>MAXVALUE</literal>, which are not real values that can be stored, + but rather they are ways of saying that the value is unbounded. + <literal>MAXVALUE</literal> can be thought of as being greater than any + other value, including "infinity" and <literal>MINVALUE</literal> as being + less than any other value, including "minus infinity". Thus the range + <literal>FROM ('infinity') TO (MAXVALUE)</literal> is not an empty range; it + allows precisely one value to be stored — "infinity". + </para> + + <para> + If <literal>DEFAULT</literal> is specified, the table will be + created as the default partition of the parent table. This option + is not available for hash-partitioned tables. A partition key value + not fitting into any other partition of the given parent will be + routed to the default partition. + </para> + + <para> + When a table has an existing <literal>DEFAULT</literal> partition and + a new partition is added to it, the default partition must + be scanned to verify that it does not contain any rows which properly + belong in the new partition. If the default partition contains a + large number of rows, this may be slow. The scan will be skipped if + the default partition is a foreign table or if it has a constraint which + proves that it cannot contain rows which should be placed in the new + partition. + </para> + + <para> + When creating a hash partition, a modulus and remainder must be specified. + The modulus must be a positive integer, and the remainder must be a + non-negative integer less than the modulus. Typically, when initially + setting up a hash-partitioned table, you should choose a modulus equal to + the number of partitions and assign every table the same modulus and a + different remainder (see examples, below). However, it is not required + that every partition have the same modulus, only that every modulus which + occurs among the partitions of a hash-partitioned table is a factor of the + next larger modulus. This allows the number of partitions to be increased + incrementally without needing to move all the data at once. For example, + suppose you have a hash-partitioned table with 8 partitions, each of which + has modulus 8, but find it necessary to increase the number of partitions + to 16. You can detach one of the modulus-8 partitions, create two new + modulus-16 partitions covering the same portion of the key space (one with + a remainder equal to the remainder of the detached partition, and the + other with a remainder equal to that value plus 8), and repopulate them + with data. You can then repeat this -- perhaps at a later time -- for + each modulus-8 partition until none remain. While this may still involve + a large amount of data movement at each step, it is still better than + having to create a whole new table and move all the data at once. + </para> + + <para> + A partition must have the same column names and types as the partitioned + table to which it belongs. Modifications to the column names or types of + a partitioned table will automatically propagate to all partitions. + <literal>CHECK</literal> constraints will be inherited automatically by + every partition, but an individual partition may specify additional + <literal>CHECK</literal> constraints; additional constraints with the + same name and condition as in the parent will be merged with the parent + constraint. Defaults may be specified separately for each partition. + But note that a partition's default value is not applied when inserting + a tuple through a partitioned table. + </para> + + <para> + Rows inserted into a partitioned table will be automatically routed to + the correct partition. If no suitable partition exists, an error will + occur. + </para> + + <para> + Operations such as <command>TRUNCATE</command> + which normally affect a table and all of its + inheritance children will cascade to all partitions, but may also be + performed on an individual partition. + </para> + + <para> + Note that creating a partition using <literal>PARTITION OF</literal> + requires taking an <literal>ACCESS EXCLUSIVE</literal> lock on the + parent partitioned table. Likewise, dropping a partition + with <command>DROP TABLE</command> requires taking + an <literal>ACCESS EXCLUSIVE</literal> lock on the parent table. + It is possible to use <link linkend="sql-altertable"><command>ALTER + TABLE ATTACH/DETACH PARTITION</command></link> to perform these + operations with a weaker lock, thus reducing interference with + concurrent operations on the partitioned table. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LIKE <replaceable>source_table</replaceable> [ <replaceable>like_option</replaceable> ... ]</literal></term> + <listitem> + <para> + The <literal>LIKE</literal> clause specifies a table from which + the new table automatically copies all column names, their data types, + and their not-null constraints. + </para> + <para> + Unlike <literal>INHERITS</literal>, the new table and original table + are completely decoupled after creation is complete. Changes to the + original table will not be applied to the new table, and it is not + possible to include data of the new table in scans of the original + table. + </para> + <para> + Also unlike <literal>INHERITS</literal>, columns and + constraints copied by <literal>LIKE</literal> are not merged with similarly + named columns and constraints. + If the same name is specified explicitly or in another + <literal>LIKE</literal> clause, an error is signaled. + </para> + <para> + The optional <replaceable>like_option</replaceable> clauses specify + which additional properties of the original table to copy. Specifying + <literal>INCLUDING</literal> copies the property, specifying + <literal>EXCLUDING</literal> omits the property. + <literal>EXCLUDING</literal> is the default. If multiple specifications + are made for the same kind of object, the last one is used. The + available options are: + + <variablelist> + <varlistentry> + <term><literal>INCLUDING COMMENTS</literal></term> + <listitem> + <para> + Comments for the copied columns, constraints, and indexes will be + copied. The default behavior is to exclude comments, resulting in + the copied columns and constraints in the new table having no + comments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING COMPRESSION</literal></term> + <listitem> + <para> + Compression method of the columns will be copied. The default + behavior is to exclude compression methods, resulting in columns + having the default compression method. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING CONSTRAINTS</literal></term> + <listitem> + <para> + <literal>CHECK</literal> constraints will be copied. No distinction + is made between column constraints and table constraints. Not-null + constraints are always copied to the new table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING DEFAULTS</literal></term> + <listitem> + <para> + Default expressions for the copied column definitions will be + copied. Otherwise, default expressions are not copied, resulting in + the copied columns in the new table having null defaults. Note that + copying defaults that call database-modification functions, such as + <function>nextval</function>, may create a functional linkage + between the original and new tables. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING GENERATED</literal></term> + <listitem> + <para> + Any generation expressions of copied column definitions will be + copied. By default, new columns will be regular base columns. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING IDENTITY</literal></term> + <listitem> + <para> + Any identity specifications of copied column definitions will be + copied. A new sequence is created for each identity column of the + new table, separate from the sequences associated with the old + table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING INDEXES</literal></term> + <listitem> + <para> + Indexes, <literal>PRIMARY KEY</literal>, <literal>UNIQUE</literal>, + and <literal>EXCLUDE</literal> constraints on the original table + will be created on the new table. Names for the new indexes and + constraints are chosen according to the default rules, regardless of + how the originals were named. (This behavior avoids possible + duplicate-name failures for the new indexes.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING STATISTICS</literal></term> + <listitem> + <para> + Extended statistics are copied to the new table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING STORAGE</literal></term> + <listitem> + <para> + <literal>STORAGE</literal> settings for the copied column + definitions will be copied. The default behavior is to exclude + <literal>STORAGE</literal> settings, resulting in the copied columns + in the new table having type-specific default settings. For more on + <literal>STORAGE</literal> settings, see <xref + linkend="storage-toast"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INCLUDING ALL</literal></term> + <listitem> + <para> + <literal>INCLUDING ALL</literal> is an abbreviated form selecting + all the available individual options. (It could be useful to write + individual <literal>EXCLUDING</literal> clauses after + <literal>INCLUDING ALL</literal> to select all but some specific + options.) + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The <literal>LIKE</literal> clause can also be used to copy column + definitions from views, foreign tables, or composite types. + Inapplicable options (e.g., <literal>INCLUDING INDEXES</literal> from + a view) are ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONSTRAINT <replaceable class="parameter">constraint_name</replaceable></literal></term> + <listitem> + <para> + An optional name for a column or table constraint. If the + constraint is violated, the constraint name is present in error messages, + so constraint names like <literal>col must be positive</literal> can be used + to communicate helpful constraint information to client applications. + (Double-quotes are needed to specify constraint names that contain spaces.) + If a constraint name is not specified, the system generates a name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOT NULL</literal></term> + <listitem> + <para> + The column is not allowed to contain null values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + The column is allowed to contain null values. This is the default. + </para> + + <para> + This clause is only provided for compatibility with + non-standard SQL databases. Its use is discouraged in new + applications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CHECK ( <replaceable class="parameter">expression</replaceable> ) [ NO INHERIT ] </literal></term> + <listitem> + <para> + The <literal>CHECK</literal> clause specifies an expression producing a + Boolean result which new or updated rows must satisfy for an + insert or update operation to succeed. Expressions evaluating + to TRUE or UNKNOWN succeed. Should any row of an insert or + update operation produce a FALSE result, an error exception is + raised and the insert or update does not alter the database. A + check constraint specified as a column constraint should + reference that column's value only, while an expression + appearing in a table constraint can reference multiple columns. + </para> + + <para> + Currently, <literal>CHECK</literal> expressions cannot contain + subqueries nor refer to variables other than columns of the + current row (see <xref linkend="ddl-constraints-check-constraints"/>). + The system column <literal>tableoid</literal> + may be referenced, but not any other system column. + </para> + + <para> + A constraint marked with <literal>NO INHERIT</literal> will not propagate to + child tables. + </para> + + <para> + When a table has multiple <literal>CHECK</literal> constraints, + they will be tested for each row in alphabetical order by name, + after checking <literal>NOT NULL</literal> constraints. + (<productname>PostgreSQL</productname> versions before 9.5 did not honor any + particular firing order for <literal>CHECK</literal> constraints.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT + <replaceable>default_expr</replaceable></literal></term> + <listitem> + <para> + The <literal>DEFAULT</literal> clause assigns a default data value for + the column whose column definition it appears within. The value + is any variable-free expression (in particular, cross-references + to other columns in the current table are not allowed). Subqueries + are not allowed either. The data type of the default expression must + match the data type of the column. + </para> + + <para> + The default expression will be used in any insert operation that + does not specify a value for the column. If there is no default + for a column, then the default is null. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>GENERATED ALWAYS AS ( <replaceable>generation_expr</replaceable> ) STORED</literal><indexterm><primary>generated column</primary></indexterm></term> + <listitem> + <para> + This clause creates the column as a <firstterm>generated + column</firstterm>. The column cannot be written to, and when read the + result of the specified expression will be returned. + </para> + + <para> + The keyword <literal>STORED</literal> is required to signify that the + column will be computed on write and will be stored on disk. + </para> + + <para> + The generation expression can refer to other columns in the table, but + not other generated columns. Any functions and operators used must be + immutable. References to other tables are not allowed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( <replaceable>sequence_options</replaceable> ) ]</literal></term> + <listitem> + <para> + This clause creates the column as an <firstterm>identity + column</firstterm>. It will have an implicit sequence attached to it + and the column in new rows will automatically have values from the + sequence assigned to it. + Such a column is implicitly <literal>NOT NULL</literal>. + </para> + + <para> + The clauses <literal>ALWAYS</literal> and <literal>BY DEFAULT</literal> + determine how explicitly user-specified values are handled in + <command>INSERT</command> and <command>UPDATE</command> commands. + </para> + + <para> + 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. See <xref linkend="sql-insert"/> + for details. (In the <command>COPY</command> command, user-specified + values are always used regardless of this setting.) + </para> + + <para> + In an <command>UPDATE</command> command, if <literal>ALWAYS</literal> is + selected, any update of the column to any value other than + <literal>DEFAULT</literal> will be rejected. If <literal>BY + DEFAULT</literal> is selected, the column can be updated normally. + (There is no <literal>OVERRIDING</literal> clause for the + <command>UPDATE</command> command.) + </para> + + <para> + The optional <replaceable>sequence_options</replaceable> clause can be + used to override the options of the sequence. + See <xref linkend="sql-createsequence"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>UNIQUE [ NULLS [ NOT ] DISTINCT ]</literal> (column constraint)</term> + <term><literal>UNIQUE [ NULLS [ NOT ] DISTINCT ] ( <replaceable class="parameter">column_name</replaceable> [, ... ] )</literal> + <optional> <literal>INCLUDE ( <replaceable class="parameter">column_name</replaceable> [, ...])</literal> </optional> (table constraint)</term> + + <listitem> + <para> + The <literal>UNIQUE</literal> constraint specifies that a + group of one or more columns of a table can contain + only unique values. The behavior of a unique table constraint + is the same as that of a unique column constraint, with the + additional capability to span multiple columns. The constraint + therefore enforces that any two rows must differ in at least one + of these columns. + </para> + + <para> + For the purpose of a unique constraint, null values are not + considered equal, unless <literal>NULLS NOT DISTINCT</literal> is + specified. + </para> + + <para> + Each unique constraint should name a set of columns that is + different from the set of columns named by any other unique or + primary key constraint defined for the table. (Otherwise, redundant + unique constraints will be discarded.) + </para> + + <para> + When establishing a unique constraint for a multi-level partition + hierarchy, all the columns in the partition key of the target + partitioned table, as well as those of all its descendant partitioned + tables, must be included in the constraint definition. + </para> + + <para> + Adding a unique constraint will automatically create a unique btree + index on the column or group of columns used in the constraint. + </para> + + <para> + The optional <literal>INCLUDE</literal> clause adds to that index + one or more columns that are simply <quote>payload</quote>: uniqueness + is not enforced on them, and the index cannot be searched on the basis + of those columns. However they can be retrieved by an index-only scan. + Note that although the constraint is not enforced on included columns, + it still depends on them. Consequently, some operations on such columns + (e.g., <literal>DROP COLUMN</literal>) can cause cascaded constraint and + index deletion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PRIMARY KEY</literal> (column constraint)</term> + <term><literal>PRIMARY KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] )</literal> + <optional> <literal>INCLUDE ( <replaceable class="parameter">column_name</replaceable> [, ...])</literal> </optional> (table constraint)</term> + <listitem> + <para> + The <literal>PRIMARY KEY</literal> constraint specifies that a column or + columns of a table can contain only unique (non-duplicate), nonnull + values. Only one primary key can be specified for a table, whether as a + column constraint or a table constraint. + </para> + + <para> + The primary key constraint should name a set of columns that is + different from the set of columns named by any unique + constraint defined for the same table. (Otherwise, the unique + constraint is redundant and will be discarded.) + </para> + + <para> + <literal>PRIMARY KEY</literal> enforces the same data constraints as + a combination of <literal>UNIQUE</literal> and <literal>NOT + NULL</literal>. However, + identifying a set of columns as the primary key also provides metadata + about the design of the schema, since a primary key implies that other + tables can rely on this set of columns as a unique identifier for rows. + </para> + + <para> + When placed on a partitioned table, <literal>PRIMARY KEY</literal> + constraints share the restrictions previously described + for <literal>UNIQUE</literal> constraints. + </para> + + <para> + Adding a <literal>PRIMARY KEY</literal> constraint will automatically + create a unique btree index on the column or group of columns used in the + constraint. + </para> + + <para> + The optional <literal>INCLUDE</literal> clause adds to that index + one or more columns that are simply <quote>payload</quote>: uniqueness + is not enforced on them, and the index cannot be searched on the basis + of those columns. However they can be retrieved by an index-only scan. + Note that although the constraint is not enforced on included columns, + it still depends on them. Consequently, some operations on such columns + (e.g., <literal>DROP COLUMN</literal>) can cause cascaded constraint and + index deletion. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createtable-exclude"> + <term><literal>EXCLUDE [ USING <replaceable class="parameter">index_method</replaceable> ] ( <replaceable class="parameter">exclude_element</replaceable> WITH <replaceable class="parameter">operator</replaceable> [, ... ] ) <replaceable class="parameter">index_parameters</replaceable> [ WHERE ( <replaceable class="parameter">predicate</replaceable> ) ]</literal></term> + <listitem> + <para> + The <literal>EXCLUDE</literal> clause defines an exclusion + constraint, which guarantees that if + any two rows are compared on the specified column(s) or + expression(s) using the specified operator(s), not all of these + comparisons will return <literal>TRUE</literal>. If all of the + specified operators test for equality, this is equivalent to a + <literal>UNIQUE</literal> constraint, although an ordinary unique constraint + will be faster. However, exclusion constraints can specify + constraints that are more general than simple equality. + For example, you can specify a constraint that + no two rows in the table contain overlapping circles + (see <xref linkend="datatype-geometric"/>) by using the + <literal>&&</literal> operator. + </para> + + <para> + Exclusion constraints are implemented using + an index, so each specified operator must be associated with an + appropriate operator class + (see <xref linkend="indexes-opclass"/>) for the index access + method <replaceable>index_method</replaceable>. + The operators are required to be commutative. + Each <replaceable class="parameter">exclude_element</replaceable> + can optionally specify an operator class and/or ordering options; + these are described fully under + <xref linkend="sql-createindex"/>. + </para> + + <para> + The access method must support <literal>amgettuple</literal> (see <xref + linkend="indexam"/>); at present this means <acronym>GIN</acronym> + cannot be used. Although it's allowed, there is little point in using + B-tree or hash indexes with an exclusion constraint, because this + does nothing that an ordinary unique constraint doesn't do better. + So in practice the access method will always be <acronym>GiST</acronym> or + <acronym>SP-GiST</acronym>. + </para> + + <para> + The <replaceable class="parameter">predicate</replaceable> allows you to specify an + exclusion constraint on a subset of the table; internally this creates a + partial index. Note that parentheses are required around the predicate. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> ) ] [ MATCH <replaceable class="parameter">matchtype</replaceable> ] [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ]</literal> (column constraint)</term> + + <term><literal>FOREIGN KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] ) + REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> [, ... ] ) ] + [ MATCH <replaceable class="parameter">matchtype</replaceable> ] + [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] + [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ]</literal> + (table constraint)</term> + + <listitem> + <para> + These clauses specify a foreign key constraint, which requires + that a group of one or more columns of the new table must only + contain values that match values in the referenced + column(s) of some row of the referenced table. If the <replaceable + class="parameter">refcolumn</replaceable> list is omitted, the + primary key of the <replaceable class="parameter">reftable</replaceable> + is used. The referenced columns must be the columns of a non-deferrable + unique or primary key constraint in the referenced table. The user + must have <literal>REFERENCES</literal> permission on the referenced table + (either the whole table, or the specific referenced columns). The + addition of a foreign key constraint requires a + <literal>SHARE ROW EXCLUSIVE</literal> lock on the referenced table. + Note that foreign key constraints cannot be defined between temporary + tables and permanent tables. + </para> + + <para> + A value inserted into the referencing column(s) is matched against the + values of the referenced table and referenced columns using the + given match type. There are three match types: <literal>MATCH + FULL</literal>, <literal>MATCH PARTIAL</literal>, and <literal>MATCH + SIMPLE</literal> (which is the default). <literal>MATCH + FULL</literal> will not allow one column of a multicolumn foreign key + to be null unless all foreign key columns are null; if they are all + null, the row is not required to have a match in the referenced table. + <literal>MATCH SIMPLE</literal> allows any of the foreign key columns + to be null; if any of them are null, the row is not required to have a + match in the referenced table. + <literal>MATCH PARTIAL</literal> is not yet implemented. + (Of course, <literal>NOT NULL</literal> constraints can be applied to the + referencing column(s) to prevent these cases from arising.) + </para> + + <para> + In addition, when the data in the referenced columns is changed, + certain actions are performed on the data in this table's + columns. The <literal>ON DELETE</literal> clause specifies the + action to perform when a referenced row in the referenced table is + being deleted. Likewise, the <literal>ON UPDATE</literal> + clause specifies the action to perform when a referenced column + in the referenced table is being updated to a new value. If the + row is updated, but the referenced column is not actually + changed, no action is done. Referential actions other than the + <literal>NO ACTION</literal> check cannot be deferred, even if + the constraint is declared deferrable. There are the following possible + actions for each clause: + + <variablelist> + <varlistentry> + <term><literal>NO ACTION</literal></term> + <listitem> + <para> + Produce an error indicating that the deletion or update + would create a foreign key constraint violation. + If the constraint is deferred, this + error will be produced at constraint check time if there still + exist any referencing rows. This is the default action. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Produce an error indicating that the deletion or update + would create a foreign key constraint violation. + This is the same as <literal>NO ACTION</literal> except that + the check is not deferrable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Delete any rows referencing the deleted row, or update the + values of the referencing column(s) to the new values of the + referenced columns, respectively. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET NULL [ ( <replaceable>column_name</replaceable> [, ... ] ) ]</literal></term> + <listitem> + <para> + Set all of the referencing columns, or a specified subset of the + referencing columns, to null. A subset of columns can only be + specified for <literal>ON DELETE</literal> actions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SET DEFAULT [ ( <replaceable>column_name</replaceable> [, ... ] ) ]</literal></term> + <listitem> + <para> + Set all of the referencing columns, or a specified subset of the + referencing columns, to their default values. A subset of columns + can only be specified for <literal>ON DELETE</literal> actions. + (There must be a row in the referenced table matching the default + values, if they are not null, or the operation will fail.) + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + If the referenced column(s) are changed frequently, it might be wise to + add an index to the referencing column(s) so that referential actions + associated with the foreign key constraint can be performed more + efficiently. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFERRABLE</literal></term> + <term><literal>NOT DEFERRABLE</literal></term> + <listitem> + <para> + This controls whether the constraint can be deferred. A + constraint that is not deferrable will be checked immediately + after every command. Checking of constraints that are + deferrable can be postponed until the end of the transaction + (using the <link linkend="sql-set-constraints"><command>SET CONSTRAINTS</command></link> command). + <literal>NOT DEFERRABLE</literal> is the default. + Currently, only <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, + <literal>EXCLUDE</literal>, and + <literal>REFERENCES</literal> (foreign key) constraints accept this + clause. <literal>NOT NULL</literal> and <literal>CHECK</literal> constraints are not + deferrable. Note that deferrable constraints cannot be used as + conflict arbitrators in an <command>INSERT</command> statement that + includes an <literal>ON CONFLICT DO UPDATE</literal> clause. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INITIALLY IMMEDIATE</literal></term> + <term><literal>INITIALLY DEFERRED</literal></term> + <listitem> + <para> + If a constraint is deferrable, this clause specifies the default + time to check the constraint. If the constraint is + <literal>INITIALLY IMMEDIATE</literal>, it is checked after each + statement. This is the default. If the constraint is + <literal>INITIALLY DEFERRED</literal>, it is checked only at the + end of the transaction. The constraint check time can be + altered with the <link linkend="sql-set-constraints"><command>SET CONSTRAINTS</command></link> command. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createtable-method"> + <term><literal>USING <replaceable class="parameter">method</replaceable></literal></term> + <listitem> + <para> + This optional clause specifies the table access method to use to store + the contents for the new table; the method needs be an access method of + type <literal>TABLE</literal>. See <xref linkend="tableam"/> for more + information. If this option is not specified, the default table access + method is chosen for the new table. See <xref + linkend="guc-default-table-access-method"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional storage parameters for a table or index; + see <xref linkend="sql-createtable-storage-parameters"/> below for more + information. For backward-compatibility the <literal>WITH</literal> + clause for a table can also include <literal>OIDS=FALSE</literal> to + specify that rows of the new table should not contain OIDs (object + identifiers), <literal>OIDS=TRUE</literal> is not supported anymore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITHOUT OIDS</literal></term> + <listitem> + <para> + This is backward-compatible syntax for declaring a table + <literal>WITHOUT OIDS</literal>, creating a table <literal>WITH + OIDS</literal> is not supported anymore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ON COMMIT</literal></term> + <listitem> + <para> + The behavior of temporary tables at the end of a transaction + block can be controlled using <literal>ON COMMIT</literal>. + The three options are: + + <variablelist> + <varlistentry> + <term><literal>PRESERVE ROWS</literal></term> + <listitem> + <para> + No special action is taken at the ends of transactions. + This is the default behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DELETE ROWS</literal></term> + <listitem> + <para> + All rows in the temporary table will be deleted at the end + of each transaction block. Essentially, an automatic <link + linkend="sql-truncate"><command>TRUNCATE</command></link> is done + at each commit. When used on a partitioned table, this + is not cascaded to its partitions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP</literal></term> + <listitem> + <para> + The temporary table will be dropped at the end of the current + transaction block. When used on a partitioned table, this action + drops its partitions and when used on tables with inheritance + children, it drops the dependent children. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry id="sql-createtable-tablespace"> + <term><literal>TABLESPACE <replaceable class="parameter">tablespace_name</replaceable></literal></term> + <listitem> + <para> + The <replaceable class="parameter">tablespace_name</replaceable> is the name + of the tablespace in which the new table is to be created. + If not specified, + <xref linkend="guc-default-tablespace"/> is consulted, or + <xref linkend="guc-temp-tablespaces"/> if the table is temporary. For + partitioned tables, since no storage is required for the table itself, + the tablespace specified overrides <literal>default_tablespace</literal> + as the default tablespace to use for any newly created partitions when no + other tablespace is explicitly specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USING INDEX TABLESPACE <replaceable class="parameter">tablespace_name</replaceable></literal></term> + <listitem> + <para> + This clause allows selection of the tablespace in which the index + associated with a <literal>UNIQUE</literal>, <literal>PRIMARY + KEY</literal>, or <literal>EXCLUDE</literal> constraint will be created. + If not specified, + <xref linkend="guc-default-tablespace"/> is consulted, or + <xref linkend="guc-temp-tablespaces"/> if the table is temporary. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <refsect2 id="sql-createtable-storage-parameters" xreflabel="Storage Parameters"> + <title>Storage Parameters</title> + + <indexterm zone="sql-createtable-storage-parameters"> + <primary>storage parameters</primary> + </indexterm> + + <para> + The <literal>WITH</literal> clause can specify <firstterm>storage parameters</firstterm> + for tables, and for indexes associated with a <literal>UNIQUE</literal>, + <literal>PRIMARY KEY</literal>, or <literal>EXCLUDE</literal> constraint. + Storage parameters for + indexes are documented in <xref linkend="sql-createindex"/>. + The storage parameters currently + available for tables are listed below. For many of these parameters, as + shown, there is an additional parameter with the same name prefixed with + <literal>toast.</literal>, which controls the behavior of the + table's secondary <acronym>TOAST</acronym> table, if any + (see <xref linkend="storage-toast"/> for more information about TOAST). + If a table parameter value is set and the + equivalent <literal>toast.</literal> parameter is not, the TOAST table + will use the table's parameter value. + Specifying these parameters for partitioned tables is not supported, + but you may specify them for individual leaf partitions. + </para> + + <variablelist> + + <varlistentry id="reloption-fillfactor" xreflabel="fillfactor"> + <term><varname>fillfactor</varname> (<type>integer</type>) + <indexterm> + <primary><varname>fillfactor</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + The fillfactor for a table is a percentage between 10 and 100. + 100 (complete packing) is the default. When a smaller fillfactor + is specified, <command>INSERT</command> operations pack table pages only + to the indicated percentage; the remaining space on each page is + reserved for updating rows on that page. This gives <command>UPDATE</command> + a chance to place the updated copy of a row on the same page as the + original, which is more efficient than placing it on a different + page, and makes <link linkend="storage-hot">heap-only tuple + updates</link> more likely. + For a table whose entries are never updated, complete packing is the + best choice, but in heavily updated tables smaller fillfactors are + appropriate. This parameter cannot be set for TOAST tables. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-toast-tuple-target" xreflabel="toast_tuple_target"> + <term><literal>toast_tuple_target</literal> (<type>integer</type>) + <indexterm> + <primary><varname>toast_tuple_target</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + The toast_tuple_target specifies the minimum tuple length required before + we try to compress and/or move long column values into TOAST tables, and + is also the target length we try to reduce the length below once toasting + begins. This affects columns marked as External (for move), + Main (for compression), or Extended (for both) and applies only to new + tuples. There is no effect on existing rows. + By default this parameter is set to allow at least 4 tuples per block, + which with the default block size will be 2040 bytes. Valid values are + between 128 bytes and the (block size - header), by default 8160 bytes. + Changing this value may not be useful for very short or very long rows. + Note that the default setting is often close to optimal, and + it is possible that setting this parameter could have negative + effects in some cases. + This parameter cannot be set for TOAST tables. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-parallel-workers" xreflabel="parallel_workers"> + <term><literal>parallel_workers</literal> (<type>integer</type>) + <indexterm> + <primary><varname>parallel_workers</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + This sets the number of workers that should be used to assist a parallel + scan of this table. If not set, the system will determine a value based + on the relation size. The actual number of workers chosen by the planner + or by utility statements that use parallel scans may be less, for example + due to the setting of <xref linkend="guc-max-worker-processes"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-enabled" xreflabel="autovacuum_enabled"> + <term><literal>autovacuum_enabled</literal>, <literal>toast.autovacuum_enabled</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>autovacuum_enabled</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Enables or disables the autovacuum daemon for a particular table. + If true, the autovacuum daemon will perform automatic <command>VACUUM</command> + and/or <command>ANALYZE</command> operations on this table following the rules + discussed in <xref linkend="autovacuum"/>. + If false, this table will not be autovacuumed, except to prevent + transaction ID wraparound. See <xref linkend="vacuum-for-wraparound"/> for + more about wraparound prevention. + Note that the autovacuum daemon does not run at all (except to prevent + transaction ID wraparound) if the <xref linkend="guc-autovacuum"/> + parameter is false; setting individual tables' storage parameters does + not override that. Therefore there is seldom much point in explicitly + setting this storage parameter to <literal>true</literal>, only + to <literal>false</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-vacuum-index-cleanup" xreflabel="vacuum_index_cleanup"> + <term><literal>vacuum_index_cleanup</literal>, <literal>toast.vacuum_index_cleanup</literal> (<type>enum</type>) + <indexterm> + <primary><varname>vacuum_index_cleanup</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Forces or disables index cleanup when <command>VACUUM</command> + is run on this table. The default value is + <literal>AUTO</literal>. With <literal>OFF</literal>, index + cleanup is disabled, with <literal>ON</literal> it is enabled, + and with <literal>AUTO</literal> a decision is made dynamically, + each time <command>VACUUM</command> runs. The dynamic behavior + allows <command>VACUUM</command> to avoid needlessly scanning + indexes to remove very few dead tuples. Forcibly disabling all + index cleanup can speed up <command>VACUUM</command> very + significantly, but may also lead to severely bloated indexes if + table modifications are frequent. The + <literal>INDEX_CLEANUP</literal> parameter of <link + linkend="sql-vacuum"><command>VACUUM</command></link>, if + specified, overrides the value of this option. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-vacuum-truncate" xreflabel="vacuum_truncate"> + <term><literal>vacuum_truncate</literal>, <literal>toast.vacuum_truncate</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>vacuum_truncate</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Enables or disables vacuum to try to truncate off any empty pages + at the end of this table. The default value is <literal>true</literal>. + If <literal>true</literal>, <command>VACUUM</command> and + autovacuum do the truncation and the disk space for + the truncated pages is returned to the operating system. + Note that the truncation requires <literal>ACCESS EXCLUSIVE</literal> + lock on the table. The <literal>TRUNCATE</literal> parameter + of <link linkend="sql-vacuum"><command>VACUUM</command></link>, if specified, overrides the value + of this option. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-threshold" xreflabel="autovacuum_vacuum_threshold"> + <term><literal>autovacuum_vacuum_threshold</literal>, <literal>toast.autovacuum_vacuum_threshold</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_threshold</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-threshold"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-scale-factor" xreflabel="autovacuum_vacuum_scale_factor"> + <term><literal>autovacuum_vacuum_scale_factor</literal>, <literal>toast.autovacuum_vacuum_scale_factor</literal> (<type>floating point</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_scale_factor</varname> </primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-scale-factor"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-insert-threshold" xreflabel="autovacuum_vacuum_insert_threshold"> + <term><literal>autovacuum_vacuum_insert_threshold</literal>, <literal>toast.autovacuum_vacuum_insert_threshold</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_insert_threshold</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-insert-threshold"/> + parameter. The special value of -1 may be used to disable insert vacuums on the table. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-insert-scale-factor" xreflabel="autovacuum_vacuum_insert_scale_factor"> + <term><literal>autovacuum_vacuum_insert_scale_factor</literal>, <literal>toast.autovacuum_vacuum_insert_scale_factor</literal> (<type>floating point</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_insert_scale_factor</varname> </primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-insert-scale-factor"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-analyze-threshold" xreflabel="autovacuum_analyze_threshold"> + <term><literal>autovacuum_analyze_threshold</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_analyze_threshold</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-analyze-threshold"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-analyze-scale-factor" xreflabel="autovacuum_analyze_scale_factor"> + <term><literal>autovacuum_analyze_scale_factor</literal> (<type>floating point</type>) + <indexterm> + <primary><varname>autovacuum_analyze_scale_factor</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-analyze-scale-factor"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-cost-delay" xreflabel="autovacuum_vacuum_cost_delay"> + <term><literal>autovacuum_vacuum_cost_delay</literal>, <literal>toast.autovacuum_vacuum_cost_delay</literal> (<type>floating point</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_cost_delay</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-cost-delay"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-vacuum-cost-limit" xreflabel="autovacuum_vacuum_cost_limit"> + <term><literal>autovacuum_vacuum_cost_limit</literal>, <literal>toast.autovacuum_vacuum_cost_limit</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_vacuum_cost_limit</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-vacuum-cost-limit"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-freeze-min-age" xreflabel="autovacuum_freeze_min_age"> + <term><literal>autovacuum_freeze_min_age</literal>, <literal>toast.autovacuum_freeze_min_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_freeze_min_age</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-vacuum-freeze-min-age"/> + parameter. Note that autovacuum will ignore + per-table <literal>autovacuum_freeze_min_age</literal> parameters that are + larger than half the + system-wide <xref linkend="guc-autovacuum-freeze-max-age"/> setting. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-freeze-max-age" xreflabel="autovacuum_freeze_max_age"> + <term><literal>autovacuum_freeze_max_age</literal>, <literal>toast.autovacuum_freeze_max_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_freeze_max_age</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-autovacuum-freeze-max-age"/> + parameter. Note that autovacuum will ignore + per-table <literal>autovacuum_freeze_max_age</literal> parameters that are + larger than the system-wide setting (it can only be set smaller). + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-freeze-table-age" xreflabel="autovacuum_freeze_table_age"> + <term><literal>autovacuum_freeze_table_age</literal>, <literal>toast.autovacuum_freeze_table_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_freeze_table_age</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-vacuum-freeze-table-age"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-multixact-freeze-min-age" xreflabel="autovacuum_multixact_freeze_min_age"> + <term><literal>autovacuum_multixact_freeze_min_age</literal>, <literal>toast.autovacuum_multixact_freeze_min_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_multixact_freeze_min_age</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-vacuum-multixact-freeze-min-age"/> + parameter. Note that autovacuum will ignore + per-table <literal>autovacuum_multixact_freeze_min_age</literal> parameters + that are larger than half the + system-wide <xref linkend="guc-autovacuum-multixact-freeze-max-age"/> + setting. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-multixact-freeze-max-age" xreflabel="autovacuum_multixact_freeze_max_age"> + <term><literal>autovacuum_multixact_freeze_max_age</literal>, <literal>toast.autovacuum_multixact_freeze_max_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_multixact_freeze_max_age</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value + for <xref linkend="guc-autovacuum-multixact-freeze-max-age"/> parameter. + Note that autovacuum will ignore + per-table <literal>autovacuum_multixact_freeze_max_age</literal> parameters + that are larger than the system-wide setting (it can only be set + smaller). + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-autovacuum-multixact-freeze-table-age" xreflabel="autovacuum_multixact_freeze_table_age"> + <term><literal>autovacuum_multixact_freeze_table_age</literal>, <literal>toast.autovacuum_multixact_freeze_table_age</literal> (<type>integer</type>) + <indexterm> + <primary><varname>autovacuum_multixact_freeze_table_age</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Per-table value + for <xref linkend="guc-vacuum-multixact-freeze-table-age"/> parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-log-autovacuum-min-duration" xreflabel="log_autovacuum_min_duration"> + <term><literal>log_autovacuum_min_duration</literal>, <literal>toast.log_autovacuum_min_duration</literal> (<type>integer</type>) + <indexterm> + <primary><varname>log_autovacuum_min_duration</varname></primary> + <secondary>storage parameter</secondary> + </indexterm> + </term> + <listitem> + <para> + Per-table value for <xref linkend="guc-log-autovacuum-min-duration"/> + parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry id="reloption-user-catalog-table" xreflabel="user_catalog_table"> + <term><literal>user_catalog_table</literal> (<type>boolean</type>) + <indexterm> + <primary><varname>user_catalog_table</varname> storage parameter</primary> + </indexterm> + </term> + <listitem> + <para> + Declare the table as an additional catalog table for purposes of + logical replication. See + <xref linkend="logicaldecoding-capabilities"/> for details. + This parameter cannot be set for TOAST tables. + </para> + </listitem> + </varlistentry> + + </variablelist> + + </refsect2> + </refsect1> + + <refsect1 id="sql-createtable-notes"> + <title>Notes</title> + <para> + <productname>PostgreSQL</productname> automatically creates an + index for each unique constraint and primary key constraint to + enforce uniqueness. Thus, it is not necessary to create an + index explicitly for primary key columns. (See <xref + linkend="sql-createindex"/> for more information.) + </para> + + <para> + Unique constraints and primary keys are not inherited in the + current implementation. This makes the combination of + inheritance and unique constraints rather dysfunctional. + </para> + + <para> + A table cannot have more than 1600 columns. (In practice, the + effective limit is usually lower because of tuple-length constraints.) + </para> + + </refsect1> + + + <refsect1 id="sql-createtable-examples"> + <title>Examples</title> + + <para> + Create table <structname>films</structname> and table + <structname>distributors</structname>: + +<programlisting> +CREATE TABLE films ( + code char(5) CONSTRAINT firstkey PRIMARY KEY, + title varchar(40) NOT NULL, + did integer NOT NULL, + date_prod date, + kind varchar(10), + len interval hour to minute +); + +CREATE TABLE distributors ( + did integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, + name varchar(40) NOT NULL CHECK (name <> '') +); +</programlisting> + </para> + + <para> + Create a table with a 2-dimensional array: + +<programlisting> +CREATE TABLE array_int ( + vector int[][] +); +</programlisting> + </para> + + <para> + Define a unique table constraint for the table + <literal>films</literal>. Unique table constraints can be defined + on one or more columns of the table: + +<programlisting> +CREATE TABLE films ( + code char(5), + title varchar(40), + did integer, + date_prod date, + kind varchar(10), + len interval hour to minute, + CONSTRAINT production UNIQUE(date_prod) +); +</programlisting> + </para> + + <para> + Define a check column constraint: + +<programlisting> +CREATE TABLE distributors ( + did integer CHECK (did > 100), + name varchar(40) +); +</programlisting> + </para> + + <para> + Define a check table constraint: + +<programlisting> +CREATE TABLE distributors ( + did integer, + name varchar(40), + CONSTRAINT con1 CHECK (did > 100 AND name <> '') +); +</programlisting> + </para> + + <para> + Define a primary key table constraint for the table + <structname>films</structname>: + +<programlisting> +CREATE TABLE films ( + code char(5), + title varchar(40), + did integer, + date_prod date, + kind varchar(10), + len interval hour to minute, + CONSTRAINT code_title PRIMARY KEY(code,title) +); +</programlisting> + </para> + + <para> + Define a primary key constraint for table + <structname>distributors</structname>. The following two examples are + equivalent, the first using the table constraint syntax, the second + the column constraint syntax: + +<programlisting> +CREATE TABLE distributors ( + did integer, + name varchar(40), + PRIMARY KEY(did) +); + +CREATE TABLE distributors ( + did integer PRIMARY KEY, + name varchar(40) +); +</programlisting> + </para> + + <para> + Assign a literal constant default value for the column + <literal>name</literal>, arrange for the default value of column + <literal>did</literal> to be generated by selecting the next value + of a sequence object, and make the default value of + <literal>modtime</literal> be the time at which the row is + inserted: + +<programlisting> +CREATE TABLE distributors ( + name varchar(40) DEFAULT 'Luso Films', + did integer DEFAULT nextval('distributors_serial'), + modtime timestamp DEFAULT current_timestamp +); +</programlisting> + </para> + + <para> + Define two <literal>NOT NULL</literal> column constraints on the table + <classname>distributors</classname>, one of which is explicitly + given a name: + +<programlisting> +CREATE TABLE distributors ( + did integer CONSTRAINT no_null NOT NULL, + name varchar(40) NOT NULL +); +</programlisting> + </para> + + <para> + Define a unique constraint for the <literal>name</literal> column: + +<programlisting> +CREATE TABLE distributors ( + did integer, + name varchar(40) UNIQUE +); +</programlisting> + + The same, specified as a table constraint: + +<programlisting> +CREATE TABLE distributors ( + did integer, + name varchar(40), + UNIQUE(name) +); +</programlisting> + </para> + + <para> + Create the same table, specifying 70% fill factor for both the table + and its unique index: + +<programlisting> +CREATE TABLE distributors ( + did integer, + name varchar(40), + UNIQUE(name) WITH (fillfactor=70) +) +WITH (fillfactor=70); +</programlisting> + </para> + + <para> + Create table <structname>circles</structname> with an exclusion + constraint that prevents any two circles from overlapping: + +<programlisting> +CREATE TABLE circles ( + c circle, + EXCLUDE USING gist (c WITH &&) +); +</programlisting> + </para> + + <para> + Create table <structname>cinemas</structname> in tablespace <structname>diskvol1</structname>: + +<programlisting> +CREATE TABLE cinemas ( + id serial, + name text, + location text +) TABLESPACE diskvol1; +</programlisting> + </para> + + <para> + Create a composite type and a typed table: +<programlisting> +CREATE TYPE employee_type AS (name text, salary numeric); + +CREATE TABLE employees OF employee_type ( + PRIMARY KEY (name), + salary WITH OPTIONS DEFAULT 1000 +); +</programlisting></para> + + <para> + Create a range partitioned table: +<programlisting> +CREATE TABLE measurement ( + logdate date not null, + peaktemp int, + unitsales int +) PARTITION BY RANGE (logdate); +</programlisting></para> + + <para> + Create a range partitioned table with multiple columns in the partition key: +<programlisting> +CREATE TABLE measurement_year_month ( + logdate date not null, + peaktemp int, + unitsales int +) PARTITION BY RANGE (EXTRACT(YEAR FROM logdate), EXTRACT(MONTH FROM logdate)); +</programlisting></para> + + <para> + Create a list partitioned table: +<programlisting> +CREATE TABLE cities ( + city_id bigserial not null, + name text not null, + population bigint +) PARTITION BY LIST (left(lower(name), 1)); +</programlisting></para> + + <para> + Create a hash partitioned table: +<programlisting> +CREATE TABLE orders ( + order_id bigint not null, + cust_id bigint not null, + status text +) PARTITION BY HASH (order_id); +</programlisting></para> + + <para> + Create partition of a range partitioned table: +<programlisting> +CREATE TABLE measurement_y2016m07 + PARTITION OF measurement ( + unitsales DEFAULT 0 +) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); +</programlisting></para> + + <para> + Create a few partitions of a range partitioned table with multiple + columns in the partition key: +<programlisting> +CREATE TABLE measurement_ym_older + PARTITION OF measurement_year_month + FOR VALUES FROM (MINVALUE, MINVALUE) TO (2016, 11); + +CREATE TABLE measurement_ym_y2016m11 + PARTITION OF measurement_year_month + FOR VALUES FROM (2016, 11) TO (2016, 12); + +CREATE TABLE measurement_ym_y2016m12 + PARTITION OF measurement_year_month + FOR VALUES FROM (2016, 12) TO (2017, 01); + +CREATE TABLE measurement_ym_y2017m01 + PARTITION OF measurement_year_month + FOR VALUES FROM (2017, 01) TO (2017, 02); +</programlisting></para> + + <para> + Create partition of a list partitioned table: +<programlisting> +CREATE TABLE cities_ab + PARTITION OF cities ( + CONSTRAINT city_id_nonzero CHECK (city_id != 0) +) FOR VALUES IN ('a', 'b'); +</programlisting></para> + + <para> + Create partition of a list partitioned table that is itself further + partitioned and then add a partition to it: +<programlisting> +CREATE TABLE cities_ab + PARTITION OF cities ( + CONSTRAINT city_id_nonzero CHECK (city_id != 0) +) FOR VALUES IN ('a', 'b') PARTITION BY RANGE (population); + +CREATE TABLE cities_ab_10000_to_100000 + PARTITION OF cities_ab FOR VALUES FROM (10000) TO (100000); +</programlisting></para> + + <para> + Create partitions of a hash partitioned table: +<programlisting> +CREATE TABLE orders_p1 PARTITION OF orders + FOR VALUES WITH (MODULUS 4, REMAINDER 0); +CREATE TABLE orders_p2 PARTITION OF orders + FOR VALUES WITH (MODULUS 4, REMAINDER 1); +CREATE TABLE orders_p3 PARTITION OF orders + FOR VALUES WITH (MODULUS 4, REMAINDER 2); +CREATE TABLE orders_p4 PARTITION OF orders + FOR VALUES WITH (MODULUS 4, REMAINDER 3); +</programlisting></para> + + <para> + Create a default partition: +<programlisting> +CREATE TABLE cities_partdef + PARTITION OF cities DEFAULT; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-createtable-compatibility" xreflabel="Compatibility"> + <title>Compatibility</title> + + <para> + The <command>CREATE TABLE</command> command conforms to the + <acronym>SQL</acronym> standard, with exceptions listed below. + </para> + + <refsect2> + <title>Temporary Tables</title> + + <para> + Although the syntax of <literal>CREATE TEMPORARY TABLE</literal> + resembles that of the SQL standard, the effect is not the same. In the + standard, + temporary tables are defined just once and automatically exist (starting + with empty contents) in every session that needs them. + <productname>PostgreSQL</productname> instead + requires each session to issue its own <literal>CREATE TEMPORARY + TABLE</literal> command for each temporary table to be used. This allows + different sessions to use the same temporary table name for different + purposes, whereas the standard's approach constrains all instances of a + given temporary table name to have the same table structure. + </para> + + <para> + The standard's definition of the behavior of temporary tables is + widely ignored. <productname>PostgreSQL</productname>'s behavior + on this point is similar to that of several other SQL databases. + </para> + + <para> + The SQL standard also distinguishes between global and local temporary + tables, where a local temporary table has a separate set of contents for + each SQL module within each session, though its definition is still shared + across sessions. Since <productname>PostgreSQL</productname> does not + support SQL modules, this distinction is not relevant in + <productname>PostgreSQL</productname>. + </para> + + <para> + For compatibility's sake, <productname>PostgreSQL</productname> will + accept the <literal>GLOBAL</literal> and <literal>LOCAL</literal> keywords + in a temporary table declaration, but they currently have no effect. + Use of these keywords is discouraged, since future versions of + <productname>PostgreSQL</productname> might adopt a more + standard-compliant interpretation of their meaning. + </para> + + <para> + The <literal>ON COMMIT</literal> clause for temporary tables + also resembles the SQL standard, but has some differences. + If the <literal>ON COMMIT</literal> clause is omitted, SQL specifies that the + default behavior is <literal>ON COMMIT DELETE ROWS</literal>. However, the + default behavior in <productname>PostgreSQL</productname> is + <literal>ON COMMIT PRESERVE ROWS</literal>. The <literal>ON COMMIT + DROP</literal> option does not exist in SQL. + </para> + </refsect2> + + <refsect2> + <title>Non-Deferred Uniqueness Constraints</title> + + <para> + When a <literal>UNIQUE</literal> or <literal>PRIMARY KEY</literal> constraint is + not deferrable, <productname>PostgreSQL</productname> checks for + uniqueness immediately whenever a row is inserted or modified. + The SQL standard says that uniqueness should be enforced only at + the end of the statement; this makes a difference when, for example, + a single command updates multiple key values. To obtain + standard-compliant behavior, declare the constraint as + <literal>DEFERRABLE</literal> but not deferred (i.e., <literal>INITIALLY + IMMEDIATE</literal>). Be aware that this can be significantly slower than + immediate uniqueness checking. + </para> + </refsect2> + + <refsect2> + <title>Column Check Constraints</title> + + <para> + The SQL standard says that <literal>CHECK</literal> column constraints + can only refer to the column they apply to; only <literal>CHECK</literal> + table constraints can refer to multiple columns. + <productname>PostgreSQL</productname> does not enforce this + restriction; it treats column and table check constraints alike. + </para> + </refsect2> + + <refsect2> + <title><literal>EXCLUDE</literal> Constraint</title> + + <para> + The <literal>EXCLUDE</literal> constraint type is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect2> + + <refsect2> + <title>Foreign-Key Constraint Actions</title> + + <para> + The ability to specify column lists in the foreign-key actions + <literal>SET DEFAULT</literal> and <literal>SET NULL</literal> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect2> + + <refsect2> + <title><literal>NULL</literal> <quote>Constraint</quote></title> + + <para> + The <literal>NULL</literal> <quote>constraint</quote> (actually a + non-constraint) is a <productname>PostgreSQL</productname> + extension to the SQL standard that is included for compatibility with some + other database systems (and for symmetry with the <literal>NOT + NULL</literal> constraint). Since it is the default for any + column, its presence is simply noise. + </para> + </refsect2> + + <refsect2> + <title>Constraint Naming</title> + + <para> + The SQL standard says that table and domain constraints must have names + that are unique across the schema containing the table or domain. + <productname>PostgreSQL</productname> is laxer: it only requires + constraint names to be unique across the constraints attached to a + particular table or domain. However, this extra freedom does not exist + for index-based constraints (<literal>UNIQUE</literal>, + <literal>PRIMARY KEY</literal>, and <literal>EXCLUDE</literal> + constraints), because the associated index is named the same as the + constraint, and index names must be unique across all relations within + the same schema. + </para> + + <para> + Currently, <productname>PostgreSQL</productname> does not record names + for <literal>NOT NULL</literal> constraints at all, so they are not + subject to the uniqueness restriction. This might change in a future + release. + </para> + </refsect2> + + <refsect2> + <title>Inheritance</title> + + <para> + Multiple inheritance via the <literal>INHERITS</literal> clause is + a <productname>PostgreSQL</productname> language extension. + SQL:1999 and later define single inheritance using a + different syntax and different semantics. SQL:1999-style + inheritance is not yet supported by + <productname>PostgreSQL</productname>. + </para> + </refsect2> + + <refsect2> + <title>Zero-Column Tables</title> + + <para> + <productname>PostgreSQL</productname> allows a table of no columns + to be created (for example, <literal>CREATE TABLE foo();</literal>). This + is an extension from the SQL standard, which does not allow zero-column + tables. Zero-column tables are not in themselves very useful, but + disallowing them creates odd special cases for <command>ALTER TABLE + DROP COLUMN</command>, so it seems cleaner to ignore this spec restriction. + </para> + </refsect2> + + <refsect2> + <title>Multiple Identity Columns</title> + + <para> + <productname>PostgreSQL</productname> allows a table to have more than one + identity column. The standard specifies that a table can have at most one + identity column. This is relaxed mainly to give more flexibility for + doing schema changes or migrations. Note that + the <command>INSERT</command> command supports only one override clause + that applies to the entire statement, so having multiple identity columns + with different behaviors is not well supported. + </para> + </refsect2> + + <refsect2> + <title>Generated Columns</title> + + <para> + The option <literal>STORED</literal> is not standard but is also used by + other SQL implementations. The SQL standard does not specify the storage + of generated columns. + </para> + </refsect2> + + <refsect2> + <title><literal>LIKE</literal> Clause</title> + + <para> + While a <literal>LIKE</literal> clause exists in the SQL standard, many of the + options that <productname>PostgreSQL</productname> accepts for it are not + in the standard, and some of the standard's options are not implemented + by <productname>PostgreSQL</productname>. + </para> + </refsect2> + + <refsect2> + <title><literal>WITH</literal> Clause</title> + + <para> + The <literal>WITH</literal> clause is a <productname>PostgreSQL</productname> + extension; storage parameters are not in the standard. + </para> + </refsect2> + + <refsect2> + <title>Tablespaces</title> + + <para> + The <productname>PostgreSQL</productname> concept of tablespaces is not + part of the standard. Hence, the clauses <literal>TABLESPACE</literal> + and <literal>USING INDEX TABLESPACE</literal> are extensions. + </para> + </refsect2> + + <refsect2> + <title>Typed Tables</title> + + <para> + Typed tables implement a subset of the SQL standard. According to + the standard, a typed table has columns corresponding to the + underlying composite type as well as one other column that is + the <quote>self-referencing column</quote>. + <productname>PostgreSQL</productname> does not support self-referencing + columns explicitly. + </para> + </refsect2> + + <refsect2> + <title><literal>PARTITION BY</literal> Clause</title> + + <para> + The <literal>PARTITION BY</literal> clause is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect2> + + <refsect2> + <title><literal>PARTITION OF</literal> Clause</title> + + <para> + The <literal>PARTITION OF</literal> clause is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect2> + + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertable"/></member> + <member><xref linkend="sql-droptable"/></member> + <member><xref linkend="sql-createtableas"/></member> + <member><xref linkend="sql-createtablespace"/></member> + <member><xref linkend="sql-createtype"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_table_as.sgml b/doc/src/sgml/ref/create_table_as.sgml new file mode 100644 index 0000000..8429333 --- /dev/null +++ b/doc/src/sgml/ref/create_table_as.sgml @@ -0,0 +1,362 @@ +<!-- +doc/src/sgml/ref/create_table_as.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtableas"> + <indexterm zone="sql-createtableas"> + <primary>CREATE TABLE AS</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TABLE AS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TABLE AS</refname> + <refpurpose>define a new table from the results of a query</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] <replaceable>table_name</replaceable> + [ (<replaceable>column_name</replaceable> [, ...] ) ] + [ USING <replaceable class="parameter">method</replaceable> ] + [ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) | WITHOUT OIDS ] + [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] + [ TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> ] + AS <replaceable>query</replaceable> + [ WITH [ NO ] DATA ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TABLE AS</command> creates a table and fills it + with data computed by a <command>SELECT</command> command. + The table columns have the + names and data types associated with the output columns of the + <command>SELECT</command> (except that you can override the column + names by giving an explicit list of new column names). + </para> + + <para> + <command>CREATE TABLE AS</command> bears some resemblance to + creating a view, but it is really quite different: it creates a new + table and evaluates the query just once to fill the new table + initially. The new table will not track subsequent changes to the + source tables of the query. In contrast, a view re-evaluates its + defining <command>SELECT</command> statement whenever it is + queried. + </para> + + <para> + <command>CREATE TABLE AS</command> requires <literal>CREATE</literal> + privilege on the schema used for the table. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>GLOBAL</literal> or <literal>LOCAL</literal></term> + <listitem> + <para> + Ignored for compatibility. Use of these keywords is deprecated; + refer to <xref linkend="sql-createtable"/> for details. + </para> + </listitem> + </varlistentry> + </variablelist> + + <variablelist> + <varlistentry> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + If specified, the table is created as a temporary table. + Refer to <xref linkend="sql-createtable"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>UNLOGGED</literal></term> + <listitem> + <para> + If specified, the table is created as an unlogged table. + Refer to <xref linkend="sql-createtable"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a relation with the same name already + exists; simply issue a notice and leave the table unmodified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>column_name</replaceable></term> + <listitem> + <para> + The name of a column in the new table. If column names are not + provided, they are taken from the output column names of the query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USING <replaceable class="parameter">method</replaceable></literal></term> + <listitem> + <para> + This optional clause specifies the table access method to use to store + the contents for the new table; the method needs be an access method of + type <literal>TABLE</literal>. See <xref linkend="tableam"/> for more + information. If this option is not specified, the default table access + method is chosen for the new table. See <xref + linkend="guc-default-table-access-method"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional storage parameters for the new table; + see <xref linkend="sql-createtable-storage-parameters"/> in the + <xref linkend="sql-createtable"/> documentation for more + information. For backward-compatibility the <literal>WITH</literal> + clause for a table can also include <literal>OIDS=FALSE</literal> to + specify that rows of the new table should contain no OIDs (object + identifiers), <literal>OIDS=TRUE</literal> is not supported anymore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITHOUT OIDS</literal></term> + <listitem> + <para> + This is backward-compatible syntax for declaring a table + <literal>WITHOUT OIDS</literal>, creating a table <literal>WITH + OIDS</literal> is not supported anymore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ON COMMIT</literal></term> + <listitem> + <para> + The behavior of temporary tables at the end of a transaction + block can be controlled using <literal>ON COMMIT</literal>. + The three options are: + + <variablelist> + <varlistentry> + <term><literal>PRESERVE ROWS</literal></term> + <listitem> + <para> + No special action is taken at the ends of transactions. + This is the default behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DELETE ROWS</literal></term> + <listitem> + <para> + All rows in the temporary table will be deleted at the end + of each transaction block. Essentially, an automatic <link + linkend="sql-truncate"><command>TRUNCATE</command></link> is done + at each commit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DROP</literal></term> + <listitem> + <para> + The temporary table will be dropped at the end of the current + transaction block. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TABLESPACE <replaceable class="parameter">tablespace_name</replaceable></literal></term> + <listitem> + <para> + The <replaceable class="parameter">tablespace_name</replaceable> is the name + of the tablespace in which the new table is to be created. + If not specified, + <xref linkend="guc-default-tablespace"/> is consulted, or + <xref linkend="guc-temp-tablespaces"/> if the table is temporary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>query</replaceable></term> + <listitem> + <para> + A <link linkend="sql-select"><command>SELECT</command></link>, <link + linkend="sql-table"><command>TABLE</command></link>, or <link linkend="sql-values"><command>VALUES</command></link> + command, or an <link linkend="sql-execute"><command>EXECUTE</command></link> command that runs a + prepared <command>SELECT</command>, <command>TABLE</command>, or + <command>VALUES</command> query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH [ NO ] DATA</literal></term> + <listitem> + <para> + This clause specifies whether or not the data produced by the query + should be copied into the new table. If not, only the table structure + is copied. The default is to copy the data. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + This command is functionally similar to <xref + linkend="sql-selectinto"/>, but it is + preferred since it is less likely to be confused with other uses of + the <command>SELECT INTO</command> syntax. Furthermore, <command>CREATE + TABLE AS</command> offers a superset of the functionality offered + by <command>SELECT INTO</command>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a new table <literal>films_recent</literal> consisting of only + recent entries from the table <literal>films</literal>: + +<programlisting> +CREATE TABLE films_recent AS + SELECT * FROM films WHERE date_prod >= '2002-01-01'; +</programlisting> + </para> + + <para> + To copy a table completely, the short form using + the <literal>TABLE</literal> command can also be used: + +<programlisting> +CREATE TABLE films2 AS + TABLE films; +</programlisting> + </para> + + <para> + Create a new temporary table <literal>films_recent</literal>, consisting of + only recent entries from the table <literal>films</literal>, using a + prepared statement. The new table will be dropped at commit: + +<programlisting> +PREPARE recentfilms(date) AS + SELECT * FROM films WHERE date_prod > $1; +CREATE TEMP TABLE films_recent ON COMMIT DROP AS + EXECUTE recentfilms('2002-01-01'); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE TABLE AS</command> conforms to the <acronym>SQL</acronym> + standard. The following are nonstandard extensions: + + <itemizedlist spacing="compact"> + <listitem> + <para> + The standard requires parentheses around the subquery clause; in + <productname>PostgreSQL</productname>, these parentheses are + optional. + </para> + </listitem> + + <listitem> + <para> + In the standard, the <literal>WITH [ NO ] DATA</literal> clause + is required; in PostgreSQL it is optional. + </para> + </listitem> + + <listitem> + <para><productname>PostgreSQL</productname> handles temporary tables in a way + rather different from the standard; see + <xref linkend="sql-createtable"/> + for details. + </para> + </listitem> + + <listitem> + <para> + The <literal>WITH</literal> clause is a <productname>PostgreSQL</productname> + extension; storage parameters are not in the standard. + </para> + </listitem> + + <listitem> + <para> + The <productname>PostgreSQL</productname> concept of tablespaces is not + part of the standard. Hence, the clause <literal>TABLESPACE</literal> + is an extension. + </para> + </listitem> + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-creatematerializedview"/></member> + <member><xref linkend="sql-createtable"/></member> + <member><xref linkend="sql-execute"/></member> + <member><xref linkend="sql-select"/></member> + <member><xref linkend="sql-selectinto"/></member> + <member><xref linkend="sql-values"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_tablespace.sgml b/doc/src/sgml/ref/create_tablespace.sgml new file mode 100644 index 0000000..84fa7ee --- /dev/null +++ b/doc/src/sgml/ref/create_tablespace.sgml @@ -0,0 +1,187 @@ +<!-- +doc/src/sgml/ref/create_tablespace.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtablespace"> + <indexterm zone="sql-createtablespace"> + <primary>CREATE TABLESPACE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TABLESPACE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TABLESPACE</refname> + <refpurpose>define a new tablespace</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TABLESPACE <replaceable class="parameter">tablespace_name</replaceable> + [ OWNER { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } ] + LOCATION '<replaceable class="parameter">directory</replaceable>' + [ WITH ( <replaceable class="parameter">tablespace_option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TABLESPACE</command> registers a new cluster-wide + tablespace. The tablespace name must be distinct from the name of any + existing tablespace in the database cluster. + </para> + + <para> + A tablespace allows superusers to define an alternative location on + the file system where the data files containing database objects + (such as tables and indexes) can reside. + </para> + + <para> + A user with appropriate privileges can pass + <replaceable class="parameter">tablespace_name</replaceable> to + <command>CREATE DATABASE</command>, <command>CREATE TABLE</command>, + <command>CREATE INDEX</command> or <command>ADD CONSTRAINT</command> to have the data + files for these objects stored within the specified tablespace. + </para> + + <warning> + <para> + A tablespace cannot be used independently of the cluster in which it + is defined; see <xref linkend="manage-ag-tablespaces"/>. + </para> + </warning> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">tablespace_name</replaceable></term> + <listitem> + <para> + The name of a tablespace to be created. The name cannot + begin with <literal>pg_</literal>, as such names + are reserved for system tablespaces. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + The name of the user who will own the tablespace. If omitted, + defaults to the user executing the command. Only superusers + can create tablespaces, but they can assign ownership of tablespaces + to non-superusers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">directory</replaceable></term> + <listitem> + <para> + The directory that will be used for the tablespace. The directory + must exist (<command>CREATE TABLESPACE</command> will not create it), + should be empty, and must be owned by the + <productname>PostgreSQL</productname> system user. The directory must be + specified by an absolute path name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">tablespace_option</replaceable></term> + <listitem> + <para> + A tablespace parameter to be set or reset. Currently, the only + available parameters are <varname>seq_page_cost</varname>, + <varname>random_page_cost</varname>, <varname>effective_io_concurrency</varname> + and <varname>maintenance_io_concurrency</varname>. + Setting these values for a particular tablespace will override the + planner's usual estimate of the cost of reading pages from tables in + that tablespace, and the executor's prefetching behavior, as established + by the configuration parameters of the + same name (see <xref linkend="guc-seq-page-cost"/>, + <xref linkend="guc-random-page-cost"/>, + <xref linkend="guc-effective-io-concurrency"/>, + <xref linkend="guc-maintenance-io-concurrency"/>). This may be useful if + one tablespace is located on a disk which is faster or slower than the + remainder of the I/O subsystem. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Tablespaces are only supported on systems that support symbolic links. + </para> + + <para> + <command>CREATE TABLESPACE</command> cannot be executed inside a transaction + block. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To create a tablespace <literal>dbspace</literal> at file system location + <literal>/data/dbs</literal>, first create the directory using operating + system facilities and set the correct ownership: +<programlisting> +mkdir /data/dbs +chown postgres:postgres /data/dbs +</programlisting> + Then issue the tablespace creation command inside + <productname>PostgreSQL</productname>: +<programlisting> +CREATE TABLESPACE dbspace LOCATION '/data/dbs'; +</programlisting> + </para> + + <para> + To create a tablespace owned by a different database user, use a command + like this: +<programlisting> +CREATE TABLESPACE indexspace OWNER genevieve LOCATION '/data/indexes'; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE TABLESPACE</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createdatabase"/></member> + <member><xref linkend="sql-createtable"/></member> + <member><xref linkend="sql-createindex"/></member> + <member><xref linkend="sql-droptablespace"/></member> + <member><xref linkend="sql-altertablespace"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_transform.sgml b/doc/src/sgml/ref/create_transform.sgml new file mode 100644 index 0000000..34bdc60 --- /dev/null +++ b/doc/src/sgml/ref/create_transform.sgml @@ -0,0 +1,214 @@ +<!-- +doc/src/sgml/ref/create_transform.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtransform"> + <indexterm zone="sql-createtransform"> + <primary>CREATE TRANSFORM</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TRANSFORM</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TRANSFORM</refname> + <refpurpose>define a new transform</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] TRANSFORM FOR <replaceable>type_name</replaceable> LANGUAGE <replaceable>lang_name</replaceable> ( + FROM SQL WITH FUNCTION <replaceable>from_sql_function_name</replaceable> [ (<replaceable>argument_type</replaceable> [, ...]) ], + TO SQL WITH FUNCTION <replaceable>to_sql_function_name</replaceable> [ (<replaceable>argument_type</replaceable> [, ...]) ] +); +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-createtransform-description"> + <title>Description</title> + + <para> + <command>CREATE TRANSFORM</command> defines a new transform. + <command>CREATE OR REPLACE TRANSFORM</command> will either create a new + transform, or replace an existing definition. + </para> + + <para> + A transform specifies how to adapt a data type to a procedural language. + For example, when writing a function in PL/Python using + the <type>hstore</type> type, PL/Python has no prior knowledge how to + present <type>hstore</type> values in the Python environment. Language + implementations usually default to using the text representation, but that + is inconvenient when, for example, an associative array or a list would be + more appropriate. + </para> + + <para> + A transform specifies two functions: + <itemizedlist> + <listitem> + <para> + A <quote>from SQL</quote> function that converts the type from the SQL + environment to the language. This function will be invoked on the + arguments of a function written in the language. + </para> + </listitem> + + <listitem> + <para> + A <quote>to SQL</quote> function that converts the type from the + language to the SQL environment. This function will be invoked on the + return value of a function written in the language. + </para> + </listitem> + </itemizedlist> + It is not necessary to provide both of these functions. If one is not + specified, the language-specific default behavior will be used if + necessary. (To prevent a transformation in a certain direction from + happening at all, you could also write a transform function that always + errors out.) + </para> + + <para> + To be able to create a transform, you must own and + have <literal>USAGE</literal> privilege on the type, have + <literal>USAGE</literal> privilege on the language, and own and + have <literal>EXECUTE</literal> privilege on the from-SQL and to-SQL + functions, if specified. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>type_name</replaceable></term> + + <listitem> + <para> + The name of the data type of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lang_name</replaceable></term> + + <listitem> + <para> + The name of the language of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><replaceable>from_sql_function_name</replaceable>[(<replaceable>argument_type</replaceable> [, ...])]</literal></term> + + <listitem> + <para> + The name of the function for converting the type from the SQL + environment to the language. It must take one argument of + type <type>internal</type> and return type <type>internal</type>. The + actual argument will be of the type for the transform, and the function + should be coded as if it were. (But it is not allowed to declare an + SQL-level function returning <type>internal</type> without at + least one argument of type <type>internal</type>.) The actual return + value will be something specific to the language implementation. + If no argument list is specified, the function name must be unique in + its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal><replaceable>to_sql_function_name</replaceable>[(<replaceable>argument_type</replaceable> [, ...])]</literal></term> + + <listitem> + <para> + The name of the function for converting the type from the language to + the SQL environment. It must take one argument of type + <type>internal</type> and return the type that is the type for the + transform. The actual argument value will be something specific to the + language implementation. + If no argument list is specified, the function name must be unique in + its schema. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createtransform-notes"> + <title>Notes</title> + + <para> + Use <link linkend="sql-droptransform"><command>DROP TRANSFORM</command></link> to remove transforms. + </para> + </refsect1> + + <refsect1 id="sql-createtransform-examples"> + <title>Examples</title> + + <para> + To create a transform for type <type>hstore</type> and language + <literal>plpython3u</literal>, first set up the type and the language: +<programlisting> +CREATE TYPE hstore ...; + +CREATE EXTENSION plpython3u; +</programlisting> + Then create the necessary functions: +<programlisting> +CREATE FUNCTION hstore_to_plpython(val internal) RETURNS internal +LANGUAGE C STRICT IMMUTABLE +AS ...; + +CREATE FUNCTION plpython_to_hstore(val internal) RETURNS hstore +LANGUAGE C STRICT IMMUTABLE +AS ...; +</programlisting> + And finally create the transform to connect them all together: +<programlisting> +CREATE TRANSFORM FOR hstore LANGUAGE plpython3u ( + FROM SQL WITH FUNCTION hstore_to_plpython(internal), + TO SQL WITH FUNCTION plpython_to_hstore(internal) +); +</programlisting> + In practice, these commands would be wrapped up in an extension. + </para> + + <para> + The <filename>contrib</filename> section contains a number of extensions + that provide transforms, which can serve as real-world examples. + </para> + </refsect1> + + <refsect1 id="sql-createtransform-compat"> + <title>Compatibility</title> + + <para> + This form of <command>CREATE TRANSFORM</command> is a + <productname>PostgreSQL</productname> extension. There is a <command>CREATE + TRANSFORM</command> command in the <acronym>SQL</acronym> standard, but it + is for adapting data types to client languages. That usage is not supported + by <productname>PostgreSQL</productname>. + </para> + </refsect1> + + <refsect1 id="sql-createtransform-seealso"> + <title>See Also</title> + + <para> + <xref linkend="sql-createfunction"/>, + <xref linkend="sql-createlanguage"/>, + <xref linkend="sql-createtype"/>, + <xref linkend="sql-droptransform"/> + </para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_trigger.sgml b/doc/src/sgml/ref/create_trigger.sgml new file mode 100644 index 0000000..ee42f41 --- /dev/null +++ b/doc/src/sgml/ref/create_trigger.sgml @@ -0,0 +1,777 @@ +<!-- +doc/src/sgml/ref/create_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtrigger"> + <indexterm zone="sql-createtrigger"> + <primary>CREATE TRIGGER</primary> + </indexterm> + + <indexterm> + <primary>transition tables</primary> + <seealso>ephemeral named relation</seealso> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TRIGGER</refname> + <refpurpose>define a new trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] [ CONSTRAINT ] TRIGGER <replaceable class="parameter">name</replaceable> { BEFORE | AFTER | INSTEAD OF } { <replaceable class="parameter">event</replaceable> [ OR ... ] } + ON <replaceable class="parameter">table_name</replaceable> + [ FROM <replaceable class="parameter">referenced_table_name</replaceable> ] + [ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ] + [ REFERENCING { { OLD | NEW } TABLE [ AS ] <replaceable class="parameter">transition_relation_name</replaceable> } [ ... ] ] + [ FOR [ EACH ] { ROW | STATEMENT } ] + [ WHEN ( <replaceable class="parameter">condition</replaceable> ) ] + EXECUTE { FUNCTION | PROCEDURE } <replaceable class="parameter">function_name</replaceable> ( <replaceable class="parameter">arguments</replaceable> ) + +<phrase>where <replaceable class="parameter">event</replaceable> can be one of:</phrase> + + INSERT + UPDATE [ OF <replaceable class="parameter">column_name</replaceable> [, ... ] ] + DELETE + TRUNCATE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TRIGGER</command> creates a new trigger. + <command>CREATE OR REPLACE TRIGGER</command> will either create a + new trigger, or replace an existing trigger. The + trigger will be associated with the specified table, view, or foreign table + and will execute the specified + function <replaceable class="parameter">function_name</replaceable> when + certain operations are performed on that table. + </para> + + <para> + To replace the current definition of an existing trigger, use + <command>CREATE OR REPLACE TRIGGER</command>, specifying the existing + trigger's name and parent table. All other properties are replaced. + </para> + + <para> + The trigger can be specified to fire before the + operation is attempted on a row (before constraints are checked and + the <command>INSERT</command>, <command>UPDATE</command>, or + <command>DELETE</command> is attempted); or after the operation has + completed (after constraints are checked and the + <command>INSERT</command>, <command>UPDATE</command>, or + <command>DELETE</command> has completed); or instead of the operation + (in the case of inserts, updates or deletes on a view). + If the trigger fires before or instead of the event, the trigger can skip + the operation for the current row, or change the row being inserted (for + <command>INSERT</command> and <command>UPDATE</command> operations + only). If the trigger fires after the event, all changes, including + the effects of other triggers, are <quote>visible</quote> + to the trigger. + </para> + + <para> + A trigger that is marked <literal>FOR EACH ROW</literal> is called + once for every row that the operation modifies. For example, a + <command>DELETE</command> that affects 10 rows will cause any + <literal>ON DELETE</literal> triggers on the target relation to be + called 10 separate times, once for each deleted row. In contrast, a + trigger that is marked <literal>FOR EACH STATEMENT</literal> only + executes once for any given operation, regardless of how many rows + it modifies (in particular, an operation that modifies zero rows + will still result in the execution of any applicable <literal>FOR + EACH STATEMENT</literal> triggers). + </para> + + <para> + Triggers that are specified to fire <literal>INSTEAD OF</literal> the trigger + event must be marked <literal>FOR EACH ROW</literal>, and can only be defined + on views. <literal>BEFORE</literal> and <literal>AFTER</literal> triggers on a view + must be marked as <literal>FOR EACH STATEMENT</literal>. + </para> + + <para> + In addition, triggers may be defined to fire for + <command>TRUNCATE</command>, though only + <literal>FOR EACH STATEMENT</literal>. + </para> + + <para> + The following table summarizes which types of triggers may be used on + tables, views, and foreign tables: + </para> + + <informaltable id="supported-trigger-types"> + <tgroup cols="4"> + <thead> + <row> + <entry>When</entry> + <entry>Event</entry> + <entry>Row-level</entry> + <entry>Statement-level</entry> + </row> + </thead> + <tbody> + <row> + <entry align="center" morerows="1"><literal>BEFORE</literal></entry> + <entry align="center"><command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command></entry> + <entry align="center">Tables and foreign tables</entry> + <entry align="center">Tables, views, and foreign tables</entry> + </row> + <row> + <entry align="center"><command>TRUNCATE</command></entry> + <entry align="center">—</entry> + <entry align="center">Tables</entry> + </row> + <row> + <entry align="center" morerows="1"><literal>AFTER</literal></entry> + <entry align="center"><command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command></entry> + <entry align="center">Tables and foreign tables</entry> + <entry align="center">Tables, views, and foreign tables</entry> + </row> + <row> + <entry align="center"><command>TRUNCATE</command></entry> + <entry align="center">—</entry> + <entry align="center">Tables</entry> + </row> + <row> + <entry align="center" morerows="1"><literal>INSTEAD OF</literal></entry> + <entry align="center"><command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command></entry> + <entry align="center">Views</entry> + <entry align="center">—</entry> + </row> + <row> + <entry align="center"><command>TRUNCATE</command></entry> + <entry align="center">—</entry> + <entry align="center">—</entry> + </row> + </tbody> + </tgroup> + </informaltable> + + <para> + Also, a trigger definition can specify a Boolean <literal>WHEN</literal> + condition, which will be tested to see whether the trigger should + be fired. In row-level triggers the <literal>WHEN</literal> condition can + examine the old and/or new values of columns of the row. Statement-level + triggers can also have <literal>WHEN</literal> conditions, although the feature + is not so useful for them since the condition cannot refer to any values + in the table. + </para> + + <para> + If multiple triggers of the same kind are defined for the same event, + they will be fired in alphabetical order by name. + </para> + + <para> + When the <literal>CONSTRAINT</literal> option is specified, this command creates a + <firstterm>constraint trigger</firstterm>.<indexterm><primary>trigger</primary> + <secondary>constraint trigger</secondary></indexterm> + This is the same as a regular trigger + except that the timing of the trigger firing can be adjusted using + <link linkend="sql-set-constraints"><command>SET CONSTRAINTS</command></link>. + Constraint triggers must be <literal>AFTER ROW</literal> triggers on plain + tables (not foreign tables). They + can be fired either at the end of the statement causing the triggering + event, or at the end of the containing transaction; in the latter case they + are said to be <firstterm>deferred</firstterm>. A pending deferred-trigger firing + can also be forced to happen immediately by using <command>SET + CONSTRAINTS</command>. Constraint triggers are expected to raise an exception + when the constraints they implement are violated. + </para> + + <para> + The <literal>REFERENCING</literal> option enables collection + of <firstterm>transition relations</firstterm>, which are row sets that include all + of the rows inserted, deleted, or modified by the current SQL statement. + This feature lets the trigger see a global view of what the statement did, + not just one row at a time. This option is only allowed for + an <literal>AFTER</literal> trigger that is not a constraint trigger; also, if + the trigger is an <literal>UPDATE</literal> trigger, it must not specify + a <replaceable class="parameter">column_name</replaceable> list. + <literal>OLD TABLE</literal> may only be specified once, and only for a trigger + that can fire on <literal>UPDATE</literal> or <literal>DELETE</literal>; it creates a + transition relation containing the <firstterm>before-images</firstterm> of all rows + updated or deleted by the statement. + Similarly, <literal>NEW TABLE</literal> may only be specified once, and only for + a trigger that can fire on <literal>UPDATE</literal> or <literal>INSERT</literal>; + it creates a transition relation containing the <firstterm>after-images</firstterm> + of all rows updated or inserted by the statement. + </para> + + <para> + <command>SELECT</command> does not modify any rows so you cannot + create <command>SELECT</command> triggers. Rules and views may provide + workable solutions to problems that seem to need <command>SELECT</command> + triggers. + </para> + + <para> + Refer to <xref linkend="triggers"/> for more information about triggers. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name to give the new trigger. This must be distinct from + the name of any other trigger for the same table. + The name cannot be schema-qualified — the trigger inherits the + schema of its table. For a constraint trigger, this is also the name to + use when modifying the trigger's behavior using + <command>SET CONSTRAINTS</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BEFORE</literal></term> + <term><literal>AFTER</literal></term> + <term><literal>INSTEAD OF</literal></term> + <listitem> + <para> + Determines whether the function is called before, after, or instead of + the event. A constraint trigger can only be specified as + <literal>AFTER</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">event</replaceable></term> + <listitem> + <para> + One of <literal>INSERT</literal>, <literal>UPDATE</literal>, + <literal>DELETE</literal>, or <literal>TRUNCATE</literal>; + this specifies the event that will fire the trigger. Multiple + events can be specified using <literal>OR</literal>, except when + transition relations are requested. + </para> + + <para> + For <literal>UPDATE</literal> events, it is possible to + specify a list of columns using this syntax: +<synopsis> +UPDATE OF <replaceable>column_name1</replaceable> [, <replaceable>column_name2</replaceable> ... ] +</synopsis> + The trigger will only fire if at least one of the listed columns + is mentioned as a target of the <command>UPDATE</command> command + or if one of the listed columns is a generated column that depends on a + column that is the target of the <command>UPDATE</command>. + </para> + + <para> + <literal>INSTEAD OF UPDATE</literal> events do not allow a list of columns. + A column list cannot be specified when requesting transition relations, + either. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table, view, or foreign + table the trigger is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">referenced_table_name</replaceable></term> + <listitem> + <para> + The (possibly schema-qualified) name of another table referenced by the + constraint. This option is used for foreign-key constraints and is not + recommended for general use. This can only be specified for + constraint triggers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFERRABLE</literal></term> + <term><literal>NOT DEFERRABLE</literal></term> + <term><literal>INITIALLY IMMEDIATE</literal></term> + <term><literal>INITIALLY DEFERRED</literal></term> + <listitem> + <para> + The default timing of the trigger. + See the <xref linkend="sql-createtable"/> documentation for details of + these constraint options. This can only be specified for constraint + triggers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REFERENCING</literal></term> + <listitem> + <para> + This keyword immediately precedes the declaration of one or two + relation names that provide access to the transition relations of the + triggering statement. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OLD TABLE</literal></term> + <term><literal>NEW TABLE</literal></term> + <listitem> + <para> + This clause indicates whether the following relation name is for the + before-image transition relation or the after-image transition + relation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">transition_relation_name</replaceable></term> + <listitem> + <para> + The (unqualified) name to be used within the trigger for this + transition relation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FOR EACH ROW</literal></term> + <term><literal>FOR EACH STATEMENT</literal></term> + + <listitem> + <para> + This specifies whether the trigger function should be fired + once for every row affected by the trigger event, or just once + per SQL statement. If neither is specified, <literal>FOR EACH + STATEMENT</literal> is the default. Constraint triggers can only + be specified <literal>FOR EACH ROW</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + A Boolean expression that determines whether the trigger function + will actually be executed. If <literal>WHEN</literal> is specified, the + function will only be called if the <replaceable + class="parameter">condition</replaceable> returns <literal>true</literal>. + In <literal>FOR EACH ROW</literal> triggers, the <literal>WHEN</literal> + condition can refer to columns of the old and/or new row values + by writing <literal>OLD.<replaceable + class="parameter">column_name</replaceable></literal> or + <literal>NEW.<replaceable + class="parameter">column_name</replaceable></literal> respectively. + Of course, <literal>INSERT</literal> triggers cannot refer to <literal>OLD</literal> + and <literal>DELETE</literal> triggers cannot refer to <literal>NEW</literal>. + </para> + + <para><literal>INSTEAD OF</literal> triggers do not support <literal>WHEN</literal> + conditions. + </para> + + <para> + Currently, <literal>WHEN</literal> expressions cannot contain + subqueries. + </para> + + <para> + Note that for constraint triggers, evaluation of the <literal>WHEN</literal> + condition is not deferred, but occurs immediately after the row update + operation is performed. If the condition does not evaluate to true then + the trigger is not queued for deferred execution. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + A user-supplied function that is declared as taking no arguments + and returning type <literal>trigger</literal>, which is executed when + the trigger fires. + </para> + + <para> + In the syntax of <literal>CREATE TRIGGER</literal>, the keywords + <literal>FUNCTION</literal> and <literal>PROCEDURE</literal> are + equivalent, but the referenced function must in any case be a function, + not a procedure. The use of the keyword <literal>PROCEDURE</literal> + here is historical and deprecated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">arguments</replaceable></term> + <listitem> + <para> + An optional comma-separated list of arguments to be provided to + the function when the trigger is executed. The arguments are + literal string constants. Simple names and numeric constants + can be written here, too, but they will all be converted to + strings. Please check the description of the implementation + language of the trigger function to find out how these arguments + can be accessed within the function; it might be different from + normal function arguments. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createtrigger-notes"> + <title>Notes</title> + + <para> + To create or replace a trigger on a table, the user must have the + <literal>TRIGGER</literal> privilege on the table. The user must + also have <literal>EXECUTE</literal> privilege on the trigger function. + </para> + + <para> + Use <link linkend="sql-droptrigger"><command>DROP TRIGGER</command></link> to remove a trigger. + </para> + + <para> + Creating a row-level trigger on a partitioned table will cause an + identical <quote>clone</quote> trigger to be created on each of its + existing partitions; and any partitions created or attached later will have + an identical trigger, too. If there is a conflictingly-named trigger on a + child partition already, an error occurs unless <command>CREATE OR REPLACE + TRIGGER</command> is used, in which case that trigger is replaced with a + clone trigger. When a partition is detached from its parent, its clone + triggers are removed. + </para> + + <para> + A column-specific trigger (one defined using the <literal>UPDATE OF + <replaceable>column_name</replaceable></literal> syntax) will fire when any + of its columns are listed as targets in the <command>UPDATE</command> + command's <literal>SET</literal> list. It is possible for a column's value + to change even when the trigger is not fired, because changes made to the + row's contents by <literal>BEFORE UPDATE</literal> triggers are not considered. + Conversely, a command such as <literal>UPDATE ... SET x = x ...</literal> + will fire a trigger on column <literal>x</literal>, even though the column's + value did not change. + </para> + + <para> + In a <literal>BEFORE</literal> trigger, the <literal>WHEN</literal> condition is + evaluated just before the function is or would be executed, so using + <literal>WHEN</literal> is not materially different from testing the same + condition at the beginning of the trigger function. Note in particular + that the <literal>NEW</literal> row seen by the condition is the current value, + as possibly modified by earlier triggers. Also, a <literal>BEFORE</literal> + trigger's <literal>WHEN</literal> condition is not allowed to examine the + system columns of the <literal>NEW</literal> row (such as <literal>ctid</literal>), + because those won't have been set yet. + </para> + + <para> + In an <literal>AFTER</literal> trigger, the <literal>WHEN</literal> condition is + evaluated just after the row update occurs, and it determines whether an + event is queued to fire the trigger at the end of statement. So when an + <literal>AFTER</literal> trigger's <literal>WHEN</literal> condition does not return + true, it is not necessary to queue an event nor to re-fetch the row at end + of statement. This can result in significant speedups in statements that + modify many rows, if the trigger only needs to be fired for a few of the + rows. + </para> + + <para> + In some cases it is possible for a single SQL command to fire more than + one kind of trigger. For instance an <command>INSERT</command> with + an <literal>ON CONFLICT DO UPDATE</literal> clause may cause both insert and + update operations, so it will fire both kinds of triggers as needed. + The transition relations supplied to triggers are + specific to their event type; thus an <command>INSERT</command> trigger + will see only the inserted rows, while an <command>UPDATE</command> + trigger will see only the updated rows. + </para> + + <para> + Row updates or deletions caused by foreign-key enforcement actions, such + as <literal>ON UPDATE CASCADE</literal> or <literal>ON DELETE SET NULL</literal>, are + treated as part of the SQL command that caused them (note that such + actions are never deferred). Relevant triggers on the affected table will + be fired, so that this provides another way in which an SQL command might + fire triggers not directly matching its type. In simple cases, triggers + that request transition relations will see all changes caused in their + table by a single original SQL command as a single transition relation. + However, there are cases in which the presence of an <literal>AFTER ROW</literal> + trigger that requests transition relations will cause the foreign-key + enforcement actions triggered by a single SQL command to be split into + multiple steps, each with its own transition relation(s). In such cases, + any statement-level triggers that are present will be fired once per + creation of a transition relation set, ensuring that the triggers see + each affected row in a transition relation once and only once. + </para> + + <para> + Statement-level triggers on a view are fired only if the action on the + view is handled by a row-level <literal>INSTEAD OF</literal> trigger. + If the action is handled by an <literal>INSTEAD</literal> rule, then + whatever statements are emitted by the rule are executed in place of the + original statement naming the view, so that the triggers that will be + fired are those on tables named in the replacement statements. + Similarly, if the view is automatically updatable, then the action is + handled by automatically rewriting the statement into an action on the + view's base table, so that the base table's statement-level triggers are + the ones that are fired. + </para> + + <para> + Modifying a partitioned table or a table with inheritance children fires + statement-level triggers attached to the explicitly named table, but not + statement-level triggers for its partitions or child tables. In contrast, + row-level triggers are fired on the rows in affected partitions or + child tables, even if they are not explicitly named in the query. + If a statement-level trigger has been defined with transition relations + named by a <literal>REFERENCING</literal> clause, then before and after + images of rows are visible from all affected partitions or child tables. + In the case of inheritance children, the row images include only columns + that are present in the table that the trigger is attached to. + </para> + + <para> + Currently, row-level triggers with transition relations cannot be defined + on partitions or inheritance child tables. Also, triggers on partitioned + tables may not be <literal>INSTEAD OF</literal>. + </para> + + <para> + Currently, the <literal>OR REPLACE</literal> option is not supported for + constraint triggers. + </para> + + <para> + Replacing an existing trigger within a transaction that has already + performed updating actions on the trigger's table is not recommended. + Trigger firing decisions, or portions of firing decisions, that have + already been made will not be reconsidered, so the effects could be + surprising. + </para> + + <para> + There are a few built-in trigger functions that can be used to + solve common problems without having to write your own trigger code; + see <xref linkend="functions-trigger"/>. + </para> + </refsect1> + + <refsect1 id="sql-createtrigger-examples"> + <title>Examples</title> + + <para> + Execute the function <function>check_account_update</function> whenever + a row of the table <literal>accounts</literal> is about to be updated: + +<programlisting> +CREATE TRIGGER check_update + BEFORE UPDATE ON accounts + FOR EACH ROW + EXECUTE FUNCTION check_account_update(); +</programlisting> + + Modify that trigger definition to only execute the function if + column <literal>balance</literal> is specified as a target in + the <command>UPDATE</command> command: + +<programlisting> +CREATE OR REPLACE TRIGGER check_update + BEFORE UPDATE OF balance ON accounts + FOR EACH ROW + EXECUTE FUNCTION check_account_update(); +</programlisting> + + This form only executes the function if column <literal>balance</literal> + has in fact changed value: + +<programlisting> +CREATE TRIGGER check_update + BEFORE UPDATE ON accounts + FOR EACH ROW + WHEN (OLD.balance IS DISTINCT FROM NEW.balance) + EXECUTE FUNCTION check_account_update(); +</programlisting> + + Call a function to log updates of <literal>accounts</literal>, but only if + something changed: + +<programlisting> +CREATE TRIGGER log_update + AFTER UPDATE ON accounts + FOR EACH ROW + WHEN (OLD.* IS DISTINCT FROM NEW.*) + EXECUTE FUNCTION log_account_update(); +</programlisting> + + Execute the function <function>view_insert_row</function> for each row to insert + rows into the tables underlying a view: + +<programlisting> +CREATE TRIGGER view_insert + INSTEAD OF INSERT ON my_view + FOR EACH ROW + EXECUTE FUNCTION view_insert_row(); +</programlisting> + + Execute the function <function>check_transfer_balances_to_zero</function> for each + statement to confirm that the <literal>transfer</literal> rows offset to a net of + zero: + +<programlisting> +CREATE TRIGGER transfer_insert + AFTER INSERT ON transfer + REFERENCING NEW TABLE AS inserted + FOR EACH STATEMENT + EXECUTE FUNCTION check_transfer_balances_to_zero(); +</programlisting> + + Execute the function <function>check_matching_pairs</function> for each row to + confirm that changes are made to matching pairs at the same time (by the + same statement): + +<programlisting> +CREATE TRIGGER paired_items_update + AFTER UPDATE ON paired_items + REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab + FOR EACH ROW + EXECUTE FUNCTION check_matching_pairs(); +</programlisting> + </para> + + <para> + <xref linkend="trigger-example"/> contains a complete example of a trigger + function written in C. + </para> + </refsect1> + + <refsect1 id="sql-createtrigger-compatibility"> + <title>Compatibility</title> + + <!-- + It's not clear whether SQL/MED contemplates triggers on foreign tables. + Its <drop basic column definition> General Rules do mention the possibility + of a reference from a trigger column list. On the other hand, nothing + overrides the fact that CREATE TRIGGER only targets base tables. For now, + do not document the compatibility status of triggers on foreign tables. + --> + + <para> + The <command>CREATE TRIGGER</command> statement in + <productname>PostgreSQL</productname> implements a subset of the + <acronym>SQL</acronym> standard. The following functionalities are currently + missing: + + <itemizedlist> + <listitem> + <para> + While transition table names for <literal>AFTER</literal> triggers are + specified using the <literal>REFERENCING</literal> clause in the standard way, + the row variables used in <literal>FOR EACH ROW</literal> triggers may not be + specified in a <literal>REFERENCING</literal> clause. They are available in a + manner that is dependent on the language in which the trigger function + is written, but is fixed for any one language. Some languages + effectively behave as though there is a <literal>REFERENCING</literal> clause + containing <literal>OLD ROW AS OLD NEW ROW AS NEW</literal>. + </para> + </listitem> + + <listitem> + <para> + The standard allows transition tables to be used with + column-specific <literal>UPDATE</literal> triggers, but then the set of rows + that should be visible in the transition tables depends on the + trigger's column list. This is not currently implemented by + <productname>PostgreSQL</productname>. + </para> + </listitem> + + <listitem> + <para> + <productname>PostgreSQL</productname> only allows the execution + of a user-defined function for the triggered action. The standard + allows the execution of a number of other SQL commands, such as + <command>CREATE TABLE</command>, as the triggered action. This + limitation is not hard to work around by creating a user-defined + function that executes the desired commands. + </para> + </listitem> + + </itemizedlist> + </para> + + <para> + SQL specifies that multiple triggers should be fired in + time-of-creation order. <productname>PostgreSQL</productname> uses + name order, which was judged to be more convenient. + </para> + + <para> + SQL specifies that <literal>BEFORE DELETE</literal> triggers on cascaded + deletes fire <emphasis>after</emphasis> the cascaded <literal>DELETE</literal> completes. + The <productname>PostgreSQL</productname> behavior is for <literal>BEFORE + DELETE</literal> to always fire before the delete action, even a cascading + one. This is considered more consistent. There is also nonstandard + behavior if <literal>BEFORE</literal> triggers modify rows or prevent + updates during an update that is caused by a referential action. This can + lead to constraint violations or stored data that does not honor the + referential constraint. + </para> + + <para> + The ability to specify multiple actions for a single trigger using + <literal>OR</literal> is a <productname>PostgreSQL</productname> extension of + the SQL standard. + </para> + + <para> + The ability to fire triggers for <command>TRUNCATE</command> is a + <productname>PostgreSQL</productname> extension of the SQL standard, as is the + ability to define statement-level triggers on views. + </para> + + <para> + <command>CREATE CONSTRAINT TRIGGER</command> is a + <productname>PostgreSQL</productname> extension of the <acronym>SQL</acronym> + standard. + So is the <literal>OR REPLACE</literal> option. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertrigger"/></member> + <member><xref linkend="sql-droptrigger"/></member> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-set-constraints"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_tsconfig.sgml b/doc/src/sgml/ref/create_tsconfig.sgml new file mode 100644 index 0000000..390d3cf --- /dev/null +++ b/doc/src/sgml/ref/create_tsconfig.sgml @@ -0,0 +1,126 @@ +<!-- +doc/src/sgml/ref/create_tsconfig.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtsconfig"> + <indexterm zone="sql-createtsconfig"> + <primary>CREATE TEXT SEARCH CONFIGURATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TEXT SEARCH CONFIGURATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TEXT SEARCH CONFIGURATION</refname> + <refpurpose>define a new text search configuration</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TEXT SEARCH CONFIGURATION <replaceable class="parameter">name</replaceable> ( + PARSER = <replaceable class="parameter">parser_name</replaceable> | + COPY = <replaceable class="parameter">source_config</replaceable> +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TEXT SEARCH CONFIGURATION</command> creates a new text + search configuration. A text search configuration specifies a text + search parser that can divide a string into tokens, plus dictionaries + that can be used to determine which tokens are of interest for searching. + </para> + + <para> + If only the parser is specified, then the new text search configuration + initially has no mappings from token types to dictionaries, and therefore + will ignore all words. Subsequent <command>ALTER TEXT SEARCH + CONFIGURATION</command> commands must be used to create mappings to + make the configuration useful. Alternatively, an existing text search + configuration can be copied. + </para> + + <para> + If a schema name is given then the text search configuration is created in + the specified schema. Otherwise it is created in the current schema. + </para> + + <para> + The user who defines a text search configuration becomes its owner. + </para> + + <para> + Refer to <xref linkend="textsearch"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the text search configuration to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">parser_name</replaceable></term> + <listitem> + <para> + The name of the text search parser to use for this configuration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">source_config</replaceable></term> + <listitem> + <para> + The name of an existing text search configuration to copy. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The <literal>PARSER</literal> and <literal>COPY</literal> options are mutually + exclusive, because when an existing configuration is copied, its + parser selection is copied too. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CREATE TEXT SEARCH CONFIGURATION</command> statement + in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsconfig"/></member> + <member><xref linkend="sql-droptsconfig"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_tsdictionary.sgml b/doc/src/sgml/ref/create_tsdictionary.sgml new file mode 100644 index 0000000..0608104 --- /dev/null +++ b/doc/src/sgml/ref/create_tsdictionary.sgml @@ -0,0 +1,141 @@ +<!-- +doc/src/sgml/ref/create_tsdictionary.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtsdictionary"> + <indexterm zone="sql-createtsdictionary"> + <primary>CREATE TEXT SEARCH DICTIONARY</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TEXT SEARCH DICTIONARY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TEXT SEARCH DICTIONARY</refname> + <refpurpose>define a new text search dictionary</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TEXT SEARCH DICTIONARY <replaceable class="parameter">name</replaceable> ( + TEMPLATE = <replaceable class="parameter">template</replaceable> + [, <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">value</replaceable> [, ... ]] +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TEXT SEARCH DICTIONARY</command> creates a new text search + dictionary. A text search dictionary specifies a way of recognizing + interesting or uninteresting words for searching. A dictionary depends + on a text search template, which specifies the functions that actually + perform the work. Typically the dictionary provides some options that + control the detailed behavior of the template's functions. + </para> + + <para> + If a schema name is given then the text search dictionary is created in the + specified schema. Otherwise it is created in the current schema. + </para> + + <para> + The user who defines a text search dictionary becomes its owner. + </para> + + <para> + Refer to <xref linkend="textsearch"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the text search dictionary to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">template</replaceable></term> + <listitem> + <para> + The name of the text search template that will define the basic + behavior of this dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">option</replaceable></term> + <listitem> + <para> + The name of a template-specific option to be set for this dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + The value to use for a template-specific option. If the value + is not a simple identifier or number, it must be quoted (but you can + always quote it, if you wish). + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The options can appear in any order. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example command creates a Snowball-based dictionary + with a nonstandard list of stop words. + </para> + +<programlisting> +CREATE TEXT SEARCH DICTIONARY my_russian ( + template = snowball, + language = russian, + stopwords = myrussian +); +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>CREATE TEXT SEARCH DICTIONARY</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsdictionary"/></member> + <member><xref linkend="sql-droptsdictionary"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_tsparser.sgml b/doc/src/sgml/ref/create_tsparser.sgml new file mode 100644 index 0000000..088d923 --- /dev/null +++ b/doc/src/sgml/ref/create_tsparser.sgml @@ -0,0 +1,153 @@ +<!-- +doc/src/sgml/ref/create_tsparser.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtsparser"> + <indexterm zone="sql-createtsparser"> + <primary>CREATE TEXT SEARCH PARSER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TEXT SEARCH PARSER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TEXT SEARCH PARSER</refname> + <refpurpose>define a new text search parser</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TEXT SEARCH PARSER <replaceable class="parameter">name</replaceable> ( + START = <replaceable class="parameter">start_function</replaceable> , + GETTOKEN = <replaceable class="parameter">gettoken_function</replaceable> , + END = <replaceable class="parameter">end_function</replaceable> , + LEXTYPES = <replaceable class="parameter">lextypes_function</replaceable> + [, HEADLINE = <replaceable class="parameter">headline_function</replaceable> ] +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TEXT SEARCH PARSER</command> creates a new text search + parser. A text search parser defines a method for splitting a text + string into tokens and assigning types (categories) to the tokens. + A parser is not particularly useful by itself, but must be bound into a + text search configuration along with some text search dictionaries + to be used for searching. + </para> + + <para> + If a schema name is given then the text search parser is created in the + specified schema. Otherwise it is created in the current schema. + </para> + + <para> + You must be a superuser to use <command>CREATE TEXT SEARCH PARSER</command>. + (This restriction is made because an erroneous text search parser + definition could confuse or even crash the server.) + </para> + + <para> + Refer to <xref linkend="textsearch"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the text search parser to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">start_function</replaceable></term> + <listitem> + <para> + The name of the start function for the parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">gettoken_function</replaceable></term> + <listitem> + <para> + The name of the get-next-token function for the parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">end_function</replaceable></term> + <listitem> + <para> + The name of the end function for the parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lextypes_function</replaceable></term> + <listitem> + <para> + The name of the lextypes function for the parser (a function that + returns information about the set of token types it produces). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">headline_function</replaceable></term> + <listitem> + <para> + The name of the headline function for the parser (a function that + summarizes a set of tokens). + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The function names can be schema-qualified if necessary. Argument types + are not given, since the argument list for each type of function is + predetermined. All except the headline function are required. + </para> + + <para> + The arguments can appear in any order, not only the one shown above. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no + <command>CREATE TEXT SEARCH PARSER</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsparser"/></member> + <member><xref linkend="sql-droptsparser"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_tstemplate.sgml b/doc/src/sgml/ref/create_tstemplate.sgml new file mode 100644 index 0000000..5b82d55 --- /dev/null +++ b/doc/src/sgml/ref/create_tstemplate.sgml @@ -0,0 +1,126 @@ +<!-- +doc/src/sgml/ref/create_tstemplate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtstemplate"> + <indexterm zone="sql-createtstemplate"> + <primary>CREATE TEXT SEARCH TEMPLATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TEXT SEARCH TEMPLATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TEXT SEARCH TEMPLATE</refname> + <refpurpose>define a new text search template</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TEXT SEARCH TEMPLATE <replaceable class="parameter">name</replaceable> ( + [ INIT = <replaceable class="parameter">init_function</replaceable> , ] + LEXIZE = <replaceable class="parameter">lexize_function</replaceable> +) +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TEXT SEARCH TEMPLATE</command> creates a new text search + template. Text search templates define the functions that implement + text search dictionaries. A template is not useful by itself, but must + be instantiated as a dictionary to be used. The dictionary typically + specifies parameters to be given to the template functions. + </para> + + <para> + If a schema name is given then the text search template is created in the + specified schema. Otherwise it is created in the current schema. + </para> + + <para> + You must be a superuser to use <command>CREATE TEXT SEARCH + TEMPLATE</command>. This restriction is made because an erroneous text + search template definition could confuse or even crash the server. + The reason for separating templates from dictionaries is that a template + encapsulates the <quote>unsafe</quote> aspects of defining a dictionary. + The parameters that can be set when defining a dictionary are safe for + unprivileged users to set, and so creating a dictionary need not be a + privileged operation. + </para> + + <para> + Refer to <xref linkend="textsearch"/> for further information. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the text search template to be created. The name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">init_function</replaceable></term> + <listitem> + <para> + The name of the init function for the template. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lexize_function</replaceable></term> + <listitem> + <para> + The name of the lexize function for the template. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The function names can be schema-qualified if necessary. Argument types + are not given, since the argument list for each type of function is + predetermined. The lexize function is required, but the init function + is optional. + </para> + + <para> + The arguments can appear in any order, not only the one shown above. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no + <command>CREATE TEXT SEARCH TEMPLATE</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertstemplate"/></member> + <member><xref linkend="sql-droptstemplate"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_type.sgml b/doc/src/sgml/ref/create_type.sgml new file mode 100644 index 0000000..693423e --- /dev/null +++ b/doc/src/sgml/ref/create_type.sgml @@ -0,0 +1,1029 @@ +<!-- +doc/src/sgml/ref/create_type.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createtype"> + <indexterm zone="sql-createtype"> + <primary>CREATE TYPE</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE TYPE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE TYPE</refname> + <refpurpose>define a new data type</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE TYPE <replaceable class="parameter">name</replaceable> AS + ( [ <replaceable class="parameter">attribute_name</replaceable> <replaceable class="parameter">data_type</replaceable> [ COLLATE <replaceable>collation</replaceable> ] [, ... ] ] ) + +CREATE TYPE <replaceable class="parameter">name</replaceable> AS ENUM + ( [ '<replaceable class="parameter">label</replaceable>' [, ... ] ] ) + +CREATE TYPE <replaceable class="parameter">name</replaceable> AS RANGE ( + SUBTYPE = <replaceable class="parameter">subtype</replaceable> + [ , SUBTYPE_OPCLASS = <replaceable class="parameter">subtype_operator_class</replaceable> ] + [ , COLLATION = <replaceable class="parameter">collation</replaceable> ] + [ , CANONICAL = <replaceable class="parameter">canonical_function</replaceable> ] + [ , SUBTYPE_DIFF = <replaceable class="parameter">subtype_diff_function</replaceable> ] + [ , MULTIRANGE_TYPE_NAME = <replaceable class="parameter">multirange_type_name</replaceable> ] +) + +CREATE TYPE <replaceable class="parameter">name</replaceable> ( + INPUT = <replaceable class="parameter">input_function</replaceable>, + OUTPUT = <replaceable class="parameter">output_function</replaceable> + [ , RECEIVE = <replaceable class="parameter">receive_function</replaceable> ] + [ , SEND = <replaceable class="parameter">send_function</replaceable> ] + [ , TYPMOD_IN = <replaceable class="parameter">type_modifier_input_function</replaceable> ] + [ , TYPMOD_OUT = <replaceable class="parameter">type_modifier_output_function</replaceable> ] + [ , ANALYZE = <replaceable class="parameter">analyze_function</replaceable> ] + [ , SUBSCRIPT = <replaceable class="parameter">subscript_function</replaceable> ] + [ , INTERNALLENGTH = { <replaceable class="parameter">internallength</replaceable> | VARIABLE } ] + [ , PASSEDBYVALUE ] + [ , ALIGNMENT = <replaceable class="parameter">alignment</replaceable> ] + [ , STORAGE = <replaceable class="parameter">storage</replaceable> ] + [ , LIKE = <replaceable class="parameter">like_type</replaceable> ] + [ , CATEGORY = <replaceable class="parameter">category</replaceable> ] + [ , PREFERRED = <replaceable class="parameter">preferred</replaceable> ] + [ , DEFAULT = <replaceable class="parameter">default</replaceable> ] + [ , ELEMENT = <replaceable class="parameter">element</replaceable> ] + [ , DELIMITER = <replaceable class="parameter">delimiter</replaceable> ] + [ , COLLATABLE = <replaceable class="parameter">collatable</replaceable> ] +) + +CREATE TYPE <replaceable class="parameter">name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE TYPE</command> registers a new data type for use in + the current database. The user who defines a type becomes its + owner. + </para> + + <para> + If a schema name is given then the type is created in the specified + schema. Otherwise it is created in the current schema. The type + name must be distinct from the name of any existing type or domain + in the same schema. (Because tables have associated data types, + the type name must also be distinct from the name of any existing + table in the same schema.) + </para> + + <para> + There are five forms of <command>CREATE TYPE</command>, as shown in the + syntax synopsis above. They respectively create a <firstterm>composite + type</firstterm>, an <firstterm>enum type</firstterm>, a <firstterm>range type</firstterm>, a + <firstterm>base type</firstterm>, or a <firstterm>shell type</firstterm>. The first four + of these are discussed in turn below. A shell type is simply a placeholder + for a type to be defined later; it is created by issuing <command>CREATE + TYPE</command> with no parameters except for the type name. Shell types + are needed as forward references when creating range types and base types, + as discussed in those sections. + </para> + + <refsect2> + <title>Composite Types</title> + + <para> + The first form of <command>CREATE TYPE</command> + creates a composite type. + The composite type is specified by a list of attribute names and data types. + An attribute's collation can be specified too, if its data type is + collatable. A composite type is essentially the same as the row type + of a table, but using <command>CREATE TYPE</command> avoids the need to + create an actual table when all that is wanted is to define a type. + A stand-alone composite type is useful, for example, as the argument or + return type of a function. + </para> + + <para> + To be able to create a composite type, you must + have <literal>USAGE</literal> privilege on all attribute types. + </para> + </refsect2> + + <refsect2 id="sql-createtype-enum"> + <title>Enumerated Types</title> + + <para> + The second form of <command>CREATE TYPE</command> creates an enumerated + (enum) type, as described in <xref linkend="datatype-enum"/>. + Enum types take a list of quoted labels, each of which + must be less than <symbol>NAMEDATALEN</symbol> bytes long (64 bytes in a + standard <productname>PostgreSQL</productname> build). (It is possible to + create an enumerated type with zero labels, but such a type cannot be used + to hold values before at least one label is added using <link + linkend="sql-altertype"><command>ALTER TYPE</command></link>.) + </para> + </refsect2> + + <refsect2 id="sql-createtype-range"> + <title>Range Types</title> + + <para> + The third form of <command>CREATE TYPE</command> creates a new + range type, as described in <xref linkend="rangetypes"/>. + </para> + + <para> + The range type's <replaceable class="parameter">subtype</replaceable> can + be any type with an associated b-tree operator class (to determine the + ordering of values for the range type). Normally the subtype's default + b-tree operator class is used to determine ordering; to use a non-default + operator class, specify its name with <replaceable + class="parameter">subtype_opclass</replaceable>. If the subtype is + collatable, and you want to use a non-default collation in the range's + ordering, specify the desired collation with the <replaceable + class="parameter">collation</replaceable> option. + </para> + + <para> + The optional <replaceable class="parameter">canonical</replaceable> + function must take one argument of the range type being defined, and + return a value of the same type. This is used to convert range values + to a canonical form, when applicable. See <xref + linkend="rangetypes-defining"/> for more information. Creating a + <replaceable class="parameter">canonical</replaceable> function + is a bit tricky, since it must be defined before the range type can be + declared. To do this, you must first create a shell type, which is a + placeholder type that has no properties except a name and an + owner. This is done by issuing the command <literal>CREATE TYPE + <replaceable>name</replaceable></literal>, with no additional parameters. Then + the function can be declared using the shell type as argument and result, + and finally the range type can be declared using the same name. This + automatically replaces the shell type entry with a valid range type. + </para> + + <para> + The optional <replaceable class="parameter">subtype_diff</replaceable> + function must take two values of the + <replaceable class="parameter">subtype</replaceable> type as argument, + and return a <type>double precision</type> value representing the + difference between the two given values. While this is optional, + providing it allows much greater efficiency of GiST indexes on columns of + the range type. See <xref linkend="rangetypes-defining"/> for more + information. + </para> + + <para> + The optional <replaceable class="parameter">multirange_type_name</replaceable> + parameter specifies the name of the corresponding multirange type. If not + specified, this name is chosen automatically as follows. + If the range type name contains the substring <literal>range</literal>, then + the multirange type name is formed by replacement of the <literal>range</literal> + substring with <literal>multirange</literal> in the range + type name. Otherwise, the multirange type name is formed by appending a + <literal>_multirange</literal> suffix to the range type name. + </para> + </refsect2> + + <refsect2> + <title>Base Types</title> + + <para> + The fourth form of <command>CREATE TYPE</command> creates a new base type + (scalar type). To create a new base type, you must be a superuser. + (This restriction is made because an erroneous type definition could + confuse or even crash the server.) + </para> + + <para> + The parameters can appear in any order, not only that + illustrated above, and most are optional. You must register + two or more functions (using <command>CREATE FUNCTION</command>) before + defining the type. The support functions + <replaceable class="parameter">input_function</replaceable> and + <replaceable class="parameter">output_function</replaceable> + are required, while the functions + <replaceable class="parameter">receive_function</replaceable>, + <replaceable class="parameter">send_function</replaceable>, + <replaceable class="parameter">type_modifier_input_function</replaceable>, + <replaceable class="parameter">type_modifier_output_function</replaceable>, + <replaceable class="parameter">analyze_function</replaceable>, and + <replaceable class="parameter">subscript_function</replaceable> + are optional. Generally these functions have to be coded in C + or another low-level language. + </para> + + <para> + The <replaceable class="parameter">input_function</replaceable> + converts the type's external textual representation to the internal + representation used by the operators and functions defined for the type. + <replaceable class="parameter">output_function</replaceable> + performs the reverse transformation. The input function can be + declared as taking one argument of type <type>cstring</type>, + or as taking three arguments of types + <type>cstring</type>, <type>oid</type>, <type>integer</type>. + The first argument is the input text as a C string, the second + argument is the type's own OID (except for array types, which instead + receive their element type's OID), + and the third is the <literal>typmod</literal> of the destination column, if known + (-1 will be passed if not). + The input function must return a value of the data type itself. + Usually, an input function should be declared STRICT; if it is not, + it will be called with a NULL first parameter when reading a NULL + input value. The function must still return NULL in this case, unless + it raises an error. + (This case is mainly meant to support domain input functions, which + might need to reject NULL inputs.) + The output function must be + declared as taking one argument of the new data type. + The output function must return type <type>cstring</type>. + Output functions are not invoked for NULL values. + </para> + + <para> + The optional <replaceable class="parameter">receive_function</replaceable> + converts the type's external binary representation to the internal + representation. If this function is not supplied, the type cannot + participate in binary input. The binary representation should be + chosen to be cheap to convert to internal form, while being reasonably + portable. (For example, the standard integer data types use network + byte order as the external binary representation, while the internal + representation is in the machine's native byte order.) The receive + function should perform adequate checking to ensure that the value is + valid. + The receive function can be declared as taking one argument of type + <type>internal</type>, or as taking three arguments of types + <type>internal</type>, <type>oid</type>, <type>integer</type>. + The first argument is a pointer to a <type>StringInfo</type> buffer + holding the received byte string; the optional arguments are the + same as for the text input function. + The receive function must return a value of the data type itself. + Usually, a receive function should be declared STRICT; if it is not, + it will be called with a NULL first parameter when reading a NULL + input value. The function must still return NULL in this case, unless + it raises an error. + (This case is mainly meant to support domain receive functions, which + might need to reject NULL inputs.) + Similarly, the optional + <replaceable class="parameter">send_function</replaceable> converts + from the internal representation to the external binary representation. + If this function is not supplied, the type cannot participate in binary + output. The send function must be + declared as taking one argument of the new data type. + The send function must return type <type>bytea</type>. + Send functions are not invoked for NULL values. + </para> + + <para> + You should at this point be wondering how the input and output functions + can be declared to have results or arguments of the new type, when they + have to be created before the new type can be created. The answer is that + the type should first be defined as a <firstterm>shell type</firstterm>, which is a + placeholder type that has no properties except a name and an owner. This + is done by issuing the command <literal>CREATE TYPE + <replaceable>name</replaceable></literal>, with no additional parameters. Then the + C I/O functions can be defined referencing the shell type. Finally, + <command>CREATE TYPE</command> with a full definition replaces the shell entry + with a complete, valid type definition, after which the new type can be + used normally. + </para> + + <para> + The optional + <replaceable class="parameter">type_modifier_input_function</replaceable> + and <replaceable class="parameter">type_modifier_output_function</replaceable> + are needed if the type supports modifiers, that is optional constraints + attached to a type declaration, such as <literal>char(5)</literal> or + <literal>numeric(30,2)</literal>. <productname>PostgreSQL</productname> allows + user-defined types to take one or more simple constants or identifiers as + modifiers. However, this information must be capable of being packed into a + single non-negative integer value for storage in the system catalogs. The + <replaceable class="parameter">type_modifier_input_function</replaceable> + is passed the declared modifier(s) in the form of a <type>cstring</type> + array. It must check the values for validity (throwing an error if they + are wrong), and if they are correct, return a single non-negative + <type>integer</type> value that will be stored as the column <quote>typmod</quote>. + Type modifiers will be rejected if the type does not have a + <replaceable class="parameter">type_modifier_input_function</replaceable>. + The <replaceable class="parameter">type_modifier_output_function</replaceable> + converts the internal integer typmod value back to the correct form for + user display. It must return a <type>cstring</type> value that is the exact + string to append to the type name; for example <type>numeric</type>'s + function might return <literal>(30,2)</literal>. + It is allowed to omit the + <replaceable class="parameter">type_modifier_output_function</replaceable>, + in which case the default display format is just the stored typmod integer + value enclosed in parentheses. + </para> + + <para> + The optional <replaceable class="parameter">analyze_function</replaceable> + performs type-specific statistics collection for columns of the data type. + By default, <command>ANALYZE</command> will attempt to gather statistics using + the type's <quote>equals</quote> and <quote>less-than</quote> operators, if there + is a default b-tree operator class for the type. For non-scalar types + this behavior is likely to be unsuitable, so it can be overridden by + specifying a custom analysis function. The analysis function must be + declared to take a single argument of type <type>internal</type>, and return + a <type>boolean</type> result. The detailed API for analysis functions appears + in <filename>src/include/commands/vacuum.h</filename>. + </para> + + <para> + The optional <replaceable class="parameter">subscript_function</replaceable> + allows the data type to be subscripted in SQL commands. Specifying this + function does not cause the type to be considered a <quote>true</quote> + array type; for example, it will not be a candidate for the result type + of <literal>ARRAY[]</literal> constructs. But if subscripting a value + of the type is a natural notation for extracting data from it, then + a <replaceable class="parameter">subscript_function</replaceable> can + be written to define what that means. The subscript function must be + declared to take a single argument of type <type>internal</type>, and + return an <type>internal</type> result, which is a pointer to a struct + of methods (functions) that implement subscripting. + The detailed API for subscript functions appears + in <filename>src/include/nodes/subscripting.h</filename>. + It may also be useful to read the array implementation + in <filename>src/backend/utils/adt/arraysubs.c</filename>, + or the simpler code + in <filename>contrib/hstore/hstore_subs.c</filename>. + Additional information appears in + <xref linkend="sql-createtype-array"/> below. + </para> + + <para> + While the details of the new type's internal representation are only + known to the I/O functions and other functions you create to work with + the type, there are several properties of the internal representation + that must be declared to <productname>PostgreSQL</productname>. + Foremost of these is + <replaceable class="parameter">internallength</replaceable>. + Base data types can be fixed-length, in which case + <replaceable class="parameter">internallength</replaceable> is a + positive integer, or variable-length, indicated by setting + <replaceable class="parameter">internallength</replaceable> + to <literal>VARIABLE</literal>. (Internally, this is represented + by setting <literal>typlen</literal> to -1.) The internal representation of all + variable-length types must start with a 4-byte integer giving the total + length of this value of the type. (Note that the length field is often + encoded, as described in <xref linkend="storage-toast"/>; it's unwise + to access it directly.) + </para> + + <para> + The optional flag <literal>PASSEDBYVALUE</literal> indicates that + values of this data type are passed by value, rather than by + reference. Types passed by value must be fixed-length, and their internal + representation cannot be larger than the size of the <type>Datum</type> type + (4 bytes on some machines, 8 bytes on others). + </para> + + <para> + The <replaceable class="parameter">alignment</replaceable> parameter + specifies the storage alignment required for the data type. The + allowed values equate to alignment on 1, 2, 4, or 8 byte boundaries. + Note that variable-length types must have an alignment of at least + 4, since they necessarily contain an <type>int4</type> as their first component. + </para> + + <para> + The <replaceable class="parameter">storage</replaceable> parameter + allows selection of storage strategies for variable-length data + types. (Only <literal>plain</literal> is allowed for fixed-length + types.) <literal>plain</literal> specifies that data of the type + will always be stored in-line and not compressed. + <literal>extended</literal> specifies that the system will first + try to compress a long data value, and will move the value out of + the main table row if it's still too long. + <literal>external</literal> allows the value to be moved out of the + main table, but the system will not try to compress it. + <literal>main</literal> allows compression, but discourages moving + the value out of the main table. (Data items with this storage + strategy might still be moved out of the main table if there is no + other way to make a row fit, but they will be kept in the main + table preferentially over <literal>extended</literal> and + <literal>external</literal> items.) + </para> + + <para> + All <replaceable class="parameter">storage</replaceable> values other + than <literal>plain</literal> imply that the functions of the data type + can handle values that have been <firstterm>toasted</firstterm>, as described + in <xref linkend="storage-toast"/> and <xref linkend="xtypes-toast"/>. + The specific other value given merely determines the default TOAST + storage strategy for columns of a toastable data type; users can pick + other strategies for individual columns using <literal>ALTER TABLE + SET STORAGE</literal>. + </para> + + <para> + The <replaceable class="parameter">like_type</replaceable> parameter + provides an alternative method for specifying the basic representation + properties of a data type: copy them from some existing type. The values of + <replaceable class="parameter">internallength</replaceable>, + <replaceable class="parameter">passedbyvalue</replaceable>, + <replaceable class="parameter">alignment</replaceable>, and + <replaceable class="parameter">storage</replaceable> are copied from the + named type. (It is possible, though usually undesirable, to override + some of these values by specifying them along with the <literal>LIKE</literal> + clause.) Specifying representation this way is especially useful when + the low-level implementation of the new type <quote>piggybacks</quote> on an + existing type in some fashion. + </para> + + <para> + The <replaceable class="parameter">category</replaceable> and + <replaceable class="parameter">preferred</replaceable> parameters can be + used to help control which implicit cast will be applied in ambiguous + situations. Each data type belongs to a category named by a single ASCII + character, and each type is either <quote>preferred</quote> or not within its + category. The parser will prefer casting to preferred types (but only from + other types within the same category) when this rule is helpful in + resolving overloaded functions or operators. For more details see <xref + linkend="typeconv"/>. For types that have no implicit casts to or from any + other types, it is sufficient to leave these settings at the defaults. + However, for a group of related types that have implicit casts, it is often + helpful to mark them all as belonging to a category and select one or two + of the <quote>most general</quote> types as being preferred within the category. + The <replaceable class="parameter">category</replaceable> parameter is + especially useful when adding a user-defined type to an existing built-in + category, such as the numeric or string types. However, it is also + possible to create new entirely-user-defined type categories. Select any + ASCII character other than an upper-case letter to name such a category. + </para> + + <para> + A default value can be specified, in case a user wants columns of the + data type to default to something other than the null value. + Specify the default with the <literal>DEFAULT</literal> key word. + (Such a default can be overridden by an explicit <literal>DEFAULT</literal> + clause attached to a particular column.) + </para> + + <para> + To indicate that a type is a fixed-length array type, + specify the type of the array + elements using the <literal>ELEMENT</literal> key word. For example, to + define an array of 4-byte integers (<type>int4</type>), specify + <literal>ELEMENT = int4</literal>. For more details, + see <xref linkend="sql-createtype-array"/> below. + </para> + + <para> + To indicate the delimiter to be used between values in the external + representation of arrays of this type, <replaceable + class="parameter">delimiter</replaceable> can be + set to a specific character. The default delimiter is the comma + (<literal>,</literal>). Note that the delimiter is associated + with the array element type, not the array type itself. + </para> + + <para> + If the optional Boolean + parameter <replaceable class="parameter">collatable</replaceable> + is true, column definitions and expressions of the type may carry + collation information through use of + the <literal>COLLATE</literal> clause. It is up to the + implementations of the functions operating on the type to actually + make use of the collation information; this does not happen + automatically merely by marking the type collatable. + </para> + </refsect2> + + <refsect2 id="sql-createtype-array" xreflabel="Array Types"> + <title>Array Types</title> + + <para> + Whenever a user-defined type is created, + <productname>PostgreSQL</productname> automatically creates an + associated array type, whose name consists of the element type's + name prepended with an underscore, and truncated if necessary to keep + it less than <symbol>NAMEDATALEN</symbol> bytes long. (If the name + so generated collides with an existing type name, the process is + repeated until a non-colliding name is found.) + This implicitly-created array type is variable length and uses the + built-in input and output functions <literal>array_in</literal> and + <literal>array_out</literal>. Furthermore, this type is what the system + uses for constructs such as <literal>ARRAY[]</literal> over the + user-defined type. The array type tracks any changes in its + element type's owner or schema, and is dropped if the element type is. + </para> + + <para> + You might reasonably ask why there is an <option>ELEMENT</option> + option, if the system makes the correct array type automatically. + The main case where it's useful to use <option>ELEMENT</option> is when you are + making a fixed-length type that happens to be internally an array of a number of + identical things, and you want to allow these things to be accessed + directly by subscripting, in addition to whatever operations you plan + to provide for the type as a whole. For example, type <type>point</type> + is represented as just two floating-point numbers, which can be accessed + using <literal>point[0]</literal> and <literal>point[1]</literal>. + Note that + this facility only works for fixed-length types whose internal form + is exactly a sequence of identical fixed-length fields. + For historical reasons (i.e., this is clearly wrong but it's far too + late to change it), subscripting of fixed-length array types starts from + zero, rather than from one as for variable-length arrays. + </para> + + <para> + Specifying the <option>SUBSCRIPT</option> option allows a data type to + be subscripted, even though the system does not otherwise regard it as + an array type. The behavior just described for fixed-length arrays is + actually implemented by the <option>SUBSCRIPT</option> handler + function <function>raw_array_subscript_handler</function>, which is + used automatically if you specify <option>ELEMENT</option> for a + fixed-length type without also writing <option>SUBSCRIPT</option>. + </para> + + <para> + When specifying a custom <option>SUBSCRIPT</option> function, it is + not necessary to specify <option>ELEMENT</option> unless + the <option>SUBSCRIPT</option> handler function needs to + consult <structfield>typelem</structfield> to find out what to return. + Be aware that specifying <option>ELEMENT</option> causes the system to + assume that the new type contains, or is somehow physically dependent on, + the element type; thus for example changing properties of the element + type won't be allowed if there are any columns of the dependent type. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a type to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">attribute_name</replaceable></term> + <listitem> + <para> + The name of an attribute (column) for the composite type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The name of an existing data type to become a column of the + composite type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">collation</replaceable></term> + <listitem> + <para> + The name of an existing collation to be associated with a column of + a composite type, or with a range type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">label</replaceable></term> + <listitem> + <para> + A string literal representing the textual label associated with + one value of an enum type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">subtype</replaceable></term> + <listitem> + <para> + The name of the element type that the range type will represent ranges + of. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">subtype_operator_class</replaceable></term> + <listitem> + <para> + The name of a b-tree operator class for the subtype. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">canonical_function</replaceable></term> + <listitem> + <para> + The name of the canonicalization function for the range type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">subtype_diff_function</replaceable></term> + <listitem> + <para> + The name of a difference function for the subtype. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">multirange_type_name</replaceable></term> + <listitem> + <para> + The name of the corresponding multirange type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">input_function</replaceable></term> + <listitem> + <para> + The name of a function that converts data from the type's + external textual form to its internal form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_function</replaceable></term> + <listitem> + <para> + The name of a function that converts data from the type's + internal form to its external textual form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">receive_function</replaceable></term> + <listitem> + <para> + The name of a function that converts data from the type's + external binary form to its internal form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">send_function</replaceable></term> + <listitem> + <para> + The name of a function that converts data from the type's + internal form to its external binary form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">type_modifier_input_function</replaceable></term> + <listitem> + <para> + The name of a function that converts an array of modifier(s) for the type + into internal form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">type_modifier_output_function</replaceable></term> + <listitem> + <para> + The name of a function that converts the internal form of the type's + modifier(s) to external textual form. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">analyze_function</replaceable></term> + <listitem> + <para> + The name of a function that performs statistical analysis for the + data type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">subscript_function</replaceable></term> + <listitem> + <para> + The name of a function that defines what subscripting a value of the + data type does. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">internallength</replaceable></term> + <listitem> + <para> + A numeric constant that specifies the length in bytes of the new + type's internal representation. The default assumption is that + it is variable-length. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">alignment</replaceable></term> + <listitem> + <para> + The storage alignment requirement of the data type. If specified, + it must be <literal>char</literal>, <literal>int2</literal>, + <literal>int4</literal>, or <literal>double</literal>; the + default is <literal>int4</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">storage</replaceable></term> + <listitem> + <para> + The storage strategy for the data type. If specified, must be + <literal>plain</literal>, <literal>external</literal>, + <literal>extended</literal>, or <literal>main</literal>; the + default is <literal>plain</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">like_type</replaceable></term> + <listitem> + <para> + The name of an existing data type that the new type will have the + same representation as. The values of + <replaceable class="parameter">internallength</replaceable>, + <replaceable class="parameter">passedbyvalue</replaceable>, + <replaceable class="parameter">alignment</replaceable>, and + <replaceable class="parameter">storage</replaceable> + are copied from that type, unless overridden by explicit + specification elsewhere in this <command>CREATE TYPE</command> command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">category</replaceable></term> + <listitem> + <para> + The category code (a single ASCII character) for this type. + The default is <literal>'U'</literal> for <quote>user-defined type</quote>. + Other standard category codes can be found in + <xref linkend="catalog-typcategory-table"/>. You may also choose + other ASCII characters in order to create custom categories. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">preferred</replaceable></term> + <listitem> + <para> + True if this type is a preferred type within its type category, + else false. The default is false. Be very careful about creating + a new preferred type within an existing type category, as this + could cause surprising changes in behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">default</replaceable></term> + <listitem> + <para> + The default value for the data type. If this is omitted, the + default is null. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">element</replaceable></term> + <listitem> + <para> + The type being created is an array; this specifies the type of + the array elements. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">delimiter</replaceable></term> + <listitem> + <para> + The delimiter character to be used between values in arrays made + of this type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">collatable</replaceable></term> + <listitem> + <para> + True if this type's operations can use collation information. + The default is false. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-createtype-notes"> + <title>Notes</title> + + <para> + Because there are no restrictions on use of a data type once it's been + created, creating a base type or range type is tantamount to granting + public execute permission on the functions mentioned in the type definition. + This is usually + not an issue for the sorts of functions that are useful in a type + definition. But you might want to think twice before designing a type + in a way that would require <quote>secret</quote> information to be used + while converting it to or from external form. + </para> + + <para> + Before <productname>PostgreSQL</productname> version 8.3, the name of + a generated array type was always exactly the element type's name with one + underscore character (<literal>_</literal>) prepended. (Type names were + therefore restricted in length to one fewer character than other names.) + While this is still usually the case, the array type name may vary from + this in case of maximum-length names or collisions with user type names + that begin with underscore. Writing code that depends on this convention + is therefore deprecated. Instead, use + <structname>pg_type</structname>.<structfield>typarray</structfield> to locate the array type + associated with a given type. + </para> + + <para> + It may be advisable to avoid using type and table names that begin with + underscore. While the server will change generated array type names to + avoid collisions with user-given names, there is still risk of confusion, + particularly with old client software that may assume that type names + beginning with underscores always represent arrays. + </para> + + <para> + Before <productname>PostgreSQL</productname> version 8.2, the shell-type + creation syntax + <literal>CREATE TYPE <replaceable>name</replaceable></literal> did not exist. + The way to create a new base type was to create its input function first. + In this approach, <productname>PostgreSQL</productname> will first see + the name of the new data type as the return type of the input function. + The shell type is implicitly created in this situation, and then it + can be referenced in the definitions of the remaining I/O functions. + This approach still works, but is deprecated and might be disallowed in + some future release. Also, to avoid accidentally cluttering + the catalogs with shell types as a result of simple typos in function + definitions, a shell type will only be made this way when the input + function is written in C. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This example creates a composite type and uses it in + a function definition: +<programlisting> +CREATE TYPE compfoo AS (f1 int, f2 text); + +CREATE FUNCTION getfoo() RETURNS SETOF compfoo AS $$ + SELECT fooid, fooname FROM foo +$$ LANGUAGE SQL; +</programlisting> + </para> + + <para> + This example creates an enumerated type and uses it in + a table definition: +<programlisting> +CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed'); + +CREATE TABLE bug ( + id serial, + description text, + status bug_status +); +</programlisting> + </para> + + <para> + This example creates a range type: +<programlisting> +CREATE TYPE float8_range AS RANGE (subtype = float8, subtype_diff = float8mi); +</programlisting> + </para> + + <para> + This example creates the base data type <type>box</type> and then uses the + type in a table definition: +<programlisting> +CREATE TYPE box; + +CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ; +CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ; + +CREATE TYPE box ( + INTERNALLENGTH = 16, + INPUT = my_box_in_function, + OUTPUT = my_box_out_function +); + +CREATE TABLE myboxes ( + id integer, + description box +); +</programlisting> + </para> + + <para> + If the internal structure of <type>box</type> were an array of four + <type>float4</type> elements, we might instead use: +<programlisting> +CREATE TYPE box ( + INTERNALLENGTH = 16, + INPUT = my_box_in_function, + OUTPUT = my_box_out_function, + ELEMENT = float4 +); +</programlisting> + which would allow a box value's component numbers to be accessed + by subscripting. Otherwise the type behaves the same as before. + </para> + + <para> + This example creates a large object type and uses it in + a table definition: +<programlisting> +CREATE TYPE bigobj ( + INPUT = lo_filein, OUTPUT = lo_fileout, + INTERNALLENGTH = VARIABLE +); +CREATE TABLE big_objs ( + id integer, + obj bigobj +); +</programlisting> + </para> + + <para> + More examples, including suitable input and output functions, are + in <xref linkend="xtypes"/>. + </para> + </refsect1> + + <refsect1 id="sql-createtype-compatibility"> + <title>Compatibility</title> + + <para> + The first form of the <command>CREATE TYPE</command> command, which + creates a composite type, conforms to the <acronym>SQL</acronym> standard. + The other forms are <productname>PostgreSQL</productname> + extensions. The <command>CREATE TYPE</command> statement in + the <acronym>SQL</acronym> standard also defines other forms that are not + implemented in <productname>PostgreSQL</productname>. + </para> + + <para> + The ability to create a composite type with zero attributes is + a <productname>PostgreSQL</productname>-specific deviation from the + standard (analogous to the same case in <command>CREATE TABLE</command>). + </para> + </refsect1> + + <refsect1 id="sql-createtype-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertype"/></member> + <member><xref linkend="sql-createdomain"/></member> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-droptype"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_user.sgml b/doc/src/sgml/ref/create_user.sgml new file mode 100644 index 0000000..48d2089 --- /dev/null +++ b/doc/src/sgml/ref/create_user.sgml @@ -0,0 +1,78 @@ +<!-- +doc/src/sgml/ref/create_user.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createuser"> + <indexterm zone="sql-createuser"> + <primary>CREATE USER</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE USER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE USER</refname> + <refpurpose>define a new database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE USER <replaceable class="parameter">name</replaceable> [ [ WITH ] <replaceable class="parameter">option</replaceable> [ ... ] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + SUPERUSER | NOSUPERUSER + | CREATEDB | NOCREATEDB + | CREATEROLE | NOCREATEROLE + | INHERIT | NOINHERIT + | LOGIN | NOLOGIN + | REPLICATION | NOREPLICATION + | BYPASSRLS | NOBYPASSRLS + | CONNECTION LIMIT <replaceable class="parameter">connlimit</replaceable> + | [ ENCRYPTED ] PASSWORD '<replaceable class="parameter">password</replaceable>' | PASSWORD NULL + | VALID UNTIL '<replaceable class="parameter">timestamp</replaceable>' + | IN ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | IN GROUP <replaceable class="parameter">role_name</replaceable> [, ...] + | ROLE <replaceable class="parameter">role_name</replaceable> [, ...] + | ADMIN <replaceable class="parameter">role_name</replaceable> [, ...] + | USER <replaceable class="parameter">role_name</replaceable> [, ...] + | SYSID <replaceable class="parameter">uid</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE USER</command> is now an alias for + <link linkend="sql-createrole"><command>CREATE ROLE</command></link>. + The only difference is that when the command is spelled + <command>CREATE USER</command>, <literal>LOGIN</literal> is assumed + by default, whereas <literal>NOLOGIN</literal> is assumed when + the command is spelled + <command>CREATE ROLE</command>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>CREATE USER</command> statement is a + <productname>PostgreSQL</productname> extension. The SQL standard + leaves the definition of users to the implementation. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrole"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/create_user_mapping.sgml b/doc/src/sgml/ref/create_user_mapping.sgml new file mode 100644 index 0000000..55debd5 --- /dev/null +++ b/doc/src/sgml/ref/create_user_mapping.sgml @@ -0,0 +1,132 @@ +<!-- +doc/src/sgml/ref/create_user_mapping.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createusermapping"> + <indexterm zone="sql-createusermapping"> + <primary>CREATE USER MAPPING</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE USER MAPPING</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE USER MAPPING</refname> + <refpurpose>define a new mapping of a user to a foreign server</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE USER MAPPING [ IF NOT EXISTS ] FOR { <replaceable class="parameter">user_name</replaceable> | USER | CURRENT_ROLE | CURRENT_USER | PUBLIC } + SERVER <replaceable class="parameter">server_name</replaceable> + [ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [ , ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE USER MAPPING</command> defines a mapping of a user + to a foreign server. A user mapping typically encapsulates + connection information that a foreign-data wrapper uses together + with the information encapsulated by a foreign server to access an + external data resource. + </para> + + <para> + The owner of a foreign server can create user mappings for that + server for any user. Also, a user can create a user mapping for + their own user name if <literal>USAGE</literal> privilege on the server has + been granted to the user. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF NOT EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if a mapping of the given user to the given foreign + server already exists. A notice is issued in this case. Note that there + is no guarantee that the existing user mapping is anything like the one + that would have been created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + The name of an existing user that is mapped to foreign server. + <literal>CURRENT_ROLE</literal>, <literal>CURRENT_USER</literal>, and <literal>USER</literal> match the name of + the current user. When <literal>PUBLIC</literal> is specified, a + so-called public mapping is created that is used when no + user-specific mapping is applicable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + The name of an existing server for which the user mapping is + to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies the options of the user mapping. The + options typically define the actual user name and password of + the mapping. Option names must be unique. The allowed option + names and values are specific to the server's foreign-data wrapper. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a user mapping for user <literal>bob</literal>, server <literal>foo</literal>: +<programlisting> +CREATE USER MAPPING FOR bob SERVER foo OPTIONS (user 'bob', password 'secret'); +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE USER MAPPING</command> conforms to ISO/IEC 9075-9 (SQL/MED). + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterusermapping"/></member> + <member><xref linkend="sql-dropusermapping"/></member> + <member><xref linkend="sql-createforeigndatawrapper"/></member> + <member><xref linkend="sql-createserver"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/create_view.sgml b/doc/src/sgml/ref/create_view.sgml new file mode 100644 index 0000000..3b26205 --- /dev/null +++ b/doc/src/sgml/ref/create_view.sgml @@ -0,0 +1,575 @@ +<!-- +doc/src/sgml/ref/create_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-createview"> + <indexterm zone="sql-createview"> + <primary>CREATE VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>CREATE VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>CREATE VIEW</refname> + <refpurpose>define a new view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] [ RECURSIVE ] VIEW <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] + [ WITH ( <replaceable class="parameter">view_option_name</replaceable> [= <replaceable class="parameter">view_option_value</replaceable>] [, ... ] ) ] + AS <replaceable class="parameter">query</replaceable> + [ WITH [ CASCADED | LOCAL ] CHECK OPTION ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>CREATE VIEW</command> defines a view of a query. The view + is not physically materialized. Instead, the query is run every time + the view is referenced in a query. + </para> + + <para> + <command>CREATE OR REPLACE VIEW</command> is similar, but if a view + of the same name already exists, it is replaced. The new query must + generate the same columns that were generated by the existing view query + (that is, the same column names in the same order and with the same data + types), but it may add additional columns to the end of the list. The + calculations giving rise to the output columns may be completely different. + </para> + + <para> + If a schema name is given (for example, <literal>CREATE VIEW + myschema.myview ...</literal>) then the view is created in the specified + schema. Otherwise it is created in the current schema. Temporary + views exist in a special schema, so a schema name cannot be given + when creating a temporary view. The name of the view must be + distinct from the name of any other relation (table, sequence, index, view, + materialized view, or foreign table) in the same schema. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + If specified, the view is created as a temporary view. + Temporary views are automatically dropped at the end of the + current session. Existing + permanent relations with the same name are not visible to the + current session while the temporary view exists, unless they are + referenced with schema-qualified names. + </para> + + <para> + If any of the tables referenced by the view are temporary, + the view is created as a temporary view (whether + <literal>TEMPORARY</literal> is specified or not). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RECURSIVE</literal> + <indexterm zone="sql-createview"> + <primary>RECURSIVE</primary> + <secondary>in views</secondary> + </indexterm> + </term> + <listitem> + <para> + Creates a recursive view. The syntax +<synopsis> +CREATE RECURSIVE VIEW [ <replaceable>schema</replaceable> . ] <replaceable>view_name</replaceable> (<replaceable>column_names</replaceable>) AS SELECT <replaceable>...</replaceable>; +</synopsis> + is equivalent to +<synopsis> +CREATE VIEW [ <replaceable>schema</replaceable> . ] <replaceable>view_name</replaceable> AS WITH RECURSIVE <replaceable>view_name</replaceable> (<replaceable>column_names</replaceable>) AS (SELECT <replaceable>...</replaceable>) SELECT <replaceable>column_names</replaceable> FROM <replaceable>view_name</replaceable>; +</synopsis> + A view column name list must be specified for a recursive view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a view to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + An optional list of names to be used for columns of the view. + If not given, the column names are deduced from the query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH ( <replaceable class="parameter">view_option_name</replaceable> [= <replaceable class="parameter">view_option_value</replaceable>] [, ... ] )</literal></term> + <listitem> + <para> + This clause specifies optional parameters for a view; the following + parameters are supported: + + <variablelist> + <varlistentry> + <term><literal>check_option</literal> (<type>enum</type>)</term> + <listitem> + <para> + This parameter may be either <literal>local</literal> or + <literal>cascaded</literal>, and is equivalent to specifying + <literal>WITH [ CASCADED | LOCAL ] CHECK OPTION</literal> (see below). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>security_barrier</literal> (<type>boolean</type>)</term> + <listitem> + <para> + This should be used if the view is intended to provide row-level + security. See <xref linkend="rules-privileges"/> for full details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>security_invoker</literal> (<type>boolean</type>)</term> + <listitem> + <para> + This option causes the underlying base relations to be checked + against the privileges of the user of the view rather than the view + owner. See the notes below for full details. + </para> + </listitem> + </varlistentry> + </variablelist> + + All of the above options can be changed on existing views using <link + linkend="sql-alterview"><command>ALTER VIEW</command></link>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">query</replaceable></term> + <listitem> + <para> + A <link linkend="sql-select"><command>SELECT</command></link> or + <link linkend="sql-values"><command>VALUES</command></link> command + which will provide the columns and rows of the view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH [ CASCADED | LOCAL ] CHECK OPTION</literal> + <indexterm zone="sql-createview"> + <primary>CHECK OPTION</primary> + </indexterm> + <indexterm zone="sql-createview"> + <primary>WITH CHECK OPTION</primary> + </indexterm> + </term> + <listitem> + <para> + This option controls the behavior of automatically updatable views. When + this option is specified, <command>INSERT</command> and <command>UPDATE</command> + commands on the view will be checked to ensure that new rows satisfy the + view-defining condition (that is, the new rows are checked to ensure that + they are visible through the view). If they are not, the update will be + rejected. If the <literal>CHECK OPTION</literal> is not specified, + <command>INSERT</command> and <command>UPDATE</command> commands on the view are + allowed to create rows that are not visible through the view. The + following check options are supported: + + <variablelist> + <varlistentry> + <term><literal>LOCAL</literal></term> + <listitem> + <para> + New rows are only checked against the conditions defined directly in + the view itself. Any conditions defined on underlying base views are + not checked (unless they also specify the <literal>CHECK OPTION</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADED</literal></term> + <listitem> + <para> + New rows are checked against the conditions of the view and all + underlying base views. If the <literal>CHECK OPTION</literal> is specified, + and neither <literal>LOCAL</literal> nor <literal>CASCADED</literal> is specified, + then <literal>CASCADED</literal> is assumed. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The <literal>CHECK OPTION</literal> may not be used with <literal>RECURSIVE</literal> + views. + </para> + + <para> + Note that the <literal>CHECK OPTION</literal> is only supported on views that + are automatically updatable, and do not have <literal>INSTEAD OF</literal> + triggers or <literal>INSTEAD</literal> rules. If an automatically updatable + view is defined on top of a base view that has <literal>INSTEAD OF</literal> + triggers, then the <literal>LOCAL CHECK OPTION</literal> may be used to check + the conditions on the automatically updatable view, but the conditions + on the base view with <literal>INSTEAD OF</literal> triggers will not be + checked (a cascaded check option will not cascade down to a + trigger-updatable view, and any check options defined directly on a + trigger-updatable view will be ignored). If the view or any of its base + relations has an <literal>INSTEAD</literal> rule that causes the + <command>INSERT</command> or <command>UPDATE</command> command to be rewritten, then + all check options will be ignored in the rewritten query, including any + checks from automatically updatable views defined on top of the relation + with the <literal>INSTEAD</literal> rule. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use the <link linkend="sql-dropview"><command>DROP VIEW</command></link> + statement to drop views. + </para> + + <para> + Be careful that the names and types of the view's columns will be + assigned the way you want. For example: +<programlisting> +CREATE VIEW vista AS SELECT 'Hello World'; +</programlisting> + is bad form because the column name defaults to <literal>?column?</literal>; + also, the column data type defaults to <type>text</type>, which might not + be what you wanted. Better style for a string literal in a view's + result is something like: +<programlisting> +CREATE VIEW vista AS SELECT text 'Hello World' AS hello; +</programlisting> + </para> + + <para> + By default, access to the underlying base relations referenced in the view + is determined by the permissions of the view owner. In some cases, this + can be used to provide secure but restricted access to the underlying + tables. However, not all views are secure against tampering; see <xref + linkend="rules-privileges"/> for details. + </para> + + <para> + If the view has the <literal>security_invoker</literal> property set to + <literal>true</literal>, access to the underlying base relations is + determined by the permissions of the user executing the query, rather than + the view owner. Thus, the user of a security invoker view must have the + relevant permissions on the view and its underlying base relations. + </para> + + <para> + If any of the underlying base relations is a security invoker view, it + will be treated as if it had been accessed directly from the original + query. Thus, a security invoker view will always check its underlying + base relations using the permissions of the current user, even if it is + accessed from a view without the <literal>security_invoker</literal> + property. + </para> + + <para> + If any of the underlying base relations has + <link linkend="ddl-rowsecurity">row-level security</link> enabled, then + by default, the row-level security policies of the view owner are applied, + and access to any additional relations referred to by those policies is + determined by the permissions of the view owner. However, if the view has + <literal>security_invoker</literal> set to <literal>true</literal>, then + the policies and permissions of the invoking user are used instead, as if + the base relations had been referenced directly from the query using the + view. + </para> + + <para> + Functions called in the view are treated the same as if they had been + called directly from the query using the view. Therefore, the user of + a view must have permissions to call all functions used by the view. + Functions in the view are executed with the privileges of the user + executing the query or the function owner, depending on whether the + functions are defined as <literal>SECURITY INVOKER</literal> or + <literal>SECURITY DEFINER</literal>. Thus, for example, calling + <literal>CURRENT_USER</literal> directly in a view will always return the + invoking user, not the view owner. This is not affected by the view's + <literal>security_invoker</literal> setting, and so a view with + <literal>security_invoker</literal> set to <literal>false</literal> is + <emphasis>not</emphasis> equivalent to a + <literal>SECURITY DEFINER</literal> function and those concepts should not + be confused. + </para> + + <para> + The user creating or replacing a view must have <literal>USAGE</literal> + privileges on any schemas referred to in the view query, in order to look + up the referenced objects in those schemas. Note, however, that this + lookup only happens when the view is created or replaced. Therefore, the + user of the view only requires the <literal>USAGE</literal> privilege on + the schema containing the view, not on the schemas referred to in the view + query, even for a security invoker view. + </para> + + <para> + When <command>CREATE OR REPLACE VIEW</command> is used on an existing + view, only the view's defining SELECT rule, plus any + <literal>WITH ( ... )</literal> parameters and its + <literal>CHECK OPTION</literal> are changed. + Other view properties, including ownership, permissions, and non-SELECT + rules, remain unchanged. You must own the view + to replace it (this includes being a member of the owning role). + </para> + + <refsect2 id="sql-createview-updatable-views"> + <title>Updatable Views</title> + + <indexterm zone="sql-createview-updatable-views"> + <primary>updatable views</primary> + </indexterm> + + <para> + Simple views are automatically updatable: the system will allow + <command>INSERT</command>, <command>UPDATE</command> and <command>DELETE</command> statements + to be used on the view in the same way as on a regular table. A view is + automatically updatable if it satisfies all of the following conditions: + + <itemizedlist> + <listitem> + <para> + The view must have exactly one entry in its <literal>FROM</literal> list, + which must be a table or another updatable view. + </para> + </listitem> + + <listitem> + <para> + The view definition must not contain <literal>WITH</literal>, + <literal>DISTINCT</literal>, <literal>GROUP BY</literal>, <literal>HAVING</literal>, + <literal>LIMIT</literal>, or <literal>OFFSET</literal> clauses at the top level. + </para> + </listitem> + + <listitem> + <para> + The view definition must not contain set operations (<literal>UNION</literal>, + <literal>INTERSECT</literal> or <literal>EXCEPT</literal>) at the top level. + </para> + </listitem> + + <listitem> + <para> + The view's select list must not contain any aggregates, window functions + or set-returning functions. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + An automatically updatable view may contain a mix of updatable and + non-updatable columns. A column is updatable if it is a simple reference + to an updatable column of the underlying base relation; otherwise the + column is read-only, and an error will be raised if an <command>INSERT</command> + or <command>UPDATE</command> statement attempts to assign a value to it. + </para> + + <para> + If the view is automatically updatable the system will convert any + <command>INSERT</command>, <command>UPDATE</command> or <command>DELETE</command> statement + on the view into the corresponding statement on the underlying base + relation. <command>INSERT</command> statements that have an <literal>ON + CONFLICT UPDATE</literal> clause are fully supported. + </para> + + <para> + If an automatically updatable view contains a <literal>WHERE</literal> + condition, the condition restricts which rows of the base relation are + available to be modified by <command>UPDATE</command> and <command>DELETE</command> + statements on the view. However, an <command>UPDATE</command> is allowed to + change a row so that it no longer satisfies the <literal>WHERE</literal> + condition, and thus is no longer visible through the view. Similarly, + an <command>INSERT</command> command can potentially insert base-relation rows + that do not satisfy the <literal>WHERE</literal> condition and thus are not + visible through the view (<literal>ON CONFLICT UPDATE</literal> may + similarly affect an existing row not visible through the view). + The <literal>CHECK OPTION</literal> may be used to prevent + <command>INSERT</command> and <command>UPDATE</command> commands from creating + such rows that are not visible through the view. + </para> + + <para> + If an automatically updatable view is marked with the + <literal>security_barrier</literal> property then all the view's <literal>WHERE</literal> + conditions (and any conditions using operators which are marked as <literal>LEAKPROOF</literal>) + will always be evaluated before any conditions that a user of the view has + added. See <xref linkend="rules-privileges"/> for full details. Note that, + due to this, rows which are not ultimately returned (because they do not + pass the user's <literal>WHERE</literal> conditions) may still end up being locked. + <command>EXPLAIN</command> can be used to see which conditions are + applied at the relation level (and therefore do not lock rows) and which are + not. + </para> + + <para> + A more complex view that does not satisfy all these conditions is + read-only by default: the system will not allow an insert, update, or + delete on the view. You can get the effect of an updatable view by + creating <literal>INSTEAD OF</literal> triggers on the view, which must + convert attempted inserts, etc. on the view into appropriate actions + on other tables. For more information see <xref + linkend="sql-createtrigger"/>. Another possibility is to create rules + (see <xref linkend="sql-createrule"/>), but in practice triggers are + easier to understand and use correctly. + </para> + + <para> + Note that the user performing the insert, update or delete on the view + must have the corresponding insert, update or delete privilege on the + view. In addition, by default, the view's owner must have the relevant + privileges on the underlying base relations, whereas the user performing + the update does not need any permissions on the underlying base relations + (see <xref linkend="rules-privileges"/>). However, if the view has + <literal>security_invoker</literal> set to <literal>true</literal>, the + user performing the update, rather than the view owner, must have the + relevant privileges on the underlying base relations. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a view consisting of all comedy films: + +<programlisting> +CREATE VIEW comedies AS + SELECT * + FROM films + WHERE kind = 'Comedy'; +</programlisting> + This will create a view containing the columns that are in the + <literal>film</literal> table at the time of view creation. Though + <literal>*</literal> was used to create the view, columns added later to + the table will not be part of the view. + </para> + + <para> + Create a view with <literal>LOCAL CHECK OPTION</literal>: + +<programlisting> +CREATE VIEW universal_comedies AS + SELECT * + FROM comedies + WHERE classification = 'U' + WITH LOCAL CHECK OPTION; +</programlisting> + This will create a view based on the <literal>comedies</literal> view, showing + only films with <literal>kind = 'Comedy'</literal> and + <literal>classification = 'U'</literal>. Any attempt to <command>INSERT</command> or + <command>UPDATE</command> a row in the view will be rejected if the new row + doesn't have <literal>classification = 'U'</literal>, but the film + <literal>kind</literal> will not be checked. + </para> + + <para> + Create a view with <literal>CASCADED CHECK OPTION</literal>: + +<programlisting> +CREATE VIEW pg_comedies AS + SELECT * + FROM comedies + WHERE classification = 'PG' + WITH CASCADED CHECK OPTION; +</programlisting> + This will create a view that checks both the <literal>kind</literal> and + <literal>classification</literal> of new rows. + </para> + + <para> + Create a view with a mix of updatable and non-updatable columns: + +<programlisting> +CREATE VIEW comedies AS + SELECT f.*, + country_code_to_name(f.country_code) AS country, + (SELECT avg(r.rating) + FROM user_ratings r + WHERE r.film_id = f.id) AS avg_rating + FROM films f + WHERE f.kind = 'Comedy'; +</programlisting> + This view will support <command>INSERT</command>, <command>UPDATE</command> and + <command>DELETE</command>. All the columns from the <literal>films</literal> table will + be updatable, whereas the computed columns <literal>country</literal> and + <literal>avg_rating</literal> will be read-only. + </para> + + <para> + Create a recursive view consisting of the numbers from 1 to 100: +<programlisting> +CREATE RECURSIVE VIEW public.nums_1_100 (n) AS + VALUES (1) +UNION ALL + SELECT n+1 FROM nums_1_100 WHERE n < 100; +</programlisting> + Notice that although the recursive view's name is schema-qualified in this + <command>CREATE</command>, its internal self-reference is not schema-qualified. + This is because the implicitly-created CTE's name cannot be + schema-qualified. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>CREATE OR REPLACE VIEW</command> is a + <productname>PostgreSQL</productname> language extension. + So is the concept of a temporary view. + The <literal>WITH ( ... )</literal> clause is an extension as well, as are + security barrier views and security invoker views. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterview"/></member> + <member><xref linkend="sql-dropview"/></member> + <member><xref linkend="sql-creatematerializedview"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/createdb.sgml b/doc/src/sgml/ref/createdb.sgml new file mode 100644 index 0000000..671cd36 --- /dev/null +++ b/doc/src/sgml/ref/createdb.sgml @@ -0,0 +1,426 @@ +<!-- +doc/src/sgml/ref/createdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-createdb"> + <indexterm zone="app-createdb"> + <primary>createdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>createdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>createdb</refname> + <refpurpose>create a new <productname>PostgreSQL</productname> database</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>createdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>dbname</replaceable> + <arg choice="opt"><replaceable>description</replaceable></arg></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="r1-app-createdb-1"> + <title>Description</title> + <para> + <application>createdb</application> creates a new <productname>PostgreSQL</productname> + database. + </para> + + <para> + Normally, the database user who executes this command becomes the owner of + the new database. + However, a different owner can be specified via the <option>-O</option> + option, if the executing user has appropriate privileges. + </para> + + <para> + <application>createdb</application> is a wrapper around the + <acronym>SQL</acronym> command <link linkend="sql-createdatabase"><command>CREATE DATABASE</command></link>. + There is no effective difference between creating databases via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>createdb</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">dbname</replaceable></term> + <listitem> + <para> + Specifies the name of the database to be created. The name must be + unique among all <productname>PostgreSQL</productname> databases in this cluster. + The default is to create a database with the same name as the + current system user. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">description</replaceable></term> + <listitem> + <para> + Specifies a comment to be associated with the newly created + database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable class="parameter">tablespace</replaceable></option></term> + <term><option>--tablespace=<replaceable class="parameter">tablespace</replaceable></option></term> + <listitem> + <para> + Specifies the default tablespace for the database. (This name + is processed as a double-quoted identifier.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>createdb</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E <replaceable class="parameter">encoding</replaceable></option></term> + <term><option>--encoding=<replaceable class="parameter">encoding</replaceable></option></term> + <listitem> + <para> + Specifies the character encoding scheme to be used in this + database. The character sets supported by the + <productname>PostgreSQL</productname> server are described in + <xref linkend="multibyte-charset-supported"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l <replaceable class="parameter">locale</replaceable></option></term> + <term><option>--locale=<replaceable class="parameter">locale</replaceable></option></term> + <listitem> + <para> + Specifies the locale to be used in this database. This is equivalent + to specifying both <option>--lc-collate</option> and <option>--lc-ctype</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--lc-collate=<replaceable class="parameter">locale</replaceable></option></term> + <listitem> + <para> + Specifies the LC_COLLATE setting to be used in this database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--lc-ctype=<replaceable class="parameter">locale</replaceable></option></term> + <listitem> + <para> + Specifies the LC_CTYPE setting to be used in this database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--icu-locale=<replaceable class="parameter">locale</replaceable></option></term> + <listitem> + <para> + Specifies the ICU locale ID to be used in this database, if the + ICU locale provider is selected. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--locale-provider={<literal>libc</literal>|<literal>icu</literal>}</option></term> + <listitem> + <para> + Specifies the locale provider for the database's default collation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O <replaceable class="parameter">owner</replaceable></option></term> + <term><option>--owner=<replaceable class="parameter">owner</replaceable></option></term> + <listitem> + <para> + Specifies the database user who will own the new database. + (This name is processed as a double-quoted identifier.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">template</replaceable></option></term> + <term><option>--strategy=<replaceable class="parameter">strategy</replaceable></option></term> + <listitem> + <para> + Specifies the database creation strategy. See + <xref linkend="create-database-strategy" /> for more details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">template</replaceable></option></term> + <term><option>--template=<replaceable class="parameter">template</replaceable></option></term> + <listitem> + <para> + Specifies the template database from which to build this + database. (This name is processed as a double-quoted identifier.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>createdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>createdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + The options <option>-D</option>, <option>-l</option>, <option>-E</option>, + <option>-O</option>, and + <option>-T</option> correspond to options of the underlying + SQL command <link linkend="sql-createdatabase"><command>CREATE DATABASE</command></link>; see there for more information + about them. + </para> + + <para> + <application>createdb</application> also accepts the following + command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server is running. If the value begins with a slash, it is used + as the directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or the local Unix domain socket file + extension on which the server is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>createdb</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>createdb</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>createdb</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to when creating the + new database. If not specified, the <literal>postgres</literal> + database will be used; if that does not exist (or if it is the name + of the new database being created), <literal>template1</literal> will + be used. + This can be a <link linkend="libpq-connstring">connection + string</link>. If so, connection string parameters will override any + conflicting command line options. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <listitem> + <para> + If set, the name of the database to create, unless overridden on + the command line. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters. <envar>PGUSER</envar> also + determines the name of the database to create, if it is not + specified on the command line or by <envar>PGDATABASE</envar>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-createdatabase"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To create the database <literal>demo</literal> using the default + database server: +<screen> +<prompt>$ </prompt><userinput>createdb demo</userinput> +</screen> + </para> + + <para> + To create the database <literal>demo</literal> using the + server on host <literal>eden</literal>, port 5000, using the + <literal>template0</literal> template database, here is the + command-line command and the underlying SQL command: +<screen> +<prompt>$ </prompt><userinput>createdb -p 5000 -h eden -T template0 -e demo</userinput> +<computeroutput>CREATE DATABASE demo TEMPLATE template0;</computeroutput> +</screen></para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-dropdb"/></member> + <member><xref linkend="sql-createdatabase"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/createuser.sgml b/doc/src/sgml/ref/createuser.sgml new file mode 100644 index 0000000..0e1a39a --- /dev/null +++ b/doc/src/sgml/ref/createuser.sgml @@ -0,0 +1,506 @@ +<!-- +doc/src/sgml/ref/createuser.sgml +PostgreSQL documentation +--> + +<refentry id="app-createuser"> + <indexterm zone="app-createuser"> + <primary>createuser</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>createuser</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>createuser</refname> + <refpurpose>define a new <productname>PostgreSQL</productname> user account</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>createuser</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>username</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1> + <title>Description</title> + <para> + <application>createuser</application> creates a + new <productname>PostgreSQL</productname> user (or more precisely, a role). + Only superusers and users with <literal>CREATEROLE</literal> privilege can create + new users, so <application>createuser</application> must be + invoked by someone who can connect as a superuser or a user with + <literal>CREATEROLE</literal> privilege. + </para> + + <para> + If you wish to create a role with the <literal>SUPERUSER</literal>, + <literal>REPLICATION</literal>, or <literal>BYPASSRLS</literal> privilege, + you must connect as a superuser, not merely with + <literal>CREATEROLE</literal> privilege. + Being a superuser implies the ability to bypass all access permission + checks within the database, so superuser access should not be granted + lightly. <literal>CREATEROLE</literal> also conveys + <link linkend='role-creation'>very extensive privileges</link>. + </para> + + <para> + <application>createuser</application> is a wrapper around the + <acronym>SQL</acronym> command <link linkend="sql-createrole"><command>CREATE ROLE</command></link>. + There is no effective difference between creating users via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>createuser</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">username</replaceable></term> + <listitem> + <para> + Specifies the name of the <productname>PostgreSQL</productname> user + to be created. + This name must be different from all existing roles in this + <productname>PostgreSQL</productname> installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c <replaceable class="parameter">number</replaceable></option></term> + <term><option>--connection-limit=<replaceable class="parameter">number</replaceable></option></term> + <listitem> + <para> + Set a maximum number of connections for the new user. + The default is to set no limit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d</option></term> + <term><option>--createdb</option></term> + <listitem> + <para> + The new user will be allowed to create databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D</option></term> + <term><option>--no-createdb</option></term> + <listitem> + <para> + The new user will not be allowed to create databases. This is the + default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>createuser</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E</option></term> + <term><option>--encrypted</option></term> + <listitem> + <para> + This option is obsolete but still accepted for backward + compatibility. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-g <replaceable class="parameter">role</replaceable></option></term> + <term><option>--role=<replaceable class="parameter">role</replaceable></option></term> + <listitem> + <para> + Indicates role to which this role will be added immediately as a new + member. Multiple roles to which this role will be added as a member + can be specified by writing multiple + <option>-g</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <term><option>--inherit</option></term> + <listitem> + <para> + The new role will automatically inherit privileges of roles + it is a member of. + This is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I</option></term> + <term><option>--no-inherit</option></term> + <listitem> + <para> + The new role will not automatically inherit privileges of roles + it is a member of. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--interactive</option></term> + <listitem> + <para> + Prompt for the user name if none is specified on the command line, and + also prompt for whichever of the options + <option>-d</option>/<option>-D</option>, + <option>-r</option>/<option>-R</option>, + <option>-s</option>/<option>-S</option> is not specified on the command + line. (This was the default behavior up to PostgreSQL 9.1.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <term><option>--login</option></term> + <listitem> + <para> + The new user will be allowed to log in (that is, the user name + can be used as the initial session user identifier). + This is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-L</option></term> + <term><option>--no-login</option></term> + <listitem> + <para> + The new user will not be allowed to log in. + (A role without login privilege is still useful as a means of + managing database permissions.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <term><option>--pwprompt</option></term> + <listitem> + <para> + If given, <application>createuser</application> will issue a prompt for + the password of the new user. This is not necessary if you do not plan + on using password authentication. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r</option></term> + <term><option>--createrole</option></term> + <listitem> + <para> + The new user will be allowed to create, alter, drop, comment on, + change the security label for, and grant or revoke membership in + other roles; that is, + this user will have <literal>CREATEROLE</literal> privilege. + See <xref linkend='role-creation' /> for more details about what + capabilities are conferred by this privilege. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option></term> + <term><option>--no-createrole</option></term> + <listitem> + <para> + The new user will not be allowed to create new roles. This is the + default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--superuser</option></term> + <listitem> + <para> + The new user will be a superuser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S</option></term> + <term><option>--no-superuser</option></term> + <listitem> + <para> + The new user will not be a superuser. This is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>createuser</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--replication</option></term> + <listitem> + <para> + The new user will have the <literal>REPLICATION</literal> privilege, + which is described more fully in the documentation for <xref + linkend="sql-createrole"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-replication</option></term> + <listitem> + <para> + The new user will not have the <literal>REPLICATION</literal> + privilege, which is described more fully in the documentation for <xref + linkend="sql-createrole"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>createuser</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + <application>createuser</application> also accepts the following + command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server + is running. If the value begins with a slash, it is used + as the directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as (not the user name to create). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>createuser</application> to prompt for a + password (for connecting to the server, not for the + password of the new user). + </para> + + <para> + This option is never essential, since + <application>createuser</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>createuser</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-createrole"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To create a user <literal>joe</literal> on the default database + server: +<screen> +<prompt>$ </prompt><userinput>createuser joe</userinput> +</screen> + </para> + + <para> + To create a user <literal>joe</literal> on the default database + server with prompting for some additional attributes: +<screen> +<prompt>$ </prompt><userinput>createuser --interactive joe</userinput> +<computeroutput>Shall the new role be a superuser? (y/n) </computeroutput><userinput>n</userinput> +<computeroutput>Shall the new role be allowed to create databases? (y/n) </computeroutput><userinput>n</userinput> +<computeroutput>Shall the new role be allowed to create more new roles? (y/n) </computeroutput><userinput>n</userinput> +</screen> + </para> + + <para> + To create the same user <literal>joe</literal> using the + server on host <literal>eden</literal>, port 5000, with attributes explicitly specified, + taking a look at the underlying command: +<screen> +<prompt>$ </prompt><userinput>createuser -h eden -p 5000 -S -D -R -e joe</userinput> +<computeroutput>CREATE ROLE joe NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;</computeroutput> +</screen> + </para> + + <para> + To create the user <literal>joe</literal> as a superuser, + and assign a password immediately: +<screen> +<prompt>$ </prompt><userinput>createuser -P -s -e joe</userinput> +<computeroutput>Enter password for new role: </computeroutput><userinput>xyzzy</userinput> +<computeroutput>Enter it again: </computeroutput><userinput>xyzzy</userinput> +<computeroutput>CREATE ROLE joe PASSWORD 'md5b5f5ba1a423792b526f799ae4eb3d59e' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;</computeroutput> +</screen> + In the above example, the new password isn't actually echoed when typed, + but we show what was typed for clarity. As you see, the password is + encrypted before it is sent to the client. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-dropuser"/></member> + <member><xref linkend="sql-createrole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/deallocate.sgml b/doc/src/sgml/ref/deallocate.sgml new file mode 100644 index 0000000..3875e50 --- /dev/null +++ b/doc/src/sgml/ref/deallocate.sgml @@ -0,0 +1,98 @@ +<!-- +doc/src/sgml/ref/deallocate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-deallocate"> + <indexterm zone="sql-deallocate"> + <primary>DEALLOCATE</primary> + </indexterm> + + <indexterm zone="sql-deallocate"> + <primary>prepared statements</primary> + <secondary>removing</secondary> + </indexterm> + + <refmeta> + <refentrytitle>DEALLOCATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DEALLOCATE</refname> + <refpurpose>deallocate a prepared statement</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DEALLOCATE [ PREPARE ] { <replaceable class="parameter">name</replaceable> | ALL } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DEALLOCATE</command> is used to deallocate a previously + prepared SQL statement. If you do not explicitly deallocate a + prepared statement, it is deallocated when the session ends. + </para> + + <para> + For more information on prepared statements, see <xref + linkend="sql-prepare"/>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>PREPARE</literal></term> + <listitem> + <para> + This key word is ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the prepared statement to deallocate. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Deallocate all prepared statements. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard includes a <command>DEALLOCATE</command> + statement, but it is only for use in embedded SQL. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-execute"/></member> + <member><xref linkend="sql-prepare"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/declare.sgml b/doc/src/sgml/ref/declare.sgml new file mode 100644 index 0000000..bbbd335 --- /dev/null +++ b/doc/src/sgml/ref/declare.sgml @@ -0,0 +1,361 @@ +<!-- +doc/src/sgml/ref/declare.sgml +PostgreSQL documentation +--> + +<refentry id="sql-declare"> + <indexterm zone="sql-declare"> + <primary>DECLARE</primary> + </indexterm> + + <indexterm zone="sql-declare"> + <primary>cursor</primary> + <secondary>DECLARE</secondary> + </indexterm> + + <refmeta> + <refentrytitle>DECLARE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DECLARE</refname> + <refpurpose>define a cursor</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DECLARE <replaceable class="parameter">name</replaceable> [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ] + CURSOR [ { WITH | WITHOUT } HOLD ] FOR <replaceable class="parameter">query</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DECLARE</command> allows a user to create cursors, which + can be used to retrieve + a small number of rows at a time out of a larger query. + After the cursor is created, rows are fetched from it using + <link linkend="sql-fetch"><command>FETCH</command></link>. + </para> + + <note> + <para> + This page describes usage of cursors at the SQL command level. + If you are trying to use cursors inside a <application>PL/pgSQL</application> + function, the rules are different — + see <xref linkend="plpgsql-cursors"/>. + </para> + </note> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the cursor to be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BINARY</literal></term> + <listitem> + <para> + Causes the cursor to return data in binary rather than in text format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ASENSITIVE</literal></term> + <term><literal>INSENSITIVE</literal></term> + <listitem> + <para> + Cursor sensitivity determines whether changes to the data underlying the + cursor, done in the same transaction, after the cursor has been + declared, are visible in the cursor. <literal>INSENSITIVE</literal> + means they are not visible, <literal>ASENSITIVE</literal> means the + behavior is implementation-dependent. A third behavior, + <literal>SENSITIVE</literal>, meaning that such changes are visible in + the cursor, is not available in <productname>PostgreSQL</productname>. + In <productname>PostgreSQL</productname>, all cursors are insensitive; + so these key words have no effect and are only accepted for + compatibility with the SQL standard. + </para> + + <para> + Specifying <literal>INSENSITIVE</literal> together with <literal>FOR + UPDATE</literal> or <literal>FOR SHARE</literal> is an error. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SCROLL</literal></term> + <term><literal>NO SCROLL</literal></term> + <listitem> + <para><literal>SCROLL</literal> specifies that the cursor can be used + to retrieve rows in a nonsequential fashion (e.g., + backward). Depending upon the complexity of the query's + execution plan, specifying <literal>SCROLL</literal> might impose + a performance penalty on the query's execution time. + <literal>NO SCROLL</literal> specifies that the cursor cannot be + used to retrieve rows in a nonsequential fashion. The default is to + allow scrolling in some cases; this is not the same as specifying + <literal>SCROLL</literal>. See <xref linkend="sql-declare-notes"/> + below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WITH HOLD</literal></term> + <term><literal>WITHOUT HOLD</literal></term> + <listitem> + <para><literal>WITH HOLD</literal> specifies that the cursor can + continue to be used after the transaction that created it + successfully commits. <literal>WITHOUT HOLD</literal> specifies + that the cursor cannot be used outside of the transaction that + created it. If neither <literal>WITHOUT HOLD</literal> nor + <literal>WITH HOLD</literal> is specified, <literal>WITHOUT + HOLD</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">query</replaceable></term> + <listitem> + <para> + A <link linkend="sql-select"><command>SELECT</command></link> or + <link linkend="sql-values"><command>VALUES</command></link> command + which will provide the rows to be returned by the cursor. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The key words <literal>ASENSITIVE</literal>, <literal>BINARY</literal>, + <literal>INSENSITIVE</literal>, and <literal>SCROLL</literal> can + appear in any order. + </para> + </refsect1> + + <refsect1 id="sql-declare-notes" xreflabel="Notes"> + <title>Notes</title> + + <para> + Normal cursors return data in text format, the same as a + <command>SELECT</command> would produce. The <literal>BINARY</literal> option + specifies that the cursor should return data in binary format. + This reduces conversion effort for both the server and client, + at the cost of more programmer effort to deal with platform-dependent + binary data formats. + As an example, if a query returns a value of one from an integer column, + you would get a string of <literal>1</literal> with a default cursor, + whereas with a binary cursor you would get + a 4-byte field containing the internal representation of the value + (in big-endian byte order). + </para> + + <para> + Binary cursors should be used carefully. Many applications, + including <application>psql</application>, are not prepared to + handle binary cursors and expect data to come back in the text + format. + </para> + + <note> + <para> + When the client application uses the <quote>extended query</quote> protocol + to issue a <command>FETCH</command> command, the Bind protocol message + specifies whether data is to be retrieved in text or binary format. + This choice overrides the way that the cursor is defined. The concept + of a binary cursor as such is thus obsolete when using extended query + protocol — any cursor can be treated as either text or binary. + </para> + </note> + + <para> + Unless <literal>WITH HOLD</literal> is specified, the cursor + created by this command can only be used within the current + transaction. Thus, <command>DECLARE</command> without <literal>WITH + HOLD</literal> is useless outside a transaction block: the cursor would + survive only to the completion of the statement. Therefore + <productname>PostgreSQL</productname> reports an error if such a + command is used outside a transaction block. + Use + <link linkend="sql-begin"><command>BEGIN</command></link> and + <link linkend="sql-commit"><command>COMMIT</command></link> + (or <link linkend="sql-rollback"><command>ROLLBACK</command></link>) + to define a transaction block. + </para> + + <para> + If <literal>WITH HOLD</literal> is specified and the transaction + that created the cursor successfully commits, the cursor can + continue to be accessed by subsequent transactions in the same + session. (But if the creating transaction is aborted, the cursor + is removed.) A cursor created with <literal>WITH HOLD</literal> + is closed when an explicit <command>CLOSE</command> command is + issued on it, or the session ends. In the current implementation, + the rows represented by a held cursor are copied into a temporary + file or memory area so that they remain available for subsequent + transactions. + </para> + + <para> + <literal>WITH HOLD</literal> may not be specified when the query + includes <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>. + </para> + + <para> + The <literal>SCROLL</literal> option should be specified when defining a + cursor that will be used to fetch backwards. This is required by + the SQL standard. However, for compatibility with earlier + versions, <productname>PostgreSQL</productname> will allow + backward fetches without <literal>SCROLL</literal>, if the cursor's query + plan is simple enough that no extra overhead is needed to support + it. However, application developers are advised not to rely on + using backward fetches from a cursor that has not been created + with <literal>SCROLL</literal>. If <literal>NO SCROLL</literal> is + specified, then backward fetches are disallowed in any case. + </para> + + <para> + Backward fetches are also disallowed when the query + includes <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>; therefore + <literal>SCROLL</literal> may not be specified in this case. + </para> + + <caution> + <para> + Scrollable cursors may give unexpected + results if they invoke any volatile functions (see <xref + linkend="xfunc-volatility"/>). When a previously fetched row is + re-fetched, the functions might be re-executed, perhaps leading to + results different from the first time. It's best to + specify <literal>NO SCROLL</literal> for a query involving volatile + functions. If that is not practical, one workaround + is to declare the cursor <literal>SCROLL WITH HOLD</literal> and commit the + transaction before reading any rows from it. This will force the + entire output of the cursor to be materialized in temporary storage, + so that volatile functions are executed exactly once for each row. + </para> + </caution> + + <para> + If the cursor's query includes <literal>FOR UPDATE</literal> or <literal>FOR + SHARE</literal>, then returned rows are locked at the time they are first + fetched, in the same way as for a regular + <link linkend="sql-select"><command>SELECT</command></link> command with + these options. + In addition, the returned rows will be the most up-to-date versions. + </para> + + <caution> + <para> + It is generally recommended to use <literal>FOR UPDATE</literal> if the cursor + is intended to be used with <command>UPDATE ... WHERE CURRENT OF</command> or + <command>DELETE ... WHERE CURRENT OF</command>. Using <literal>FOR UPDATE</literal> + prevents other sessions from changing the rows between the time they are + fetched and the time they are updated. Without <literal>FOR UPDATE</literal>, + a subsequent <literal>WHERE CURRENT OF</literal> command will have no effect if + the row was changed since the cursor was created. + </para> + + <para> + Another reason to use <literal>FOR UPDATE</literal> is that without it, a + subsequent <literal>WHERE CURRENT OF</literal> might fail if the cursor query + does not meet the SQL standard's rules for being <quote>simply + updatable</quote> (in particular, the cursor must reference just one table + and not use grouping or <literal>ORDER BY</literal>). Cursors + that are not simply updatable might work, or might not, depending on plan + choice details; so in the worst case, an application might work in testing + and then fail in production. If <literal>FOR UPDATE</literal> is + specified, the cursor is guaranteed to be updatable. + </para> + + <para> + The main reason not to use <literal>FOR UPDATE</literal> with <literal>WHERE + CURRENT OF</literal> is if you need the cursor to be scrollable, or to be + isolated from concurrent updates (that is, continue to show the old + data). If this is a requirement, pay close heed to the caveats shown + above. + </para> + </caution> + + <para> + The SQL standard only makes provisions for cursors in embedded + <acronym>SQL</acronym>. The <productname>PostgreSQL</productname> + server does not implement an <command>OPEN</command> statement for + cursors; a cursor is considered to be open when it is declared. + However, <application>ECPG</application>, the embedded SQL + preprocessor for <productname>PostgreSQL</productname>, supports + the standard SQL cursor conventions, including those involving + <command>DECLARE</command> and <command>OPEN</command> statements. + </para> + + <para> + You can see all available cursors by querying the <link + linkend="view-pg-cursors"><structname>pg_cursors</structname></link> + system view. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To declare a cursor: +<programlisting> +DECLARE liahona CURSOR FOR SELECT * FROM films; +</programlisting> + See <xref linkend="sql-fetch"/> for more + examples of cursor usage. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard allows cursors only in embedded + <acronym>SQL</acronym> and in modules. <productname>PostgreSQL</productname> + permits cursors to be used interactively. + </para> + + <para> + According to the SQL standard, changes made to insensitive cursors by + <literal>UPDATE ... WHERE CURRENT OF</literal> and <literal>DELETE + ... WHERE CURRENT OF</literal> statements are visible in that same + cursor. <productname>PostgreSQL</productname> treats these statements like + all other data changing statements in that they are not visible in + insensitive cursors. + </para> + + <para> + Binary cursors are a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-close"/></member> + <member><xref linkend="sql-fetch"/></member> + <member><xref linkend="sql-move"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/delete.sgml b/doc/src/sgml/ref/delete.sgml new file mode 100644 index 0000000..1b81b4e --- /dev/null +++ b/doc/src/sgml/ref/delete.sgml @@ -0,0 +1,289 @@ +<!-- +doc/src/sgml/ref/delete.sgml +PostgreSQL documentation +--> + +<refentry id="sql-delete"> + <indexterm zone="sql-delete"> + <primary>DELETE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DELETE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DELETE</refname> + <refpurpose>delete rows of a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ] +DELETE FROM [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> ] + [ USING <replaceable class="parameter">from_item</replaceable> [, ...] ] + [ WHERE <replaceable class="parameter">condition</replaceable> | WHERE CURRENT OF <replaceable class="parameter">cursor_name</replaceable> ] + [ RETURNING * | <replaceable class="parameter">output_expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DELETE</command> deletes rows that satisfy the + <literal>WHERE</literal> clause from the specified table. If the + <literal>WHERE</literal> clause is absent, the effect is to delete + all rows in the table. The result is a valid, but empty table. + </para> + + <tip> + <para> + <link linkend="sql-truncate"><command>TRUNCATE</command></link> provides a + faster mechanism to remove all rows from a table. + </para> + </tip> + + <para> + There are two ways to delete rows in a table using information + contained in other tables in the database: using sub-selects, or + specifying additional tables in the <literal>USING</literal> clause. + Which technique is more appropriate depends on the specific + circumstances. + </para> + + <para> + The optional <literal>RETURNING</literal> clause causes <command>DELETE</command> + to compute and return value(s) based on each row actually deleted. + Any expression using the table's columns, and/or columns of other + tables mentioned in <literal>USING</literal>, can be computed. + The syntax of the <literal>RETURNING</literal> list is identical to that of the + output list of <command>SELECT</command>. + </para> + + <para> + You must have the <literal>DELETE</literal> privilege on the table + to delete from it, as well as the <literal>SELECT</literal> + privilege for any table in the <literal>USING</literal> clause or + whose values are read in the <replaceable + class="parameter">condition</replaceable>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">with_query</replaceable></term> + <listitem> + <para> + The <literal>WITH</literal> clause allows you to specify one or more + subqueries that can be referenced by name in the <command>DELETE</command> + query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> + for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to delete rows + from. If <literal>ONLY</literal> is specified before the table name, + matching rows are deleted from the named table only. If + <literal>ONLY</literal> is not specified, matching rows are also deleted + from any tables inheriting from the named table. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">alias</replaceable></term> + <listitem> + <para> + A substitute name for the target table. When an alias is + provided, it completely hides the actual name of the table. For + example, given <literal>DELETE FROM foo AS f</literal>, the remainder + of the <command>DELETE</command> statement must refer to this + table as <literal>f</literal> not <literal>foo</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">from_item</replaceable></term> + <listitem> + <para> + A table expression allowing columns from other tables to appear + in the <literal>WHERE</literal> condition. This uses the same + syntax as the <link linkend="sql-from"><literal>FROM</literal></link> + clause of a <command>SELECT</command> statement; for example, an alias + for the table name can be specified. Do not repeat the target + table as a <replaceable class="parameter">from_item</replaceable> + unless you wish to set up a self-join (in which case it must appear + with an alias in the <replaceable>from_item</replaceable>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + An expression that returns a value of type <type>boolean</type>. + Only rows for which this expression returns <literal>true</literal> + will be deleted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">cursor_name</replaceable></term> + <listitem> + <para> + The name of the cursor to use in a <literal>WHERE CURRENT OF</literal> + condition. The row to be deleted is the one most recently fetched + from this cursor. The cursor must be a non-grouping + query on the <command>DELETE</command>'s target table. + Note that <literal>WHERE CURRENT OF</literal> cannot be + specified together with a Boolean condition. See + <xref linkend="sql-declare"/> + for more information about using cursors with + <literal>WHERE CURRENT OF</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_expression</replaceable></term> + <listitem> + <para> + An expression to be computed and returned by the <command>DELETE</command> + command after each row is deleted. The expression can use any + column names of the table named by <replaceable class="parameter">table_name</replaceable> + or table(s) listed in <literal>USING</literal>. + Write <literal>*</literal> to return all columns. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_name</replaceable></term> + <listitem> + <para> + A name to use for a returned column. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, a <command>DELETE</command> command returns a command + tag of the form +<screen> +DELETE <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number + of rows deleted. Note that the number may be less than the number of + rows that matched the <replaceable + class="parameter">condition</replaceable> when deletes were + suppressed by a <literal>BEFORE DELETE</literal> trigger. If <replaceable + class="parameter">count</replaceable> is 0, no rows were deleted by + the query (this is not considered an error). + </para> + + <para> + If the <command>DELETE</command> command contains a <literal>RETURNING</literal> + clause, the result will be similar to that of a <command>SELECT</command> + statement containing the columns and values defined in the + <literal>RETURNING</literal> list, computed over the row(s) deleted by the + command. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <productname>PostgreSQL</productname> lets you reference columns of + other tables in the <literal>WHERE</literal> condition by specifying the + other tables in the <literal>USING</literal> clause. For example, + to delete all films produced by a given producer, one can do: +<programlisting> +DELETE FROM films USING producers + WHERE producer_id = producers.id AND producers.name = 'foo'; +</programlisting> + What is essentially happening here is a join between <structname>films</structname> + and <structname>producers</structname>, with all successfully joined + <structname>films</structname> rows being marked for deletion. + This syntax is not standard. A more standard way to do it is: +<programlisting> +DELETE FROM films + WHERE producer_id IN (SELECT id FROM producers WHERE name = 'foo'); +</programlisting> + In some cases the join style is easier to write or faster to + execute than the sub-select style. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Delete all films but musicals: +<programlisting> +DELETE FROM films WHERE kind <> 'Musical'; +</programlisting> + </para> + + <para> + Clear the table <literal>films</literal>: +<programlisting> +DELETE FROM films; +</programlisting> + </para> + + <para> + Delete completed tasks, returning full details of the deleted rows: +<programlisting> +DELETE FROM tasks WHERE status = 'DONE' RETURNING *; +</programlisting> + </para> + + <para> + Delete the row of <structname>tasks</structname> on which the cursor + <literal>c_tasks</literal> is currently positioned: +<programlisting> +DELETE FROM tasks WHERE CURRENT OF c_tasks; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to the <acronym>SQL</acronym> standard, except + that the <literal>USING</literal> and <literal>RETURNING</literal> clauses + are <productname>PostgreSQL</productname> extensions, as is the ability + to use <literal>WITH</literal> with <command>DELETE</command>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-truncate"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/discard.sgml b/doc/src/sgml/ref/discard.sgml new file mode 100644 index 0000000..bf44c52 --- /dev/null +++ b/doc/src/sgml/ref/discard.sgml @@ -0,0 +1,118 @@ +<!-- +doc/src/sgml/ref/discard.sgml +PostgreSQL documentation +--> + +<refentry id="sql-discard"> + <indexterm zone="sql-discard"> + <primary>DISCARD</primary> + </indexterm> + + <refmeta> + <refentrytitle>DISCARD</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DISCARD</refname> + <refpurpose>discard session state</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DISCARD { ALL | PLANS | SEQUENCES | TEMPORARY | TEMP } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DISCARD</command> releases internal resources associated with a + database session. This command is useful for partially or fully + resetting the session's state. There are several subcommands to + release different types of resources; the <command>DISCARD ALL</command> + variant subsumes all the others, and also resets additional state. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>PLANS</literal></term> + <listitem> + <para> + Releases all cached query plans, forcing re-planning to occur + the next time the associated prepared statement is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SEQUENCES</literal></term> + <listitem> + <para> + Discards all cached sequence-related state, + including <function>currval()</function>/<function>lastval()</function> + information and any preallocated sequence values that have not + yet been returned by <function>nextval()</function>. + (See <xref linkend="sql-createsequence"/> for a description of + preallocated sequence values.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + Drops all temporary tables created in the current session. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Releases all temporary resources associated with the current + session and resets the session to its initial state. + Currently, this has the same effect as executing the following sequence + of statements: +<programlisting> +CLOSE ALL; +SET SESSION AUTHORIZATION DEFAULT; +RESET ALL; +DEALLOCATE ALL; +UNLISTEN *; +SELECT pg_advisory_unlock_all(); +DISCARD PLANS; +DISCARD TEMP; +DISCARD SEQUENCES; +</programlisting></para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>DISCARD ALL</command> cannot be executed inside a transaction block. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DISCARD</command> is a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/do.sgml b/doc/src/sgml/ref/do.sgml new file mode 100644 index 0000000..96901b7 --- /dev/null +++ b/doc/src/sgml/ref/do.sgml @@ -0,0 +1,135 @@ +<!-- +doc/src/sgml/ref/do.sgml +PostgreSQL documentation +--> + +<refentry id="sql-do"> + <indexterm zone="sql-do"> + <primary>DO</primary> + </indexterm> + + <indexterm zone="sql-do"> + <primary>anonymous code blocks</primary> + </indexterm> + + <refmeta> + <refentrytitle>DO</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DO</refname> + <refpurpose>execute an anonymous code block</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DO [ LANGUAGE <replaceable class="parameter">lang_name</replaceable> ] <replaceable class="parameter">code</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DO</command> executes an anonymous code block, or in other + words a transient anonymous function in a procedural language. + </para> + + <para> + The code block is treated as though it were the body of a function + with no parameters, returning <type>void</type>. It is parsed and + executed a single time. + </para> + + <para> + The optional <literal>LANGUAGE</literal> clause can be written either + before or after the code block. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">code</replaceable></term> + <listitem> + <para> + The procedural language code to be executed. This must be specified + as a string literal, just as in <command>CREATE FUNCTION</command>. + Use of a dollar-quoted literal is recommended. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lang_name</replaceable></term> + <listitem> + <para> + The name of the procedural language the code is written in. + If omitted, the default is <literal>plpgsql</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The procedural language to be used must already have been installed + into the current database by means of <command>CREATE EXTENSION</command>. + <literal>plpgsql</literal> is installed by default, but other languages are not. + </para> + + <para> + The user must have <literal>USAGE</literal> privilege for the procedural + language, or must be a superuser if the language is untrusted. + This is the same privilege requirement as for creating a function + in the language. + </para> + + <para> + If <command>DO</command> is executed in a transaction block, then the + procedure code cannot execute transaction control statements. Transaction + control statements are only allowed if <command>DO</command> is executed in + its own transaction. + </para> + </refsect1> + + <refsect1 id="sql-do-examples"> + <title>Examples</title> + <para> + Grant all privileges on all views in schema <literal>public</literal> to + role <literal>webuser</literal>: +<programlisting> +DO $$DECLARE r record; +BEGIN + FOR r IN SELECT table_schema, table_name FROM information_schema.tables + WHERE table_type = 'VIEW' AND table_schema = 'public' + LOOP + EXECUTE 'GRANT ALL ON ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' TO webuser'; + END LOOP; +END$$; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DO</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createlanguage"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/drop_access_method.sgml b/doc/src/sgml/ref/drop_access_method.sgml new file mode 100644 index 0000000..a908a64 --- /dev/null +++ b/doc/src/sgml/ref/drop_access_method.sgml @@ -0,0 +1,111 @@ +<!-- +doc/src/sgml/ref/drop_access_method.sgml +PostgreSQL documentation +--> + +<refentry id="sql-drop-access-method"> + <indexterm zone="sql-drop-access-method"> + <primary>DROP ACCESS METHOD</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP ACCESS METHOD</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP ACCESS METHOD</refname> + <refpurpose>remove an access method</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP ACCESS METHOD [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP ACCESS METHOD</command> removes an existing access method. + Only superusers can drop access methods. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the access method does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing access method. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the access method + (such as operator classes, operator families, and indexes), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the access method if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop the access method <literal>heptree</literal>: +<programlisting> +DROP ACCESS METHOD heptree; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP ACCESS METHOD</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-create-access-method"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_aggregate.sgml b/doc/src/sgml/ref/drop_aggregate.sgml new file mode 100644 index 0000000..ba74f4f --- /dev/null +++ b/doc/src/sgml/ref/drop_aggregate.sgml @@ -0,0 +1,184 @@ +<!-- +doc/src/sgml/ref/drop_aggregate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropaggregate"> + <indexterm zone="sql-dropaggregate"> + <primary>DROP AGGREGATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP AGGREGATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP AGGREGATE</refname> + <refpurpose>remove an aggregate function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP AGGREGATE [ IF EXISTS ] <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) [, ...] [ CASCADE | RESTRICT ] + +<phrase>where <replaceable>aggregate_signature</replaceable> is:</phrase> + +* | +[ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] | +[ [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] ] ORDER BY [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP AGGREGATE</command> removes an existing + aggregate function. To execute this command the current + user must be the owner of the aggregate function. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the aggregate does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing aggregate function. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal> or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>DROP AGGREGATE</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the aggregate function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + <listitem> + <para> + An input data type on which the aggregate function operates. + To reference a zero-argument aggregate function, write <literal>*</literal> + in place of the list of argument specifications. + To reference an ordered-set aggregate function, write + <literal>ORDER BY</literal> between the direct and aggregated argument + specifications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the aggregate function + (such as views using it), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the aggregate function if any objects depend on + it. This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Alternative syntaxes for referencing ordered-set aggregates + are described under <xref linkend="sql-alteraggregate"/>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To remove the aggregate function <literal>myavg</literal> for type + <type>integer</type>: +<programlisting> +DROP AGGREGATE myavg(integer); +</programlisting> + </para> + + <para> + To remove the hypothetical-set aggregate function <literal>myrank</literal>, + which takes an arbitrary list of ordering columns and a matching list + of direct arguments: +<programlisting> +DROP AGGREGATE myrank(VARIADIC "any" ORDER BY VARIADIC "any"); +</programlisting> + </para> + + <para> + To remove multiple aggregate functions in one command: +<programlisting> +DROP AGGREGATE myavg(integer), myavg(bigint); +</programlisting></para> +</refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP AGGREGATE</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteraggregate"/></member> + <member><xref linkend="sql-createaggregate"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_cast.sgml b/doc/src/sgml/ref/drop_cast.sgml new file mode 100644 index 0000000..5cb704b --- /dev/null +++ b/doc/src/sgml/ref/drop_cast.sgml @@ -0,0 +1,117 @@ +<!-- +doc/src/sgml/ref/drop_cast.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropcast"> + <indexterm zone="sql-dropcast"> + <primary>DROP CAST</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP CAST</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP CAST</refname> + <refpurpose>remove a cast</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP CAST [ IF EXISTS ] (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>) [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-dropcast-description"> + <title>Description</title> + + <para> + <command>DROP CAST</command> removes a previously defined cast. + </para> + + <para> + To be able to drop a cast, you must own the source or the target + data type. These are the same privileges that are required to + create a cast. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the cast does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>source_type</replaceable></term> + + <listitem> + <para> + The name of the source data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>target_type</replaceable></term> + + <listitem> + <para> + The name of the target data type of the cast. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no + dependencies on casts. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropcast-examples"> + <title>Examples</title> + + <para> + To drop the cast from type <type>text</type> to type <type>int</type>: +<programlisting> +DROP CAST (text AS int); +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropcast-compat"> + <title>Compatibility</title> + + <para> + The <command>DROP CAST</command> command conforms to the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createcast"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_collation.sgml b/doc/src/sgml/ref/drop_collation.sgml new file mode 100644 index 0000000..60867b0 --- /dev/null +++ b/doc/src/sgml/ref/drop_collation.sgml @@ -0,0 +1,114 @@ +<!-- +doc/src/sgml/ref/drop_collation.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropcollation"> + <indexterm zone="sql-dropcollation"> + <primary>DROP COLLATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP COLLATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP COLLATION</refname> + <refpurpose>remove a collation</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP COLLATION [ IF EXISTS ] <replaceable>name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-dropcollation-description"> + <title>Description</title> + + <para> + <command>DROP COLLATION</command> removes a previously defined collation. + To be able to drop a collation, you must own the collation. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the collation does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>name</replaceable></term> + + <listitem> + <para> + The name of the collation. The collation name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the collation, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the collation if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropcollation-examples"> + <title>Examples</title> + + <para> + To drop the collation named <literal>german</literal>: +<programlisting> +DROP COLLATION german; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropcollation-compat"> + <title>Compatibility</title> + + <para> + The <command>DROP COLLATION</command> command conforms to the + <acronym>SQL</acronym> standard, apart from the <literal>IF + EXISTS</literal> option, which is a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altercollation"/></member> + <member><xref linkend="sql-createcollation"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_conversion.sgml b/doc/src/sgml/ref/drop_conversion.sgml new file mode 100644 index 0000000..08558ad --- /dev/null +++ b/doc/src/sgml/ref/drop_conversion.sgml @@ -0,0 +1,107 @@ +<!-- +doc/src/sgml/ref/drop_conversion.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropconversion"> + <indexterm zone="sql-dropconversion"> + <primary>DROP CONVERSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP CONVERSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP CONVERSION</refname> + <refpurpose>remove a conversion</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP CONVERSION [ IF EXISTS ] <replaceable>name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-dropconversion-description"> + <title>Description</title> + + <para> + <command>DROP CONVERSION</command> removes a previously defined conversion. + To be able to drop a conversion, you must own the conversion. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the conversion does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>name</replaceable></term> + + <listitem> + <para> + The name of the conversion. The conversion name can be + schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no + dependencies on conversions. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropconversion-examples"> + <title>Examples</title> + + <para> + To drop the conversion named <literal>myname</literal>: +<programlisting> +DROP CONVERSION myname; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropconversion-compat"> + <title>Compatibility</title> + + <para> + There is no <command>DROP CONVERSION</command> statement in the SQL + standard, but a <command>DROP TRANSLATION</command> statement that + goes along with the <command>CREATE TRANSLATION</command> statement + that is similar to the <command>CREATE CONVERSION</command> + statement in PostgreSQL. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterconversion"/></member> + <member><xref linkend="sql-createconversion"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_database.sgml b/doc/src/sgml/ref/drop_database.sgml new file mode 100644 index 0000000..ff01450 --- /dev/null +++ b/doc/src/sgml/ref/drop_database.sgml @@ -0,0 +1,126 @@ +<!-- +doc/src/sgml/ref/drop_database.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropdatabase"> + <indexterm zone="sql-dropdatabase"> + <primary>DROP DATABASE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP DATABASE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP DATABASE</refname> + <refpurpose>remove a database</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP DATABASE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be:</phrase> + + FORCE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP DATABASE</command> drops a database. It removes the + catalog entries for the database and deletes the directory + containing the data. It can only be executed by the database owner. + It cannot be executed while you are connected to the target database. + (Connect to <literal>postgres</literal> or any other database to issue this + command.) + Also, if anyone else is connected to the target database, this command will + fail unless you use the <literal>FORCE</literal> option described below. + </para> + + <para> + <command>DROP DATABASE</command> cannot be undone. Use it with care! + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the database does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the database to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORCE</literal></term> + <listitem> + <para> + Attempt to terminate all existing connections to the target database. + It doesn't terminate if prepared transactions, active logical replication + slots or subscriptions are present in the target database. + </para> + <para> + This will fail if the current user has no permissions to terminate other + connections. Required permissions are the same as with + <literal>pg_terminate_backend</literal>, described in + <xref linkend="functions-admin-signal"/>. This will also fail if we + are not able to terminate connections. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>DROP DATABASE</command> cannot be executed inside a transaction + block. + </para> + + <para> + This command cannot be executed while connected to the target + database. Thus, it might be more convenient to use the program + <xref linkend="app-dropdb"/> instead, + which is a wrapper around this command. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP DATABASE</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createdatabase"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/drop_domain.sgml b/doc/src/sgml/ref/drop_domain.sgml new file mode 100644 index 0000000..b18faf3 --- /dev/null +++ b/doc/src/sgml/ref/drop_domain.sgml @@ -0,0 +1,114 @@ +<!-- +doc/src/sgml/ref/drop_domain.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropdomain"> + <indexterm zone="sql-dropdomain"> + <primary>DROP DOMAIN</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP DOMAIN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP DOMAIN</refname> + <refpurpose>remove a domain</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP DOMAIN [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP DOMAIN</command> removes a domain. Only the owner of + a domain can remove it. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the domain does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing domain. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the domain (such as + table columns), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the domain if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropdomain-examples"> + <title>Examples</title> + + <para> + To remove the domain <type>box</type>: + +<programlisting> +DROP DOMAIN box; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropdomain-compatibility"> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, except for the + <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1 id="sql-dropdomain-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createdomain"/></member> + <member><xref linkend="sql-alterdomain"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_event_trigger.sgml b/doc/src/sgml/ref/drop_event_trigger.sgml new file mode 100644 index 0000000..137884c --- /dev/null +++ b/doc/src/sgml/ref/drop_event_trigger.sgml @@ -0,0 +1,115 @@ +<!-- +doc/src/sgml/ref/drop_event_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropeventtrigger"> + <indexterm zone="sql-dropeventtrigger"> + <primary>DROP EVENT TRIGGER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP EVENT TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP EVENT TRIGGER</refname> + <refpurpose>remove an event trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP EVENT TRIGGER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP EVENT TRIGGER</command> removes an existing event trigger. + To execute this command, the current user must be the owner of the event + trigger. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the event trigger does not exist. A notice + is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the event trigger to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the trigger, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the trigger if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropeventtrigger-examples"> + <title>Examples</title> + + <para> + Destroy the trigger <literal>snitch</literal>: + +<programlisting> +DROP EVENT TRIGGER snitch; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropeventtrigger-compatibility"> + <title>Compatibility</title> + + <para> + There is no <command>DROP EVENT TRIGGER</command> statement in the + SQL standard. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createeventtrigger"/></member> + <member><xref linkend="sql-altereventtrigger"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_extension.sgml b/doc/src/sgml/ref/drop_extension.sgml new file mode 100644 index 0000000..484e5d9 --- /dev/null +++ b/doc/src/sgml/ref/drop_extension.sgml @@ -0,0 +1,126 @@ +<!-- +doc/src/sgml/ref/drop_extension.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropextension"> + <indexterm zone="sql-dropextension"> + <primary>DROP EXTENSION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP EXTENSION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP EXTENSION</refname> + <refpurpose>remove an extension</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP EXTENSION [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP EXTENSION</command> removes extensions from the database. + Dropping an extension causes its member objects, and other explicitly + dependent routines (see <xref linkend="sql-alterroutine"/>, + the <literal>DEPENDS ON EXTENSION <replaceable>extension_name</replaceable> + </literal> action), to be dropped as well. + </para> + + <para> + You must own the extension to use <command>DROP EXTENSION</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the extension does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an installed extension. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the extension, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + This option prevents the specified extensions from being dropped if + other objects, besides these extensions, their members, and their + explicitly dependent routines, depend on them. This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To remove the extension <literal>hstore</literal> from the current + database: +<programlisting> +DROP EXTENSION hstore; +</programlisting> + This command will fail if any of <literal>hstore</literal>'s objects + are in use in the database, for example if any tables have columns + of the <type>hstore</type> type. Add the <literal>CASCADE</literal> option to + forcibly remove those dependent objects as well. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP EXTENSION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createextension"/></member> + <member><xref linkend="sql-alterextension"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_foreign_data_wrapper.sgml b/doc/src/sgml/ref/drop_foreign_data_wrapper.sgml new file mode 100644 index 0000000..e53178b --- /dev/null +++ b/doc/src/sgml/ref/drop_foreign_data_wrapper.sgml @@ -0,0 +1,114 @@ +<!-- +doc/src/sgml/ref/drop_foreign_data_wrapper.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropforeigndatawrapper"> + <indexterm zone="sql-dropforeigndatawrapper"> + <primary>DROP FOREIGN DATA WRAPPER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP FOREIGN DATA WRAPPER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP FOREIGN DATA WRAPPER</refname> + <refpurpose>remove a foreign-data wrapper</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP FOREIGN DATA WRAPPER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP FOREIGN DATA WRAPPER</command> removes an existing + foreign-data wrapper. To execute this command, the current user + must be the owner of the foreign-data wrapper. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the foreign-data wrapper does not + exist. A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing foreign-data wrapper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the foreign-data + wrapper (such as foreign tables and servers), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the foreign-data wrapper if any objects depend + on it. This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop the foreign-data wrapper <literal>dbi</literal>: +<programlisting> +DROP FOREIGN DATA WRAPPER dbi; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP FOREIGN DATA WRAPPER</command> conforms to ISO/IEC + 9075-9 (SQL/MED). The <literal>IF EXISTS</literal> clause is + a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createforeigndatawrapper"/></member> + <member><xref linkend="sql-alterforeigndatawrapper"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_foreign_table.sgml b/doc/src/sgml/ref/drop_foreign_table.sgml new file mode 100644 index 0000000..07b3fd4 --- /dev/null +++ b/doc/src/sgml/ref/drop_foreign_table.sgml @@ -0,0 +1,115 @@ +<!-- +doc/src/sgml/ref/drop_foreign_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropforeigntable"> + <indexterm zone="sql-dropforeigntable"> + <primary>DROP FOREIGN TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP FOREIGN TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP FOREIGN TABLE</refname> + <refpurpose>remove a foreign table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP FOREIGN TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP FOREIGN TABLE</command> removes a foreign table. + Only the owner of a foreign table can remove it. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the foreign table does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the foreign table to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the foreign table (such as + views), and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the foreign table if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To destroy two foreign tables, <literal>films</literal> and + <literal>distributors</literal>: + +<programlisting> +DROP FOREIGN TABLE films, distributors; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to ISO/IEC 9075-9 (SQL/MED), except that the + standard only allows one foreign table to be dropped per command, and apart + from the <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterforeigntable"/></member> + <member><xref linkend="sql-createforeigntable"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_function.sgml b/doc/src/sgml/ref/drop_function.sgml new file mode 100644 index 0000000..d84bebc --- /dev/null +++ b/doc/src/sgml/ref/drop_function.sgml @@ -0,0 +1,192 @@ +<!-- +doc/src/sgml/ref/drop_function.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropfunction"> + <indexterm zone="sql-dropfunction"> + <primary>DROP FUNCTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP FUNCTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP FUNCTION</refname> + <refpurpose>remove a function</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP FUNCTION [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] [, ...] + [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP FUNCTION</command> removes the definition of an existing + function. To execute this command the user must be the + owner of the function. The argument types to the + function must be specified, since several different functions + can exist with the same name and different argument lists. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the function does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing function. If no + argument list is specified, the name must be unique in its schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Note that <command>DROP FUNCTION</command> does not actually pay + any attention to <literal>OUT</literal> arguments, since only the input + arguments are needed to determine the function's identity. + So it is sufficient to list the <literal>IN</literal>, <literal>INOUT</literal>, + and <literal>VARIADIC</literal> arguments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>DROP FUNCTION</command> does not actually pay + any attention to argument names, since only the argument data + types are needed to determine the function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the function's arguments (optionally + schema-qualified), if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the function (such as + operators or triggers), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the function if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropfunction-examples"> + <title>Examples</title> + + <para> + This command removes the square root function: + +<programlisting> +DROP FUNCTION sqrt(integer); +</programlisting></para> + + <para> + Drop multiple functions in one command: +<programlisting> +DROP FUNCTION sqrt(integer), sqrt(bigint); +</programlisting></para> + + <para> + If the function name is unique in its schema, it can be referred to without + an argument list: +<programlisting> +DROP FUNCTION update_employee_salaries; +</programlisting> + Note that this is different from +<programlisting> +DROP FUNCTION update_employee_salaries(); +</programlisting> + which refers to a function with zero arguments, whereas the first variant + can refer to a function with any number of arguments, including zero, as + long as the name is unique. + </para> + </refsect1> + + <refsect1 id="sql-dropfunction-compatibility"> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, with + these <productname>PostgreSQL</productname> extensions: + <itemizedlist> + <listitem> + <para>The standard only allows one function to be dropped per command.</para> + </listitem> + <listitem> + <para>The <literal>IF EXISTS</literal> option</para> + </listitem> + <listitem> + <para>The ability to specify argument modes and names</para> + </listitem> + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createfunction"/></member> + <member><xref linkend="sql-alterfunction"/></member> + <member><xref linkend="sql-dropprocedure"/></member> + <member><xref linkend="sql-droproutine"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_group.sgml b/doc/src/sgml/ref/drop_group.sgml new file mode 100644 index 0000000..eb7dc18 --- /dev/null +++ b/doc/src/sgml/ref/drop_group.sgml @@ -0,0 +1,53 @@ +<!-- +doc/src/sgml/ref/drop_group.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropgroup"> + <indexterm zone="sql-dropgroup"> + <primary>DROP GROUP</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP GROUP</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP GROUP</refname> + <refpurpose>remove a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP GROUP [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP GROUP</command> is now an alias for + <link linkend="sql-droprole"><command>DROP ROLE</command></link>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP GROUP</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-droprole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_index.sgml b/doc/src/sgml/ref/drop_index.sgml new file mode 100644 index 0000000..aabc85e --- /dev/null +++ b/doc/src/sgml/ref/drop_index.sgml @@ -0,0 +1,143 @@ +<!-- +doc/src/sgml/ref/drop_index.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropindex"> + <indexterm zone="sql-dropindex"> + <primary>DROP INDEX</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP INDEX</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP INDEX</refname> + <refpurpose>remove an index</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP INDEX [ CONCURRENTLY ] [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP INDEX</command> drops an existing index from the database + system. To execute this command you must be the owner of + the index. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>CONCURRENTLY</literal></term> + <listitem> + <para> + Drop the index without locking out concurrent selects, inserts, updates, + and deletes on the index's table. A normal <command>DROP INDEX</command> + acquires an <literal>ACCESS EXCLUSIVE</literal> lock on the table, + blocking other accesses until the index drop can be completed. With + this option, the command instead waits until conflicting transactions + have completed. + </para> + <para> + There are several caveats to be aware of when using this option. + Only one index name can be specified, and the <literal>CASCADE</literal> option + is not supported. (Thus, an index that supports a <literal>UNIQUE</literal> or + <literal>PRIMARY KEY</literal> constraint cannot be dropped this way.) + Also, regular <command>DROP INDEX</command> commands can be + performed within a transaction block, but + <command>DROP INDEX CONCURRENTLY</command> cannot. + Lastly, indexes on partitioned tables cannot be dropped using this + option. + </para> + <para> + For temporary tables, <command>DROP INDEX</command> is always + non-concurrent, as no other session can access them, and + non-concurrent index drop is cheaper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the index does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an index to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the index, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the index if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This command will remove the index <literal>title_idx</literal>: + +<programlisting> +DROP INDEX title_idx; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP INDEX</command> is a + <productname>PostgreSQL</productname> language extension. There + are no provisions for indexes in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createindex"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_language.sgml b/doc/src/sgml/ref/drop_language.sgml new file mode 100644 index 0000000..8ba6621 --- /dev/null +++ b/doc/src/sgml/ref/drop_language.sgml @@ -0,0 +1,125 @@ +<!-- +doc/src/sgml/ref/drop_language.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droplanguage"> + <indexterm zone="sql-droplanguage"> + <primary>DROP LANGUAGE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP LANGUAGE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP LANGUAGE</refname> + <refpurpose>remove a procedural language</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP [ PROCEDURAL ] LANGUAGE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP LANGUAGE</command> removes the definition of a + previously registered procedural language. You must be a superuser + or the owner of the language to use <command>DROP LANGUAGE</command>. + </para> + + <note> + <para> + As of <productname>PostgreSQL</productname> 9.1, most procedural + languages have been made into <quote>extensions</quote>, and should + therefore be removed with <link linkend="sql-dropextension"><command>DROP EXTENSION</command></link> + not <command>DROP LANGUAGE</command>. + </para> + </note> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the language does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing procedural language. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the language (such as + functions in the language), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the language if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This command removes the procedural language + <literal>plsample</literal>: + +<programlisting> +DROP LANGUAGE plsample; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP LANGUAGE</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterlanguage"/></member> + <member><xref linkend="sql-createlanguage"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_materialized_view.sgml b/doc/src/sgml/ref/drop_materialized_view.sgml new file mode 100644 index 0000000..c8f3bc5 --- /dev/null +++ b/doc/src/sgml/ref/drop_materialized_view.sgml @@ -0,0 +1,116 @@ +<!-- +doc/src/sgml/ref/drop_materialized_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropmaterializedview"> + <indexterm zone="sql-dropmaterializedview"> + <primary>DROP MATERIALIZED VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP MATERIALIZED VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP MATERIALIZED VIEW</refname> + <refpurpose>remove a materialized view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP MATERIALIZED VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP MATERIALIZED VIEW</command> drops an existing materialized + view. To execute this command you must be the owner of the materialized + view. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the materialized view does not exist. A notice + is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the materialized view to + remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the materialized view (such as + other materialized views, or regular views), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the materialized view if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This command will remove the materialized view called + <literal>order_summary</literal>: +<programlisting> +DROP MATERIALIZED VIEW order_summary; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP MATERIALIZED VIEW</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-creatematerializedview"/></member> + <member><xref linkend="sql-altermaterializedview"/></member> + <member><xref linkend="sql-refreshmaterializedview"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_opclass.sgml b/doc/src/sgml/ref/drop_opclass.sgml new file mode 100644 index 0000000..4cb4cc3 --- /dev/null +++ b/doc/src/sgml/ref/drop_opclass.sgml @@ -0,0 +1,149 @@ +<!-- +doc/src/sgml/ref/drop_opclass.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropopclass"> + <indexterm zone="sql-dropopclass"> + <primary>DROP OPERATOR CLASS</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP OPERATOR CLASS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP OPERATOR CLASS</refname> + <refpurpose>remove an operator class</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP OPERATOR CLASS [ IF EXISTS ] <replaceable class="parameter">name</replaceable> USING <replaceable class="parameter">index_method</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP OPERATOR CLASS</command> drops an existing operator class. + To execute this command you must be the owner of the operator class. + </para> + + <para> + <command>DROP OPERATOR CLASS</command> does not drop any of the operators + or functions referenced by the class. If there are any indexes depending + on the operator class, you will need to specify + <literal>CASCADE</literal> for the drop to complete. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the operator class does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator class. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index access method the operator class is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the operator class (such as + indexes), and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the operator class if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>DROP OPERATOR CLASS</command> will not drop the operator family + containing the class, even if there is nothing else left in the + family (in particular, in the case where the family was implicitly + created by <command>CREATE OPERATOR CLASS</command>). An empty operator + family is harmless, but for the sake of tidiness you might wish to + remove the family with <command>DROP OPERATOR FAMILY</command>; or perhaps + better, use <command>DROP OPERATOR FAMILY</command> in the first place. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the B-tree operator class <literal>widget_ops</literal>: + +<programlisting> +DROP OPERATOR CLASS widget_ops USING btree; +</programlisting> + + This command will not succeed if there are any existing indexes + that use the operator class. Add <literal>CASCADE</literal> to drop + such indexes along with the operator class. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP OPERATOR CLASS</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteropclass"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-dropopfamily"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_operator.sgml b/doc/src/sgml/ref/drop_operator.sgml new file mode 100644 index 0000000..7bcdd08 --- /dev/null +++ b/doc/src/sgml/ref/drop_operator.sgml @@ -0,0 +1,146 @@ +<!-- +doc/src/sgml/ref/drop_operator.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropoperator"> + <indexterm zone="sql-dropoperator"> + <primary>DROP OPERATOR</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP OPERATOR</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP OPERATOR</refname> + <refpurpose>remove an operator</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP OPERATOR [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ( { <replaceable class="parameter">left_type</replaceable> | NONE } , <replaceable class="parameter">right_type</replaceable> ) [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP OPERATOR</command> drops an existing operator from + the database system. To execute this command you must be the owner + of the operator. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the operator does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">left_type</replaceable></term> + <listitem> + <para> + The data type of the operator's left operand; write + <literal>NONE</literal> if the operator has no left operand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">right_type</replaceable></term> + <listitem> + <para> + The data type of the operator's right operand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the operator (such as views + using it), and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the operator if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the power operator <literal>a^b</literal> for type <type>integer</type>: +<programlisting> +DROP OPERATOR ^ (integer, integer); +</programlisting> + </para> + + <para> + Remove the bitwise-complement prefix operator + <literal>~b</literal> for type <type>bit</type>: +<programlisting> +DROP OPERATOR ~ (none, bit); +</programlisting> + </para> + + <para> + Remove multiple operators in one command: +<programlisting> +DROP OPERATOR ~ (none, bit), ^ (integer, integer); +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP OPERATOR</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createoperator"/></member> + <member><xref linkend="sql-alteroperator"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_opfamily.sgml b/doc/src/sgml/ref/drop_opfamily.sgml new file mode 100644 index 0000000..c1bcd0d --- /dev/null +++ b/doc/src/sgml/ref/drop_opfamily.sgml @@ -0,0 +1,138 @@ +<!-- +doc/src/sgml/ref/drop_opfamily.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropopfamily"> + <indexterm zone="sql-dropopfamily"> + <primary>DROP OPERATOR FAMILY</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP OPERATOR FAMILY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP OPERATOR FAMILY</refname> + <refpurpose>remove an operator family</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP OPERATOR FAMILY [ IF EXISTS ] <replaceable class="parameter">name</replaceable> USING <replaceable class="parameter">index_method</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP OPERATOR FAMILY</command> drops an existing operator family. + To execute this command you must be the owner of the operator family. + </para> + + <para> + <command>DROP OPERATOR FAMILY</command> includes dropping any operator + classes contained in the family, but it does not drop any of the operators + or functions referenced by the family. If there are any indexes depending + on operator classes within the family, you will need to specify + <literal>CASCADE</literal> for the drop to complete. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the operator family does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing operator family. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_method</replaceable></term> + <listitem> + <para> + The name of the index access method the operator family is for. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the operator family, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the operator family if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the B-tree operator family <literal>float_ops</literal>: + +<programlisting> +DROP OPERATOR FAMILY float_ops USING btree; +</programlisting> + + This command will not succeed if there are any existing indexes + that use operator classes within the family. Add <literal>CASCADE</literal> to + drop such indexes along with the operator family. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP OPERATOR FAMILY</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alteropfamily"/></member> + <member><xref linkend="sql-createopfamily"/></member> + <member><xref linkend="sql-alteropclass"/></member> + <member><xref linkend="sql-createopclass"/></member> + <member><xref linkend="sql-dropopclass"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_owned.sgml b/doc/src/sgml/ref/drop_owned.sgml new file mode 100644 index 0000000..efda01a --- /dev/null +++ b/doc/src/sgml/ref/drop_owned.sgml @@ -0,0 +1,126 @@ +<!-- +doc/src/sgml/ref/drop_owned.sgml +PostgreSQL documentation +--> + +<refentry id="sql-drop-owned"> + <indexterm zone="sql-drop-owned"> + <primary>DROP OWNED</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP OWNED</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP OWNED</refname> + <refpurpose>remove database objects owned by a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP OWNED BY { <replaceable class="parameter">name</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP OWNED</command> drops all the objects within the current + database that are owned by one of the specified roles. Any + privileges granted to the given roles on objects in the current + database or on shared objects (databases, tablespaces, configuration + parameters) will also be revoked. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a role whose objects will be dropped, and whose + privileges will be revoked. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the affected objects, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the objects owned by a role if any other database + objects depend on one of the affected objects. This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + <para> + <command>DROP OWNED</command> is often used to prepare for the + removal of one or more roles. Because <command>DROP OWNED</command> + only affects the objects in the current database, it is usually + necessary to execute this command in each database that contains + objects owned by a role that is to be removed. + </para> + + <para> + Using the <literal>CASCADE</literal> option might make the command + recurse to objects owned by other users. + </para> + + <para> + The <link linkend="sql-reassign-owned"><command>REASSIGN OWNED</command></link> command is an alternative that + reassigns the ownership of all the database objects owned by one or + more roles. However, <command>REASSIGN OWNED</command> does not deal with + privileges for other objects. + </para> + + <para> + Databases and tablespaces owned by the role(s) will not be removed. + </para> + + <para> + See <xref linkend="role-removal"/> for more discussion. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>DROP OWNED</command> command is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-reassign-owned"/></member> + <member><xref linkend="sql-droprole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_policy.sgml b/doc/src/sgml/ref/drop_policy.sgml new file mode 100644 index 0000000..d7d3771 --- /dev/null +++ b/doc/src/sgml/ref/drop_policy.sgml @@ -0,0 +1,119 @@ +<!-- +doc/src/sgml/ref/drop_policy.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droppolicy"> + <indexterm zone="sql-droppolicy"> + <primary>DROP POLICY</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP POLICY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP POLICY</refname> + <refpurpose>remove a row-level security policy from a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP POLICY [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP POLICY</command> removes the specified policy from the table. + Note that if the last policy is removed for a table and the table still has + row-level security enabled via <command>ALTER TABLE</command>, then the + default-deny policy will be used. <literal>ALTER TABLE ... DISABLE ROW + LEVEL SECURITY</literal> can be used to disable row-level security for a + table, whether policies for the table exist or not. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the policy does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the policy to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table that + the policy is on. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no + dependencies on policies. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To drop the policy called <literal>p1</literal> on the table named + <literal>my_table</literal>: + +<programlisting> +DROP POLICY p1 ON my_table; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP POLICY</command> is a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createpolicy"/></member> + <member><xref linkend="sql-alterpolicy"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_procedure.sgml b/doc/src/sgml/ref/drop_procedure.sgml new file mode 100644 index 0000000..84e6b09 --- /dev/null +++ b/doc/src/sgml/ref/drop_procedure.sgml @@ -0,0 +1,231 @@ +<!-- +doc/src/sgml/ref/drop_procedure.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropprocedure"> + <indexterm zone="sql-dropprocedure"> + <primary>DROP PROCEDURE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP PROCEDURE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP PROCEDURE</refname> + <refpurpose>remove a procedure</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP PROCEDURE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] [, ...] + [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP PROCEDURE</command> removes the definition of one or more + existing procedures. To execute this command the user must be the + owner of the procedure(s). The argument types to the + procedure(s) usually must be specified, since several different procedures + can exist with the same name and different argument lists. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the procedure does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing procedure. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. If omitted, + the default is <literal>IN</literal> (but see below). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of an argument. + Note that <command>DROP PROCEDURE</command> does not actually pay + any attention to argument names, since only the argument data + types are used to determine the procedure's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type(s) of the procedure's arguments (optionally + schema-qualified), if any. + See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the procedure, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the procedure if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-dropprocedure-notes"> + <title>Notes</title> + + <para> + If there is only one procedure of the given name, the argument list + can be omitted. Omit the parentheses too in this case. + </para> + + <para> + In <productname>PostgreSQL</productname>, it's sufficient to list the + input (including <literal>INOUT</literal>) arguments, + because no two routines of the same name are allowed to share the same + input-argument list. Moreover, the <command>DROP</command> command + will not actually check that you wrote the types + of <literal>OUT</literal> arguments correctly; so any arguments that + are explicitly marked <literal>OUT</literal> are just noise. But + writing them is recommendable for consistency with the + corresponding <command>CREATE</command> command. + </para> + + <para> + For compatibility with the SQL standard, it is also allowed to write + all the argument data types (including those of <literal>OUT</literal> + arguments) without + any <replaceable class="parameter">argmode</replaceable> markers. + When this is done, the types of the procedure's <literal>OUT</literal> + argument(s) <emphasis>will</emphasis> be verified against the command. + This provision creates an ambiguity, in that when the argument list + contains no <replaceable class="parameter">argmode</replaceable> + markers, it's unclear which rule is intended. + The <command>DROP</command> command will attempt the lookup both ways, + and will throw an error if two different procedures are found. + To avoid the risk of such ambiguity, it's recommendable to + write <literal>IN</literal> markers explicitly rather than letting them + be defaulted, thus forcing the + traditional <productname>PostgreSQL</productname> interpretation to be + used. + </para> + + <para> + The lookup rules just explained are also used by other commands that + act on existing procedures, such as <command>ALTER PROCEDURE</command> + and <command>COMMENT ON PROCEDURE</command>. + </para> + </refsect1> + + <refsect1 id="sql-dropprocedure-examples"> + <title>Examples</title> + + <para> + If there is only one procedure <literal>do_db_maintenance</literal>, + this command is sufficient to drop it: +<programlisting> +DROP PROCEDURE do_db_maintenance; +</programlisting> + </para> + + <para> + Given this procedure definition: +<programlisting> +CREATE PROCEDURE do_db_maintenance(IN target_schema text, OUT results text) ... +</programlisting> + any one of these commands would work to drop it: +<programlisting> +DROP PROCEDURE do_db_maintenance(IN target_schema text, OUT results text); +DROP PROCEDURE do_db_maintenance(IN text, OUT text); +DROP PROCEDURE do_db_maintenance(IN text); +DROP PROCEDURE do_db_maintenance(text); +DROP PROCEDURE do_db_maintenance(text, text); -- potentially ambiguous +</programlisting> + However, the last example would be ambiguous if there is also, say, +<programlisting> +CREATE PROCEDURE do_db_maintenance(IN target_schema text, IN options text) ... +</programlisting></para> + </refsect1> + + <refsect1 id="sql-dropprocedure-compatibility"> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, with + these <productname>PostgreSQL</productname> extensions: + <itemizedlist> + <listitem> + <para>The standard only allows one procedure to be dropped per command.</para> + </listitem> + <listitem> + <para>The <literal>IF EXISTS</literal> option is an extension.</para> + </listitem> + <listitem> + <para>The ability to specify argument modes and names is an + extension, and the lookup rules differ when modes are given.</para> + </listitem> + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createprocedure"/></member> + <member><xref linkend="sql-alterprocedure"/></member> + <member><xref linkend="sql-dropfunction"/></member> + <member><xref linkend="sql-droproutine"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_publication.sgml b/doc/src/sgml/ref/drop_publication.sgml new file mode 100644 index 0000000..5dcbb83 --- /dev/null +++ b/doc/src/sgml/ref/drop_publication.sgml @@ -0,0 +1,105 @@ +<!-- +doc/src/sgml/ref/drop_publication.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droppublication"> + <indexterm zone="sql-droppublication"> + <primary>DROP PUBLICATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP PUBLICATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP PUBLICATION</refname> + <refpurpose>remove a publication</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP PUBLICATION [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP PUBLICATION</command> removes an existing publication from + the database. + </para> + + <para> + A publication can only be dropped by its owner or a superuser. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the publication does not exist. A notice is + issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing publication. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no dependencies + on publications. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop a publication: +<programlisting> +DROP PUBLICATION mypublication; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP PUBLICATION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createpublication"/></member> + <member><xref linkend="sql-alterpublication"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/drop_role.sgml b/doc/src/sgml/ref/drop_role.sgml new file mode 100644 index 0000000..13dc1cc --- /dev/null +++ b/doc/src/sgml/ref/drop_role.sgml @@ -0,0 +1,124 @@ +<!-- +doc/src/sgml/ref/drop_role.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droprole"> + <indexterm zone="sql-droprole"> + <primary>DROP ROLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP ROLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP ROLE</refname> + <refpurpose>remove a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP ROLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP ROLE</command> removes the specified role(s). + To drop a superuser role, you must be a superuser yourself; + to drop non-superuser roles, you must have <literal>CREATEROLE</literal> + privilege. + </para> + + <para> + A role cannot be removed if it is still referenced in any database + of the cluster; an error will be raised if so. Before dropping the role, + you must drop all the objects it owns (or reassign their ownership) + and revoke any privileges the role has been granted on other objects. + The <link linkend="sql-reassign-owned"><command>REASSIGN + OWNED</command></link> and <link linkend="sql-drop-owned"><command>DROP + OWNED</command></link> + commands can be useful for this purpose; see <xref linkend="role-removal"/> + for more discussion. + </para> + + <para> + However, it is not necessary to remove role memberships involving + the role; <command>DROP ROLE</command> automatically revokes any memberships + of the target role in other roles, and of other roles in the target role. + The other roles are not dropped nor otherwise affected. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the role does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the role to remove. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <productname>PostgreSQL</productname> includes a program <xref + linkend="app-dropuser"/> that has the + same functionality as this command (in fact, it calls this command) + but can be run from the command shell. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To drop a role: +<programlisting> +DROP ROLE jonathan; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard defines <command>DROP ROLE</command>, but it allows + only one role to be dropped at a time, and it specifies different + privilege requirements than <productname>PostgreSQL</productname> uses. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrole"/></member> + <member><xref linkend="sql-alterrole"/></member> + <member><xref linkend="sql-set-role"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_routine.sgml b/doc/src/sgml/ref/drop_routine.sgml new file mode 100644 index 0000000..0a0a140 --- /dev/null +++ b/doc/src/sgml/ref/drop_routine.sgml @@ -0,0 +1,123 @@ +<!-- +doc/src/sgml/ref/drop_routine.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droproutine"> + <indexterm zone="sql-droproutine"> + <primary>DROP ROUTINE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP ROUTINE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP ROUTINE</refname> + <refpurpose>remove a routine</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP ROUTINE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] [, ...] + [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP ROUTINE</command> removes the definition of one or more + existing routines. The term <quote>routine</quote> includes + aggregate functions, normal functions, and procedures. See + under <xref linkend="sql-dropaggregate"/>, <xref linkend="sql-dropfunction"/>, + and <xref linkend="sql-dropprocedure"/> for the description of the + parameters, more examples, and further details. + </para> + </refsect1> + + <refsect1 id="sql-droproutine-notes"> + <title>Notes</title> + + <para> + The lookup rules used by <command>DROP ROUTINE</command> are + fundamentally the same as for <command>DROP PROCEDURE</command>; in + particular, <command>DROP ROUTINE</command> shares that command's + behavior of considering an argument list that has + no <replaceable class="parameter">argmode</replaceable> markers to be + possibly using the SQL standard's definition that <literal>OUT</literal> + arguments are included in the list. (<command>DROP AGGREGATE</command> + and <command>DROP FUNCTION</command> do not do that.) + </para> + + <para> + In some cases where the same name is shared by routines of different + kinds, it is possible for <command>DROP ROUTINE</command> to fail with + an ambiguity error when a more specific command (<command>DROP + FUNCTION</command>, etc.) would work. Specifying the argument type + list more carefully will also resolve such problems. + </para> + + <para> + These lookup rules are also used by other commands that + act on existing routines, such as <command>ALTER ROUTINE</command> + and <command>COMMENT ON ROUTINE</command>. + </para> + </refsect1> + + <refsect1 id="sql-droproutine-examples"> + <title>Examples</title> + + <para> + To drop the routine <literal>foo</literal> for type + <type>integer</type>: +<programlisting> +DROP ROUTINE foo(integer); +</programlisting> + This command will work independent of whether <literal>foo</literal> is an + aggregate, function, or procedure. + </para> + </refsect1> + + <refsect1 id="sql-droproutine-compatibility"> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, with + these <productname>PostgreSQL</productname> extensions: + <itemizedlist> + <listitem> + <para>The standard only allows one routine to be dropped per command.</para> + </listitem> + <listitem> + <para>The <literal>IF EXISTS</literal> option is an extension.</para> + </listitem> + <listitem> + <para>The ability to specify argument modes and names is an + extension, and the lookup rules differ when modes are given.</para> + </listitem> + <listitem> + <para>User-definable aggregate functions are an extension.</para> + </listitem> + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-dropaggregate"/></member> + <member><xref linkend="sql-dropfunction"/></member> + <member><xref linkend="sql-dropprocedure"/></member> + <member><xref linkend="sql-alterroutine"/></member> + </simplelist> + + <para> + Note that there is no <literal>CREATE ROUTINE</literal> command. + </para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_rule.sgml b/doc/src/sgml/ref/drop_rule.sgml new file mode 100644 index 0000000..cc5d00e --- /dev/null +++ b/doc/src/sgml/ref/drop_rule.sgml @@ -0,0 +1,123 @@ +<!-- +doc/src/sgml/ref/drop_rule.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droprule"> + <indexterm zone="sql-droprule"> + <primary>DROP RULE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP RULE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP RULE</refname> + <refpurpose>remove a rewrite rule</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP RULE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP RULE</command> drops a rewrite rule. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the rule does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the rule to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table or view that + the rule applies to. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the rule, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the rule if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To drop the rewrite rule <literal>newrule</literal>: + +<programlisting> +DROP RULE newrule ON mytable; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP RULE</command> is a + <productname>PostgreSQL</productname> language extension, as is the + entire query rewrite system. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createrule"/></member> + <member><xref linkend="sql-alterrule"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_schema.sgml b/doc/src/sgml/ref/drop_schema.sgml new file mode 100644 index 0000000..4d5d9f5 --- /dev/null +++ b/doc/src/sgml/ref/drop_schema.sgml @@ -0,0 +1,131 @@ +<!-- +doc/src/sgml/ref/drop_schema.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropschema"> + <indexterm zone="sql-dropschema"> + <primary>DROP SCHEMA</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP SCHEMA</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP SCHEMA</refname> + <refpurpose>remove a schema</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP SCHEMA [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP SCHEMA</command> removes schemas from the database. + </para> + + <para> + A schema can only be dropped by its owner or a superuser. Note that + the owner can drop the schema (and thereby all contained objects) + even if they do not own some of the objects within the schema. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the schema does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a schema. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects (tables, functions, etc.) that are + contained in the schema, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the schema if it contains any objects. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Using the <literal>CASCADE</literal> option might make the command + remove objects in other schemas besides the one(s) named. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To remove schema <literal>mystuff</literal> from the database, + along with everything it contains: + +<programlisting> +DROP SCHEMA mystuff CASCADE; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP SCHEMA</command> is fully conforming with the SQL + standard, except that the standard only allows one schema to be + dropped per command, and apart from the + <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterschema"/></member> + <member><xref linkend="sql-createschema"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_sequence.sgml b/doc/src/sgml/ref/drop_sequence.sgml new file mode 100644 index 0000000..387c98e --- /dev/null +++ b/doc/src/sgml/ref/drop_sequence.sgml @@ -0,0 +1,115 @@ +<!-- +doc/src/sgml/ref/drop_sequence.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropsequence"> + <indexterm zone="sql-dropsequence"> + <primary>DROP SEQUENCE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP SEQUENCE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP SEQUENCE</refname> + <refpurpose>remove a sequence</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP SEQUENCE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP SEQUENCE</command> removes sequence number + generators. A sequence can only be dropped by its owner or a superuser. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the sequence does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a sequence. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the sequence, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the sequence if any objects depend on it. This + is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To remove the sequence <literal>serial</literal>: + +<programlisting> +DROP SEQUENCE serial; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP SEQUENCE</command> conforms to the <acronym>SQL</acronym> + standard, except that the standard only allows one + sequence to be dropped per command, and apart from the + <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createsequence"/></member> + <member><xref linkend="sql-altersequence"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_server.sgml b/doc/src/sgml/ref/drop_server.sgml new file mode 100644 index 0000000..f83a661 --- /dev/null +++ b/doc/src/sgml/ref/drop_server.sgml @@ -0,0 +1,114 @@ +<!-- +doc/src/sgml/ref/drop_server.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropserver"> + <indexterm zone="sql-dropserver"> + <primary>DROP SERVER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP SERVER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP SERVER</refname> + <refpurpose>remove a foreign server descriptor</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP SERVER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP SERVER</command> removes an existing foreign server + descriptor. To execute this command, the current user must be the + owner of the server. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the server does not exist. A notice is + issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of an existing server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the server (such as + user mappings), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the server if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop a server <literal>foo</literal> if it exists: +<programlisting> +DROP SERVER IF EXISTS foo; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP SERVER</command> conforms to ISO/IEC 9075-9 + (SQL/MED). The <literal>IF EXISTS</literal> clause is + a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createserver"/></member> + <member><xref linkend="sql-alterserver"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_statistics.sgml b/doc/src/sgml/ref/drop_statistics.sgml new file mode 100644 index 0000000..1532ca9 --- /dev/null +++ b/doc/src/sgml/ref/drop_statistics.sgml @@ -0,0 +1,108 @@ +<!-- +doc/src/sgml/ref/drop_statistics.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropstatistics"> + <indexterm zone="sql-dropstatistics"> + <primary>DROP STATISTICS</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP STATISTICS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP STATISTICS</refname> + <refpurpose>remove extended statistics</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP STATISTICS [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP STATISTICS</command> removes statistics object(s) from the + database. Only the statistics object's owner, the schema owner, or a + superuser can drop a statistics object. + </para> + + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the statistics object does not exist. A notice + is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the statistics object to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no dependencies + on statistics. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To destroy two statistics objects in different schemas, without failing + if they don't exist: + +<programlisting> +DROP STATISTICS IF EXISTS + accounting.users_uid_creation, + public.grants_user_role; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP STATISTICS</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterstatistics"/></member> + <member><xref linkend="sql-createstatistics"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_subscription.sgml b/doc/src/sgml/ref/drop_subscription.sgml new file mode 100644 index 0000000..d79f137 --- /dev/null +++ b/doc/src/sgml/ref/drop_subscription.sgml @@ -0,0 +1,134 @@ +<!-- +doc/src/sgml/ref/drop_subscription.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropsubscription"> + <indexterm zone="sql-dropsubscription"> + <primary>DROP SUBSCRIPTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP SUBSCRIPTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP SUBSCRIPTION</refname> + <refpurpose>remove a subscription</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP SUBSCRIPTION [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP SUBSCRIPTION</command> removes a subscription from the + database cluster. + </para> + + <para> + A subscription can only be dropped by a superuser. + </para> + + <para> + <command>DROP SUBSCRIPTION</command> cannot be executed inside a + transaction block if the subscription is associated with a replication + slot. (You can use <command>ALTER SUBSCRIPTION</command> to unset the + slot.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a subscription to be dropped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <term><literal>RESTRICT</literal></term> + + <listitem> + <para> + These key words do not have any effect, since there are no dependencies + on subscriptions. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + When dropping a subscription that is associated with a replication slot on + the remote host (the normal state), <command>DROP SUBSCRIPTION</command> + will connect to the remote host and try to drop the replication slot (and + any remaining table synchronization slots) as + part of its operation. This is necessary so that the resources allocated + for the subscription on the remote host are released. If this fails, + either because the remote host is not reachable or because the remote + replication slot cannot be dropped or does not exist or never existed, + the <command>DROP SUBSCRIPTION</command> command will fail. To proceed + in this situation, first disable the subscription by executing + <literal>ALTER SUBSCRIPTION ... DISABLE</literal>, and then disassociate + it from the replication slot by executing + <literal>ALTER SUBSCRIPTION ... SET (slot_name = NONE)</literal>. + After that, <command>DROP SUBSCRIPTION</command> will no longer attempt any + actions on a remote host. Note that if the remote replication slot still + exists, it (and any related table synchronization slots) should then be + dropped manually; otherwise it/they will continue to + reserve WAL and might eventually cause the disk to fill up. See + also <xref linkend="logical-replication-subscription-slot"/>. + </para> + + <para> + If a subscription is associated with a replication slot, then <command>DROP + SUBSCRIPTION</command> cannot be executed inside a transaction block. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop a subscription: +<programlisting> +DROP SUBSCRIPTION mysub; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP SUBSCRIPTION</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createsubscription"/></member> + <member><xref linkend="sql-altersubscription"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/drop_table.sgml b/doc/src/sgml/ref/drop_table.sgml new file mode 100644 index 0000000..450458f --- /dev/null +++ b/doc/src/sgml/ref/drop_table.sgml @@ -0,0 +1,129 @@ +<!-- +doc/src/sgml/ref/drop_table.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptable"> + <indexterm zone="sql-droptable"> + <primary>DROP TABLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TABLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TABLE</refname> + <refpurpose>remove a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TABLE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TABLE</command> removes tables from the database. + Only the table owner, the schema owner, and superuser can drop a + table. To empty a table of rows + without destroying the table, use <link linkend="sql-delete"><command>DELETE</command></link> + or <link linkend="sql-truncate"><command>TRUNCATE</command></link>. + </para> + + <para> + <command>DROP TABLE</command> always removes any indexes, rules, + triggers, and constraints that exist for the target table. + However, to drop a table that is referenced by a view or a foreign-key + constraint of another table, <literal>CASCADE</literal> must be + specified. (<literal>CASCADE</literal> will remove a dependent view entirely, + but in the foreign-key case it will only remove the foreign-key + constraint, not the other table entirely.) + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the table does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to drop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the table (such as + views), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the table if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To destroy two tables, <literal>films</literal> and + <literal>distributors</literal>: + +<programlisting> +DROP TABLE films, distributors; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, except that the standard only + allows one table to be dropped per command, and apart from the + <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertable"/></member> + <member><xref linkend="sql-createtable"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_tablespace.sgml b/doc/src/sgml/ref/drop_tablespace.sgml new file mode 100644 index 0000000..047e4e0 --- /dev/null +++ b/doc/src/sgml/ref/drop_tablespace.sgml @@ -0,0 +1,110 @@ +<!-- +doc/src/sgml/ref/drop_tablespace.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptablespace"> + <indexterm zone="sql-droptablespace"> + <primary>DROP TABLESPACE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TABLESPACE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TABLESPACE</refname> + <refpurpose>remove a tablespace</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TABLESPACE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TABLESPACE</command> removes a tablespace from the system. + </para> + + <para> + A tablespace can only be dropped by its owner or a superuser. + The tablespace must be empty of all database objects before it can be + dropped. It is possible that objects in other databases might still reside + in the tablespace even if no objects in the current database are using + the tablespace. Also, if the tablespace is listed in the <xref + linkend="guc-temp-tablespaces"/> setting of any active session, the + <command>DROP</command> might fail due to temporary files residing in the + tablespace. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the tablespace does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a tablespace. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>DROP TABLESPACE</command> cannot be executed inside a transaction block. + </para> + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To remove tablespace <literal>mystuff</literal> from the system: +<programlisting> +DROP TABLESPACE mystuff; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP TABLESPACE</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtablespace"/></member> + <member><xref linkend="sql-altertablespace"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_transform.sgml b/doc/src/sgml/ref/drop_transform.sgml new file mode 100644 index 0000000..544a966 --- /dev/null +++ b/doc/src/sgml/ref/drop_transform.sgml @@ -0,0 +1,128 @@ +<!-- +doc/src/sgml/ref/drop_transform.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptransform"> + <indexterm zone="sql-droptransform"> + <primary>DROP TRANSFORM</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TRANSFORM</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TRANSFORM</refname> + <refpurpose>remove a transform</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TRANSFORM [ IF EXISTS ] FOR <replaceable>type_name</replaceable> LANGUAGE <replaceable>lang_name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-droptransform-description"> + <title>Description</title> + + <para> + <command>DROP TRANSFORM</command> removes a previously defined transform. + </para> + + <para> + To be able to drop a transform, you must own the type and the language. + These are the same privileges that are required to create a transform. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the transform does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>type_name</replaceable></term> + + <listitem> + <para> + The name of the data type of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>lang_name</replaceable></term> + + <listitem> + <para> + The name of the language of the transform. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the transform, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the transform if any objects depend on it. This is the + default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-droptransform-examples"> + <title>Examples</title> + + <para> + To drop the transform for type <type>hstore</type> and language + <literal>plpython3u</literal>: +<programlisting> +DROP TRANSFORM FOR hstore LANGUAGE plpython3u; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-droptransform-compat"> + <title>Compatibility</title> + + <para> + This form of <command>DROP TRANSFORM</command> is a + <productname>PostgreSQL</productname> extension. See <xref + linkend="sql-createtransform"/> for details. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtransform"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_trigger.sgml b/doc/src/sgml/ref/drop_trigger.sgml new file mode 100644 index 0000000..728541e --- /dev/null +++ b/doc/src/sgml/ref/drop_trigger.sgml @@ -0,0 +1,127 @@ +<!-- +doc/src/sgml/ref/drop_trigger.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptrigger"> + <indexterm zone="sql-droptrigger"> + <primary>DROP TRIGGER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TRIGGER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TRIGGER</refname> + <refpurpose>remove a trigger</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TRIGGER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TRIGGER</command> removes an existing + trigger definition. To execute this command, the current + user must be the owner of the table for which the trigger is defined. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the trigger does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the trigger to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table for which + the trigger is defined. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the trigger, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the trigger if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-droptrigger-examples"> + <title>Examples</title> + + <para> + Destroy the trigger <literal>if_dist_exists</literal> on the table + <literal>films</literal>: + +<programlisting> +DROP TRIGGER if_dist_exists ON films; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-droptrigger-compatibility"> + <title>Compatibility</title> + + <para> + The <command>DROP TRIGGER</command> statement in + <productname>PostgreSQL</productname> is incompatible with the SQL + standard. In the SQL standard, trigger names are not local to + tables, so the command is simply <literal>DROP TRIGGER + <replaceable>name</replaceable></literal>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtrigger"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_tsconfig.sgml b/doc/src/sgml/ref/drop_tsconfig.sgml new file mode 100644 index 0000000..9eec4ba --- /dev/null +++ b/doc/src/sgml/ref/drop_tsconfig.sgml @@ -0,0 +1,121 @@ +<!-- +doc/src/sgml/ref/drop_tsconfig.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptsconfig"> + <indexterm zone="sql-droptsconfig"> + <primary>DROP TEXT SEARCH CONFIGURATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TEXT SEARCH CONFIGURATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TEXT SEARCH CONFIGURATION</refname> + <refpurpose>remove a text search configuration</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TEXT SEARCH CONFIGURATION [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TEXT SEARCH CONFIGURATION</command> drops an existing text + search configuration. To execute this command you must be the owner of the + configuration. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the text search configuration does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search + configuration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the text search configuration, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the text search configuration if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the text search configuration <literal>my_english</literal>: + +<programlisting> +DROP TEXT SEARCH CONFIGURATION my_english; +</programlisting> + + This command will not succeed if there are any existing indexes + that reference the configuration in <function>to_tsvector</function> calls. + Add <literal>CASCADE</literal> to + drop such indexes along with the text search configuration. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP TEXT SEARCH CONFIGURATION</command> statement in + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsconfig"/></member> + <member><xref linkend="sql-createtsconfig"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_tsdictionary.sgml b/doc/src/sgml/ref/drop_tsdictionary.sgml new file mode 100644 index 0000000..8d22cfd --- /dev/null +++ b/doc/src/sgml/ref/drop_tsdictionary.sgml @@ -0,0 +1,120 @@ +<!-- +doc/src/sgml/ref/drop_tsdictionary.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptsdictionary"> + <indexterm zone="sql-droptsdictionary"> + <primary>DROP TEXT SEARCH DICTIONARY</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TEXT SEARCH DICTIONARY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TEXT SEARCH DICTIONARY</refname> + <refpurpose>remove a text search dictionary</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TEXT SEARCH DICTIONARY [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TEXT SEARCH DICTIONARY</command> drops an existing text + search dictionary. To execute this command you must be the owner of the + dictionary. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the text search dictionary does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search + dictionary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the text search dictionary, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the text search dictionary if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the text search dictionary <literal>english</literal>: + +<programlisting> +DROP TEXT SEARCH DICTIONARY english; +</programlisting> + + This command will not succeed if there are any existing text search + configurations that use the dictionary. Add <literal>CASCADE</literal> to + drop such configurations along with the dictionary. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP TEXT SEARCH DICTIONARY</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsdictionary"/></member> + <member><xref linkend="sql-createtsdictionary"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_tsparser.sgml b/doc/src/sgml/ref/drop_tsparser.sgml new file mode 100644 index 0000000..2b647cc --- /dev/null +++ b/doc/src/sgml/ref/drop_tsparser.sgml @@ -0,0 +1,118 @@ +<!-- +doc/src/sgml/ref/drop_tsparser.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptsparser"> + <indexterm zone="sql-droptsparser"> + <primary>DROP TEXT SEARCH PARSER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TEXT SEARCH PARSER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TEXT SEARCH PARSER</refname> + <refpurpose>remove a text search parser</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TEXT SEARCH PARSER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TEXT SEARCH PARSER</command> drops an existing text search + parser. You must be a superuser to use this command. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the text search parser does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search parser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the text search parser, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the text search parser if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the text search parser <literal>my_parser</literal>: + +<programlisting> +DROP TEXT SEARCH PARSER my_parser; +</programlisting> + + This command will not succeed if there are any existing text search + configurations that use the parser. Add <literal>CASCADE</literal> to + drop such configurations along with the parser. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP TEXT SEARCH PARSER</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertsparser"/></member> + <member><xref linkend="sql-createtsparser"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_tstemplate.sgml b/doc/src/sgml/ref/drop_tstemplate.sgml new file mode 100644 index 0000000..972b90a --- /dev/null +++ b/doc/src/sgml/ref/drop_tstemplate.sgml @@ -0,0 +1,119 @@ +<!-- +doc/src/sgml/ref/drop_tstemplate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptstemplate"> + <indexterm zone="sql-droptstemplate"> + <primary>DROP TEXT SEARCH TEMPLATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TEXT SEARCH TEMPLATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TEXT SEARCH TEMPLATE</refname> + <refpurpose>remove a text search template</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TEXT SEARCH TEMPLATE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TEXT SEARCH TEMPLATE</command> drops an existing text search + template. You must be a superuser to use this command. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the text search template does not exist. + A notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing text search + template. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the text search template, + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the text search template if any objects depend on it. + This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Remove the text search template <literal>thesaurus</literal>: + +<programlisting> +DROP TEXT SEARCH TEMPLATE thesaurus; +</programlisting> + + This command will not succeed if there are any existing text search + dictionaries that use the template. Add <literal>CASCADE</literal> to + drop such dictionaries along with the template. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>DROP TEXT SEARCH TEMPLATE</command> statement in the + SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertstemplate"/></member> + <member><xref linkend="sql-createtstemplate"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_type.sgml b/doc/src/sgml/ref/drop_type.sgml new file mode 100644 index 0000000..9e555c0 --- /dev/null +++ b/doc/src/sgml/ref/drop_type.sgml @@ -0,0 +1,116 @@ +<!-- +doc/src/sgml/ref/drop_type.sgml +PostgreSQL documentation +--> + +<refentry id="sql-droptype"> + <indexterm zone="sql-droptype"> + <primary>DROP TYPE</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP TYPE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP TYPE</refname> + <refpurpose>remove a data type</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP TYPE [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP TYPE</command> removes a user-defined data type. + Only the owner of a type can remove it. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the type does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the data type to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the type (such as + table columns, functions, and operators), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the type if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-droptype-examples"> + <title>Examples</title> + + <para> + To remove the data type <type>box</type>: +<programlisting> +DROP TYPE box; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-droptype-compatibility"> + <title>Compatibility</title> + + <para> + This command is similar to the corresponding command in the SQL + standard, apart from the <literal>IF EXISTS</literal> + option, which is a <productname>PostgreSQL</productname> extension. + But note that much of the <command>CREATE TYPE</command> command + and the data type extension mechanisms in + <productname>PostgreSQL</productname> differ from the SQL standard. + </para> + </refsect1> + + <refsect1 id="sql-droptype-see-also"> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-altertype"/></member> + <member><xref linkend="sql-createtype"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_user.sgml b/doc/src/sgml/ref/drop_user.sgml new file mode 100644 index 0000000..74e736b --- /dev/null +++ b/doc/src/sgml/ref/drop_user.sgml @@ -0,0 +1,55 @@ +<!-- +doc/src/sgml/ref/drop_user.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropuser"> + <indexterm zone="sql-dropuser"> + <primary>DROP USER</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP USER</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP USER</refname> + <refpurpose>remove a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP USER [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP USER</command> is simply an alternate spelling of + <link linkend="sql-droprole"><command>DROP ROLE</command></link>. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>DROP USER</command> statement is a + <productname>PostgreSQL</productname> extension. The SQL standard + leaves the definition of users to the implementation. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-droprole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_user_mapping.sgml b/doc/src/sgml/ref/drop_user_mapping.sgml new file mode 100644 index 0000000..9e8896a --- /dev/null +++ b/doc/src/sgml/ref/drop_user_mapping.sgml @@ -0,0 +1,110 @@ +<!-- +doc/src/sgml/ref/drop_user_mapping.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropusermapping"> + <indexterm zone="sql-dropusermapping"> + <primary>DROP USER MAPPING</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP USER MAPPING</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP USER MAPPING</refname> + <refpurpose>remove a user mapping for a foreign server</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP USER MAPPING [ IF EXISTS ] FOR { <replaceable class="parameter">user_name</replaceable> | USER | CURRENT_ROLE | CURRENT_USER | PUBLIC } SERVER <replaceable class="parameter">server_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP USER MAPPING</command> removes an existing user + mapping from foreign server. + </para> + + <para> + The owner of a foreign server can drop user mappings for that server + for any user. Also, a user can drop a user mapping for their own + user name if <literal>USAGE</literal> privilege on the server has been + granted to the user. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the user mapping does not exist. A + notice is issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">user_name</replaceable></term> + <listitem> + <para> + User name of the mapping. <literal>CURRENT_ROLE</literal>, <literal>CURRENT_USER</literal>, + and <literal>USER</literal> match the name of the current + user. <literal>PUBLIC</literal> is used to match all present and + future user names in the system. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + Server name of the user mapping. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Drop a user mapping <literal>bob</literal>, server <literal>foo</literal> if it exists: +<programlisting> +DROP USER MAPPING IF EXISTS FOR bob SERVER foo; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>DROP USER MAPPING</command> conforms to ISO/IEC 9075-9 + (SQL/MED). The <literal>IF EXISTS</literal> clause is + a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createusermapping"/></member> + <member><xref linkend="sql-alterusermapping"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/drop_view.sgml b/doc/src/sgml/ref/drop_view.sgml new file mode 100644 index 0000000..a1c550e --- /dev/null +++ b/doc/src/sgml/ref/drop_view.sgml @@ -0,0 +1,114 @@ +<!-- +doc/src/sgml/ref/drop_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-dropview"> + <indexterm zone="sql-dropview"> + <primary>DROP VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>DROP VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>DROP VIEW</refname> + <refpurpose>remove a view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +DROP VIEW [ IF EXISTS ] <replaceable class="parameter">name</replaceable> [, ...] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>DROP VIEW</command> drops an existing view. To execute + this command you must be the owner of the view. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>IF EXISTS</literal></term> + <listitem> + <para> + Do not throw an error if the view does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the view to remove. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically drop objects that depend on the view (such as + other views), + and in turn all objects that depend on those objects + (see <xref linkend="ddl-depend"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to drop the view if any objects depend on it. This is + the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This command will remove the view called <literal>kinds</literal>: +<programlisting> +DROP VIEW kinds; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to the SQL standard, except that the standard only + allows one view to be dropped per command, and apart from the + <literal>IF EXISTS</literal> option, which is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-alterview"/></member> + <member><xref linkend="sql-createview"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/dropdb.sgml b/doc/src/sgml/ref/dropdb.sgml new file mode 100644 index 0000000..d36aed3 --- /dev/null +++ b/doc/src/sgml/ref/dropdb.sgml @@ -0,0 +1,317 @@ +<!-- +doc/src/sgml/ref/dropdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-dropdb"> + <indexterm zone="app-dropdb"> + <primary>dropdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>dropdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>dropdb</refname> + <refpurpose>remove a <productname>PostgreSQL</productname> database</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>dropdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="plain"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1> + <title>Description</title> + + <para> + <application>dropdb</application> destroys an existing + <productname>PostgreSQL</productname> database. + The user who executes this command must be a database + superuser or the owner of the database. + </para> + + <para> + <application>dropdb</application> is a wrapper around the + <acronym>SQL</acronym> command <link linkend="sql-dropdatabase"><command>DROP DATABASE</command></link>. + There is no effective difference between dropping databases via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>dropdb</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">dbname</replaceable></term> + <listitem> + <para> + Specifies the name of the database to be removed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>dropdb</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f</option></term> + <term><option>--force</option></term> + <listitem> + <para> + Attempt to terminate all existing connections to the target database + before dropping it. See <xref linkend="sql-dropdatabase"/> for more + information on this option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <term><option>--interactive</option></term> + <listitem> + <para> + Issues a verification prompt before doing anything destructive. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>dropdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-exists</option></term> + <listitem> + <para> + Do not throw an error if the database does not exist. A notice is issued + in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>dropdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + + </para> + + <para> + <application>dropdb</application> also accepts the following + command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server + is running. If the value begins with a slash, it is used + as the directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>dropdb</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>dropdb</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>dropdb</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to in order to drop the + target database. If not specified, the <literal>postgres</literal> + database will be used; if that does not exist (or is the database + being dropped), <literal>template1</literal> will be used. + This can be a <link linkend="libpq-connstring">connection + string</link>. If so, connection string parameters will override any + conflicting command line options. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-dropdatabase"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To destroy the database <literal>demo</literal> on the default + database server: +<screen> +<prompt>$ </prompt><userinput>dropdb demo</userinput> +</screen> + </para> + + <para> + To destroy the database <literal>demo</literal> using the + server on host <literal>eden</literal>, port 5000, with verification and a peek + at the underlying command: +<screen> +<prompt>$ </prompt><userinput>dropdb -p 5000 -h eden -i -e demo</userinput> +<computeroutput>Database "demo" will be permanently deleted. +Are you sure? (y/n) </computeroutput><userinput>y</userinput> +<computeroutput>DROP DATABASE demo;</computeroutput> +</screen></para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-createdb"/></member> + <member><xref linkend="sql-dropdatabase"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/dropuser.sgml b/doc/src/sgml/ref/dropuser.sgml new file mode 100644 index 0000000..8158050 --- /dev/null +++ b/doc/src/sgml/ref/dropuser.sgml @@ -0,0 +1,294 @@ +<!-- +doc/src/sgml/ref/dropuser.sgml +PostgreSQL documentation +--> + +<refentry id="app-dropuser"> + <indexterm zone="app-dropuser"> + <primary>dropuser</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>dropuser</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>dropuser</refname> + <refpurpose>remove a <productname>PostgreSQL</productname> user account</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>dropuser</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>username</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1> + <title>Description</title> + + <para> + <application>dropuser</application> removes an existing + <productname>PostgreSQL</productname> user. + Only superusers and users with the <literal>CREATEROLE</literal> privilege can + remove <productname>PostgreSQL</productname> users. (To remove a + superuser, you must yourself be a superuser.) + </para> + + <para> + <application>dropuser</application> is a wrapper around the + <acronym>SQL</acronym> command <link linkend="sql-droprole"><command>DROP ROLE</command></link>. + There is no effective difference between dropping users via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>dropuser</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">username</replaceable></term> + <listitem> + <para> + Specifies the name of the <productname>PostgreSQL</productname> user to be removed. + You will be prompted for a name if none is specified on the command + line and the <option>-i</option>/<option>--interactive</option> option + is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>dropuser</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <term><option>--interactive</option></term> + <listitem> + <para> + Prompt for confirmation before actually removing the user, and prompt + for the user name if none is specified on the command line. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>dropuser</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-exists</option></term> + <listitem> + <para> + Do not throw an error if the user does not exist. A notice is + issued in this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>dropuser</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + <application>dropuser</application> also accepts the following + command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server + is running. If the value begins with a slash, it is used + as the directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as (not the user name to drop). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>dropuser</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>dropuser</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>dropuser</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-droprole"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To remove user <literal>joe</literal> from the default database + server: +<screen> +<prompt>$ </prompt><userinput>dropuser joe</userinput> +</screen> + </para> + + <para> + To remove user <literal>joe</literal> using the server on host + <literal>eden</literal>, port 5000, with verification and a peek at the underlying + command: +<screen> +<prompt>$ </prompt><userinput>dropuser -p 5000 -h eden -i -e joe</userinput> +<computeroutput>Role "joe" will be permanently removed. +Are you sure? (y/n) </computeroutput><userinput>y</userinput> +<computeroutput>DROP ROLE joe;</computeroutput> +</screen></para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-createuser"/></member> + <member><xref linkend="sql-droprole"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/ecpg-ref.sgml b/doc/src/sgml/ref/ecpg-ref.sgml new file mode 100644 index 0000000..f3b6034 --- /dev/null +++ b/doc/src/sgml/ref/ecpg-ref.sgml @@ -0,0 +1,278 @@ +<!-- +doc/src/sgml/ref/ecpg-ref.sgml +PostgreSQL documentation +--> + +<refentry id="app-ecpg"> + <indexterm zone="app-ecpg"> + <primary>ecpg</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>ecpg</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname><application>ecpg</application></refname> + <refpurpose>embedded SQL C preprocessor</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>ecpg</command> + <arg choice="opt" rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="plain" rep="repeat"><replaceable>file</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="app-ecpg-description"> + <title>Description</title> + + <para> + <command>ecpg</command> is the embedded SQL preprocessor for C + programs. It converts C programs with embedded SQL statements to + normal C code by replacing the SQL invocations with special + function calls. The output files can then be processed with any C + compiler tool chain. + </para> + + <para> + <command>ecpg</command> will convert each input file given on the + command line to the corresponding C output file. If an input file + name does not have any extension, <filename>.pgc</filename> is + assumed. The file's extension will be replaced + by <filename>.c</filename> to construct the output file name. + But the output file name can be overridden using the + <option>-o</option> option. + </para> + + <para> + If an input file name is just <literal>-</literal>, + <command>ecpg</command> reads the program from standard input + (and writes to standard output, unless that is overridden + with <option>-o</option>). + </para> + + <para> + This reference page does not describe the embedded SQL language. + See <xref linkend="ecpg"/> for more information on that topic. + </para> + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <command>ecpg</command> accepts the following command-line + arguments: + + <variablelist> + <varlistentry> + <term><option>-c</option></term> + <listitem> + <para> + Automatically generate certain C code from SQL code. Currently, this + works for <literal>EXEC SQL TYPE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C <replaceable>mode</replaceable></option></term> + <listitem> + <para> + Set a compatibility mode. <replaceable>mode</replaceable> can + be <literal>INFORMIX</literal>, + <literal>INFORMIX_SE</literal>, or <literal>ORACLE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable>symbol</replaceable></option></term> + <listitem> + <para> + Define a C preprocessor symbol. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h</option></term> + <listitem> + <para> + Process header files. When this option is specified, the output file + extension becomes <literal>.h</literal> not <literal>.c</literal>, + and the default input file extension is <literal>.pgh</literal> + not <literal>.pgc</literal>. Also, the <option>-c</option> option is + forced on. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <listitem> + <para> + Parse system include files as well. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I <replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Specify an additional include path, used to find files included + via <literal>EXEC SQL INCLUDE</literal>. Defaults are + <filename>.</filename> (current directory), + <filename>/usr/local/include</filename>, the + <productname>PostgreSQL</productname> include directory which + is defined at compile time (default: + <filename>/usr/local/pgsql/include</filename>), and + <filename>/usr/include</filename>, in that order. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable>filename</replaceable></option></term> + <listitem> + <para> + Specifies that <command>ecpg</command> should write all + its output to the given <replaceable>filename</replaceable>. + Write <literal>-o -</literal> to send all output to standard output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r <replaceable>option</replaceable></option></term> + <listitem> + <para> + Selects run-time behavior. <replaceable>Option</replaceable> can be + one of the following: + <variablelist> + <varlistentry> + <term><option>no_indicator</option></term> + <listitem> + <para> + Do not use indicators but instead use special values to represent + null values. Historically there have been databases using this approach. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>prepare</option></term> + <listitem> + <para> + Prepare all statements before using them. Libecpg will keep a cache of + prepared statements and reuse a statement if it gets executed again. If the + cache runs full, libecpg will free the least used statement. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>questionmarks</option></term> + <listitem> + <para> + Allow question mark as placeholder for compatibility reasons. + This used to be the default long ago. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option></term> + <listitem> + <para> + Turn on autocommit of transactions. In this mode, each SQL command is + automatically committed unless it is inside an explicit + transaction block. In the default mode, commands are committed + only when <command>EXEC SQL COMMIT</command> is issued. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <listitem> + <para> + Print additional information including the version and the + "include" path. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>ecpg</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>ecpg</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Notes</title> + + <para> + When compiling the preprocessed C code files, the compiler needs to + be able to find the <application>ECPG</application> header files in the + <productname>PostgreSQL</productname> include directory. Therefore, you might + have to use the <option>-I</option> option when invoking the compiler + (e.g., <literal>-I/usr/local/pgsql/include</literal>). + </para> + + <para> + Programs using C code with embedded SQL have to be linked against + the <filename>libecpg</filename> library, for example using the + linker options <literal>-L/usr/local/pgsql/lib -lecpg</literal>. + </para> + + <para> + The value of either of these directories that is appropriate for + the installation can be found out using <xref + linkend="app-pgconfig"/>. + </para> + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + If you have an embedded SQL C source file named + <filename>prog1.pgc</filename>, you can create an executable + program using the following sequence of commands: +<programlisting> +ecpg prog1.pgc +cc -I/usr/local/pgsql/include -c prog1.c +cc -o prog1 prog1.o -L/usr/local/pgsql/lib -lecpg +</programlisting></para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/end.sgml b/doc/src/sgml/ref/end.sgml new file mode 100644 index 0000000..4986529 --- /dev/null +++ b/doc/src/sgml/ref/end.sgml @@ -0,0 +1,112 @@ +<!-- +doc/src/sgml/ref/end.sgml +PostgreSQL documentation +--> + +<refentry id="sql-end"> + <indexterm zone="sql-end"> + <primary>END</primary> + </indexterm> + + <refmeta> + <refentrytitle>END</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>END</refname> + <refpurpose>commit the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +END [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>END</command> commits the current transaction. All changes + made by the transaction become visible to others and are guaranteed + to be durable if a crash occurs. This command is a + <productname>PostgreSQL</productname> extension + that is equivalent to <link linkend="sql-commit"><command>COMMIT</command></link>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>WORK</literal></term> + <term><literal>TRANSACTION</literal></term> + <listitem> + <para> + Optional key words. They have no effect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>AND CHAIN</literal></term> + <listitem> + <para> + If <literal>AND CHAIN</literal> is specified, a new transaction is + immediately started with the same transaction characteristics (see <xref + linkend="sql-set-transaction"/>) as the just finished one. Otherwise, + no new transaction is started. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-rollback"><command>ROLLBACK</command></link> to + abort a transaction. + </para> + + <para> + Issuing <command>END</command> when not inside a transaction does + no harm, but it will provoke a warning message. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To commit the current transaction and make all changes permanent: +<programlisting> +END; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>END</command> is a <productname>PostgreSQL</productname> + extension that provides functionality equivalent to <link + linkend="sql-commit"><command>COMMIT</command></link>, which is + specified in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/execute.sgml b/doc/src/sgml/ref/execute.sgml new file mode 100644 index 0000000..1d887f3 --- /dev/null +++ b/doc/src/sgml/ref/execute.sgml @@ -0,0 +1,121 @@ +<!-- +doc/src/sgml/ref/execute.sgml +PostgreSQL documentation +--> + +<refentry id="sql-execute"> + <indexterm zone="sql-execute"> + <primary>EXECUTE</primary> + </indexterm> + + <indexterm zone="sql-execute"> + <primary>prepared statements</primary> + <secondary>executing</secondary> + </indexterm> + + <refmeta> + <refentrytitle>EXECUTE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>EXECUTE</refname> + <refpurpose>execute a prepared statement</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +EXECUTE <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">parameter</replaceable> [, ...] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>EXECUTE</command> is used to execute a previously prepared + statement. Since prepared statements only exist for the duration of a + session, the prepared statement must have been created by a + <command>PREPARE</command> statement executed earlier in the + current session. + </para> + + <para> + If the <command>PREPARE</command> statement that created the statement + specified some parameters, a compatible set of parameters must be + passed to the <command>EXECUTE</command> statement, or else an + error is raised. Note that (unlike functions) prepared statements are + not overloaded based on the type or number of their parameters; the + name of a prepared statement must be unique within a database session. + </para> + + <para> + For more information on the creation and usage of prepared statements, + see <xref linkend="sql-prepare"/>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the prepared statement to execute. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">parameter</replaceable></term> + <listitem> + <para> + The actual value of a parameter to the prepared statement. This + must be an expression yielding a value that is compatible with + the data type of this parameter, as was determined when the + prepared statement was created. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + <para> + The command tag returned by <command>EXECUTE</command> + is that of the prepared statement, and not <literal>EXECUTE</literal>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + <para> + Examples are given in <xref linkend="sql-prepare-examples"/> + in the <xref linkend="sql-prepare"/> documentation. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard includes an <command>EXECUTE</command> statement, + but it is only for use in embedded SQL. This version of the + <command>EXECUTE</command> statement also uses a somewhat different + syntax. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-deallocate"/></member> + <member><xref linkend="sql-prepare"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/explain.sgml b/doc/src/sgml/ref/explain.sgml new file mode 100644 index 0000000..0fce622 --- /dev/null +++ b/doc/src/sgml/ref/explain.sgml @@ -0,0 +1,487 @@ +<!-- +doc/src/sgml/ref/explain.sgml +PostgreSQL documentation +--> + +<refentry id="sql-explain"> + <indexterm zone="sql-explain"> + <primary>EXPLAIN</primary> + </indexterm> + + <indexterm zone="sql-explain"> + <primary>prepared statements</primary> + <secondary>showing the query plan</secondary> + </indexterm> + + <indexterm zone="sql-explain"> + <primary>cursor</primary> + <secondary>showing the query plan</secondary> + </indexterm> + + <refmeta> + <refentrytitle>EXPLAIN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>EXPLAIN</refname> + <refpurpose>show the execution plan of a statement</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +EXPLAIN [ ( <replaceable class="parameter">option</replaceable> [, ...] ) ] <replaceable class="parameter">statement</replaceable> +EXPLAIN [ ANALYZE ] [ VERBOSE ] <replaceable class="parameter">statement</replaceable> + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + ANALYZE [ <replaceable class="parameter">boolean</replaceable> ] + VERBOSE [ <replaceable class="parameter">boolean</replaceable> ] + COSTS [ <replaceable class="parameter">boolean</replaceable> ] + SETTINGS [ <replaceable class="parameter">boolean</replaceable> ] + BUFFERS [ <replaceable class="parameter">boolean</replaceable> ] + WAL [ <replaceable class="parameter">boolean</replaceable> ] + TIMING [ <replaceable class="parameter">boolean</replaceable> ] + SUMMARY [ <replaceable class="parameter">boolean</replaceable> ] + FORMAT { TEXT | XML | JSON | YAML } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + This command displays the execution plan that the + <productname>PostgreSQL</productname> planner generates for the + supplied statement. The execution plan shows how the table(s) + referenced by the statement will be scanned — by plain sequential scan, + index scan, etc. — and if multiple tables are referenced, what join + algorithms will be used to bring together the required rows from + each input table. + </para> + + <para> + The most critical part of the display is the estimated statement execution + cost, which is the planner's guess at how long it will take to run the + statement (measured in cost units that are arbitrary, but conventionally + mean disk page fetches). Actually two numbers + are shown: the start-up cost before the first row can be returned, and + the total cost to return all the rows. For most queries the total cost + is what matters, but in contexts such as a subquery in <literal>EXISTS</literal>, the planner + will choose the smallest start-up cost instead of the smallest total cost + (since the executor will stop after getting one row, anyway). + Also, if you limit the number of rows to return with a <literal>LIMIT</literal> clause, + the planner makes an appropriate interpolation between the endpoint + costs to estimate which plan is really the cheapest. + </para> + + <para> + The <literal>ANALYZE</literal> option causes the statement to be actually + executed, not only planned. Then actual run time statistics are added to + the display, including the total elapsed time expended within each plan + node (in milliseconds) and the total number of rows it actually returned. + This is useful for seeing whether the planner's estimates + are close to reality. + </para> + + <important> + <para> + Keep in mind that the statement is actually executed when + the <literal>ANALYZE</literal> option is used. Although + <command>EXPLAIN</command> will discard any output that a + <command>SELECT</command> would return, other side effects of the + statement will happen as usual. If you wish to use + <command>EXPLAIN ANALYZE</command> on an + <command>INSERT</command>, <command>UPDATE</command>, + <command>DELETE</command>, <command>MERGE</command>, + <command>CREATE TABLE AS</command>, + or <command>EXECUTE</command> statement + without letting the command affect your data, use this approach: +<programlisting> +BEGIN; +EXPLAIN ANALYZE ...; +ROLLBACK; +</programlisting> + </para> + </important> + + <para> + Only the <literal>ANALYZE</literal> and <literal>VERBOSE</literal> options + can be specified, and only in that order, without surrounding the option + list in parentheses. Prior to <productname>PostgreSQL</productname> 9.0, + the unparenthesized syntax was the only one supported. It is expected that + all new options will be supported only in the parenthesized syntax. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>ANALYZE</literal></term> + <listitem> + <para> + Carry out the command and show actual run times and other statistics. + This parameter defaults to <literal>FALSE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VERBOSE</literal></term> + <listitem> + <para> + Display additional information regarding the plan. Specifically, include + the output column list for each node in the plan tree, schema-qualify + table and function names, always label variables in expressions with + their range table alias, and always print the name of each trigger for + which statistics are displayed. The query identifier will also be + displayed if one has been computed, see <xref + linkend="guc-compute-query-id"/> for more details. This parameter + defaults to <literal>FALSE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>COSTS</literal></term> + <listitem> + <para> + Include information on the estimated startup and total cost of each + plan node, as well as the estimated number of rows and the estimated + width of each row. + This parameter defaults to <literal>TRUE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SETTINGS</literal></term> + <listitem> + <para> + Include information on configuration parameters. Specifically, include + options affecting query planning with value different from the built-in + default value. This parameter defaults to <literal>FALSE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BUFFERS</literal></term> + <listitem> + <para> + Include information on buffer usage. Specifically, include the number of + shared blocks hit, read, dirtied, and written, the number of local blocks + hit, read, dirtied, and written, the number of temp blocks read and + written, and the time spent reading and writing data file blocks and + temporary file blocks (in milliseconds) if + <xref linkend="guc-track-io-timing"/> is enabled. A + <emphasis>hit</emphasis> means that a read was avoided because the block + was found already in cache when needed. + Shared blocks contain data from regular tables and indexes; + local blocks contain data from temporary tables and indexes; + while temporary blocks contain short-term working data used in sorts, + hashes, Materialize plan nodes, and similar cases. + The number of blocks <emphasis>dirtied</emphasis> indicates the number of + previously unmodified blocks that were changed by this query; while the + number of blocks <emphasis>written</emphasis> indicates the number of + previously-dirtied blocks evicted from cache by this backend during + query processing. + The number of blocks shown for an + upper-level node includes those used by all its child nodes. In text + format, only non-zero values are printed. It defaults to + <literal>FALSE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>WAL</literal></term> + <listitem> + <para> + Include information on WAL record generation. Specifically, include the + number of records, number of full page images (fpi) and the amount of WAL + generated in bytes. In text format, only non-zero values are printed. + This parameter may only be used when <literal>ANALYZE</literal> is also + enabled. It defaults to <literal>FALSE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TIMING</literal></term> + <listitem> + <para> + Include actual startup time and time spent in each node in the output. + The overhead of repeatedly reading the system clock can slow down the + query significantly on some systems, so it may be useful to set this + parameter to <literal>FALSE</literal> when only actual row counts, and + not exact times, are needed. Run time of the entire statement is + always measured, even when node-level timing is turned off with this + option. + This parameter may only be used when <literal>ANALYZE</literal> is also + enabled. It defaults to <literal>TRUE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SUMMARY</literal></term> + <listitem> + <para> + Include summary information (e.g., totaled timing information) after the + query plan. Summary information is included by default when + <literal>ANALYZE</literal> is used but otherwise is not included by + default, but can be enabled using this option. Planning time in + <command>EXPLAIN EXECUTE</command> includes the time required to fetch + the plan from the cache and the time required for re-planning, if + necessary. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORMAT</literal></term> + <listitem> + <para> + Specify the output format, which can be TEXT, XML, JSON, or YAML. + Non-text output contains the same information as the text output + format, but is easier for programs to parse. This parameter defaults to + <literal>TEXT</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">statement</replaceable></term> + <listitem> + <para> + Any <command>SELECT</command>, <command>INSERT</command>, <command>UPDATE</command>, + <command>DELETE</command>, <command>MERGE</command>, + <command>VALUES</command>, <command>EXECUTE</command>, + <command>DECLARE</command>, <command>CREATE TABLE AS</command>, or + <command>CREATE MATERIALIZED VIEW AS</command> statement, whose execution + plan you wish to see. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + The command's result is a textual description of the plan selected + for the <replaceable class="parameter">statement</replaceable>, + optionally annotated with execution statistics. + <xref linkend="using-explain"/> describes the information provided. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + In order to allow the <productname>PostgreSQL</productname> query + planner to make reasonably informed decisions when optimizing + queries, the <link + linkend="catalog-pg-statistic"><structname>pg_statistic</structname></link> + data should be up-to-date for all tables used in the query. Normally + the <link linkend="autovacuum">autovacuum daemon</link> will take care + of that automatically. But if a table has recently had substantial + changes in its contents, you might need to do a manual + <link linkend="sql-analyze"><command>ANALYZE</command></link> rather than wait for autovacuum to catch up + with the changes. + </para> + + <para> + In order to measure the run-time cost of each node in the execution + plan, the current implementation of <command>EXPLAIN + ANALYZE</command> adds profiling overhead to query execution. + As a result, running <command>EXPLAIN ANALYZE</command> + on a query can sometimes take significantly longer than executing + the query normally. The amount of overhead depends on the nature of + the query, as well as the platform being used. The worst case occurs + for plan nodes that in themselves require very little time per + execution, and on machines that have relatively slow operating + system calls for obtaining the time of day. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To show the plan for a simple query on a table with a single + <type>integer</type> column and 10000 rows: + +<programlisting> +EXPLAIN SELECT * FROM foo; + + QUERY PLAN +--------------------------------------------------------- + Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4) +(1 row) +</programlisting> + </para> + + <para> + Here is the same query, with JSON output formatting: +<programlisting> +EXPLAIN (FORMAT JSON) SELECT * FROM foo; + QUERY PLAN +-------------------------------- + [ + + { + + "Plan": { + + "Node Type": "Seq Scan",+ + "Relation Name": "foo", + + "Alias": "foo", + + "Startup Cost": 0.00, + + "Total Cost": 155.00, + + "Plan Rows": 10000, + + "Plan Width": 4 + + } + + } + + ] +(1 row) +</programlisting> + </para> + + <para> + If there is an index and we use a query with an indexable + <literal>WHERE</literal> condition, <command>EXPLAIN</command> + might show a different plan: + +<programlisting> +EXPLAIN SELECT * FROM foo WHERE i = 4; + + QUERY PLAN +-------------------------------------------------------------- + Index Scan using fi on foo (cost=0.00..5.98 rows=1 width=4) + Index Cond: (i = 4) +(2 rows) +</programlisting> + </para> + + <para> + Here is the same query, but in YAML format: +<programlisting> +EXPLAIN (FORMAT YAML) SELECT * FROM foo WHERE i='4'; + QUERY PLAN +------------------------------- + - Plan: + + Node Type: "Index Scan" + + Scan Direction: "Forward"+ + Index Name: "fi" + + Relation Name: "foo" + + Alias: "foo" + + Startup Cost: 0.00 + + Total Cost: 5.98 + + Plan Rows: 1 + + Plan Width: 4 + + Index Cond: "(i = 4)" +(1 row) +</programlisting> + + XML format is left as an exercise for the reader. + </para> + <para> + Here is the same plan with cost estimates suppressed: + +<programlisting> +EXPLAIN (COSTS FALSE) SELECT * FROM foo WHERE i = 4; + + QUERY PLAN +---------------------------- + Index Scan using fi on foo + Index Cond: (i = 4) +(2 rows) +</programlisting> + </para> + + <para> + Here is an example of a query plan for a query using an aggregate + function: + +<programlisting> +EXPLAIN SELECT sum(i) FROM foo WHERE i < 10; + + QUERY PLAN +-------------------------------------------------------------------&zwsp;-- + Aggregate (cost=23.93..23.93 rows=1 width=4) + -> Index Scan using fi on foo (cost=0.00..23.92 rows=6 width=4) + Index Cond: (i < 10) +(3 rows) +</programlisting> + </para> + + <para> + Here is an example of using <command>EXPLAIN EXECUTE</command> to + display the execution plan for a prepared query: + +<programlisting> +PREPARE query(int, int) AS SELECT sum(bar) FROM test + WHERE id > $1 AND id < $2 + GROUP BY foo; + +EXPLAIN ANALYZE EXECUTE query(100, 200); + + QUERY PLAN +-------------------------------------------------------------------&zwsp;----------------------------------------------------- + HashAggregate (cost=9.54..9.54 rows=1 width=8) (actual time=0.156..0.161 rows=11 loops=1) + Group Key: foo + -> Index Scan using test_pkey on test (cost=0.29..9.29 rows=50 width=8) (actual time=0.039..0.091 rows=99 loops=1) + Index Cond: ((id > $1) AND (id < $2)) + Planning time: 0.197 ms + Execution time: 0.225 ms +(6 rows) +</programlisting> + </para> + + <para> + Of course, the specific numbers shown here depend on the actual + contents of the tables involved. Also note that the numbers, and + even the selected query strategy, might vary between + <productname>PostgreSQL</productname> releases due to planner + improvements. In addition, the <command>ANALYZE</command> command + uses random sampling to estimate data statistics; therefore, it is + possible for cost estimates to change after a fresh run of + <command>ANALYZE</command>, even if the actual distribution of data + in the table has not changed. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>EXPLAIN</command> statement defined in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-analyze"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/fetch.sgml b/doc/src/sgml/ref/fetch.sgml new file mode 100644 index 0000000..f0f3ac2 --- /dev/null +++ b/doc/src/sgml/ref/fetch.sgml @@ -0,0 +1,418 @@ +<!-- +doc/src/sgml/ref/fetch.sgml +PostgreSQL documentation +--> + +<refentry id="sql-fetch"> + + <indexterm zone="sql-fetch"> + <primary>FETCH</primary> + </indexterm> + + <indexterm zone="sql-fetch"> + <primary>cursor</primary> + <secondary>FETCH</secondary> + </indexterm> + <refmeta> + <refentrytitle>FETCH</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>FETCH</refname> + <refpurpose>retrieve rows from a query using a cursor</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<!-- Note the "direction" bit is also in ref/move.sgml --> +<synopsis> +FETCH [ <replaceable class="parameter">direction</replaceable> ] [ FROM | IN ] <replaceable class="parameter">cursor_name</replaceable> + +<phrase>where <replaceable class="parameter">direction</replaceable> can be one of:</phrase> + + NEXT + PRIOR + FIRST + LAST + ABSOLUTE <replaceable class="parameter">count</replaceable> + RELATIVE <replaceable class="parameter">count</replaceable> + <replaceable class="parameter">count</replaceable> + ALL + FORWARD + FORWARD <replaceable class="parameter">count</replaceable> + FORWARD ALL + BACKWARD + BACKWARD <replaceable class="parameter">count</replaceable> + BACKWARD ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>FETCH</command> retrieves rows using a previously-created cursor. + </para> + + <para> + A cursor has an associated position, which is used by + <command>FETCH</command>. The cursor position can be before the first row of the + query result, on any particular row of the result, or after the last row + of the result. When created, a cursor is positioned before the first row. + After fetching some rows, the cursor is positioned on the row most recently + retrieved. If <command>FETCH</command> runs off the end of the available rows + then the cursor is left positioned after the last row, or before the first + row if fetching backward. <command>FETCH ALL</command> or <command>FETCH BACKWARD + ALL</command> will always leave the cursor positioned after the last row or before + the first row. + </para> + + <para> + The forms <literal>NEXT</literal>, <literal>PRIOR</literal>, <literal>FIRST</literal>, + <literal>LAST</literal>, <literal>ABSOLUTE</literal>, <literal>RELATIVE</literal> fetch + a single row after moving the cursor appropriately. If there is no + such row, an empty result is returned, and the cursor is left + positioned before the first row or after the last row as + appropriate. + </para> + + <para> + The forms using <literal>FORWARD</literal> and <literal>BACKWARD</literal> + retrieve the indicated number of rows moving in the forward or + backward direction, leaving the cursor positioned on the + last-returned row (or after/before all rows, if the <replaceable + class="parameter">count</replaceable> exceeds the number of rows + available). + </para> + + <para> + <literal>RELATIVE 0</literal>, <literal>FORWARD 0</literal>, and + <literal>BACKWARD 0</literal> all request fetching the current row without + moving the cursor, that is, re-fetching the most recently fetched + row. This will succeed unless the cursor is positioned before the + first row or after the last row; in which case, no row is returned. + </para> + + <note> + <para> + This page describes usage of cursors at the SQL command level. + If you are trying to use cursors inside a <application>PL/pgSQL</application> + function, the rules are different — + see <xref linkend="plpgsql-cursor-using"/>. + </para> + </note> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">direction</replaceable></term> + <listitem> + <para><replaceable class="parameter">direction</replaceable> defines + the fetch direction and number of rows to fetch. It can be one + of the following: + + <variablelist> + <varlistentry> + <term><literal>NEXT</literal></term> + <listitem> + <para> + Fetch the next row. This is the default if <replaceable + class="parameter">direction</replaceable> is omitted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PRIOR</literal></term> + <listitem> + <para> + Fetch the prior row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FIRST</literal></term> + <listitem> + <para> + Fetch the first row of the query (same as <literal>ABSOLUTE 1</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LAST</literal></term> + <listitem> + <para> + Fetch the last row of the query (same as <literal>ABSOLUTE -1</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ABSOLUTE <replaceable class="parameter">count</replaceable></literal></term> + <listitem> + <para> + Fetch the <replaceable + class="parameter">count</replaceable>'th row of the query, + or the <literal>abs(<replaceable + class="parameter">count</replaceable>)</literal>'th row from + the end if <replaceable + class="parameter">count</replaceable> is negative. Position + before first row or after last row if <replaceable + class="parameter">count</replaceable> is out of range; in + particular, <literal>ABSOLUTE 0</literal> positions before + the first row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RELATIVE <replaceable class="parameter">count</replaceable></literal></term> + <listitem> + <para> + Fetch the <replaceable + class="parameter">count</replaceable>'th succeeding row, or + the <literal>abs(<replaceable + class="parameter">count</replaceable>)</literal>'th prior + row if <replaceable class="parameter">count</replaceable> is + negative. <literal>RELATIVE 0</literal> re-fetches the + current row, if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">count</replaceable></term> + <listitem> + <para> + Fetch the next <replaceable + class="parameter">count</replaceable> rows (same as + <literal>FORWARD <replaceable + class="parameter">count</replaceable></literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Fetch all remaining rows (same as <literal>FORWARD ALL</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORWARD</literal></term> + <listitem> + <para> + Fetch the next row (same as <literal>NEXT</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORWARD <replaceable class="parameter">count</replaceable></literal></term> + <listitem> + <para> + Fetch the next <replaceable + class="parameter">count</replaceable> rows. + <literal>FORWARD 0</literal> re-fetches the current row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FORWARD ALL</literal></term> + <listitem> + <para> + Fetch all remaining rows. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BACKWARD</literal></term> + <listitem> + <para> + Fetch the prior row (same as <literal>PRIOR</literal>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BACKWARD <replaceable class="parameter">count</replaceable></literal></term> + <listitem> + <para> + Fetch the prior <replaceable + class="parameter">count</replaceable> rows (scanning + backwards). <literal>BACKWARD 0</literal> re-fetches the + current row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>BACKWARD ALL</literal></term> + <listitem> + <para> + Fetch all prior rows (scanning backwards). + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">count</replaceable></term> + <listitem> + <para><replaceable class="parameter">count</replaceable> is a + possibly-signed integer constant, determining the location or + number of rows to fetch. For <literal>FORWARD</literal> and + <literal>BACKWARD</literal> cases, specifying a negative <replaceable + class="parameter">count</replaceable> is equivalent to changing + the sense of <literal>FORWARD</literal> and <literal>BACKWARD</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">cursor_name</replaceable></term> + <listitem> + <para> + An open cursor's name. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, a <command>FETCH</command> command returns a command + tag of the form +<screen> +FETCH <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number + of rows fetched (possibly zero). Note that in + <application>psql</application>, the command tag will not actually be + displayed, since <application>psql</application> displays the fetched + rows instead. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The cursor should be declared with the <literal>SCROLL</literal> + option if one intends to use any variants of <command>FETCH</command> + other than <command>FETCH NEXT</command> or <command>FETCH FORWARD</command> with + a positive count. For simple queries + <productname>PostgreSQL</productname> will allow backwards fetch + from cursors not declared with <literal>SCROLL</literal>, but this + behavior is best not relied on. If the cursor is declared with + <literal>NO SCROLL</literal>, no backward fetches are allowed. + </para> + + <para> + <literal>ABSOLUTE</literal> fetches are not any faster than + navigating to the desired row with a relative move: the underlying + implementation must traverse all the intermediate rows anyway. + Negative absolute fetches are even worse: the query must be read to + the end to find the last row, and then traversed backward from + there. However, rewinding to the start of the query (as with + <literal>FETCH ABSOLUTE 0</literal>) is fast. + </para> + + <para> + <link linkend="sql-declare"><command>DECLARE</command></link> + is used to define a cursor. Use + <link linkend="sql-move"><command>MOVE</command></link> + to change cursor position without retrieving data. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example traverses a table using a cursor: + +<programlisting> +BEGIN WORK; + +-- Set up a cursor: +DECLARE liahona SCROLL CURSOR FOR SELECT * FROM films; + +-- Fetch the first 5 rows in the cursor liahona: +FETCH FORWARD 5 FROM liahona; + + code | title | did | date_prod | kind | len +-------+-------------------------+-----+------------+----------+------- + BL101 | The Third Man | 101 | 1949-12-23 | Drama | 01:44 + BL102 | The African Queen | 101 | 1951-08-11 | Romantic | 01:43 + JL201 | Une Femme est une Femme | 102 | 1961-03-12 | Romantic | 01:25 + P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08 + P_302 | Becket | 103 | 1964-02-03 | Drama | 02:28 + +-- Fetch the previous row: +FETCH PRIOR FROM liahona; + + code | title | did | date_prod | kind | len +-------+---------+-----+------------+--------+------- + P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08 + +-- Close the cursor and end the transaction: +CLOSE liahona; +COMMIT WORK; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard defines <command>FETCH</command> for use in + embedded SQL only. The variant of <command>FETCH</command> + described here returns the data as if it were a + <command>SELECT</command> result rather than placing it in host + variables. Other than this point, <command>FETCH</command> is + fully upward-compatible with the SQL standard. + </para> + + <para> + The <command>FETCH</command> forms involving + <literal>FORWARD</literal> and <literal>BACKWARD</literal>, as well + as the forms <literal>FETCH <replaceable + class="parameter">count</replaceable></literal> and <literal>FETCH + ALL</literal>, in which <literal>FORWARD</literal> is implicit, are + <productname>PostgreSQL</productname> extensions. + </para> + + <para> + The SQL standard allows only <literal>FROM</literal> preceding the cursor + name; the option to use <literal>IN</literal>, or to leave them out altogether, is + an extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-close"/></member> + <member><xref linkend="sql-declare"/></member> + <member><xref linkend="sql-move"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/grant.sgml b/doc/src/sgml/ref/grant.sgml new file mode 100644 index 0000000..f744b05 --- /dev/null +++ b/doc/src/sgml/ref/grant.sgml @@ -0,0 +1,479 @@ +<!-- +doc/src/sgml/ref/grant.sgml +PostgreSQL documentation +--> + +<refentry id="sql-grant"> + <indexterm zone="sql-grant"> + <primary>GRANT</primary> + </indexterm> + + <refmeta> + <refentrytitle>GRANT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>GRANT</refname> + <refpurpose>define access privileges</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER } + [, ...] | ALL [ PRIVILEGES ] } + ON { [ TABLE ] <replaceable class="parameter">table_name</replaceable> [, ...] + | ALL TABLES IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] } + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { SELECT | INSERT | UPDATE | REFERENCES } ( <replaceable class="parameter">column_name</replaceable> [, ...] ) + [, ...] | ALL [ PRIVILEGES ] ( <replaceable class="parameter">column_name</replaceable> [, ...] ) } + ON [ TABLE ] <replaceable class="parameter">table_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { USAGE | SELECT | UPDATE } + [, ...] | ALL [ PRIVILEGES ] } + ON { SEQUENCE <replaceable class="parameter">sequence_name</replaceable> [, ...] + | ALL SEQUENCES IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] } + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { CREATE | CONNECT | TEMPORARY | TEMP } [, ...] | ALL [ PRIVILEGES ] } + ON DATABASE <replaceable>database_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON DOMAIN <replaceable>domain_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON FOREIGN DATA WRAPPER <replaceable>fdw_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON FOREIGN SERVER <replaceable>server_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { EXECUTE | ALL [ PRIVILEGES ] } + ON { { FUNCTION | PROCEDURE | ROUTINE } <replaceable>routine_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...] + | ALL { FUNCTIONS | PROCEDURES | ROUTINES } IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] } + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON LANGUAGE <replaceable>lang_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } + ON LARGE OBJECT <replaceable class="parameter">loid</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { SET | ALTER SYSTEM } [, ... ] | ALL [ PRIVILEGES ] } + ON PARAMETER <replaceable class="parameter">configuration_parameter</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { { CREATE | USAGE } [, ...] | ALL [ PRIVILEGES ] } + ON SCHEMA <replaceable>schema_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { CREATE | ALL [ PRIVILEGES ] } + ON TABLESPACE <replaceable>tablespace_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT { USAGE | ALL [ PRIVILEGES ] } + ON TYPE <replaceable>type_name</replaceable> [, ...] + TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +GRANT <replaceable class="parameter">role_name</replaceable> [, ...] TO <replaceable class="parameter">role_specification</replaceable> [, ...] + [ WITH ADMIN OPTION ] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + [ GROUP ] <replaceable class="parameter">role_name</replaceable> + | PUBLIC + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-grant-description"> + <title>Description</title> + + <para> + The <command>GRANT</command> command has two basic variants: one + that grants privileges on a database object (table, column, view, + foreign table, sequence, database, foreign-data wrapper, foreign server, + function, procedure, procedural language, large object, configuration + parameter, schema, tablespace, or type), and one that grants + membership in a role. These variants are similar in many ways, but + they are different enough to be described separately. + </para> + + <refsect2 id="sql-grant-description-objects"> + <title>GRANT on Database Objects</title> + + <para> + This variant of the <command>GRANT</command> command gives specific + privileges on a database object to + one or more roles. These privileges are added + to those already granted, if any. + </para> + + <para> + The key word <literal>PUBLIC</literal> indicates that the + privileges are to be granted to all roles, including those that might + be created later. <literal>PUBLIC</literal> can be thought of as an + implicitly defined group that always includes all roles. + Any particular role will have the sum + of privileges granted directly to it, privileges granted to any role it + is presently a member of, and privileges granted to + <literal>PUBLIC</literal>. + </para> + + <para> + If <literal>WITH GRANT OPTION</literal> is specified, the recipient + of the privilege can in turn grant it to others. Without a grant + option, the recipient cannot do that. Grant options cannot be granted + to <literal>PUBLIC</literal>. + </para> + + <para> + If <literal>GRANTED BY</literal> is specified, the specified grantor must + be the current user. This clause is currently present in this form only + for SQL compatibility. + </para> + + <para> + There is no need to grant privileges to the owner of an object + (usually the user that created it), + as the owner has all privileges by default. (The owner could, + however, choose to revoke some of their own privileges for safety.) + </para> + + <para> + The right to drop an object, or to alter its definition in any way, is + not treated as a grantable privilege; it is inherent in the owner, + and cannot be granted or revoked. (However, a similar effect can be + obtained by granting or revoking membership in the role that owns + the object; see below.) The owner implicitly has all grant + options for the object, too. + </para> + + <para> + The possible privileges are: + + <variablelist> + <varlistentry> + <term><literal>SELECT</literal></term> + <term><literal>INSERT</literal></term> + <term><literal>UPDATE</literal></term> + <term><literal>DELETE</literal></term> + <term><literal>TRUNCATE</literal></term> + <term><literal>REFERENCES</literal></term> + <term><literal>TRIGGER</literal></term> + <term><literal>CREATE</literal></term> + <term><literal>CONNECT</literal></term> + <term><literal>TEMPORARY</literal></term> + <term><literal>EXECUTE</literal></term> + <term><literal>USAGE</literal></term> + <term><literal>SET</literal></term> + <term><literal>ALTER SYSTEM</literal></term> + <listitem> + <para> + Specific types of privileges, as defined in <xref linkend="ddl-priv"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TEMP</literal></term> + <listitem> + <para> + Alternative spelling for <literal>TEMPORARY</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL PRIVILEGES</literal></term> + <listitem> + <para> + Grant all of the privileges available for the object's type. + The <literal>PRIVILEGES</literal> key word is optional in + <productname>PostgreSQL</productname>, though it is required by + strict SQL. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The <literal>FUNCTION</literal> syntax works for plain functions, + aggregate functions, and window functions, but not for procedures; + use <literal>PROCEDURE</literal> for those. + Alternatively, use <literal>ROUTINE</literal> to refer to a function, + aggregate function, window function, or procedure regardless of its + precise type. + </para> + + <para> + There is also an option to grant privileges on all objects of the same + type within one or more schemas. This functionality is currently supported + only for tables, sequences, functions, and procedures. <literal>ALL + TABLES</literal> also affects views and foreign tables, just like the + specific-object <command>GRANT</command> command. <literal>ALL + FUNCTIONS</literal> also affects aggregate and window functions, but not + procedures, again just like the specific-object <command>GRANT</command> + command. Use <literal>ALL ROUTINES</literal> to include procedures. + </para> + </refsect2> + + <refsect2 id="sql-grant-description-roles"> + <title>GRANT on Roles</title> + + <para> + This variant of the <command>GRANT</command> command grants membership + in a role to one or more other roles. Membership in a role is significant + because it conveys the privileges granted to a role to each of its + members. + </para> + + <para> + If <literal>WITH ADMIN OPTION</literal> is specified, the member can + in turn grant membership in the role to others, and revoke membership + in the role as well. Without the admin option, ordinary users cannot + do that. A role is not considered to hold <literal>WITH ADMIN + OPTION</literal> on itself. Database superusers can grant or revoke + membership in any role to anyone. Roles having + <literal>CREATEROLE</literal> privilege can grant or revoke membership + in any role that is not a superuser. + </para> + + <para> + If <literal>GRANTED BY</literal> is specified, the grant is recorded as + having been done by the specified role. Only database superusers may + use this option, except when it names the same role executing the command. + </para> + + <para> + Unlike the case with privileges, membership in a role cannot be granted + to <literal>PUBLIC</literal>. Note also that this form of the command + does not allow the noise word <literal>GROUP</literal> + in <replaceable class="parameter">role_specification</replaceable>. + </para> + </refsect2> + </refsect1> + + + <refsect1 id="sql-grant-notes"> + <title>Notes</title> + + <para> + The <link linkend="sql-revoke"><command>REVOKE</command></link> command is used + to revoke access privileges. + </para> + + <para> + Since <productname>PostgreSQL</productname> 8.1, the concepts of users and + groups have been unified into a single kind of entity called a role. + It is therefore no longer necessary to use the keyword <literal>GROUP</literal> + to identify whether a grantee is a user or a group. <literal>GROUP</literal> + is still allowed in the command, but it is a noise word. + </para> + + <para> + A user may perform <command>SELECT</command>, <command>INSERT</command>, etc. on a + column if they hold that privilege for either the specific column or + its whole table. Granting the privilege at the table level and then + revoking it for one column will not do what one might wish: the + table-level grant is unaffected by a column-level operation. + </para> + + <para> + When a non-owner of an object attempts to <command>GRANT</command> privileges + on the object, the command will fail outright if the user has no + privileges whatsoever on the object. As long as some privilege is + available, the command will proceed, but it will grant only those + privileges for which the user has grant options. The <command>GRANT ALL + PRIVILEGES</command> forms will issue a warning message if no grant options are + held, while the other forms will issue a warning if grant options for + any of the privileges specifically named in the command are not held. + (In principle these statements apply to the object owner as well, but + since the owner is always treated as holding all grant options, the + cases can never occur.) + </para> + + <para> + It should be noted that database superusers can access + all objects regardless of object privilege settings. This + is comparable to the rights of <literal>root</literal> in a Unix system. + As with <literal>root</literal>, it's unwise to operate as a superuser + except when absolutely necessary. + </para> + + <para> + If a superuser chooses to issue a <command>GRANT</command> or <command>REVOKE</command> + command, the command is performed as though it were issued by the + owner of the affected object. In particular, privileges granted via + such a command will appear to have been granted by the object owner. + (For role membership, the membership appears to have been granted + by the containing role itself.) + </para> + + <para> + <command>GRANT</command> and <command>REVOKE</command> can also be done by a role + that is not the owner of the affected object, but is a member of the role + that owns the object, or is a member of a role that holds privileges + <literal>WITH GRANT OPTION</literal> on the object. In this case the + privileges will be recorded as having been granted by the role that + actually owns the object or holds the privileges + <literal>WITH GRANT OPTION</literal>. For example, if table + <literal>t1</literal> is owned by role <literal>g1</literal>, of which role + <literal>u1</literal> is a member, then <literal>u1</literal> can grant privileges + on <literal>t1</literal> to <literal>u2</literal>, but those privileges will appear + to have been granted directly by <literal>g1</literal>. Any other member + of role <literal>g1</literal> could revoke them later. + </para> + + <para> + If the role executing <command>GRANT</command> holds the required privileges + indirectly via more than one role membership path, it is unspecified + which containing role will be recorded as having done the grant. In such + cases it is best practice to use <command>SET ROLE</command> to become the + specific role you want to do the <command>GRANT</command> as. + </para> + + <para> + Granting permission on a table does not automatically extend + permissions to any sequences used by the table, including + sequences tied to <type>SERIAL</type> columns. Permissions on + sequences must be set separately. + </para> + + <para> + See <xref linkend="ddl-priv"/> for more information about specific + privilege types, as well as how to inspect objects' privileges. + </para> + </refsect1> + + <refsect1 id="sql-grant-examples"> + <title>Examples</title> + + <para> + Grant insert privilege to all users on table <literal>films</literal>: + +<programlisting> +GRANT INSERT ON films TO PUBLIC; +</programlisting> + </para> + + <para> + Grant all available privileges to user <literal>manuel</literal> on view + <literal>kinds</literal>: + +<programlisting> +GRANT ALL PRIVILEGES ON kinds TO manuel; +</programlisting> + + Note that while the above will indeed grant all privileges if executed by a + superuser or the owner of <literal>kinds</literal>, when executed by someone + else it will only grant those permissions for which the someone else has + grant options. + </para> + + <para> + Grant membership in role <literal>admins</literal> to user <literal>joe</literal>: + +<programlisting> +GRANT admins TO joe; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-grant-compatibility"> + <title>Compatibility</title> + + <para> + According to the SQL standard, the <literal>PRIVILEGES</literal> + key word in <literal>ALL PRIVILEGES</literal> is required. The + SQL standard does not support setting the privileges on more than + one object per command. + </para> + + <para> + <productname>PostgreSQL</productname> allows an object owner to revoke their + own ordinary privileges: for example, a table owner can make the table + read-only to themselves by revoking their own <literal>INSERT</literal>, + <literal>UPDATE</literal>, <literal>DELETE</literal>, and <literal>TRUNCATE</literal> + privileges. This is not possible according to the SQL standard. The + reason is that <productname>PostgreSQL</productname> treats the owner's + privileges as having been granted by the owner to themselves; therefore they + can revoke them too. In the SQL standard, the owner's privileges are + granted by an assumed entity <quote>_SYSTEM</quote>. Not being + <quote>_SYSTEM</quote>, the owner cannot revoke these rights. + </para> + + <para> + According to the SQL standard, grant options can be granted to + <literal>PUBLIC</literal>; PostgreSQL only supports granting grant options + to roles. + </para> + + <para> + The SQL standard allows the <literal>GRANTED BY</literal> option to + specify only <literal>CURRENT_USER</literal> or + <literal>CURRENT_ROLE</literal>. The other variants are PostgreSQL + extensions. + </para> + + <para> + The SQL standard provides for a <literal>USAGE</literal> privilege + on other kinds of objects: character sets, collations, + translations. + </para> + + <para> + In the SQL standard, sequences only have a <literal>USAGE</literal> + privilege, which controls the use of the <literal>NEXT VALUE FOR</literal> + expression, which is equivalent to the + function <function>nextval</function> in PostgreSQL. The sequence + privileges <literal>SELECT</literal> and <literal>UPDATE</literal> are + PostgreSQL extensions. The application of the + sequence <literal>USAGE</literal> privilege to + the <literal>currval</literal> function is also a PostgreSQL extension (as + is the function itself). + </para> + + <para> + Privileges on databases, tablespaces, schemas, languages, and + configuration parameters are + <productname>PostgreSQL</productname> extensions. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-revoke"/></member> + <member><xref linkend="sql-alterdefaultprivileges"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/import_foreign_schema.sgml b/doc/src/sgml/ref/import_foreign_schema.sgml new file mode 100644 index 0000000..f07f757 --- /dev/null +++ b/doc/src/sgml/ref/import_foreign_schema.sgml @@ -0,0 +1,166 @@ +<!-- +doc/src/sgml/ref/import_foreign_schema.sgml +PostgreSQL documentation +--> + +<refentry id="sql-importforeignschema"> + <indexterm zone="sql-importforeignschema"> + <primary>IMPORT FOREIGN SCHEMA</primary> + </indexterm> + + <refmeta> + <refentrytitle>IMPORT FOREIGN SCHEMA</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>IMPORT FOREIGN SCHEMA</refname> + <refpurpose>import table definitions from a foreign server</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +IMPORT FOREIGN SCHEMA <replaceable class="parameter">remote_schema</replaceable> + [ { LIMIT TO | EXCEPT } ( <replaceable class="parameter">table_name</replaceable> [, ...] ) ] + FROM SERVER <replaceable class="parameter">server_name</replaceable> + INTO <replaceable class="parameter">local_schema</replaceable> + [ OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ... ] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-importforeignschema-description"> + <title>Description</title> + + <para> + <command>IMPORT FOREIGN SCHEMA</command> creates foreign tables that + represent tables existing on a foreign server. The new foreign tables + will be owned by the user issuing the command and are created with + the correct column definitions and options to match the remote tables. + </para> + + <para> + By default, all tables and views existing in a particular schema on the + foreign server are imported. Optionally, the list of tables can be limited + to a specified subset, or specific tables can be excluded. The new foreign + tables are all created in the target schema, which must already exist. + </para> + + <para> + To use <command>IMPORT FOREIGN SCHEMA</command>, the user must have + <literal>USAGE</literal> privilege on the foreign server, as well as + <literal>CREATE</literal> privilege on the target schema. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">remote_schema</replaceable></term> + <listitem> + <para> + The remote schema to import from. The specific meaning of a remote schema + depends on the foreign data wrapper in use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LIMIT TO ( <replaceable class="parameter">table_name</replaceable> [, ...] )</literal></term> + <listitem> + <para> + Import only foreign tables matching one of the given table names. + Other tables existing in the foreign schema will be ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>EXCEPT ( <replaceable class="parameter">table_name</replaceable> [, ...] )</literal></term> + <listitem> + <para> + Exclude specified foreign tables from the import. All tables + existing in the foreign schema will be imported except the + ones listed here. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">server_name</replaceable></term> + <listitem> + <para> + The foreign server to import from. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">local_schema</replaceable></term> + <listitem> + <para> + The schema in which the imported foreign tables will be created. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OPTIONS ( <replaceable class="parameter">option</replaceable> '<replaceable class="parameter">value</replaceable>' [, ...] )</literal></term> + <listitem> + <para> + Options to be used during the import. + The allowed option names and values are specific to each foreign + data wrapper. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-importforeignschema-examples"> + <title>Examples</title> + + <para> + Import table definitions from a remote schema <structname>foreign_films</structname> + on server <structname>film_server</structname>, creating the foreign tables in + local schema <structname>films</structname>: + +<programlisting> +IMPORT FOREIGN SCHEMA foreign_films + FROM SERVER film_server INTO films; +</programlisting> + </para> + + <para> + As above, but import only the two tables <structname>actors</structname> and + <literal>directors</literal> (if they exist): + +<programlisting> +IMPORT FOREIGN SCHEMA foreign_films LIMIT TO (actors, directors) + FROM SERVER film_server INTO films; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-importforeignschema-compatibility"> + <title>Compatibility</title> + + <para> + The <command>IMPORT FOREIGN SCHEMA</command> command conforms to the + <acronym>SQL</acronym> standard, except that the <literal>OPTIONS</literal> + clause is a <productname>PostgreSQL</productname> extension. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createforeigntable"/></member> + <member><xref linkend="sql-createserver"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/initdb.sgml b/doc/src/sgml/ref/initdb.sgml new file mode 100644 index 0000000..8158896 --- /dev/null +++ b/doc/src/sgml/ref/initdb.sgml @@ -0,0 +1,588 @@ +<!-- +doc/src/sgml/ref/initdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-initdb"> + <indexterm zone="app-initdb"> + <primary>initdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>initdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>initdb</refname> + <refpurpose>create a new <productname>PostgreSQL</productname> database cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>initdb</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <group choice="plain"> + <group choice="opt"> + <arg choice="plain"><option>--pgdata</option></arg> + <arg choice="plain"><option>-D</option></arg> + </group> + <replaceable> directory</replaceable> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="r1-app-initdb-1"> + <title>Description</title> + <para> + <command>initdb</command> creates a new + <productname>PostgreSQL</productname> database cluster. A database + cluster is a collection of databases that are managed by a single + server instance. + </para> + + <para> + Creating a database cluster consists of creating the directories in + which the database data will live, generating the shared catalog + tables (tables that belong to the whole cluster rather than to any + particular database), and creating the <literal>postgres</literal>, + <literal>template1</literal>, and <literal>template0</literal> databases. + The <literal>postgres</literal> database is a default database meant + for use by users, utilities and third party applications. + <literal>template1</literal> and <literal>template0</literal> are + meant as source databases to be copied by later <command>CREATE + DATABASE</command> commands. <literal>template0</literal> should never + be modified, but you can add objects to <literal>template1</literal>, + which by default will be copied into databases created later. See + <xref linkend="manage-ag-templatedbs"/> for more details. + </para> + + <para> + Although <command>initdb</command> will attempt to create the + specified data directory, it might not have permission if the parent + directory of the desired data directory is root-owned. To initialize + in such a setup, create an empty data directory as root, then use + <command>chown</command> to assign ownership of that directory to the + database user account, then <command>su</command> to become the + database user to run <command>initdb</command>. + </para> + + <para> + <command>initdb</command> must be run as the user that will own the + server process, because the server needs to have access to the + files and directories that <command>initdb</command> creates. + Since the server cannot be run as root, you must not run + <command>initdb</command> as root either. (It will in fact refuse + to do so.) + </para> + + <para> + For security reasons the new cluster created by <command>initdb</command> + will only be accessible by the cluster owner by default. The + <option>--allow-group-access</option> option allows any user in the same + group as the cluster owner to read files in the cluster. This is useful + for performing backups as a non-privileged user. + </para> + + <para> + <command>initdb</command> initializes the database cluster's default locale + and character set encoding. These can also be set separately for each + database when it is created. <command>initdb</command> determines those + settings for the template databases, which will serve as the default for + all other databases. By default, <command>initdb</command> uses the + locale provider <literal>libc</literal>, takes the locale settings from + the environment, and determines the encoding from the locale settings. + This is almost always sufficient, unless there are special requirements. + </para> + + <para> + To choose a different locale for the cluster, use the option + <option>--locale</option>. There are also individual options + <option>--lc-*</option> (see below) to set values for the individual locale + categories. Note that inconsistent settings for different locale + categories can give nonsensical results, so this should be used with care. + </para> + + <para> + Alternatively, the ICU library can be used to provide locale services. + (Again, this only sets the default for subsequently created databases.) To + select this option, specify <literal>--locale-provider=icu</literal>. + To choose the specific ICU locale ID to apply, use the option + <option>--icu-locale</option>. Note that + for implementation reasons and to support legacy code, + <command>initdb</command> will still select and initialize libc locale + settings when the ICU locale provider is used. + </para> + + <para> + When <command>initdb</command> runs, it will print out the locale settings + it has chosen. If you have complex requirements or specified multiple + options, it is advisable to check that the result matches what was + intended. + </para> + + <para> + More details about locale settings can be found in <xref + linkend="locale"/>. + </para> + + <para> + To alter the default encoding, use the <option>--encoding</option>. + More details can be found in <xref linkend="multibyte"/>. + </para> + + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <variablelist> + <varlistentry> + <term><option>-A <replaceable class="parameter">authmethod</replaceable></option></term> + <term><option>--auth=<replaceable class="parameter">authmethod</replaceable></option></term> + <listitem> + <para> + This option specifies the default authentication method for local + users used in <filename>pg_hba.conf</filename> (<literal>host</literal> + and <literal>local</literal> lines). See <xref linkend="auth-pg-hba-conf"/> + for an overview of valid values. + </para> + + <para> + <command>initdb</command> will + prepopulate <filename>pg_hba.conf</filename> entries using the + specified authentication method for non-replication as well as + replication connections. + </para> + + <para> + Do not use <literal>trust</literal> unless you trust all local users on your + system. <literal>trust</literal> is the default for ease of installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--auth-host=<replaceable class="parameter">authmethod</replaceable></option></term> + <listitem> + <para> + This option specifies the authentication method for local users via + TCP/IP connections used in <filename>pg_hba.conf</filename> + (<literal>host</literal> lines). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--auth-local=<replaceable class="parameter">authmethod</replaceable></option></term> + <listitem> + <para> + This option specifies the authentication method for local users via + Unix-domain socket connections used in <filename>pg_hba.conf</filename> + (<literal>local</literal> lines). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable class="parameter">directory</replaceable></option></term> + <term><option>--pgdata=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + This option specifies the directory where the database cluster + should be stored. This is the only information required by + <command>initdb</command>, but you can avoid writing it by + setting the <envar>PGDATA</envar> environment variable, which + can be convenient since the database server + (<command>postgres</command>) can find the database + directory later by the same variable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E <replaceable class="parameter">encoding</replaceable></option></term> + <term><option>--encoding=<replaceable class="parameter">encoding</replaceable></option></term> + <listitem> + <para> + Selects the encoding of the template databases. This will also + be the default encoding of any database you create later, + unless you override it then. The default is derived from the locale, + if the libc locale provider is used, or <literal>UTF8</literal> if the + ICU locale provider is used. The character sets supported by + the <productname>PostgreSQL</productname> server are described + in <xref linkend="multibyte-charset-supported"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="app-initdb-allow-group-access" xreflabel="group access"> + <term><option>-g</option></term> + <term><option>--allow-group-access</option></term> + <listitem> + <para> + Allows users in the same group as the cluster owner to read all cluster + files created by <command>initdb</command>. This option is ignored + on <productname>Windows</productname> as it does not support + <acronym>POSIX</acronym>-style group permissions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--icu-locale=<replaceable>locale</replaceable></option></term> + <listitem> + <para> + Specifies the ICU locale ID, if the ICU locale provider is used. + </para> + </listitem> + </varlistentry> + + <varlistentry id="app-initdb-data-checksums" xreflabel="data checksums"> + <term><option>-k</option></term> + <term><option>--data-checksums</option></term> + <listitem> + <para> + Use checksums on data pages to help detect corruption by the + I/O system that would otherwise be silent. Enabling checksums + may incur a noticeable performance penalty. If set, checksums + are calculated for all objects, in all databases. All checksum + failures will be reported in the + <link linkend="monitoring-pg-stat-database-view"> + <structname>pg_stat_database</structname></link> view. + See <xref linkend="checksums" /> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--locale=<replaceable>locale</replaceable></option></term> + <listitem> + <para> + Sets the default locale for the database cluster. If this + option is not specified, the locale is inherited from the + environment that <command>initdb</command> runs in. Locale + support is described in <xref linkend="locale"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--lc-collate=<replaceable>locale</replaceable></option></term> + <term><option>--lc-ctype=<replaceable>locale</replaceable></option></term> + <term><option>--lc-messages=<replaceable>locale</replaceable></option></term> + <term><option>--lc-monetary=<replaceable>locale</replaceable></option></term> + <term><option>--lc-numeric=<replaceable>locale</replaceable></option></term> + <term><option>--lc-time=<replaceable>locale</replaceable></option></term> + + <listitem> + <para> + Like <option>--locale</option>, but only sets the locale in + the specified category. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-locale</option></term> + <listitem> + <para> + Equivalent to <option>--locale=C</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--locale-provider={<literal>libc</literal>|<literal>icu</literal>}</option></term> + <listitem> + <para> + This option sets the locale provider for databases created in the + new cluster. It can be overridden in the <command>CREATE + DATABASE</command> command when new databases are subsequently + created. The default is <literal>libc</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>initdb</command> will wait for all files to be + written safely to disk. This option causes <command>initdb</command> + to return without waiting, which is faster, but means that a + subsequent operating system crash can leave the data directory + corrupt. Generally, this option is useful for testing, but should not + be used when creating a production installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-instructions</option></term> + <listitem> + <para> + By default, <command>initdb</command> will write instructions for how + to start the cluster at the end of its output. This option causes + those instructions to be left out. This is primarily intended for use + by tools that wrap <command>initdb</command> in platform-specific + behavior, where those instructions are likely to be incorrect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--pwfile=<replaceable>filename</replaceable></option></term> + <listitem> + <para> + Makes <command>initdb</command> read the database superuser's password + from a file. The first line of the file is taken as the password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S</option></term> + <term><option>--sync-only</option></term> + <listitem> + <para> + Safely write all database files to disk and exit. This does not + perform any of the normal <application>initdb</application> operations. + Generally, this option is useful for ensuring reliable recovery after + changing <xref linkend="guc-fsync"/> from <literal>off</literal> to + <literal>on</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable>config</replaceable></option></term> + <term><option>--text-search-config=<replaceable>config</replaceable></option></term> + <listitem> + <para> + Sets the default text search configuration. + See <xref linkend="guc-default-text-search-config"/> for further information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Selects the user name of the database superuser. This defaults + to the name of the effective user running + <command>initdb</command>. It is really not important what the + superuser's name is, but one might choose to keep the + customary name <systemitem>postgres</systemitem>, even if the operating + system user's name is different. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--pwprompt</option></term> + <listitem> + <para> + Makes <command>initdb</command> prompt for a password + to give the database superuser. If you don't plan on using password + authentication, this is not important. Otherwise you won't be + able to use password authentication until you have a password + set up. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-X <replaceable class="parameter">directory</replaceable></option></term> + <term><option>--waldir=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + This option specifies the directory where the write-ahead log + should be stored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--wal-segsize=<replaceable>size</replaceable></option></term> + <listitem> + <para> + Set the <firstterm>WAL segment size</firstterm>, in megabytes. This + is the size of each individual file in the WAL log. The default size + is 16 megabytes. The value must be a power of 2 between 1 and 1024 + (megabytes). This option can only be set during initialization, and + cannot be changed later. + </para> + + <para> + It may be useful to adjust this size to control the granularity of + WAL log shipping or archiving. Also, in databases with a high volume + of WAL, the sheer number of WAL files per directory can become a + performance and management problem. Increasing the WAL file size + will reduce the number of WAL files. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other, less commonly used, options are also available: + + <variablelist> + <varlistentry> + <term><option>-d</option></term> + <term><option>--debug</option></term> + <listitem> + <para> + Print debugging output from the bootstrap backend and a few other + messages of lesser interest for the general public. + The bootstrap backend is the program <command>initdb</command> + uses to create the catalog tables. This option generates a tremendous + amount of extremely boring output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--discard-caches</option></term> + <listitem> + <para> + Run the bootstrap backend with the + <literal>debug_discard_caches=1</literal> option. + This takes a very long time and is only of use for deep debugging. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-L <replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Specifies where <command>initdb</command> should find + its input files to initialize the database cluster. This is + normally not necessary. You will be told if you need to + specify their location explicitly. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-clean</option></term> + <listitem> + <para> + By default, when <command>initdb</command> + determines that an error prevented it from completely creating the database + cluster, it removes any files it might have created before discovering + that it cannot finish the job. This option inhibits tidying-up and is + thus useful for debugging. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other options: + + <variablelist> + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>initdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>initdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATA</envar></term> + + <listitem> + <para> + Specifies the directory where the database cluster is to be + stored; can be overridden using the <option>-D</option> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>TZ</envar></term> + + <listitem> + <para> + Specifies the default time zone of the created database cluster. The + value should be a full time zone name + (see <xref linkend="datatype-timezones"/>). + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>initdb</command> can also be invoked via + <command>pg_ctl initdb</command>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pg-ctl"/></member> + <member><xref linkend="app-postgres"/></member> + <member><xref linkend="auth-pg-hba-conf"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml new file mode 100644 index 0000000..7cea703 --- /dev/null +++ b/doc/src/sgml/ref/insert.sgml @@ -0,0 +1,792 @@ +<!-- +doc/src/sgml/ref/insert.sgml +PostgreSQL documentation +--> + +<refentry id="sql-insert"> + <indexterm zone="sql-insert"> + <primary>INSERT</primary> + </indexterm> + + <refmeta> + <refentrytitle>INSERT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>INSERT</refname> + <refpurpose>create new rows in a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ] +INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replaceable class="parameter">alias</replaceable> ] [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] + [ OVERRIDING { SYSTEM | USER } VALUE ] + { DEFAULT VALUES | VALUES ( { <replaceable class="parameter">expression</replaceable> | DEFAULT } [, ...] ) [, ...] | <replaceable class="parameter">query</replaceable> } + [ ON CONFLICT [ <replaceable class="parameter">conflict_target</replaceable> ] <replaceable class="parameter">conflict_action</replaceable> ] + [ RETURNING * | <replaceable class="parameter">output_expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] ] + +<phrase>where <replaceable class="parameter">conflict_target</replaceable> can be one of:</phrase> + + ( { <replaceable class="parameter">index_column_name</replaceable> | ( <replaceable class="parameter">index_expression</replaceable> ) } [ COLLATE <replaceable class="parameter">collation</replaceable> ] [ <replaceable class="parameter">opclass</replaceable> ] [, ...] ) [ WHERE <replaceable class="parameter">index_predicate</replaceable> ] + ON CONSTRAINT <replaceable class="parameter">constraint_name</replaceable> + +<phrase>and <replaceable class="parameter">conflict_action</replaceable> is one of:</phrase> + + DO NOTHING + DO UPDATE SET { <replaceable class="parameter">column_name</replaceable> = { <replaceable class="parameter">expression</replaceable> | DEFAULT } | + ( <replaceable class="parameter">column_name</replaceable> [, ...] ) = [ ROW ] ( { <replaceable class="parameter">expression</replaceable> | DEFAULT } [, ...] ) | + ( <replaceable class="parameter">column_name</replaceable> [, ...] ) = ( <replaceable class="parameter">sub-SELECT</replaceable> ) + } [, ...] + [ WHERE <replaceable class="parameter">condition</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>INSERT</command> inserts new rows into a table. + One can insert one or more rows specified by value expressions, + or zero or more rows resulting from a query. + </para> + + <para> + The target column names can be listed in any order. If no list of + column names is given at all, the default is all the columns of the + table in their declared order; or the first <replaceable>N</replaceable> column + names, if there are only <replaceable>N</replaceable> columns supplied by the + <literal>VALUES</literal> clause or <replaceable>query</replaceable>. The values + supplied by the <literal>VALUES</literal> clause or <replaceable>query</replaceable> are + associated with the explicit or implicit column list left-to-right. + </para> + + <para> + Each column not present in the explicit or implicit column list will be + filled with a default value, either its declared default value + or null if there is none. + </para> + + <para> + If the expression for any column is not of the correct data type, + automatic type conversion will be attempted. + </para> + + <para> + <command>INSERT</command> into tables that lack unique indexes will + not be blocked by concurrent activity. Tables with unique indexes + might block if concurrent sessions perform actions that lock or modify + rows matching the unique index values being inserted; the details + are covered in <xref linkend="index-unique-checks"/>. + <literal>ON CONFLICT</literal> can be used to specify an alternative + action to raising a unique constraint or exclusion constraint + violation error. (See <xref linkend="sql-on-conflict"/> below.) + </para> + + <para> + The optional <literal>RETURNING</literal> clause causes <command>INSERT</command> + to compute and return value(s) based on each row actually inserted + (or updated, if an <literal>ON CONFLICT DO UPDATE</literal> clause was + used). This is primarily useful for obtaining values that were + supplied by defaults, such as a serial sequence number. However, + any expression using the table's columns is allowed. The syntax of + the <literal>RETURNING</literal> list is identical to that of the output + list of <command>SELECT</command>. Only rows that were successfully + inserted or updated will be returned. For example, if a row was + locked but not updated because an <literal>ON CONFLICT DO UPDATE + ... WHERE</literal> clause <replaceable + class="parameter">condition</replaceable> was not satisfied, the + row will not be returned. + </para> + + <para> + You must have <literal>INSERT</literal> privilege on a table in + order to insert into it. If <literal>ON CONFLICT DO UPDATE</literal> is + present, <literal>UPDATE</literal> privilege on the table is also + required. + </para> + + <para> + If a column list is specified, you only need + <literal>INSERT</literal> privilege on the listed columns. + Similarly, when <literal>ON CONFLICT DO UPDATE</literal> is specified, you + only need <literal>UPDATE</literal> privilege on the column(s) that are + listed to be updated. However, <literal>ON CONFLICT DO UPDATE</literal> + also requires <literal>SELECT</literal> privilege on any column whose + values are read in the <literal>ON CONFLICT DO UPDATE</literal> + expressions or <replaceable>condition</replaceable>. + </para> + + <para> + Use of the <literal>RETURNING</literal> clause requires <literal>SELECT</literal> + privilege on all columns mentioned in <literal>RETURNING</literal>. + If you use the <replaceable + class="parameter">query</replaceable> clause to insert rows from a + query, you of course need to have <literal>SELECT</literal> privilege on + any table or column used in the query. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <refsect2> + <title>Inserting</title> + + <para> + This section covers parameters that may be used when only + inserting new rows. Parameters <emphasis>exclusively</emphasis> + used with the <literal>ON CONFLICT</literal> clause are described + separately. + </para> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">with_query</replaceable></term> + <listitem> + <para> + The <literal>WITH</literal> clause allows you to specify one or more + subqueries that can be referenced by name in the <command>INSERT</command> + query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> + for details. + </para> + <para> + It is possible for the <replaceable class="parameter">query</replaceable> + (<command>SELECT</command> statement) + to also contain a <literal>WITH</literal> clause. In such a case both + sets of <replaceable>with_query</replaceable> can be referenced within + the <replaceable class="parameter">query</replaceable>, but the + second one takes precedence since it is more closely nested. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">alias</replaceable></term> + <listitem> + <para> + A substitute name for <replaceable + class="parameter">table_name</replaceable>. When an alias is + provided, it completely hides the actual name of the table. + This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> + targets a table named <varname>excluded</varname>, since that will otherwise + be taken as the name of the special table representing the row proposed + for insertion. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column in the table named by <replaceable + class="parameter">table_name</replaceable>. The column name + can be qualified with a subfield name or array subscript, if + needed. (Inserting into only some fields of a composite + column leaves the other fields null.) When referencing a + column with <literal>ON CONFLICT DO UPDATE</literal>, do not include + the table's name in the specification of a target column. For + example, <literal>INSERT INTO table_name ... ON CONFLICT DO UPDATE + SET table_name.col = 1</literal> is invalid (this follows the general + behavior for <command>UPDATE</command>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OVERRIDING SYSTEM VALUE</literal></term> + <listitem> + <para> + If this clause is specified, then any values supplied for identity + columns will override the default sequence-generated values. + </para> + + <para> + For an identity column defined as <literal>GENERATED ALWAYS</literal>, + it is an error to insert an explicit value (other than + <literal>DEFAULT</literal>) without specifying either + <literal>OVERRIDING SYSTEM VALUE</literal> or <literal>OVERRIDING USER + VALUE</literal>. (For an identity column defined as + <literal>GENERATED BY DEFAULT</literal>, <literal>OVERRIDING SYSTEM + VALUE</literal> is the normal behavior and specifying it does nothing, + but <productname>PostgreSQL</productname> allows it as an extension.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OVERRIDING USER VALUE</literal></term> + <listitem> + <para> + If this clause is specified, then any values supplied for identity + columns are ignored and the default sequence-generated values are + applied. + </para> + + <para> + This clause is useful for example when copying values between tables. + Writing <literal>INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM + tbl1</literal> will copy from <literal>tbl1</literal> all columns that + are not identity columns in <literal>tbl2</literal> while values for + the identity columns in <literal>tbl2</literal> will be generated by + the sequences associated with <literal>tbl2</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT VALUES</literal></term> + <listitem> + <para> + All columns will be filled with their default values, as if + <literal>DEFAULT</literal> were explicitly specified for each column. + (An <literal>OVERRIDING</literal> clause is not permitted in this + form.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + An expression or value to assign to the corresponding column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + The corresponding column will be filled with its default value. An + identity column will be filled with a new value generated by the + associated sequence. For a generated column, specifying this is + permitted but merely specifies the normal behavior of computing the + column from its generation expression. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">query</replaceable></term> + <listitem> + <para> + A query (<command>SELECT</command> statement) that supplies the + rows to be inserted. Refer to the + <xref linkend="sql-select"/> + statement for a description of the syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_expression</replaceable></term> + <listitem> + <para> + An expression to be computed and returned by the + <command>INSERT</command> command after each row is inserted or + updated. The expression can use any column names of the table + named by <replaceable + class="parameter">table_name</replaceable>. Write + <literal>*</literal> to return all columns of the inserted or updated + row(s). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_name</replaceable></term> + <listitem> + <para> + A name to use for a returned column. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + + <refsect2 id="sql-on-conflict" xreflabel="ON CONFLICT Clause"> + <title><literal>ON CONFLICT</literal> Clause</title> + <indexterm zone="sql-insert"> + <primary>UPSERT</primary> + </indexterm> + <indexterm zone="sql-insert"> + <primary>ON CONFLICT</primary> + </indexterm> + <para> + The optional <literal>ON CONFLICT</literal> clause specifies an + alternative action to raising a unique violation or exclusion + constraint violation error. For each individual row proposed for + insertion, either the insertion proceeds, or, if an + <emphasis>arbiter</emphasis> constraint or index specified by + <parameter>conflict_target</parameter> is violated, the + alternative <parameter>conflict_action</parameter> is taken. + <literal>ON CONFLICT DO NOTHING</literal> simply avoids inserting + a row as its alternative action. <literal>ON CONFLICT DO + UPDATE</literal> updates the existing row that conflicts with the + row proposed for insertion as its alternative action. + </para> + + <para> + <parameter>conflict_target</parameter> can perform + <emphasis>unique index inference</emphasis>. When performing + inference, it consists of one or more <replaceable + class="parameter">index_column_name</replaceable> columns and/or + <replaceable class="parameter">index_expression</replaceable> + expressions, and an optional <replaceable class="parameter">index_predicate</replaceable>. All <replaceable + class="parameter">table_name</replaceable> unique indexes that, + without regard to order, contain exactly the + <parameter>conflict_target</parameter>-specified + columns/expressions are inferred (chosen) as arbiter indexes. If + an <replaceable class="parameter">index_predicate</replaceable> is + specified, it must, as a further requirement for inference, + satisfy arbiter indexes. Note that this means a non-partial + unique index (a unique index without a predicate) will be inferred + (and thus used by <literal>ON CONFLICT</literal>) if such an index + satisfying every other criteria is available. If an attempt at + inference is unsuccessful, an error is raised. + </para> + + <para> + <literal>ON CONFLICT DO UPDATE</literal> guarantees an atomic + <command>INSERT</command> or <command>UPDATE</command> outcome; + provided there is no independent error, one of those two outcomes + is guaranteed, even under high concurrency. This is also known as + <firstterm>UPSERT</firstterm> — <quote>UPDATE or + INSERT</quote>. + </para> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">conflict_target</replaceable></term> + <listitem> + <para> + Specifies which conflicts <literal>ON CONFLICT</literal> takes + the alternative action on by choosing <firstterm>arbiter + indexes</firstterm>. Either performs <emphasis>unique index + inference</emphasis>, or names a constraint explicitly. For + <literal>ON CONFLICT DO NOTHING</literal>, it is optional to + specify a <parameter>conflict_target</parameter>; when + omitted, conflicts with all usable constraints (and unique + indexes) are handled. For <literal>ON CONFLICT DO + UPDATE</literal>, a <parameter>conflict_target</parameter> + <emphasis>must</emphasis> be provided. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">conflict_action</replaceable></term> + <listitem> + <para> + <parameter>conflict_action</parameter> specifies an + alternative <literal>ON CONFLICT</literal> action. It can be + either <literal>DO NOTHING</literal>, or a <literal>DO + UPDATE</literal> clause specifying the exact details of the + <literal>UPDATE</literal> action to be performed in case of a + conflict. The <literal>SET</literal> and + <literal>WHERE</literal> clauses in <literal>ON CONFLICT DO + UPDATE</literal> have access to the existing row using the + table's name (or an alias), and to the row proposed for insertion + using the special <varname>excluded</varname> table. + <literal>SELECT</literal> privilege is required on any column in the + target table where corresponding <varname>excluded</varname> + columns are read. + </para> + <para> + Note that the effects of all per-row <literal>BEFORE + INSERT</literal> triggers are reflected in + <varname>excluded</varname> values, since those effects may + have contributed to the row being excluded from insertion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_column_name</replaceable></term> + <listitem> + <para> + The name of a <replaceable + class="parameter">table_name</replaceable> column. Used to + infer arbiter indexes. Follows <command>CREATE + INDEX</command> format. <literal>SELECT</literal> privilege on + <replaceable class="parameter">index_column_name</replaceable> + is required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_expression</replaceable></term> + <listitem> + <para> + Similar to <replaceable + class="parameter">index_column_name</replaceable>, but used to + infer expressions on <replaceable + class="parameter">table_name</replaceable> columns appearing + within index definitions (not simple columns). Follows + <command>CREATE INDEX</command> format. <literal>SELECT</literal> + privilege on any column appearing within <replaceable + class="parameter">index_expression</replaceable> is required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">collation</replaceable></term> + <listitem> + <para> + When specified, mandates that corresponding <replaceable + class="parameter">index_column_name</replaceable> or + <replaceable class="parameter">index_expression</replaceable> + use a particular collation in order to be matched during + inference. Typically this is omitted, as collations usually + do not affect whether or not a constraint violation occurs. + Follows <command>CREATE INDEX</command> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">opclass</replaceable></term> + <listitem> + <para> + When specified, mandates that corresponding <replaceable + class="parameter">index_column_name</replaceable> or + <replaceable class="parameter">index_expression</replaceable> + use particular operator class in order to be matched during + inference. Typically this is omitted, as the + <emphasis>equality</emphasis> semantics are often equivalent + across a type's operator classes anyway, or because it's + sufficient to trust that the defined unique indexes have the + pertinent definition of equality. Follows <command>CREATE + INDEX</command> format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">index_predicate</replaceable></term> + <listitem> + <para> + Used to allow inference of partial unique indexes. Any + indexes that satisfy the predicate (which need not actually be + partial indexes) can be inferred. Follows <command>CREATE + INDEX</command> format. <literal>SELECT</literal> privilege on any + column appearing within <replaceable + class="parameter">index_predicate</replaceable> is required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">constraint_name</replaceable></term> + <listitem> + <para> + Explicitly specifies an arbiter + <emphasis>constraint</emphasis> by name, rather than inferring + a constraint or index. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + An expression that returns a value of type + <type>boolean</type>. Only rows for which this expression + returns <literal>true</literal> will be updated, although all + rows will be locked when the <literal>ON CONFLICT DO UPDATE</literal> + action is taken. Note that + <replaceable>condition</replaceable> is evaluated last, after + a conflict has been identified as a candidate to update. + </para> + </listitem> + </varlistentry> + </variablelist> + <para> + Note that exclusion constraints are not supported as arbiters with + <literal>ON CONFLICT DO UPDATE</literal>. In all cases, only + <literal>NOT DEFERRABLE</literal> constraints and unique indexes + are supported as arbiters. + </para> + + <para> + <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> + clause is a <quote>deterministic</quote> statement. This means + that the command will not be allowed to affect any single existing + row more than once; a cardinality violation error will be raised + when this situation arises. Rows proposed for insertion should + not duplicate each other in terms of attributes constrained by an + arbiter index or constraint. + </para> + + <para> + Note that it is currently not supported for the + <literal>ON CONFLICT DO UPDATE</literal> clause of an + <command>INSERT</command> applied to a partitioned table to update the + partition key of a conflicting row such that it requires the row be moved + to a new partition. + </para> + <tip> + <para> + It is often preferable to use unique index inference rather than + naming a constraint directly using <literal>ON CONFLICT ON + CONSTRAINT</literal> <replaceable class="parameter"> + constraint_name</replaceable>. Inference will continue to work + correctly when the underlying index is replaced by another more + or less equivalent index in an overlapping way, for example when + using <literal>CREATE UNIQUE INDEX ... CONCURRENTLY</literal> + before dropping the index being replaced. + </para> + </tip> + + </refsect2> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, an <command>INSERT</command> command returns a command + tag of the form +<screen> +INSERT <replaceable>oid</replaceable> <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number of + rows inserted or updated. <replaceable>oid</replaceable> is always 0 (it + used to be the <acronym>OID</acronym> assigned to the inserted row if + <replaceable>count</replaceable> was exactly one and the target table was + declared <literal>WITH OIDS</literal> and 0 otherwise, but creating a table + <literal>WITH OIDS</literal> is not supported anymore). + </para> + + <para> + If the <command>INSERT</command> command contains a <literal>RETURNING</literal> + clause, the result will be similar to that of a <command>SELECT</command> + statement containing the columns and values defined in the + <literal>RETURNING</literal> list, computed over the row(s) inserted or + updated by the command. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If the specified table is a partitioned table, each row is routed to + the appropriate partition and inserted into it. If the specified table + is a partition, an error will occur if one of the input rows violates + the partition constraint. + </para> + + <para> + You may also wish to consider using <command>MERGE</command>, since that + allows mixing <command>INSERT</command>, <command>UPDATE</command>, and + <command>DELETE</command> within a single statement. + See <xref linkend="sql-merge"/>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Insert a single row into table <literal>films</literal>: + +<programlisting> +INSERT INTO films VALUES + ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); +</programlisting> + </para> + + <para> + In this example, the <literal>len</literal> column is + omitted and therefore it will have the default value: + +<programlisting> +INSERT INTO films (code, title, did, date_prod, kind) + VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama'); +</programlisting> + </para> + + <para> + This example uses the <literal>DEFAULT</literal> clause for + the date columns rather than specifying a value: + +<programlisting> +INSERT INTO films VALUES + ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes'); +INSERT INTO films (code, title, did, date_prod, kind) + VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama'); +</programlisting> + </para> + + <para> + To insert a row consisting entirely of default values: + +<programlisting> +INSERT INTO films DEFAULT VALUES; +</programlisting> + </para> + + <para> + To insert multiple rows using the multirow <command>VALUES</command> syntax: + +<programlisting> +INSERT INTO films (code, title, did, date_prod, kind) VALUES + ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'), + ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy'); +</programlisting> + </para> + + <para> + This example inserts some rows into table + <literal>films</literal> from a table <literal>tmp_films</literal> + with the same column layout as <literal>films</literal>: + +<programlisting> +INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07'; +</programlisting> + </para> + + <para> + This example inserts into array columns: + +<programlisting> +-- Create an empty 3x3 gameboard for noughts-and-crosses +INSERT INTO tictactoe (game, board[1:3][1:3]) + VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}'); +-- The subscripts in the above example aren't really needed +INSERT INTO tictactoe (game, board) + VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}'); +</programlisting> + </para> + + <para> + Insert a single row into table <literal>distributors</literal>, returning + the sequence number generated by the <literal>DEFAULT</literal> clause: + +<programlisting> +INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') + RETURNING did; +</programlisting> + </para> + + <para> + Increment the sales count of the salesperson who manages the + account for Acme Corporation, and record the whole updated row + along with current time in a log table: +<programlisting> +WITH upd AS ( + UPDATE employees SET sales_count = sales_count + 1 WHERE id = + (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation') + RETURNING * +) +INSERT INTO employees_log SELECT *, current_timestamp FROM upd; +</programlisting> + </para> + <para> + Insert or update new distributors as appropriate. Assumes a unique + index has been defined that constrains values appearing in the + <literal>did</literal> column. Note that the special + <varname>excluded</varname> table is used to reference values originally + proposed for insertion: +<programlisting> +INSERT INTO distributors (did, dname) + VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc') + ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname; +</programlisting> + </para> + <para> + Insert a distributor, or do nothing for rows proposed for insertion + when an existing, excluded row (a row with a matching constrained + column or columns after before row insert triggers fire) exists. + Example assumes a unique index has been defined that constrains + values appearing in the <literal>did</literal> column: +<programlisting> +INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH') + ON CONFLICT (did) DO NOTHING; +</programlisting> + </para> + <para> + Insert or update new distributors as appropriate. Example assumes + a unique index has been defined that constrains values appearing in + the <literal>did</literal> column. <literal>WHERE</literal> clause is + used to limit the rows actually updated (any existing row not + updated will still be locked, though): +<programlisting> +-- Don't update existing distributors based in a certain ZIP code +INSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil Distribution') + ON CONFLICT (did) DO UPDATE + SET dname = EXCLUDED.dname || ' (formerly ' || d.dname || ')' + WHERE d.zipcode <> '21201'; + +-- Name a constraint directly in the statement (uses associated +-- index to arbitrate taking the DO NOTHING action) +INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design') + ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING; +</programlisting> + </para> + <para> + Insert new distributor if possible; otherwise + <literal>DO NOTHING</literal>. Example assumes a unique index has been + defined that constrains values appearing in the + <literal>did</literal> column on a subset of rows where the + <literal>is_active</literal> Boolean column evaluates to + <literal>true</literal>: +<programlisting> +-- This statement could infer a partial unique index on "did" +-- with a predicate of "WHERE is_active", but it could also +-- just use a regular unique constraint on "did" +INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International') + ON CONFLICT (did) WHERE is_active DO NOTHING; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>INSERT</command> conforms to the SQL standard, except that + the <literal>RETURNING</literal> clause is a + <productname>PostgreSQL</productname> extension, as is the ability + to use <literal>WITH</literal> with <command>INSERT</command>, and the ability to + specify an alternative action with <literal>ON CONFLICT</literal>. + Also, the case in + which a column name list is omitted, but not all the columns are + filled from the <literal>VALUES</literal> clause or <replaceable>query</replaceable>, + is disallowed by the standard. If you prefer a more SQL standard + conforming statement than <literal>ON CONFLICT</literal>, see + <xref linkend="sql-merge"/>. + </para> + + <para> + The SQL standard specifies that <literal>OVERRIDING SYSTEM VALUE</literal> + can only be specified if an identity column that is generated always + exists. PostgreSQL allows the clause in any case and ignores it if it is + not applicable. + </para> + + <para> + Possible limitations of the <replaceable + class="parameter">query</replaceable> clause are documented under + <xref linkend="sql-select"/>. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/listen.sgml b/doc/src/sgml/ref/listen.sgml new file mode 100644 index 0000000..2fab9d6 --- /dev/null +++ b/doc/src/sgml/ref/listen.sgml @@ -0,0 +1,153 @@ +<!-- +doc/src/sgml/ref/listen.sgml +PostgreSQL documentation +--> + +<refentry id="sql-listen"> + <indexterm zone="sql-listen"> + <primary>LISTEN</primary> + </indexterm> + + <refmeta> + <refentrytitle>LISTEN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>LISTEN</refname> + <refpurpose>listen for a notification</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +LISTEN <replaceable class="parameter">channel</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>LISTEN</command> registers the current session as a + listener on the notification channel named <replaceable + class="parameter">channel</replaceable>. + If the current session is already registered as a listener for + this notification channel, nothing is done. + </para> + + <para> + Whenever the command <command>NOTIFY <replaceable + class="parameter">channel</replaceable></command> is invoked, either + by this session or another one connected to the same database, all + the sessions currently listening on that notification channel are + notified, and each will in turn notify its connected client + application. + </para> + + <para> + A session can be unregistered for a given notification channel with the + <command>UNLISTEN</command> command. A session's listen + registrations are automatically cleared when the session ends. + </para> + + <para> + The method a client application must use to detect notification events depends on + which <productname>PostgreSQL</productname> application programming interface it + uses. With the <application>libpq</application> library, the application issues + <command>LISTEN</command> as an ordinary SQL command, and then must + periodically call the function <function>PQnotifies</function> to find out + whether any notification events have been received. Other interfaces such as + <application>libpgtcl</application> provide higher-level methods for handling notify events; indeed, + with <application>libpgtcl</application> the application programmer should not even issue + <command>LISTEN</command> or <command>UNLISTEN</command> directly. See the + documentation for the interface you are using for more details. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">channel</replaceable></term> + <listitem> + <para> + Name of a notification channel (any identifier). + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>LISTEN</command> takes effect at transaction commit. + If <command>LISTEN</command> or <command>UNLISTEN</command> is executed + within a transaction that later rolls back, the set of notification + channels being listened to is unchanged. + </para> + + <para> + A transaction that has executed <command>LISTEN</command> cannot be + prepared for two-phase commit. + </para> + + <para> + There is a race condition when first setting up a listening session: + if concurrently-committing transactions are sending notify events, + exactly which of those will the newly listening session receive? + The answer is that the session will receive all events committed after + an instant during the transaction's commit step. But that is slightly + later than any database state that the transaction could have observed + in queries. This leads to the following rule for + using <command>LISTEN</command>: first execute (and commit!) that + command, then in a new transaction inspect the database state as needed + by the application logic, then rely on notifications to find out about + subsequent changes to the database state. The first few received + notifications might refer to updates already observed in the initial + database inspection, but this is usually harmless. + </para> + + <para> + <xref linkend="sql-notify"/> + contains a more extensive + discussion of the use of <command>LISTEN</command> and + <command>NOTIFY</command>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Configure and execute a listen/notify sequence from + <application>psql</application>: + +<programlisting> +LISTEN virtual; +NOTIFY virtual; +Asynchronous notification "virtual" received from server process with PID 8448. +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>LISTEN</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-notify"/></member> + <member><xref linkend="sql-unlisten"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/load.sgml b/doc/src/sgml/ref/load.sgml new file mode 100644 index 0000000..2c214dd --- /dev/null +++ b/doc/src/sgml/ref/load.sgml @@ -0,0 +1,81 @@ +<!-- +doc/src/sgml/ref/load.sgml +PostgreSQL documentation +--> + +<refentry id="sql-load"> + <indexterm zone="sql-load"> + <primary>LOAD</primary> + </indexterm> + + <refmeta> + <refentrytitle>LOAD</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>LOAD</refname> + <refpurpose>load a shared library file</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +LOAD '<replaceable class="parameter">filename</replaceable>' +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-load-description"> + <title>Description</title> + + <para> + This command loads a shared library file into the <productname>PostgreSQL</productname> + server's address space. If the file has been loaded already, + the command does nothing. Shared library files that contain C functions + are automatically loaded whenever one of their functions is called. + Therefore, an explicit <command>LOAD</command> is usually only needed to + load a library that modifies the server's behavior through <quote>hooks</quote> + rather than providing a set of functions. + </para> + + <para> + The library file name is typically given as just a bare file name, + which is sought in the server's library search path (set + by <xref linkend="guc-dynamic-library-path"/>). Alternatively it can be + given as a full path name. In either case the platform's standard shared + library file name extension may be omitted. + See <xref linkend="xfunc-c-dynload"/> for more information on this topic. + </para> + + <indexterm> + <primary><filename>$libdir/plugins</filename></primary> + </indexterm> + + <para> + Non-superusers can only apply <command>LOAD</command> to library files + located in <filename>$libdir/plugins/</filename> — the specified + <replaceable class="parameter">filename</replaceable> must begin + with exactly that string. (It is the database administrator's + responsibility to ensure that only <quote>safe</quote> libraries + are installed there.) + </para> + </refsect1> + + <refsect1 id="sql-load-compat"> + <title>Compatibility</title> + + <para> + <command>LOAD</command> is a <productname>PostgreSQL</productname> + extension. + </para> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <para> + <xref linkend="sql-createfunction"/> + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/lock.sgml b/doc/src/sgml/ref/lock.sgml new file mode 100644 index 0000000..19e7194 --- /dev/null +++ b/doc/src/sgml/ref/lock.sgml @@ -0,0 +1,266 @@ +<!-- +doc/src/sgml/ref/lock.sgml +PostgreSQL documentation +--> + +<refentry id="sql-lock"> + <indexterm zone="sql-lock"> + <primary>LOCK</primary> + </indexterm> + + <refmeta> + <refentrytitle>LOCK</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>LOCK</refname> + <refpurpose>lock a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +LOCK [ TABLE ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] [, ...] [ IN <replaceable class="parameter">lockmode</replaceable> MODE ] [ NOWAIT ] + +<phrase>where <replaceable class="parameter">lockmode</replaceable> is one of:</phrase> + + ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE + | SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>LOCK TABLE</command> obtains a table-level lock, waiting + if necessary for any conflicting locks to be released. If + <literal>NOWAIT</literal> is specified, <command>LOCK + TABLE</command> does not wait to acquire the desired lock: if it + cannot be acquired immediately, the command is aborted and an + error is emitted. Once obtained, the lock is held for the + remainder of the current transaction. (There is no <command>UNLOCK + TABLE</command> command; locks are always released at transaction + end.) + </para> + + <para> + When a view is locked, all relations appearing in the view definition + query are also locked recursively with the same lock mode. + </para> + + <para> + When acquiring locks automatically for commands that reference + tables, <productname>PostgreSQL</productname> always uses the least + restrictive lock mode possible. <command>LOCK TABLE</command> + provides for cases when you might need more restrictive locking. + For example, suppose an application runs a transaction at the + <literal>READ COMMITTED</literal> isolation level and needs to ensure that + data in a table remains stable for the duration of the transaction. + To achieve this you could obtain <literal>SHARE</literal> lock mode over the + table before querying. This will prevent concurrent data changes + and ensure subsequent reads of the table see a stable view of + committed data, because <literal>SHARE</literal> lock mode conflicts with + the <literal>ROW EXCLUSIVE</literal> lock acquired by writers, and your + <command>LOCK TABLE <replaceable + class="parameter">name</replaceable> IN SHARE MODE</command> + statement will wait until any concurrent holders of <literal>ROW + EXCLUSIVE</literal> mode locks commit or roll back. Thus, once you + obtain the lock, there are no uncommitted writes outstanding; + furthermore none can begin until you release the lock. + </para> + + <para> + To achieve a similar effect when running a transaction at the + <literal>REPEATABLE READ</literal> or <literal>SERIALIZABLE</literal> + isolation level, you have to execute the <command>LOCK TABLE</command> statement + before executing any <command>SELECT</command> or data modification statement. + A <literal>REPEATABLE READ</literal> or <literal>SERIALIZABLE</literal> transaction's + view of data will be frozen when its first + <command>SELECT</command> or data modification statement begins. A <command>LOCK + TABLE</command> later in the transaction will still prevent concurrent writes + — but it won't ensure that what the transaction reads corresponds to + the latest committed values. + </para> + + <para> + If a transaction of this sort is going to change the data in the + table, then it should use <literal>SHARE ROW EXCLUSIVE</literal> lock mode + instead of <literal>SHARE</literal> mode. This ensures that only one + transaction of this type runs at a time. Without this, a deadlock + is possible: two transactions might both acquire <literal>SHARE</literal> + mode, and then be unable to also acquire <literal>ROW EXCLUSIVE</literal> + mode to actually perform their updates. (Note that a transaction's + own locks never conflict, so a transaction can acquire <literal>ROW + EXCLUSIVE</literal> mode when it holds <literal>SHARE</literal> mode — but not + if anyone else holds <literal>SHARE</literal> mode.) To avoid deadlocks, + make sure all transactions acquire locks on the same objects in the + same order, and if multiple lock modes are involved for a single + object, then transactions should always acquire the most + restrictive mode first. + </para> + + <para> + More information about the lock modes and locking strategies can be + found in <xref linkend="explicit-locking"/>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing table to + lock. If <literal>ONLY</literal> is specified before the table name, only that + table is locked. If <literal>ONLY</literal> is not specified, the table and all + its descendant tables (if any) are locked. Optionally, <literal>*</literal> + can be specified after the table name to explicitly indicate that + descendant tables are included. + </para> + + <para> + The command <literal>LOCK TABLE a, b;</literal> is equivalent to + <literal>LOCK TABLE a; LOCK TABLE b;</literal>. The tables are locked + one-by-one in the order specified in the <command>LOCK + TABLE</command> command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">lockmode</replaceable></term> + <listitem> + <para> + The lock mode specifies which locks this lock conflicts with. + Lock modes are described in <xref linkend="explicit-locking"/>. + </para> + + <para> + If no lock mode is specified, then <literal>ACCESS + EXCLUSIVE</literal>, the most restrictive mode, is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NOWAIT</literal></term> + <listitem> + <para> + Specifies that <command>LOCK TABLE</command> should not wait for + any conflicting locks to be released: if the specified lock(s) + cannot be acquired immediately without waiting, the transaction + is aborted. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <literal>LOCK TABLE ... IN ACCESS SHARE MODE</literal> requires <literal>SELECT</literal> + privileges on the target table. <literal>LOCK TABLE ... IN ROW EXCLUSIVE + MODE</literal> requires <literal>INSERT</literal>, <literal>UPDATE</literal>, <literal>DELETE</literal>, + or <literal>TRUNCATE</literal> privileges on the target table. All other forms of + <command>LOCK</command> require table-level <literal>UPDATE</literal>, <literal>DELETE</literal>, + or <literal>TRUNCATE</literal> privileges. + </para> + + <para> + The user performing the lock on the view must have the corresponding + privilege on the view. In addition, by default, the view's owner must + have the relevant privileges on the underlying base relations, whereas the + user performing the lock does not need any permissions on the underlying + base relations. However, if the view has + <literal>security_invoker</literal> set to <literal>true</literal> + (see <link linkend="sql-createview"><command>CREATE VIEW</command></link>), + the user performing the lock, rather than the view owner, must have the + relevant privileges on the underlying base relations. + </para> + + <para> + <command>LOCK TABLE</command> is useless outside a transaction block: the lock + would remain held only to the completion of the statement. Therefore + <productname>PostgreSQL</productname> reports an error if <command>LOCK</command> + is used outside a transaction block. + Use + <link linkend="sql-begin"><command>BEGIN</command></link> and + <link linkend="sql-commit"><command>COMMIT</command></link> + (or <link linkend="sql-rollback"><command>ROLLBACK</command></link>) + to define a transaction block. + </para> + + <para> + <command>LOCK TABLE</command> only deals with table-level locks, and so + the mode names involving <literal>ROW</literal> are all misnomers. These + mode names should generally be read as indicating the intention of + the user to acquire row-level locks within the locked table. Also, + <literal>ROW EXCLUSIVE</literal> mode is a shareable table lock. Keep in + mind that all the lock modes have identical semantics so far as + <command>LOCK TABLE</command> is concerned, differing only in the rules + about which modes conflict with which. For information on how to + acquire an actual row-level lock, see <xref linkend="locking-rows"/> + and <xref linkend="sql-for-update-share"/> + in the <xref linkend="sql-select"/> documentation. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Obtain a <literal>SHARE</literal> lock on a primary key table when going to perform + inserts into a foreign key table: + +<programlisting> +BEGIN WORK; +LOCK TABLE films IN SHARE MODE; +SELECT id FROM films + WHERE name = 'Star Wars: Episode I - The Phantom Menace'; +-- Do ROLLBACK if record was not returned +INSERT INTO films_user_comments VALUES + (_id_, 'GREAT! I was waiting for it for so long!'); +COMMIT WORK; +</programlisting> + </para> + + <para> + Take a <literal>SHARE ROW EXCLUSIVE</literal> lock on a primary key table when going to perform + a delete operation: + +<programlisting> +BEGIN WORK; +LOCK TABLE films IN SHARE ROW EXCLUSIVE MODE; +DELETE FROM films_user_comments WHERE id IN + (SELECT id FROM films WHERE rating < 5); +DELETE FROM films WHERE rating < 5; +COMMIT WORK; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>LOCK TABLE</command> in the SQL standard, + which instead uses <command>SET TRANSACTION</command> to specify + concurrency levels on transactions. <productname>PostgreSQL</productname> supports that too; + see <xref linkend="sql-set-transaction"/> for details. + </para> + + <para> + Except for <literal>ACCESS SHARE</literal>, <literal>ACCESS EXCLUSIVE</literal>, + and <literal>SHARE UPDATE EXCLUSIVE</literal> lock modes, the + <productname>PostgreSQL</productname> lock modes and the + <command>LOCK TABLE</command> syntax are compatible with those + present in <productname>Oracle</productname>. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/merge.sgml b/doc/src/sgml/ref/merge.sgml new file mode 100644 index 0000000..0995fe0 --- /dev/null +++ b/doc/src/sgml/ref/merge.sgml @@ -0,0 +1,634 @@ +<!-- +doc/src/sgml/ref/merge.sgml +PostgreSQL documentation +--> + +<refentry id="sql-merge"> + <indexterm zone="sql-merge"> + <primary>MERGE</primary> + </indexterm> + + <refmeta> + <refentrytitle>MERGE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>MERGE</refname> + <refpurpose>conditionally insert, update, or delete rows of a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH <replaceable class="parameter">with_query</replaceable> [, ...] ] +MERGE INTO [ ONLY ] <replaceable class="parameter">target_table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">target_alias</replaceable> ] +USING <replaceable class="parameter">data_source</replaceable> ON <replaceable class="parameter">join_condition</replaceable> +<replaceable class="parameter">when_clause</replaceable> [...] + +<phrase>where <replaceable class="parameter">data_source</replaceable> is:</phrase> + +{ [ ONLY ] <replaceable class="parameter">source_table_name</replaceable> [ * ] | ( <replaceable class="parameter">source_query</replaceable> ) } [ [ AS ] <replaceable class="parameter">source_alias</replaceable> ] + +<phrase>and <replaceable class="parameter">when_clause</replaceable> is:</phrase> + +{ WHEN MATCHED [ AND <replaceable class="parameter">condition</replaceable> ] THEN { <replaceable class="parameter">merge_update</replaceable> | <replaceable class="parameter">merge_delete</replaceable> | DO NOTHING } | + WHEN NOT MATCHED [ AND <replaceable class="parameter">condition</replaceable> ] THEN { <replaceable class="parameter">merge_insert</replaceable> | DO NOTHING } } + +<phrase>and <replaceable class="parameter">merge_insert</replaceable> is:</phrase> + +INSERT [( <replaceable class="parameter">column_name</replaceable> [, ...] )] +[ OVERRIDING { SYSTEM | USER } VALUE ] +{ VALUES ( { <replaceable class="parameter">expression</replaceable> | DEFAULT } [, ...] ) | DEFAULT VALUES } + +<phrase>and <replaceable class="parameter">merge_update</replaceable> is:</phrase> + +UPDATE SET { <replaceable class="parameter">column_name</replaceable> = { <replaceable class="parameter">expression</replaceable> | DEFAULT } | + ( <replaceable class="parameter">column_name</replaceable> [, ...] ) = ( { <replaceable class="parameter">expression</replaceable> | DEFAULT } [, ...] ) } [, ...] + +<phrase>and <replaceable class="parameter">merge_delete</replaceable> is:</phrase> + +DELETE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>MERGE</command> performs actions that modify rows in the + <replaceable class="parameter">target_table_name</replaceable>, + using the <replaceable class="parameter">data_source</replaceable>. + <command>MERGE</command> provides a single <acronym>SQL</acronym> + statement that can conditionally <command>INSERT</command>, + <command>UPDATE</command> or <command>DELETE</command> rows, a task + that would otherwise require multiple procedural language statements. + </para> + + <para> + First, the <command>MERGE</command> command performs a join + from <replaceable class="parameter">data_source</replaceable> to + <replaceable class="parameter">target_table_name</replaceable> + producing zero or more candidate change rows. For each candidate change + row, the status of <literal>MATCHED</literal> or <literal>NOT MATCHED</literal> + is set just once, after which <literal>WHEN</literal> clauses are evaluated + in the order specified. For each candidate change row, the first clause to + evaluate as true is executed. No more than one <literal>WHEN</literal> + clause is executed for any candidate change row. + </para> + + <para> + <command>MERGE</command> actions have the same effect as + regular <command>UPDATE</command>, <command>INSERT</command>, or + <command>DELETE</command> commands of the same names. The syntax of + those commands is different, notably that there is no <literal>WHERE</literal> + clause and no table name is specified. All actions refer to the + <replaceable class="parameter">target_table_name</replaceable>, + though modifications to other tables may be made using triggers. + </para> + + <para> + When <literal>DO NOTHING</literal> is specified, the source row is + skipped. Since actions are evaluated in their specified order, <literal>DO + NOTHING</literal> can be handy to skip non-interesting source rows before + more fine-grained handling. + </para> + + <para> + There is no separate <literal>MERGE</literal> privilege. + If you specify an update action, you must have the + <literal>UPDATE</literal> privilege on the column(s) + of the <replaceable class="parameter">target_table_name</replaceable> + that are referred to in the <literal>SET</literal> clause. + If you specify an insert action, you must have the <literal>INSERT</literal> + privilege on the <replaceable class="parameter">target_table_name</replaceable>. + If you specify an delete action, you must have the <literal>DELETE</literal> + privilege on the <replaceable class="parameter">target_table_name</replaceable>. + Privileges are tested once at statement start and are checked + whether or not particular <literal>WHEN</literal> clauses are executed. + You will require the <literal>SELECT</literal> privilege on the + <replaceable class="parameter">data_source</replaceable> and any column(s) + of the <replaceable class="parameter">target_table_name</replaceable> + referred to in a <literal>condition</literal>. + </para> + + <para> + <command>MERGE</command> is not supported if the + <replaceable class="parameter">target_table_name</replaceable> is a + materialized view, foreign table, or if it has any + rules defined on it. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">target_table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the target table to merge into. + If <literal>ONLY</literal> is specified before the table name, matching + rows are updated or deleted in the named table only. If + <literal>ONLY</literal> is not specified, matching rows are also updated + or deleted in any tables inheriting from the named table. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. The + <literal>ONLY</literal> keyword and <literal>*</literal> option do not + affect insert actions, which always insert into the named table only. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">target_alias</replaceable></term> + <listitem> + <para> + A substitute name for the target table. When an alias is + provided, it completely hides the actual name of the table. For + example, given <literal>MERGE INTO foo AS f</literal>, the remainder of the + <command>MERGE</command> statement must refer to this table as + <literal>f</literal> not <literal>foo</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">source_table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the source table, view, or + transition table. If <literal>ONLY</literal> is specified before the + table name, matching rows are included from the named table only. If + <literal>ONLY</literal> is not specified, matching rows are also included + from any tables inheriting from the named table. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">source_query</replaceable></term> + <listitem> + <para> + A query (<command>SELECT</command> statement or <command>VALUES</command> + statement) that supplies the rows to be merged into the + <replaceable class="parameter">target_table_name</replaceable>. + Refer to the <xref linkend="sql-select"/> + statement or <xref linkend="sql-values"/> + statement for a description of the syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">source_alias</replaceable></term> + <listitem> + <para> + A substitute name for the data source. When an alias is + provided, it completely hides the actual name of the table or the fact + that a query was issued. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">join_condition</replaceable></term> + <listitem> + <para> + <replaceable class="parameter">join_condition</replaceable> is + an expression resulting in a value of type + <type>boolean</type> (similar to a <literal>WHERE</literal> + clause) that specifies which rows in the + <replaceable class="parameter">data_source</replaceable> + match rows in the + <replaceable class="parameter">target_table_name</replaceable>. + </para> + <warning> + <para> + Only columns from <replaceable class="parameter">target_table_name</replaceable> + that attempt to match <replaceable class="parameter">data_source</replaceable> + rows should appear in <replaceable class="parameter">join_condition</replaceable>. + <replaceable class="parameter">join_condition</replaceable> subexpressions that + only reference <replaceable class="parameter">target_table_name</replaceable> + columns can affect which action is taken, often in surprising ways. + </para> + </warning> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">when_clause</replaceable></term> + <listitem> + <para> + At least one <literal>WHEN</literal> clause is required. + </para> + <para> + If the <literal>WHEN</literal> clause specifies <literal>WHEN MATCHED</literal> + and the candidate change row matches a row in the + <replaceable class="parameter">target_table_name</replaceable>, + the <literal>WHEN</literal> clause is executed if the + <replaceable class="parameter">condition</replaceable> is + absent or it evaluates to <literal>true</literal>. + </para> + <para> + Conversely, if the <literal>WHEN</literal> clause specifies + <literal>WHEN NOT MATCHED</literal> + and the candidate change row does not match a row in the + <replaceable class="parameter">target_table_name</replaceable>, + the <literal>WHEN</literal> clause is executed if the + <replaceable class="parameter">condition</replaceable> is + absent or it evaluates to <literal>true</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + An expression that returns a value of type <type>boolean</type>. + If this expression for a <literal>WHEN</literal> clause + returns <literal>true</literal>, then the action for that clause + is executed for that row. + </para> + <para> + A condition on a <literal>WHEN MATCHED</literal> clause can refer to columns + in both the source and the target relations. A condition on a + <literal>WHEN NOT MATCHED</literal> clause can only refer to columns from + the source relation, since by definition there is no matching target row. + Only the system attributes from the target table are accessible. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">merge_insert</replaceable></term> + <listitem> + <para> + The specification of an <literal>INSERT</literal> action that inserts + one row into the target table. + The target column names can be listed in any order. If no list of + column names is given at all, the default is all the columns of the + table in their declared order. + </para> + <para> + Each column not present in the explicit or implicit column list will be + filled with a default value, either its declared default value + or null if there is none. + </para> + <para> + If <replaceable class="parameter">target_table_name</replaceable> + is a partitioned table, each row is routed to the appropriate partition + and inserted into it. + If <replaceable class="parameter">target_table_name</replaceable> + is a partition, an error will occur if any input row violates the + partition constraint. + </para> + <para> + Column names may not be specified more than once. + <command>INSERT</command> actions cannot contain sub-selects. + </para> + <para> + Only one <literal>VALUES</literal> clause can be specified. + The <literal>VALUES</literal> clause can only refer to columns from + the source relation, since by definition there is no matching target row. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">merge_update</replaceable></term> + <listitem> + <para> + The specification of an <literal>UPDATE</literal> action that updates + the current row of the <replaceable class="parameter">target_table_name</replaceable>. + Column names may not be specified more than once. + </para> + <para> + Neither a table name nor a <literal>WHERE</literal> clause are allowed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">merge_delete</replaceable></term> + <listitem> + <para> + Specifies a <literal>DELETE</literal> action that deletes the current row + of the <replaceable class="parameter">target_table_name</replaceable>. + Do not include the table name or any other clauses, as you would normally + do with a <xref linkend="sql-delete"/> command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column in the <replaceable + class="parameter">target_table_name</replaceable>. The column name + can be qualified with a subfield name or array subscript, if + needed. (Inserting into only some fields of a composite + column leaves the other fields null.) + Do not include the table's name in the specification + of a target column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OVERRIDING SYSTEM VALUE</literal></term> + <listitem> + <para> + Without this clause, it is an error to specify an explicit value + (other than <literal>DEFAULT</literal>) for an identity column defined + as <literal>GENERATED ALWAYS</literal>. This clause overrides that + restriction. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>OVERRIDING USER VALUE</literal></term> + <listitem> + <para> + If this clause is specified, then any values supplied for identity + columns defined as <literal>GENERATED BY DEFAULT</literal> are ignored + and the default sequence-generated values are applied. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT VALUES</literal></term> + <listitem> + <para> + All columns will be filled with their default values. + (An <literal>OVERRIDING</literal> clause is not permitted in this + form.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + An expression to assign to the column. If used in a + <literal>WHEN MATCHED</literal> clause, the expression can use values + from the original row in the target table, and values from the + <literal>data_source</literal> row. + If used in a <literal>WHEN NOT MATCHED</literal> clause, the + expression can use values from the <literal>data_source</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + Set the column to its default value (which will be <literal>NULL</literal> + if no specific default expression has been assigned to it). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">with_query</replaceable></term> + <listitem> + <para> + The <literal>WITH</literal> clause allows you to specify one or more + subqueries that can be referenced by name in the <command>MERGE</command> + query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> + for details. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, a <command>MERGE</command> command returns a command + tag of the form +<screen> +MERGE <replaceable class="parameter">total_count</replaceable> +</screen> + The <replaceable class="parameter">total_count</replaceable> is the total + number of rows changed (whether inserted, updated, or deleted). + If <replaceable class="parameter">total_count</replaceable> is 0, no rows + were changed in any way. + </para> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The following steps take place during the execution of + <command>MERGE</command>. + <orderedlist> + <listitem> + <para> + Perform any <literal>BEFORE STATEMENT</literal> triggers for all + actions specified, whether or not their <literal>WHEN</literal> + clauses match. + </para> + </listitem> + <listitem> + <para> + Perform a join from source to target table. + The resulting query will be optimized normally and will produce + a set of candidate change rows. For each candidate change row, + <orderedlist> + <listitem> + <para> + Evaluate whether each row is <literal>MATCHED</literal> or + <literal>NOT MATCHED</literal>. + </para> + </listitem> + <listitem> + <para> + Test each <literal>WHEN</literal> condition in the order + specified until one returns true. + </para> + </listitem> + <listitem> + <para> + When a condition returns true, perform the following actions: + <orderedlist> + <listitem> + <para> + Perform any <literal>BEFORE ROW</literal> triggers that fire + for the action's event type. + </para> + </listitem> + <listitem> + <para> + Perform the specified action, invoking any check constraints on the + target table. + </para> + </listitem> + <listitem> + <para> + Perform any <literal>AFTER ROW</literal> triggers that fire for + the action's event type. + </para> + </listitem> + </orderedlist></para> + </listitem> + </orderedlist></para> + </listitem> + <listitem> + <para> + Perform any <literal>AFTER STATEMENT</literal> triggers for actions + specified, whether or not they actually occur. This is similar to the + behavior of an <command>UPDATE</command> statement that modifies no rows. + </para> + </listitem> + </orderedlist> + In summary, statement triggers for an event type (say, + <command>INSERT</command>) will be fired whenever we + <emphasis>specify</emphasis> an action of that kind. + In contrast, row-level triggers will fire only for the specific event type + being <emphasis>executed</emphasis>. + So a <command>MERGE</command> command might fire statement triggers for both + <command>UPDATE</command> and <command>INSERT</command>, even though only + <command>UPDATE</command> row triggers were fired. + </para> + + <para> + You should ensure that the join produces at most one candidate change row + for each target row. In other words, a target row shouldn't join to more + than one data source row. If it does, then only one of the candidate change + rows will be used to modify the target row; later attempts to modify the + row will cause an error. + This can also occur if row triggers make changes to the target table + and the rows so modified are then subsequently also modified by + <command>MERGE</command>. + If the repeated action is an <command>INSERT</command>, this will + cause a uniqueness violation, while a repeated <command>UPDATE</command> + or <command>DELETE</command> will cause a cardinality violation; the + latter behavior is required by the <acronym>SQL</acronym> standard. + This differs from historical <productname>PostgreSQL</productname> + behavior of joins in <command>UPDATE</command> and + <command>DELETE</command> statements where second and subsequent + attempts to modify the same row are simply ignored. + </para> + + <para> + If a <literal>WHEN</literal> clause omits an <literal>AND</literal> + sub-clause, it becomes the final reachable clause of that + kind (<literal>MATCHED</literal> or <literal>NOT MATCHED</literal>). + If a later <literal>WHEN</literal> clause of that kind + is specified it would be provably unreachable and an error is raised. + If no final reachable clause is specified of either kind, it is + possible that no action will be taken for a candidate change row. + </para> + + <para> + The order in which rows are generated from the data source is + indeterminate by default. + A <replaceable class="parameter">source_query</replaceable> can be + used to specify a consistent ordering, if required, which might be + needed to avoid deadlocks between concurrent transactions. + </para> + + <para> + There is no <literal>RETURNING</literal> clause with + <command>MERGE</command>. Actions of <command>INSERT</command>, + <command>UPDATE</command> and <command>DELETE</command> cannot contain + <literal>RETURNING</literal> or <literal>WITH</literal> clauses. + </para> + + <para> + When <command>MERGE</command> is run concurrently with other commands + that modify the target table, the usual transaction isolation rules + apply; see <xref linkend="transaction-iso"/> for an explanation + on the behavior at each isolation level. + You may also wish to consider using <command>INSERT ... ON CONFLICT</command> + as an alternative statement which offers the ability to run an + <command>UPDATE</command> if a concurrent <command>INSERT</command> + occurs. There are a variety of differences and restrictions between + the two statement types and they are not interchangeable. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Perform maintenance on <literal>customer_accounts</literal> based + upon new <literal>recent_transactions</literal>. + +<programlisting> +MERGE INTO customer_account ca +USING recent_transactions t +ON t.customer_id = ca.customer_id +WHEN MATCHED THEN + UPDATE SET balance = balance + transaction_value +WHEN NOT MATCHED THEN + INSERT (customer_id, balance) + VALUES (t.customer_id, t.transaction_value); +</programlisting> + </para> + + <para> + Notice that this would be exactly equivalent to the following + statement because the <literal>MATCHED</literal> result does not change + during execution. + +<programlisting> +MERGE INTO customer_account ca +USING (SELECT customer_id, transaction_value FROM recent_transactions) AS t +ON t.customer_id = ca.customer_id +WHEN MATCHED THEN + UPDATE SET balance = balance + transaction_value +WHEN NOT MATCHED THEN + INSERT (customer_id, balance) + VALUES (t.customer_id, t.transaction_value); +</programlisting> + </para> + + <para> + Attempt to insert a new stock item along with the quantity of stock. If + the item already exists, instead update the stock count of the existing + item. Don't allow entries that have zero stock. +<programlisting> +MERGE INTO wines w +USING wine_stock_changes s +ON s.winename = w.winename +WHEN NOT MATCHED AND s.stock_delta > 0 THEN + INSERT VALUES(s.winename, s.stock_delta) +WHEN MATCHED AND w.stock + s.stock_delta > 0 THEN + UPDATE SET stock = w.stock + s.stock_delta +WHEN MATCHED THEN + DELETE; +</programlisting> + + The <literal>wine_stock_changes</literal> table might be, for example, a + temporary table recently loaded into the database. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + <para> + This command conforms to the <acronym>SQL</acronym> standard. + </para> + <para> + The WITH clause and <literal>DO NOTHING</literal> action are extensions to + the <acronym>SQL</acronym> standard. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/move.sgml b/doc/src/sgml/ref/move.sgml new file mode 100644 index 0000000..89b5a24 --- /dev/null +++ b/doc/src/sgml/ref/move.sgml @@ -0,0 +1,124 @@ +<!-- +doc/src/sgml/ref/move.sgml +PostgreSQL documentation +--> + +<refentry id="sql-move"> + <indexterm zone="sql-move"> + <primary>MOVE</primary> + </indexterm> + + <indexterm zone="sql-move"> + <primary>cursor</primary> + <secondary>MOVE</secondary> + </indexterm> + + <refmeta> + <refentrytitle>MOVE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>MOVE</refname> + <refpurpose>position a cursor</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<!-- Note the "direction" bit is also in ref/fetch.sgml --> +<synopsis> +MOVE [ <replaceable class="parameter">direction</replaceable> ] [ FROM | IN ] <replaceable class="parameter">cursor_name</replaceable> + +<phrase>where <replaceable class="parameter">direction</replaceable> can be one of:</phrase> + + NEXT + PRIOR + FIRST + LAST + ABSOLUTE <replaceable class="parameter">count</replaceable> + RELATIVE <replaceable class="parameter">count</replaceable> + <replaceable class="parameter">count</replaceable> + ALL + FORWARD + FORWARD <replaceable class="parameter">count</replaceable> + FORWARD ALL + BACKWARD + BACKWARD <replaceable class="parameter">count</replaceable> + BACKWARD ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>MOVE</command> repositions a cursor without retrieving any data. + <command>MOVE</command> works exactly like the <command>FETCH</command> + command, except it only positions the cursor and does not return rows. + </para> + + <para> + The parameters for the <command>MOVE</command> command are identical to + those of the <command>FETCH</command> command; refer to + <xref linkend="sql-fetch"/> + for details on syntax and usage. + </para> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, a <command>MOVE</command> command returns a command + tag of the form +<screen> +MOVE <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number + of rows that a <command>FETCH</command> command with the same parameters + would have returned (possibly zero). + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + +<programlisting> +BEGIN WORK; +DECLARE liahona CURSOR FOR SELECT * FROM films; + +-- Skip the first 5 rows: +MOVE FORWARD 5 IN liahona; +MOVE 5 + +-- Fetch the 6th row from the cursor liahona: +FETCH 1 FROM liahona; + code | title | did | date_prod | kind | len +-------+--------+-----+------------+--------+------- + P_303 | 48 Hrs | 103 | 1982-10-22 | Action | 01:37 +(1 row) + +-- Close the cursor liahona and end the transaction: +CLOSE liahona; +COMMIT WORK; +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>MOVE</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-close"/></member> + <member><xref linkend="sql-declare"/></member> + <member><xref linkend="sql-fetch"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/notify.sgml b/doc/src/sgml/ref/notify.sgml new file mode 100644 index 0000000..d7dcbea --- /dev/null +++ b/doc/src/sgml/ref/notify.sgml @@ -0,0 +1,233 @@ +<!-- +doc/src/sgml/ref/notify.sgml +PostgreSQL documentation +--> + +<refentry id="sql-notify"> + <indexterm zone="sql-notify"> + <primary>NOTIFY</primary> + </indexterm> + + <refmeta> + <refentrytitle>NOTIFY</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>NOTIFY</refname> + <refpurpose>generate a notification</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +NOTIFY <replaceable class="parameter">channel</replaceable> [ , <replaceable class="parameter">payload</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + The <command>NOTIFY</command> command sends a notification event together + with an optional <quote>payload</quote> string to each client application that + has previously executed + <command>LISTEN <replaceable class="parameter">channel</replaceable></command> + for the specified channel name in the current database. + Notifications are visible to all users. + </para> + + <para> + <command>NOTIFY</command> provides a simple + interprocess communication mechanism for a collection of processes + accessing the same <productname>PostgreSQL</productname> database. + A payload string can be sent along with the notification, and + higher-level mechanisms for passing structured data can be built by using + tables in the database to pass additional data from notifier to listener(s). + </para> + + <para> + The information passed to the client for a notification event includes the + notification channel + name, the notifying session's server process <acronym>PID</acronym>, and the + payload string, which is an empty string if it has not been specified. + </para> + + <para> + It is up to the database designer to define the channel names that will + be used in a given database and what each one means. + Commonly, the channel name is the same as the name of some table in + the database, and the notify event essentially means, <quote>I changed this table, + take a look at it to see what's new</quote>. But no such association is enforced by + the <command>NOTIFY</command> and <command>LISTEN</command> commands. For + example, a database designer could use several different channel names + to signal different sorts of changes to a single table. Alternatively, + the payload string could be used to differentiate various cases. + </para> + + <para> + When <command>NOTIFY</command> is used to signal the occurrence of changes + to a particular table, a useful programming technique is to put the + <command>NOTIFY</command> in a statement trigger that is triggered by table updates. + In this way, notification happens automatically when the table is changed, + and the application programmer cannot accidentally forget to do it. + </para> + + <para> + <command>NOTIFY</command> interacts with SQL transactions in some important + ways. Firstly, if a <command>NOTIFY</command> is executed inside a + transaction, the notify events are not delivered until and unless the + transaction is committed. This is appropriate, since if the transaction + is aborted, all the commands within it have had no + effect, including <command>NOTIFY</command>. But it can be disconcerting if one + is expecting the notification events to be delivered immediately. Secondly, if + a listening session receives a notification signal while it is within a transaction, + the notification event will not be delivered to its connected client until just + after the transaction is completed (either committed or aborted). Again, the + reasoning is that if a notification were delivered within a transaction that was + later aborted, one would want the notification to be undone somehow — + but + the server cannot <quote>take back</quote> a notification once it has sent it to the client. + So notification events are only delivered between transactions. The upshot of this + is that applications using <command>NOTIFY</command> for real-time signaling + should try to keep their transactions short. + </para> + + <para> + If the same channel name is signaled multiple times with identical + payload strings within the same transaction, only one instance of the + notification event is delivered to listeners. + On the other hand, notifications with distinct payload strings will + always be delivered as distinct notifications. Similarly, notifications from + different transactions will never get folded into one notification. + Except for dropping later instances of duplicate notifications, + <command>NOTIFY</command> guarantees that notifications from the same + transaction get delivered in the order they were sent. It is also + guaranteed that messages from different transactions are delivered in + the order in which the transactions committed. + </para> + + <para> + It is common for a client that executes <command>NOTIFY</command> + to be listening on the same notification channel itself. In that case + it will get back a notification event, just like all the other + listening sessions. Depending on the application logic, this could + result in useless work, for example, reading a database table to + find the same updates that that session just wrote out. It is + possible to avoid such extra work by noticing whether the notifying + session's server process <acronym>PID</acronym> (supplied in the + notification event message) is the same as one's own session's + <acronym>PID</acronym> (available from <application>libpq</application>). When they + are the same, the notification event is one's own work bouncing + back, and can be ignored. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">channel</replaceable></term> + <listitem> + <para> + Name of the notification channel to be signaled (any identifier). + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><replaceable class="parameter">payload</replaceable></term> + <listitem> + <para> + The <quote>payload</quote> string to be communicated along with the + notification. This must be specified as a simple string literal. + In the default configuration it must be shorter than 8000 bytes. + (If binary data or large amounts of information need to be communicated, + it's best to put it in a database table and send the key of the record.) + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + There is a queue that holds notifications that have been sent but not + yet processed by all listening sessions. If this queue becomes full, + transactions calling <command>NOTIFY</command> will fail at commit. + The queue is quite large (8GB in a standard installation) and should be + sufficiently sized for almost every use case. However, no cleanup can take + place if a session executes <command>LISTEN</command> and then enters a + transaction for a very long time. Once the queue is half full you will see + warnings in the log file pointing you to the session that is preventing + cleanup. In this case you should make sure that this session ends its + current transaction so that cleanup can proceed. + </para> + <para> + The function <function>pg_notification_queue_usage</function> returns the + fraction of the queue that is currently occupied by pending notifications. + See <xref linkend="functions-info"/> for more information. + </para> + <para> + A transaction that has executed <command>NOTIFY</command> cannot be + prepared for two-phase commit. + </para> + + <refsect2> + <title>pg_notify</title> + + <indexterm> + <primary>pg_notify</primary> + </indexterm> + + <para> + To send a notification you can also use the function + <literal><function>pg_notify</function>(<type>text</type>, + <type>text</type>)</literal>. The function takes the channel name as the + first argument and the payload as the second. The function is much easier + to use than the <command>NOTIFY</command> command if you need to work with + non-constant channel names and payloads. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Configure and execute a listen/notify sequence from + <application>psql</application>: + +<programlisting> +LISTEN virtual; +NOTIFY virtual; +Asynchronous notification "virtual" received from server process with PID 8448. +NOTIFY virtual, 'This is the payload'; +Asynchronous notification "virtual" with payload "This is the payload" received from server process with PID 8448. + +LISTEN foo; +SELECT pg_notify('fo' || 'o', 'pay' || 'load'); +Asynchronous notification "foo" with payload "payload" received from server process with PID 14728. +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>NOTIFY</command> statement in the SQL + standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-listen"/></member> + <member><xref linkend="sql-unlisten"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_amcheck.sgml b/doc/src/sgml/ref/pg_amcheck.sgml new file mode 100644 index 0000000..20c2897 --- /dev/null +++ b/doc/src/sgml/ref/pg_amcheck.sgml @@ -0,0 +1,652 @@ +<!-- +doc/src/sgml/ref/pg_amcheck.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgamcheck"> + <indexterm zone="app-pgamcheck"> + <primary>pg_amcheck</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_amcheck</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_amcheck</refname> + <refpurpose>checks for corruption in one or more + <productname>PostgreSQL</productname> databases</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_amcheck</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_amcheck</application> supports running + <xref linkend="amcheck"/>'s corruption checking functions against one or + more databases, with options to select which schemas, tables and indexes to + check, which kinds of checking to perform, and whether to perform the checks + in parallel, and if so, the number of parallel connections to establish and + use. + </para> + + <para> + Only ordinary and toast table relations, materialized views, sequences, and + btree indexes are currently supported. Other relation types are silently + skipped. + </para> + + <para> + If <literal>dbname</literal> is specified, it should be the name of a + single database to check, and no other database selection options should + be present. Otherwise, if any database selection options are present, + all matching databases will be checked. If no such options are present, + the default database will be checked. Database selection options include + <option>--all</option>, <option>--database</option> and + <option>--exclude-database</option>. They also include + <option>--relation</option>, <option>--exclude-relation</option>, + <option>--table</option>, <option>--exclude-table</option>, + <option>--index</option>, and <option>--exclude-index</option>, + but only when such options are used with a three-part pattern + (e.g. <option>mydb*.myschema*.myrel*</option>). Finally, they include + <option>--schema</option> and <option>--exclude-schema</option> + when such options are used with a two-part pattern + (e.g. <option>mydb*.myschema*</option>). + </para> + + <para> + <replaceable>dbname</replaceable> can also be a + <link linkend="libpq-connstring">connection string</link>. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following command-line options control what is checked: + + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--all</option></term> + <listitem> + <para> + Check all databases, except for any excluded via + <option>--exclude-database</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--database=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Check databases matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>, + except for any excluded by <option>--exclude-database</option>. + This option can be specified more than once. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-database=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Exclude databases matching the given + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>. + This option can be specified more than once. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--index=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Check indexes matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>, + unless they are otherwise excluded. + This option can be specified more than once. + </para> + <para> + This is similar to the <option>--relation</option> option, except that + it applies only to indexes, not to other relation types. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-index=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Exclude indexes matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>. + This option can be specified more than once. + </para> + <para> + This is similar to the <option>--exclude-relation</option> option, + except that it applies only to indexes, not other relation types. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--relation=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Check relations matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>, + unless they are otherwise excluded. + This option can be specified more than once. + </para> + <para> + Patterns may be unqualified, e.g. <literal>myrel*</literal>, or they + may be schema-qualified, e.g. <literal>myschema*.myrel*</literal> or + database-qualified and schema-qualified, e.g. + <literal>mydb*.myschema*.myrel*</literal>. A database-qualified + pattern will add matching databases to the list of databases to be + checked. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-relation=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Exclude relations matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>. + This option can be specified more than once. + </para> + <para> + As with <option>--relation</option>, the + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> may be unqualified, schema-qualified, + or database- and schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--schema=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Check tables and indexes in schemas matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>, unless they are otherwise excluded. + This option can be specified more than once. + </para> + <para> + To select only tables in schemas matching a particular pattern, + consider using something like + <literal>--table=SCHEMAPAT.* --no-dependent-indexes</literal>. + To select only indexes, consider using something like + <literal>--index=SCHEMAPAT.*</literal>. + </para> + <para> + A schema pattern may be database-qualified. For example, you may + write <literal>--schema=mydb*.myschema*</literal> to select + schemas matching <literal>myschema*</literal> in databases matching + <literal>mydb*</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-schema=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Exclude tables and indexes in schemas matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>. + This option can be specified more than once. + </para> + <para> + As with <option>--schema</option>, the pattern may be + database-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--table=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Check tables matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>, + unless they are otherwise excluded. + This option can be specified more than once. + </para> + <para> + This is similar to the <option>--relation</option> option, except that + it applies only to tables, materialized views, and sequences, not to + indexes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-table=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Exclude tables matching the specified + <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link>. + This option can be specified more than once. + </para> + <para> + This is similar to the <option>--exclude-relation</option> option, + except that it applies only to tables, materialized views, and + sequences, not to indexes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-dependent-indexes</option></term> + <listitem> + <para> + By default, if a table is checked, any btree indexes of that table + will also be checked, even if they are not explicitly selected by + an option such as <literal>--index</literal> or + <literal>--relation</literal>. This option suppresses that behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-dependent-toast</option></term> + <listitem> + <para> + By default, if a table is checked, its toast table, if any, will also + be checked, even if it is not explicitly selected by an option + such as <literal>--table</literal> or <literal>--relation</literal>. + This option suppresses that behavior. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-strict-names</option></term> + <listitem> + <para> + By default, if an argument to <literal>--database</literal>, + <literal>--table</literal>, <literal>--index</literal>, + or <literal>--relation</literal> matches no objects, it is a fatal + error. This option downgrades that error to a warning. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following command-line options control checking of tables: + + <variablelist> + <varlistentry> + <term><option>--exclude-toast-pointers</option></term> + <listitem> + <para> + By default, whenever a toast pointer is encountered in a table, + a lookup is performed to ensure that it references apparently-valid + entries in the toast table. These checks can be quite slow, and this + option can be used to skip them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--on-error-stop</option></term> + <listitem> + <para> + After reporting all corruptions on the first page of a table where + corruption is found, stop processing that table relation and move on + to the next table or index. + </para> + <para> + Note that index checking always stops after the first corrupt page. + This option only has meaning relative to table relations. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--skip=<replaceable class="parameter">option</replaceable></option></term> + <listitem> + <para> + If <literal>all-frozen</literal> is given, table corruption checks + will skip over pages in all tables that are marked as all frozen. + </para> + <para> + If <literal>all-visible</literal> is given, table corruption checks + will skip over pages in all tables that are marked as all visible. + </para> + <para> + By default, no pages are skipped. This can be specified as + <literal>none</literal>, but since this is the default, it need not be + mentioned. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--startblock=<replaceable class="parameter">block</replaceable></option></term> + <listitem> + <para> + Start checking at the specified block number. An error will occur if + the table relation being checked has fewer than this number of blocks. + This option does not apply to indexes, and is probably only useful + when checking a single table relation. See <literal>--endblock</literal> + for further caveats. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--endblock=<replaceable class="parameter">block</replaceable></option></term> + <listitem> + <para> + End checking at the specified block number. An error will occur if the + table relation being checked has fewer than this number of blocks. + This option does not apply to indexes, and is probably only useful when + checking a single table relation. If both a regular table and a toast + table are checked, this option will apply to both, but higher-numbered + toast blocks may still be accessed while validating toast pointers, + unless that is suppressed using + <option>--exclude-toast-pointers</option>. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following command-line options control checking of B-tree indexes: + + <variablelist> + <varlistentry> + <term><option>--heapallindexed</option></term> + <listitem> + <para> + For each index checked, verify the presence of all heap tuples as index + tuples in the index using <xref linkend="amcheck"/>'s + <option>heapallindexed</option> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--parent-check</option></term> + <listitem> + <para> + For each btree index checked, use <xref linkend="amcheck"/>'s + <function>bt_index_parent_check</function> function, which performs + additional checks of parent/child relationships during index checking. + </para> + <para> + The default is to use <application>amcheck</application>'s + <function>bt_index_check</function> function, but note that use of the + <option>--rootdescend</option> option implicitly selects + <function>bt_index_parent_check</function>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--rootdescend</option></term> + <listitem> + <para> + For each index checked, re-find tuples on the leaf level by performing a + new search from the root page for each tuple using + <xref linkend="amcheck"/>'s <option>rootdescend</option> option. + </para> + <para> + Use of this option implicitly also selects the + <option>--parent-check</option> option. + </para> + <para> + This form of verification was originally written to help in the + development of btree index features. It may be of limited use or even + of no use in helping detect the kinds of corruption that occur in + practice. It may also cause corruption checking to take considerably + longer and consume considerably more resources on the server. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <warning> + <para> + The extra checks performed against B-tree indexes when the + <option>--parent-check</option> option or the + <option>--rootdescend</option> option is specified require + relatively strong relation-level locks. These checks are the only + checks that will block concurrent data modification from + <command>INSERT</command>, <command>UPDATE</command>, and + <command>DELETE</command> commands. + </para> + </warning> + + <para> + The following command-line options control the connection to the server: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">hostname</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">hostname</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is running. + If the value begins with a slash, it is used as the directory for the + Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file extension on + which the server is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U</option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires password + authentication and a password is not available by other means such as + a <filename>.pgpass</filename> file, the connection attempt will fail. + This option can be useful in batch jobs and scripts where no user is + present to enter a password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_amcheck</application> to prompt for a password + before connecting to a database. + </para> + <para> + This option is never essential, since + <application>pg_amcheck</application> will automatically prompt for a + password if the server demands password authentication. However, + <application>pg_amcheck</application> will waste a connection attempt + finding out that the server wants a password. In some cases it is + worth typing <option>-W</option> to avoid the extra connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies a database or + <link linkend="libpq-connstring">connection string</link> to be + used to discover the list of databases to be checked. If neither + <option>--all</option> nor any option including a database pattern is + used, no such connection is required and this option does nothing. + Otherwise, any connection string parameters other than + the database name which are included in the value for this option + will also be used when connecting to the databases + being checked. If this option is omitted, the default is + <literal>postgres</literal> or, if that fails, + <literal>template1</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other options are also available: + + <variablelist> + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo to stdout all SQL sent to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">num</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">num</replaceable></option></term> + <listitem> + <para> + Use <replaceable>num</replaceable> concurrent connections to the server, + or one per object to be checked, whichever is less. + </para> + <para> + The default is to use a single connection. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <term><option>--progress</option></term> + <listitem> + <para> + Show progress information. Progress information includes the number + of relations for which checking has been completed, and the total + size of those relations. It also includes the total number of relations + that will eventually be checked, and the estimated size of those + relations. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Print more messages. In particular, this will print a message for + each relation being checked, and will increase the level of detail + shown for server errors. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_amcheck</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--install-missing</option></term> + <term><option>--install-missing=<replaceable class="parameter">schema</replaceable></option></term> + <listitem> + <para> + Install any missing extensions that are required to check the + database(s). If not yet installed, each extension's objects will be + installed into the given + <replaceable class="parameter">schema</replaceable>, or if not specified + into schema <literal>pg_catalog</literal>. + </para> + <para> + At present, the only required extension is <xref linkend="amcheck"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_amcheck</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <application>pg_amcheck</application> is designed to work with + <productname>PostgreSQL</productname> 14.0 and later. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="amcheck"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_basebackup.sgml b/doc/src/sgml/ref/pg_basebackup.sgml new file mode 100644 index 0000000..a5f63bd --- /dev/null +++ b/doc/src/sgml/ref/pg_basebackup.sgml @@ -0,0 +1,1008 @@ +<!-- +doc/src/sgml/ref/pg_basebackup.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgbasebackup"> + <indexterm zone="app-pgbasebackup"> + <primary>pg_basebackup</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_basebackup</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_basebackup</refname> + <refpurpose>take a base backup of a <productname>PostgreSQL</productname> cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_basebackup</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + <application>pg_basebackup</application> is used to take a base backup of + a running <productname>PostgreSQL</productname> database cluster. The backup + is taken without affecting other clients of the database, and can be used + both for point-in-time recovery (see <xref linkend="continuous-archiving"/>) + and as the starting point for a log-shipping or streaming-replication standby + server (see <xref linkend="warm-standby"/>). + </para> + + <para> + <application>pg_basebackup</application> makes an exact copy of the database + cluster's files, while making sure the server is put into and + out of backup mode automatically. Backups are always taken of the entire + database cluster; it is not possible to back up individual databases or + database objects. For selective backups, another tool such as + <xref linkend="app-pgdump"/> must be used. + </para> + + <para> + The backup is made over a regular <productname>PostgreSQL</productname> + connection that uses the replication protocol. The connection must be made + with a user ID that has <literal>REPLICATION</literal> permissions + (see <xref linkend="role-attributes"/>) or is a superuser, + and <link linkend="auth-pg-hba-conf"><filename>pg_hba.conf</filename></link> + must permit the replication connection. The server must also be configured + with <xref linkend="guc-max-wal-senders"/> set high enough to provide at + least one walsender for the backup plus one for WAL streaming (if used). + </para> + + <para> + There can be multiple <command>pg_basebackup</command>s running at the same time, but it is usually + better from a performance point of view to take only one backup, and copy + the result. + </para> + + <para> + <application>pg_basebackup</application> can make a base backup from + not only a primary server but also a standby. To take a backup from a standby, + set up the standby so that it can accept replication connections (that is, set + <varname>max_wal_senders</varname> and <xref linkend="guc-hot-standby"/>, + and configure its <filename>pg_hba.conf</filename> appropriately). + You will also need to enable <xref linkend="guc-full-page-writes"/> on the primary. + </para> + + <para> + Note that there are some limitations in taking a backup from a standby: + + <itemizedlist> + <listitem> + <para> + The backup history file is not created in the database cluster backed up. + </para> + </listitem> + <listitem> + <para> + <application>pg_basebackup</application> cannot force the standby + to switch to a new WAL file at the end of backup. + When you are using <literal>-X none</literal>, if write activity on + the primary is low, <application>pg_basebackup</application> may + need to wait a long time for the last WAL file required for the backup + to be switched and archived. In this case, it may be useful to run + <function>pg_switch_wal</function> on the primary in order to + trigger an immediate WAL file switch. + </para> + </listitem> + <listitem> + <para> + If the standby is promoted to be primary during backup, the backup fails. + </para> + </listitem> + <listitem> + <para> + All WAL records required for the backup must contain sufficient full-page writes, + which requires you to enable <varname>full_page_writes</varname> on the primary. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + Whenever <application>pg_basebackup</application> is taking a base + backup, the server's <structname>pg_stat_progress_basebackup</structname> + view will report the progress of the backup. + See <xref linkend="basebackup-progress-reporting"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following command-line options control the location and format of the + output: + + <variablelist> + <varlistentry> + <term><option>-D <replaceable class="parameter">directory</replaceable></option></term> + <term><option>--pgdata=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Sets the target directory to write the output to. + <application>pg_basebackup</application> will create this directory + (and any missing parent directories) if it does not exist. If it + already exists, it must be empty. + </para> + <para> + When the backup is in tar format, the target directory may be + specified as <literal>-</literal> (dash), causing the tar file to be + written to <literal>stdout</literal>. + </para> + <para> + This option is required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable class="parameter">format</replaceable></option></term> + <term><option>--format=<replaceable class="parameter">format</replaceable></option></term> + <listitem> + <para> + Selects the format for the output. <replaceable>format</replaceable> + can be one of the following: + + <variablelist> + <varlistentry> + <term><literal>p</literal></term> + <term><literal>plain</literal></term> + <listitem> + <para> + Write the output as plain files, with the same layout as the + source server's data directory and tablespaces. When the cluster has + no additional tablespaces, the whole database will be placed in + the target directory. If the cluster contains additional + tablespaces, the main data directory will be placed in the + target directory, but all other tablespaces will be placed + in the same absolute path as they have on the source server. + (See <option>--tablespace-mapping</option> to change that.) + </para> + <para> + This is the default format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>t</literal></term> + <term><literal>tar</literal></term> + <listitem> + <para> + Write the output as tar files in the target directory. The main + data directory's contents will be written to a file named + <filename>base.tar</filename>, and each other tablespace will be + written to a separate tar file named after that tablespace's OID. + </para> + <para> + If the target directory is specified as <literal>-</literal> + (dash), the tar contents will be written to + standard output, suitable for piping to (for example) + <productname>gzip</productname>. This is only allowed if + the cluster has no additional tablespaces and WAL + streaming is not used. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option></term> + <term><option>--write-recovery-conf</option></term> + <listitem> + + <para> + Creates a + <link linkend="file-standby-signal"><filename>standby.signal</filename></link> + <indexterm><primary><filename>standby.signal</filename></primary><secondary>pg_basebackup --write-recovery-conf</secondary></indexterm> + file and appends + connection settings to the <filename>postgresql.auto.conf</filename> + file in the target directory (or within the base archive file when + using tar format). This eases setting up a standby server using the + results of the backup. + </para> + <para> + The <filename>postgresql.auto.conf</filename> file will record the connection + settings and, if specified, the replication slot + that <application>pg_basebackup</application> is using, so that + streaming replication will use the same settings later on. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">target</replaceable></option></term> + <term><option>--target=<replaceable class="parameter">target</replaceable></option></term> + <listitem> + + <para> + Instructs the server where to place the base backup. The default target + is <literal>client</literal>, which specifies that the backup should + be sent to the machine where <application>pg_basebackup</application> + is running. If the target is instead set to + <literal>server:/some/path</literal>, the backup will be stored on + the machine where the server is running in the + <literal>/some/path</literal> directory. Storing a backup on the + server requires superuser privileges or having privileges of the + <literal>pg_write_server_files</literal> role. If the target is set to + <literal>blackhole</literal>, the contents are discarded and not + stored anywhere. This should only be used for testing purposes, as you + will not end up with an actual backup. + </para> + + <para> + Since WAL streaming is implemented by + <application>pg_basebackup</application> rather than by the server, + this option cannot be used together with <literal>-Xstream</literal>. + Since that is the default, when this option is specified, you must also + specify either <literal>-Xfetch</literal> or <literal>-Xnone</literal>. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">olddir</replaceable>=<replaceable class="parameter">newdir</replaceable></option></term> + <term><option>--tablespace-mapping=<replaceable class="parameter">olddir</replaceable>=<replaceable class="parameter">newdir</replaceable></option></term> + <listitem> + <para> + Relocates the tablespace in directory <replaceable>olddir</replaceable> + to <replaceable>newdir</replaceable> during the backup. To be + effective, <replaceable>olddir</replaceable> must exactly match the + path specification of the tablespace as it is defined on the source + server. (But it is not an error if there is no tablespace + in <replaceable>olddir</replaceable> on the source server.) + Meanwhile <replaceable>newdir</replaceable> is a directory in the + receiving host's filesystem. As with the main target directory, + <replaceable>newdir</replaceable> need not exist already, but if + it does exist it must be empty. + Both <replaceable>olddir</replaceable> + and <replaceable>newdir</replaceable> must be absolute paths. If + either path needs to contain an equal sign (<literal>=</literal>), + precede that with a backslash. This option can be specified multiple + times for multiple tablespaces. + </para> + + <para> + If a tablespace is relocated in this way, the symbolic links inside + the main data directory are updated to point to the new location. So + the new data directory is ready to be used for a new server instance + with all tablespaces in the updated locations. + </para> + + <para> + Currently, this option only works with plain output format; it is + ignored if tar format is selected. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--waldir=<replaceable class="parameter">waldir</replaceable></option></term> + <listitem> + <para> + Sets the directory to write WAL (write-ahead log) files to. + By default WAL files will be placed in + the <filename>pg_wal</filename> subdirectory of the target + directory, but this option can be used to place them elsewhere. + <replaceable>waldir</replaceable> must be an absolute path. + As with the main target directory, + <replaceable>waldir</replaceable> need not exist already, but if + it does exist it must be empty. + This option can only be specified when + the backup is in plain format. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-X <replaceable class="parameter">method</replaceable></option></term> + <term><option>--wal-method=<replaceable class="parameter">method</replaceable></option></term> + <listitem> + <para> + Includes the required WAL (write-ahead log) files in the + backup. This will include all write-ahead logs generated during + the backup. Unless the method <literal>none</literal> is specified, + it is possible to start a postmaster in the target + directory without the need to consult the log archive, thus + making the output a completely standalone backup. + </para> + <para> + The following <replaceable>method</replaceable>s for collecting the + write-ahead logs are supported: + + <variablelist> + <varlistentry> + <term><literal>n</literal></term> + <term><literal>none</literal></term> + <listitem> + <para> + Don't include write-ahead logs in the backup. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>f</literal></term> + <term><literal>fetch</literal></term> + <listitem> + <para> + The write-ahead log files are collected at the end of the backup. + Therefore, it is necessary for the source server's + <xref linkend="guc-wal-keep-size"/> parameter to be set high + enough that the required log data is not removed before the end + of the backup. If the required log data has been recycled + before it's time to transfer it, the backup will fail and be + unusable. + </para> + <para> + When tar format is used, the write-ahead log files will be + included in the <filename>base.tar</filename> file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>s</literal></term> + <term><literal>stream</literal></term> + <listitem> + <para> + Stream write-ahead log data while the backup is being taken. + This method will open a second connection to the server and + start streaming the write-ahead log in parallel while running + the backup. Therefore, it will require two replication + connections not just one. As long as the client can keep up + with the write-ahead log data, using this method requires no + extra write-ahead logs to be saved on the source server. + </para> + <para> + When tar format is used, the write-ahead log files will be + written to a separate file named <filename>pg_wal.tar</filename> + (if the server is a version earlier than 10, the file will be named + <filename>pg_xlog.tar</filename>). + </para> + <para> + This value is the default. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-z</option></term> + <term><option>--gzip</option></term> + <listitem> + <para> + Enables gzip compression of tar file output, with the default + compression level. Compression is only available when using + the tar format, and the suffix <filename>.gz</filename> will + automatically be added to all tar filenames. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Z <replaceable class="parameter">level</replaceable></option></term> + <term><option>-Z [{client|server}-]<replaceable class="parameter">method</replaceable>[:<replaceable>detail</replaceable>]</option></term> + <term><option>--compress=<replaceable class="parameter">level</replaceable></option></term> + <term><option>--compress=[{client|server}-]<replaceable class="parameter">method</replaceable>[:<replaceable>detail</replaceable>]</option></term> + <listitem> + <para> + Requests compression of the backup. If <literal>client</literal> or + <literal>server</literal> is included, it specifies where the + compression is to be performed. Compressing on the server will reduce + transfer bandwidth but will increase server CPU consumption. The + default is <literal>client</literal> except when + <literal>--target</literal> is used. In that case, the backup is not + being sent to the client, so only server compression is sensible. + When <literal>-Xstream</literal>, which is the default, is used, + server-side compression will not be applied to the WAL. To compress + the WAL, use client-side compression, or + specify <literal>-Xfetch</literal>. + </para> + <para> + The compression method can be set to <literal>gzip</literal>, + <literal>lz4</literal>, <literal>zstd</literal>, or + <literal>none</literal> for no compression. A compression detail + string can optionally be specified. If the detail string is an + integer, it specifies the compression level. Otherwise, it should be + a comma-separated list of items, each of the form + <literal>keyword</literal> or <literal>keyword=value</literal>. + Currently, the supported keywords are <literal>level</literal> + and <literal>workers</literal>. + </para> + <para> + If no compression level is specified, the default compression level + will be used. If only a level is specified without mentioning an + algorithm, <literal>gzip</literal> compression will be used if the + level is greater than 0, and no compression will be used if the level + is 0. + </para> + <para> + When the tar format is used with <literal>gzip</literal>, + <literal>lz4</literal>, or <literal>zstd</literal>, the suffix + <filename>.gz</filename>, <filename>.lz4</filename>, or + <filename>.zst</filename>, respectively, will be automatically added to + all tar filenames. When the plain format is used, client-side + compression may not be specified, but it is still possible to request + server-side compression. If this is done, the server will compress the + backup for transmission, and the client will decompress and extract it. + </para> + <para> + When this option is used in combination with + <literal>-Xstream</literal>, <literal>pg_wal.tar</literal> will + be compressed using <literal>gzip</literal> if client-side gzip + compression is selected, but will not be compressed if any other + compression algorithm is selected, or if server-side compression + is selected. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + <para> + The following command-line options control the generation of the + backup and the invocation of the program: + + <variablelist> + <varlistentry> + <term><option>-c {fast|spread}</option></term> + <term><option>--checkpoint={fast|spread}</option></term> + <listitem> + <para> + Sets checkpoint mode to fast (immediate) or spread (the default) + (see <xref linkend="backup-lowlevel-base-backup"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C</option></term> + <term><option>--create-slot</option></term> + <listitem> + <para> + Specifies that the replication slot named by the + <literal>--slot</literal> option should be created before starting + the backup. An error is raised if the slot already exists. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l <replaceable class="parameter">label</replaceable></option></term> + <term><option>--label=<replaceable class="parameter">label</replaceable></option></term> + <listitem> + <para> + Sets the label for the backup. If none is specified, a default value of + <quote><literal>pg_basebackup base backup</literal></quote> will be used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-clean</option></term> + <listitem> + <para> + By default, when <command>pg_basebackup</command> aborts with an + error, it removes any directories it might have created before + discovering that it cannot finish the job (for example, the target + directory and write-ahead log directory). This option inhibits + tidying-up and is thus useful for debugging. + </para> + + <para> + Note that tablespace directories are not cleaned up either way. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_basebackup</command> will wait for all files + to be written safely to disk. This option causes + <command>pg_basebackup</command> to return without waiting, which is + faster, but means that a subsequent operating system crash can leave + the base backup corrupt. Generally, this option is useful for testing + but should not be used when creating a production installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <term><option>--progress</option></term> + <listitem> + <para> + Enables progress reporting. Turning this on will deliver an approximate + progress report during the backup. Since the database may change during + the backup, this is only an approximation and may not end at exactly + <literal>100%</literal>. In particular, when WAL log is included in the + backup, the total amount of data cannot be estimated in advance, and + in this case the estimated target size will increase once it passes the + total estimate without WAL. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r <replaceable class="parameter">rate</replaceable></option></term> + <term><option>--max-rate=<replaceable class="parameter">rate</replaceable></option></term> + <listitem> + <para> + Sets the maximum transfer rate at which data is collected from the + source server. This can be useful to limit the impact + of <application>pg_basebackup</application> on the server. Values + are in kilobytes per second. Use a suffix of <literal>M</literal> + to indicate megabytes per second. A suffix of <literal>k</literal> + is also accepted, and has no effect. Valid values are between 32 + kilobytes per second and 1024 megabytes per second. + </para> + <para> + This option always affects transfer of the data directory. Transfer of + WAL files is only affected if the collection method + is <literal>fetch</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable>slotname</replaceable></option></term> + <term><option>--slot=<replaceable class="parameter">slotname</replaceable></option></term> + <listitem> + <para> + This option can only be used together with <literal>-X + stream</literal>. It causes WAL streaming to use the specified + replication slot. If the base backup is intended to be used as a + streaming-replication standby using a replication slot, the standby + should then use the same replication slot name as + <xref linkend="guc-primary-slot-name"/>. This ensures that the + primary server does not remove any necessary WAL data in the time + between the end of the base backup and the start of streaming + replication on the new standby. + </para> + <para> + The specified replication slot has to exist unless the + option <option>-C</option> is also used. + </para> + <para> + If this option is not specified and the server supports temporary + replication slots (version 10 and later), then a temporary replication + slot is automatically used for WAL streaming. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Enables verbose mode. Will output some extra steps during startup and + shutdown, as well as show the exact file name that is currently being + processed if progress reporting is also enabled. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--manifest-checksums=<replaceable class="parameter">algorithm</replaceable></option></term> + <listitem> + <para> + Specifies the checksum algorithm that should be applied to each file + included in the backup manifest. Currently, the available + algorithms are <literal>NONE</literal>, <literal>CRC32C</literal>, + <literal>SHA224</literal>, <literal>SHA256</literal>, + <literal>SHA384</literal>, and <literal>SHA512</literal>. + The default is <literal>CRC32C</literal>. + </para> + <para> + If <literal>NONE</literal> is selected, the backup manifest will + not contain any checksums. Otherwise, it will contain a checksum + of each file in the backup using the specified algorithm. In addition, + the manifest will always contain a <literal>SHA256</literal> + checksum of its own contents. The <literal>SHA</literal> algorithms + are significantly more CPU-intensive than <literal>CRC32C</literal>, + so selecting one of them may increase the time required to complete + the backup. + </para> + <para> + Using a SHA hash function provides a cryptographically secure digest + of each file for users who wish to verify that the backup has not been + tampered with, while the CRC32C algorithm provides a checksum that is + much faster to calculate; it is good at catching errors due to accidental + changes but is not resistant to malicious modifications. Note that, to + be useful against an adversary who has access to the backup, the backup + manifest would need to be stored securely elsewhere or otherwise + verified not to have been modified since the backup was taken. + </para> + <para> + <xref linkend="app-pgverifybackup"/> can be used to check the + integrity of a backup against the backup manifest. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--manifest-force-encode</option></term> + <listitem> + <para> + Forces all filenames in the backup manifest to be hex-encoded. + If this option is not specified, only non-UTF8 filenames are + hex-encoded. This option is mostly intended to test that tools which + read a backup manifest file properly handle this case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-estimate-size</option></term> + <listitem> + <para> + Prevents the server from estimating the total + amount of backup data that will be streamed, resulting in the + <structfield>backup_total</structfield> column in the + <structname>pg_stat_progress_basebackup</structname> view + always being <literal>NULL</literal>. + </para> + <para> + Without this option, the backup will start by enumerating + the size of the entire database, and then go back and send + the actual contents. This may make the backup take slightly + longer, and in particular it will take longer before the first + data is sent. This option is useful to avoid such estimation + time if it's too long. + </para> + <para> + This option is not allowed when using <option>--progress</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-manifest</option></term> + <listitem> + <para> + Disables generation of a backup manifest. If this option is not + specified, the server will generate and send a backup manifest + which can be verified using <xref linkend="app-pgverifybackup"/>. + The manifest is a list of every file present in the backup with the + exception of any WAL files that may be included. It also stores the + size, last modification time, and an optional checksum for each file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-slot</option></term> + <listitem> + <para> + Prevents the creation of a temporary replication slot + for the backup. + </para> + <para> + By default, if log streaming is selected but no slot name is given + with the <option>-S</option> option, then a temporary replication + slot is created (if supported by the source server). + </para> + <para> + The main purpose of this option is to allow taking a base backup when + the server has no free replication slots. Using a replication slot + is almost always preferred, because it prevents needed WAL from being + removed by the server during the backup. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-verify-checksums</option></term> + <listitem> + <para> + Disables verification of checksums, if they are enabled on the server + the base backup is taken from. + </para> + <para> + By default, checksums are verified and checksum failures will result + in a non-zero exit status. However, the base backup will not be + removed in such a case, as if the <option>--no-clean</option> option + had been used. Checksum verification failures will also be reported + in the <link linkend="monitoring-pg-stat-database-view"> + <structname>pg_stat_database</structname></link> view. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following command-line options control the connection to the source + server: + + <variablelist> + <varlistentry> + <term><option>-d <replaceable class="parameter">connstr</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">connstr</replaceable></option></term> + <listitem> + <para> + Specifies parameters used to connect to the server, as a <link + linkend="libpq-connstring">connection string</link>; these + will override any conflicting command line options. + </para> + <para> + The option is called <literal>--dbname</literal> for consistency with other + client applications, but because <application>pg_basebackup</application> + doesn't connect to any particular database in the cluster, any database + name in the connection string will be ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for a Unix domain socket. The default is taken + from the <envar>PGHOST</envar> environment variable, if set, + else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s <replaceable class="parameter">interval</replaceable></option></term> + <term><option>--status-interval=<replaceable class="parameter">interval</replaceable></option></term> + <listitem> + <para> + Specifies the number of seconds between status packets sent back to + the source server. Smaller values allow more accurate monitoring of + backup progress from the server. + A value of zero disables periodic status updates completely, + although an update will still be sent when requested by the server, to + avoid timeout-based disconnects. The default value is 10 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Specifies the user name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Prevents issuing a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Forces <application>pg_basebackup</application> to prompt for a + password before connecting to the source server. + </para> + + <para> + This option is never essential, since + <application>pg_basebackup</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_basebackup</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other options are also available: + + <variablelist> + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Prints the <application>pg_basebackup</application> version and exits. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Shows help about <application>pg_basebackup</application> command line + arguments, and exits. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + At the beginning of the backup, a checkpoint needs to be performed on the + source server. This can take some time (especially if the option + <literal>--checkpoint=fast</literal> is not used), during + which <application>pg_basebackup</application> will appear to be idle. + </para> + + <para> + The backup will include all files in the data directory and tablespaces, + including the configuration files and any additional files placed in the + directory by third parties, except certain temporary files managed by + PostgreSQL. But only regular files and directories are copied, except that + symbolic links used for tablespaces are preserved. Symbolic links pointing + to certain directories known to PostgreSQL are copied as empty directories. + Other symbolic links and special device files are skipped. + See <xref linkend="protocol-replication"/> for the precise details. + </para> + + <para> + In plain format, tablespaces will be backed up to the same path + they have on the source server, unless the + option <literal>--tablespace-mapping</literal> is used. Without + this option, running a plain format base backup on the same host as the + server will not work if tablespaces are in use, because the backup would + have to be written to the same directory locations as the original + tablespaces. + </para> + + <para> + When tar format is used, it is the user's responsibility to unpack each + tar file before starting a PostgreSQL server that uses the data. If there + are additional tablespaces, the + tar files for them need to be unpacked in the correct locations. In this + case the symbolic links for those tablespaces will be created by the server + according to the contents of the <filename>tablespace_map</filename> file that is + included in the <filename>base.tar</filename> file. + </para> + + <para> + <application>pg_basebackup</application> works with servers of the same + or an older major version, down to 9.1. However, WAL streaming mode (<literal>-X + stream</literal>) only works with server version 9.3 and later, and tar format + (<literal>--format=tar</literal>) only works with server version 9.5 + and later. + </para> + + <para> + <application>pg_basebackup</application> will preserve group permissions + for data files if group permissions are enabled on the source cluster. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To create a base backup of the server at <literal>mydbserver</literal> + and store it in the local directory + <filename>/usr/local/pgsql/data</filename>: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -h mydbserver -D /usr/local/pgsql/data</userinput> +</screen> + </para> + + <para> + To create a backup of the local server with one compressed + tar file for each tablespace, and store it in the directory + <filename>backup</filename>, showing a progress report while running: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -D backup -Ft -z -P</userinput> +</screen> + </para> + + <para> + To create a backup of a single-tablespace local database and compress + this with <productname>bzip2</productname>: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -D - -Ft -X fetch | bzip2 > backup.tar.bz2</userinput> +</screen> + (This command will fail if there are multiple tablespaces in the + database.) + </para> + + <para> + To create a backup of a local database where the tablespace in + <filename>/opt/ts</filename> is relocated + to <filename>./backup/ts</filename>: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -D backup/data -T /opt/ts=$(pwd)/backup/ts</userinput> +</screen></para> + + <para> + To create a backup of a local server with one tar file for each tablespace + compressed with <application>gzip</application> at level 9, stored in the + directory <filename>backup</filename>: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -D backup -Ft --compress=gzip:9</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgdump"/></member> + <member><xref linkend="basebackup-progress-reporting"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_checksums.sgml b/doc/src/sgml/ref/pg_checksums.sgml new file mode 100644 index 0000000..bab9501 --- /dev/null +++ b/doc/src/sgml/ref/pg_checksums.sgml @@ -0,0 +1,229 @@ +<!-- +doc/src/sgml/ref/pg_checksums.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgchecksums"> + <indexterm zone="app-pgchecksums"> + <primary>pg_checksums</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_checksums</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_checksums</refname> + <refpurpose>enable, disable or check data checksums in a <productname>PostgreSQL</productname> database cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_checksums</command> + <arg rep="repeat" choice="opt"><replaceable class="parameter">option</replaceable></arg> + <group choice="opt"> + <group choice="opt"> + <arg choice="plain"><option>-D</option></arg> + <arg choice="plain"><option>--pgdata</option></arg> + </group> + <replaceable class="parameter">datadir</replaceable> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="r1-app-pg_checksums-1"> + <title>Description</title> + <para> + <application>pg_checksums</application> checks, enables or disables data + checksums in a <productname>PostgreSQL</productname> cluster. The server + must be shut down cleanly before running + <application>pg_checksums</application>. When verifying checksums, the exit + status is zero if there are no checksum errors, and nonzero if at least one + checksum failure is detected. When enabling or disabling checksums, the + exit status is nonzero if the operation failed. + </para> + + <para> + When verifying checksums, every file in the cluster is scanned. When + enabling checksums, each relation file block with a changed checksum is + rewritten in-place. + Disabling checksums only updates the file <filename>pg_control</filename>. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following command-line options are available: + + <variablelist> + <varlistentry> + <term><option>-D <replaceable>directory</replaceable></option></term> + <term><option>--pgdata=<replaceable>directory</replaceable></option></term> + <listitem> + <para> + Specifies the directory where the database cluster is stored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--check</option></term> + <listitem> + <para> + Checks checksums. This is the default mode if nothing else is + specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d</option></term> + <term><option>--disable</option></term> + <listitem> + <para> + Disables checksums. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--enable</option></term> + <listitem> + <para> + Enables checksums. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable>filenode</replaceable></option></term> + <term><option>--filenode=<replaceable>filenode</replaceable></option></term> + <listitem> + <para> + Only validate checksums in the relation with filenode + <replaceable>filenode</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_checksums</command> will wait for all files + to be written safely to disk. This option causes + <command>pg_checksums</command> to return without waiting, which is + faster, but means that a subsequent operating system crash can leave + the updated data directory corrupt. Generally, this option is useful + for testing but should not be used on a production installation. + This option has no effect when using <literal>--check</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <term><option>--progress</option></term> + <listitem> + <para> + Enable progress reporting. Turning this on will deliver a progress + report while checking or enabling checksums. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Enable verbose output. Lists all checked files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_checksums</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_checksums</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATA</envar></term> + + <listitem> + <para> + Specifies the directory where the database cluster is + stored; can be overridden using the <option>-D</option> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + <para> + Enabling checksums in a large cluster can potentially take a long time. + During this operation, the cluster or other programs that write to the + data directory must not be started or else data loss may occur. + </para> + <para> + When using a replication setup with tools which perform direct copies + of relation file blocks (for example <xref linkend="app-pgrewind"/>), + enabling or disabling checksums can lead to page corruptions in the + shape of incorrect checksums if the operation is not done consistently + across all nodes. When enabling or disabling checksums in a replication + setup, it is thus recommended to stop all the clusters before switching + them all consistently. Destroying all standbys, performing the operation + on the primary and finally recreating the standbys from scratch is also + safe. + </para> + <para> + If <application>pg_checksums</application> is aborted or killed while + enabling or disabling checksums, the cluster's data checksum configuration + remains unchanged, and <application>pg_checksums</application> can be + re-run to perform the same operation. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_config-ref.sgml b/doc/src/sgml/ref/pg_config-ref.sgml new file mode 100644 index 0000000..e177769 --- /dev/null +++ b/doc/src/sgml/ref/pg_config-ref.sgml @@ -0,0 +1,332 @@ +<!-- +doc/src/sgml/ref/pg_config-ref.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgconfig"> + <indexterm zone="app-pgconfig"> + <primary>pg_config</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_config</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_config</refname> + <refpurpose>retrieve information about the installed version of <productname>PostgreSQL</productname></refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_config</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + The <application>pg_config</application> utility prints configuration parameters + of the currently installed version of <productname>PostgreSQL</productname>. It is + intended, for example, to be used by software packages that want to interface + to <productname>PostgreSQL</productname> to facilitate finding the required header files + and libraries. + </para> + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + To use <application>pg_config</application>, supply one or more of the following + options: + <variablelist> + <varlistentry> + <term><option>--bindir</option></term> + <listitem> + <para> + Print the location of user executables. Use this, for example, to find + the <command>psql</command> program. This is normally also the location + where the <filename>pg_config</filename> program resides. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--docdir</option></term> + <listitem> + <para> + Print the location of documentation files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--htmldir</option></term> + <listitem> + <para> + Print the location of HTML documentation files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--includedir</option></term> + <listitem> + <para> + Print the location of C header files of the client interfaces. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--pkgincludedir</option></term> + <listitem> + <para> + Print the location of other C header files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--includedir-server</option></term> + <listitem> + <para> + Print the location of C header files for server programming. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--libdir</option></term> + <listitem> + <para> + Print the location of object code libraries. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--pkglibdir</option></term> + <listitem> + <para> + Print the location of dynamically loadable modules, or where + the server would search for them. (Other + architecture-dependent data files might also be installed in this + directory.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--localedir</option></term> + <listitem> + <para> + Print the location of locale support files. (This will be an empty + string if locale support was not configured when + <productname>PostgreSQL</productname> was built.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--mandir</option></term> + <listitem> + <para> + Print the location of manual pages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--sharedir</option></term> + <listitem> + <para> + Print the location of architecture-independent support files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--sysconfdir</option></term> + <listitem> + <para> + Print the location of system-wide configuration files. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--pgxs</option></term> + <listitem> + <para> + Print the location of extension makefiles. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--configure</option></term> + <listitem> + <para> + Print the options that were given to the <filename>configure</filename> + script when <productname>PostgreSQL</productname> was configured for building. + This can be used to reproduce the identical configuration, or + to find out with what options a binary package was built. (Note + however that binary packages often contain vendor-specific custom + patches.) See also the examples below. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--cc</option></term> + <listitem> + <para> + Print the value of the <varname>CC</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows the C compiler used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--cppflags</option></term> + <listitem> + <para> + Print the value of the <varname>CPPFLAGS</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows C compiler switches needed + at preprocessing time (typically, <literal>-I</literal> switches). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--cflags</option></term> + <listitem> + <para> + Print the value of the <varname>CFLAGS</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows C compiler switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--cflags_sl</option></term> + <listitem> + <para> + Print the value of the <varname>CFLAGS_SL</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows extra C compiler switches + used for building shared libraries. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--ldflags</option></term> + <listitem> + <para> + Print the value of the <varname>LDFLAGS</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows linker switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--ldflags_ex</option></term> + <listitem> + <para> + Print the value of the <varname>LDFLAGS_EX</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows linker switches + used for building executables only. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--ldflags_sl</option></term> + <listitem> + <para> + Print the value of the <varname>LDFLAGS_SL</varname> variable that was used for building + <productname>PostgreSQL</productname>. This shows linker switches + used for building shared libraries only. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--libs</option></term> + <listitem> + <para> + Print the value of the <varname>LIBS</varname> variable that was used for building + <productname>PostgreSQL</productname>. This normally contains <literal>-l</literal> + switches for external libraries linked into <productname>PostgreSQL</productname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--version</option></term> + <listitem> + <para> + Print the version of <productname>PostgreSQL</productname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_config</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + + If more than one option is given, the information is printed in that order, + one item per line. If no options are given, all available information + is printed, with labels. + </para> + </refsect1> + + + <refsect1> + <title>Notes</title> + + <para> + The options <option>--docdir</option>, <option>--pkgincludedir</option>, + <option>--localedir</option>, <option>--mandir</option>, + <option>--sharedir</option>, <option>--sysconfdir</option>, + <option>--cc</option>, <option>--cppflags</option>, + <option>--cflags</option>, <option>--cflags_sl</option>, + <option>--ldflags</option>, <option>--ldflags_sl</option>, + and <option>--libs</option> were added in <productname>PostgreSQL</productname> 8.1. + The option <option>--htmldir</option> was added in <productname>PostgreSQL</productname> 8.4. + The option <option>--ldflags_ex</option> was added in <productname>PostgreSQL</productname> 9.0. + </para> + </refsect1> + + + <refsect1> + <title>Example</title> + + <para> + To reproduce the build configuration of the current PostgreSQL + installation, run the following command: +<programlisting> +eval ./configure `pg_config --configure` +</programlisting> + The output of <literal>pg_config --configure</literal> contains + shell quotation marks so arguments with spaces are represented + correctly. Therefore, using <literal>eval</literal> is required + for proper results. + </para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_controldata.sgml b/doc/src/sgml/ref/pg_controldata.sgml new file mode 100644 index 0000000..b47fdca --- /dev/null +++ b/doc/src/sgml/ref/pg_controldata.sgml @@ -0,0 +1,84 @@ +<!-- +doc/src/sgml/ref/pg_controldata.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgcontroldata"> + <indexterm zone="app-pgcontroldata"> + <primary>pg_controldata</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_controldata</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_controldata</refname> + <refpurpose>display control information of a <productname>PostgreSQL</productname> database cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_controldata</command> + <arg choice="opt"><replaceable class="parameter">option</replaceable></arg> + <group choice="opt"> + <group choice="opt"> + <arg choice="plain"><option>-D</option></arg> + <arg choice="plain"><option>--pgdata</option></arg> + </group> + <replaceable class="parameter">datadir</replaceable> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="r1-app-pgcontroldata-1"> + <title>Description</title> + <para> + <command>pg_controldata</command> prints information initialized during + <command>initdb</command>, such as the catalog version. + It also shows information about write-ahead logging and checkpoint + processing. This information is cluster-wide, and not specific to any one + database. + </para> + + <para> + This utility can only be run by the user who initialized the cluster because + it requires read access to the data directory. + You can specify the data directory on the command line, or use + the environment variable <envar>PGDATA</envar>. This utility supports the options + <option>-V</option> and <option>--version</option>, which print the + <application>pg_controldata</application> version and exit. It also + supports options <option>-?</option> and <option>--help</option>, which output the + supported arguments. + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATA</envar></term> + + <listitem> + <para> + Default data directory location + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_ctl-ref.sgml b/doc/src/sgml/ref/pg_ctl-ref.sgml new file mode 100644 index 0000000..4690696 --- /dev/null +++ b/doc/src/sgml/ref/pg_ctl-ref.sgml @@ -0,0 +1,713 @@ +<!-- +doc/src/sgml/ref/pg_ctl-ref.sgml +PostgreSQL documentation +--> + +<refentry id="app-pg-ctl"> + <indexterm zone="app-pg-ctl"> + <primary>pg_ctl</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_ctl</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_ctl</refname> + <refpurpose>initialize, start, stop, or control a <productname>PostgreSQL</productname> server</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>init[db]</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + <arg choice="opt"><option>-o</option> <replaceable>initdb-options</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>start</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-l</option> <replaceable>filename</replaceable></arg> + <arg choice="opt"><option>-W</option></arg> + <arg choice="opt"><option>-t</option> <replaceable>seconds</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + <arg choice="opt"><option>-o</option> <replaceable>options</replaceable></arg> + <arg choice="opt"><option>-p</option> <replaceable>path</replaceable></arg> + <arg choice="opt"><option>-c</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>stop</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-m</option> + <group choice="plain"> + <arg choice="plain"><option>s[mart]</option></arg> + <arg choice="plain"><option>f[ast]</option></arg> + <arg choice="plain"><option>i[mmediate]</option></arg> + </group> + </arg> + <arg choice="opt"><option>-W</option></arg> + <arg choice="opt"><option>-t</option> <replaceable>seconds</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>restart</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-m</option> + <group choice="plain"> + <arg choice="plain"><option>s[mart]</option></arg> + <arg choice="plain"><option>f[ast]</option></arg> + <arg choice="plain"><option>i[mmediate]</option></arg> + </group> + </arg> + <arg choice="opt"><option>-W</option></arg> + <arg choice="opt"><option>-t</option> <replaceable>seconds</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + <arg choice="opt"><option>-o</option> <replaceable>options</replaceable></arg> + <arg choice="opt"><option>-c</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>reload</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>status</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>promote</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-W</option></arg> + <arg choice="opt"><option>-t</option> <replaceable>seconds</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>logrotate</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>kill</option></arg> + <arg choice="plain"><replaceable>signal_name</replaceable></arg> + <arg choice="plain"><replaceable>process_id</replaceable></arg> + </cmdsynopsis> + + <para>On Microsoft Windows, also:</para> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>register</option></arg> + <arg choice="opt"><option>-D</option> <replaceable>datadir</replaceable></arg> + <arg choice="opt"><option>-N</option> <replaceable>servicename</replaceable></arg> + <arg choice="opt"><option>-U</option> <replaceable>username</replaceable></arg> + <arg choice="opt"><option>-P</option> <replaceable>password</replaceable></arg> + <arg choice="opt"><option>-S</option> + <group choice="plain"> + <arg choice="plain"><option>a[uto]</option></arg> + <arg choice="plain"><option>d[emand]</option></arg> + </group> + </arg> + <arg choice="opt"><option>-e</option> <replaceable>source</replaceable></arg> + <arg choice="opt"><option>-W</option></arg> + <arg choice="opt"><option>-t</option> <replaceable>seconds</replaceable></arg> + <arg choice="opt"><option>-s</option></arg> + <arg choice="opt"><option>-o</option> <replaceable>options</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>pg_ctl</command> + <arg choice="plain"><option>unregister</option></arg> + <arg choice="opt"><option>-N</option> <replaceable>servicename</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="app-pg-ctl-description"> + <title>Description</title> + <para> + <application>pg_ctl</application> is a utility for initializing a + <productname>PostgreSQL</productname> database cluster, starting, + stopping, or restarting the <productname>PostgreSQL</productname> + database server (<xref linkend="app-postgres"/>), or displaying the + status of a running server. Although the server can be started + manually, <application>pg_ctl</application> encapsulates tasks such + as redirecting log output and properly detaching from the terminal + and process group. It also provides convenient options for + controlled shutdown. + </para> + + <para> + The <option>init</option> or <option>initdb</option> mode creates a new + <productname>PostgreSQL</productname> database cluster, that is, + a collection of databases that will be managed by a single + server instance. This mode invokes the <command>initdb</command> + command. See <xref linkend="app-initdb"/> for details. + </para> + + <para> + <option>start</option> mode launches a new server. The + server is started in the background, and its standard input is attached + to <filename>/dev/null</filename> (or <literal>nul</literal> on Windows). + On Unix-like systems, by default, the server's standard output and + standard error are sent to <application>pg_ctl</application>'s + standard output (not standard error). The standard output of + <application>pg_ctl</application> should then be redirected to a + file or piped to another process such as a log rotating program + like <application>rotatelogs</application>; otherwise <command>postgres</command> + will write its output to the controlling terminal (from the + background) and will not leave the shell's process group. On + Windows, by default the server's standard output and standard error + are sent to the terminal. These default behaviors can be changed + by using <option>-l</option> to append the server's output to a log file. + Use of either <option>-l</option> or output redirection is recommended. + </para> + + <para> + <option>stop</option> mode shuts down the server that is running in + the specified data directory. Three different + shutdown methods can be selected with the <option>-m</option> + option. <quote>Smart</quote> mode disallows new connections, then waits + for all existing clients to disconnect. + If the server is in hot standby, recovery and streaming replication + will be terminated once all clients have disconnected. + <quote>Fast</quote> mode (the default) does not wait for clients to disconnect. + All active transactions are + rolled back and clients are forcibly disconnected, then the + server is shut down. <quote>Immediate</quote> mode will abort + all server processes immediately, without a clean shutdown. This choice + will lead to a crash-recovery cycle during the next server start. + </para> + + <para> + <option>restart</option> mode effectively executes a stop followed + by a start. This allows changing the <command>postgres</command> + command-line options, or changing configuration-file options that + cannot be changed without restarting the server. + If relative paths were used on the command line during server + start, <option>restart</option> might fail unless + <application>pg_ctl</application> is executed in the same current + directory as it was during server start. + </para> + + <para> + <option>reload</option> mode simply sends the + <command>postgres</command> server process a <systemitem>SIGHUP</systemitem> + signal, causing it to reread its configuration files + (<filename>postgresql.conf</filename>, + <filename>pg_hba.conf</filename>, etc.). This allows changing + configuration-file options that do not require a full server restart + to take effect. + </para> + + <para> + <option>status</option> mode checks whether a server is running in + the specified data directory. If it is, the server's <acronym>PID</acronym> + and the command line options that were used to invoke it are displayed. + If the server is not running, <application>pg_ctl</application> returns + an exit status of 3. If an accessible data directory is not + specified, <application>pg_ctl</application> returns an exit status of 4. + </para> + + <para> + <option>promote</option> mode commands the standby server that is + running in the specified data directory to end standby mode + and begin read-write operations. + </para> + + <para> + <option>logrotate</option> mode rotates the server log file. + For details on how to use this mode with external log rotation tools, see + <xref linkend="logfile-maintenance"/>. + </para> + + <para> + <option>kill</option> mode sends a signal to a specified process. + This is primarily valuable on <productname>Microsoft Windows</productname> + which does not have a built-in <application>kill</application> command. Use + <literal>--help</literal> to see a list of supported signal names. + </para> + + <para> + <option>register</option> mode registers the <productname>PostgreSQL</productname> + server as a system service on <productname>Microsoft Windows</productname>. + The <option>-S</option> option allows selection of service start type, + either <quote>auto</quote> (start service automatically on system startup) + or <quote>demand</quote> (start service on demand). + </para> + + <para> + <option>unregister</option> mode unregisters a system service + on <productname>Microsoft Windows</productname>. This undoes the effects of the + <option>register</option> command. + </para> + </refsect1> + + <refsect1 id="app-pg-ctl-options"> + <title>Options</title> + + <variablelist> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--core-files</option></term> + <listitem> + <para> + Attempt to allow server crashes to produce core files, on platforms + where this is possible, by lifting any soft resource limit placed on + core files. + This is useful in debugging or diagnosing problems by allowing a + stack trace to be obtained from a failed server process. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable class="parameter">datadir</replaceable></option></term> + <term><option>--pgdata=<replaceable class="parameter">datadir</replaceable></option></term> + <listitem> + <para> + Specifies the file system location of the database configuration files. If + this option is omitted, the environment variable + <envar>PGDATA</envar> is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l <replaceable class="parameter">filename</replaceable></option></term> + <term><option>--log=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Append the server log output to + <replaceable>filename</replaceable>. If the file does not + exist, it is created. The <systemitem>umask</systemitem> is set to 077, + so access to the log file is disallowed to other users by default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-m <replaceable class="parameter">mode</replaceable></option></term> + <term><option>--mode=<replaceable class="parameter">mode</replaceable></option></term> + <listitem> + <para> + Specifies the shutdown mode. <replaceable>mode</replaceable> + can be <literal>smart</literal>, <literal>fast</literal>, or + <literal>immediate</literal>, or the first letter of one of + these three. If this option is omitted, <literal>fast</literal> is + the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable class="parameter">options</replaceable></option></term> + <term><option>--options=<replaceable class="parameter">options</replaceable></option></term> + <listitem> + <para> + Specifies options to be passed directly to the + <command>postgres</command> command. + <option>-o</option> can be specified multiple times, with all the given + options being passed through. + </para> + <para> + The <replaceable>options</replaceable> should usually be surrounded by single or + double quotes to ensure that they are passed through as a group. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable class="parameter">initdb-options</replaceable></option></term> + <term><option>--options=<replaceable class="parameter">initdb-options</replaceable></option></term> + <listitem> + <para> + Specifies options to be passed directly to the + <command>initdb</command> command. + <option>-o</option> can be specified multiple times, with all the given + options being passed through. + </para> + <para> + The <replaceable>initdb-options</replaceable> should usually be surrounded by single or + double quotes to ensure that they are passed through as a group. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">path</replaceable></option></term> + <listitem> + <para> + Specifies the location of the <filename>postgres</filename> + executable. By default the <filename>postgres</filename> executable is taken from the same + directory as <command>pg_ctl</command>, or failing that, the hard-wired + installation directory. It is not necessary to use this + option unless you are doing something unusual and get errors + that the <filename>postgres</filename> executable was not found. + </para> + + <para> + In <literal>init</literal> mode, this option analogously + specifies the location of the <filename>initdb</filename> + executable. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--silent</option></term> + <listitem> + <para> + Print only errors, no informational messages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">seconds</replaceable></option></term> + <term><option>--timeout=<replaceable class="parameter">seconds</replaceable></option></term> + <listitem> + <para> + Specifies the maximum number of seconds to wait when waiting for an + operation to complete (see option <option>-w</option>). Defaults to + the value of the <envar>PGCTLTIMEOUT</envar> environment variable or, if + not set, to 60 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_ctl</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--wait</option></term> + <listitem> + <para> + Wait for the operation to complete. This is supported for the + modes <literal>start</literal>, <literal>stop</literal>, + <literal>restart</literal>, <literal>promote</literal>, + and <literal>register</literal>, and is the default for those modes. + </para> + + <para> + When waiting, <command>pg_ctl</command> repeatedly checks the + server's <acronym>PID</acronym> file, sleeping for a short amount + of time between checks. Startup is considered complete when + the <acronym>PID</acronym> file indicates that the server is ready to + accept connections. Shutdown is considered complete when the server + removes the <acronym>PID</acronym> file. + <command>pg_ctl</command> returns an exit code based on the + success of the startup or shutdown. + </para> + + <para> + If the operation does not complete within the timeout (see + option <option>-t</option>), then <command>pg_ctl</command> exits with + a nonzero exit status. But note that the operation might continue in + the background and eventually succeed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--no-wait</option></term> + <listitem> + <para> + Do not wait for the operation to complete. This is the opposite of + the option <option>-w</option>. + </para> + + <para> + If waiting is disabled, the requested action is triggered, but there + is no feedback about its success. In that case, the server log file + or an external monitoring system would have to be used to check the + progress and success of the operation. + </para> + + <para> + In prior releases of PostgreSQL, this was the default except for + the <literal>stop</literal> mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_ctl</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + If an option is specified that is valid, but not relevant to the selected + operating mode, <application>pg_ctl</application> ignores it. + </para> + + <refsect2 id="app-pg-ctl-windows-options"> + <title>Options for Windows</title> + + <variablelist> + <varlistentry> + <term><option>-e <replaceable class="parameter">source</replaceable></option></term> + <listitem> + <para> + Name of the event source for <application>pg_ctl</application> to use + for logging to the event log when running as a Windows service. The + default is <literal>PostgreSQL</literal>. Note that this only controls + messages sent from <application>pg_ctl</application> itself; once + started, the server will use the event source specified + by its <xref linkend="guc-event-source"/> parameter. Should the server + fail very early in startup, before that parameter has been set, + it might also log using the default event + source name <literal>PostgreSQL</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N <replaceable class="parameter">servicename</replaceable></option></term> + <listitem> + <para> + Name of the system service to register. This name will be used + as both the service name and the display name. + The default is <literal>PostgreSQL</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P <replaceable class="parameter">password</replaceable></option></term> + <listitem> + <para> + Password for the user to run the service as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">start-type</replaceable></option></term> + <listitem> + <para> + Start type of the system service. <replaceable>start-type</replaceable> can + be <literal>auto</literal>, or <literal>demand</literal>, or + the first letter of one of these two. If this option is omitted, + <literal>auto</literal> is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name for the user to run the service as. For domain users, use the + format <literal>DOMAIN\username</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGCTLTIMEOUT</envar></term> + + <listitem> + <para> + Default limit on the number of seconds to wait when waiting for startup + or shutdown to complete. If not set, the default is 60 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGDATA</envar></term> + + <listitem> + <para> + Default data directory location. + </para> + </listitem> + </varlistentry> + + </variablelist> + + <para> + Most <command>pg_ctl</command> modes require knowing the data directory + location; therefore, the <option>-D</option> option is required + unless <envar>PGDATA</envar> is set. + </para> + + <para> + <command>pg_ctl</command>, like most other <productname>PostgreSQL</productname> + utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + For additional variables that affect the server, + see <xref linkend="app-postgres"/>. + </para> + </refsect1> + + + <refsect1> + <title>Files</title> + + <variablelist> + <varlistentry> + <term><filename>postmaster.pid</filename></term> + + <listitem> + <para> + <application>pg_ctl</application> examines this file in the data + directory to determine whether the server is currently running. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>postmaster.opts</filename></term> + + <listitem> + <para>If this file exists in the data directory, + <application>pg_ctl</application> (in <option>restart</option> mode) + will pass the contents of the file as options to + <application>postgres</application>, unless overridden + by the <option>-o</option> option. The contents of this file + are also displayed in <option>status</option> mode. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + + <refsect1 id="r1-app-pgctl-2"> + <title>Examples</title> + + <refsect2 id="r2-app-pgctl-3"> + <title>Starting the Server</title> + + <para> + To start the server, waiting until the server is + accepting connections: +<screen> +<prompt>$</prompt> <userinput>pg_ctl start</userinput> +</screen> + </para> + + <para> + To start the server using port 5433, and + running without <function>fsync</function>, use: +<screen> +<prompt>$</prompt> <userinput>pg_ctl -o "-F -p 5433" start</userinput> +</screen></para> + </refsect2> + + <refsect2 id="r2-app-pgctl-4"> + <title>Stopping the Server</title> + <para> + To stop the server, use: +<screen> +<prompt>$</prompt> <userinput>pg_ctl stop</userinput> +</screen> + The <option>-m</option> option allows control over + <emphasis>how</emphasis> the server shuts down: +<screen> +<prompt>$</prompt> <userinput>pg_ctl stop -m smart</userinput> +</screen></para> + </refsect2> + + <refsect2 id="r2-app-pgctl-5"> + <title>Restarting the Server</title> + + <para> + Restarting the server is almost equivalent to stopping the + server and starting it again, except that by default, + <command>pg_ctl</command> saves and reuses the command line options that + were passed to the previously-running instance. To restart + the server using the same options as before, use: +<screen> +<prompt>$</prompt> <userinput>pg_ctl restart</userinput> +</screen> + </para> + + <para> + But if <option>-o</option> is specified, that replaces any previous options. + To restart using port 5433, disabling <function>fsync</function> upon restart: +<screen> +<prompt>$</prompt> <userinput>pg_ctl -o "-F -p 5433" restart</userinput> +</screen></para> + </refsect2> + + <refsect2 id="r2-app-pgctl-6"> + <title>Showing the Server Status</title> + + <para> + Here is sample status output from + <application>pg_ctl</application>: +<screen> +<prompt>$</prompt> <userinput>pg_ctl status</userinput> +<computeroutput> +pg_ctl: server is running (PID: 13718) +/usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data" "-p" "5433" "-B" "128" +</computeroutput></screen> + The second line is the command that would be invoked in restart mode. + </para> + </refsect2> + </refsect1> + + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-initdb"/></member> + <member><xref linkend="app-postgres"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_dump.sgml b/doc/src/sgml/ref/pg_dump.sgml new file mode 100644 index 0000000..c19e0b6 --- /dev/null +++ b/doc/src/sgml/ref/pg_dump.sgml @@ -0,0 +1,1538 @@ +<!-- +doc/src/sgml/ref/pg_dump.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgdump"> + <indexterm zone="app-pgdump"> + <primary>pg_dump</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_dump</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_dump</refname> + + <refpurpose> + extract a <productname>PostgreSQL</productname> database into a script file or other archive file + </refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_dump</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="pg-dump-description"> + <title>Description</title> + + <para> + <application>pg_dump</application> is a utility for backing up a + <productname>PostgreSQL</productname> database. It makes consistent + backups even if the database is being used concurrently. + <application>pg_dump</application> does not block other users + accessing the database (readers or writers). + </para> + + <para> + <application>pg_dump</application> only dumps a single database. + To back up an entire cluster, or to back up global objects that are + common to all databases in a cluster (such as roles and tablespaces), + use <xref linkend="app-pg-dumpall"/>. + </para> + + <para> + Dumps can be output in script or archive file formats. Script + dumps are plain-text files containing the SQL commands required + to reconstruct the database to the state it was in at the time it was + saved. To restore from such a script, feed it to <xref + linkend="app-psql"/>. Script files + can be used to reconstruct the database even on other machines and + other architectures; with some modifications, even on other SQL + database products. + </para> + + <para> + The alternative archive file formats must be used with + <xref linkend="app-pgrestore"/> to rebuild the database. They + allow <application>pg_restore</application> to be selective about + what is restored, or even to reorder the items prior to being + restored. + The archive file formats are designed to be portable across + architectures. + </para> + + <para> + When used with one of the archive file formats and combined with + <application>pg_restore</application>, + <application>pg_dump</application> provides a flexible archival and + transfer mechanism. <application>pg_dump</application> can be used to + backup an entire database, then <application>pg_restore</application> + can be used to examine the archive and/or select which parts of the + database are to be restored. The most flexible output file formats are + the <quote>custom</quote> format (<option>-Fc</option>) and the + <quote>directory</quote> format (<option>-Fd</option>). They allow + for selection and reordering of all archived items, support parallel + restoration, and are compressed by default. The <quote>directory</quote> + format is the only format that supports parallel dumps. + </para> + + <para> + While running <application>pg_dump</application>, one should examine the + output for any warnings (printed on standard error), especially in + light of the limitations listed below. + </para> + + </refsect1> + + <refsect1 id="pg-dump-options"> + <title>Options</title> + + <para> + The following command-line options control the content and + format of the output. + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">dbname</replaceable></term> + <listitem> + <para> + Specifies the name of the database to be dumped. If this is + not specified, the environment variable + <envar>PGDATABASE</envar> is used. If that is not set, the + user name specified for the connection is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-a</option></term> + <term><option>--data-only</option></term> + <listitem> + <para> + Dump only the data, not the schema (data definitions). + Table data, large objects, and sequence values are dumped. + </para> + + <para> + This option is similar to, but for historical reasons not identical + to, specifying <option>--section=data</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-b</option></term> + <term><option>--blobs</option></term> + <listitem> + <para> + Include large objects in the dump. This is the default behavior + except when <option>--schema</option>, <option>--table</option>, or + <option>--schema-only</option> is specified. The <option>-b</option> + switch is therefore only useful to add large objects to dumps + where a specific schema or table has been requested. Note that + blobs are considered data and therefore will be included when + <option>--data-only</option> is used, but not + when <option>--schema-only</option> is. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-B</option></term> + <term><option>--no-blobs</option></term> + <listitem> + <para> + Exclude large objects in the dump. + </para> + + <para> + When both <option>-b</option> and <option>-B</option> are given, the behavior + is to output large objects, when data is being dumped, see the + <option>-b</option> documentation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--clean</option></term> + <listitem> + <para> + Output commands to <command>DROP</command> all the dumped + database objects prior to outputting the commands for creating them. + This option is useful when the restore is to overwrite an existing + database. If any of the objects do not exist in the destination + database, ignorable error messages will be reported during + restore, unless <option>--if-exists</option> is also specified. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C</option></term> + <term><option>--create</option></term> + <listitem> + <para> + Begin the output with a command to create the + database itself and reconnect to the created database. (With a + script of this form, it doesn't matter which database in the + destination installation you connect to before running the script.) + If <option>--clean</option> is also specified, the script drops and + recreates the target database before reconnecting to it. + </para> + + <para> + With <option>--create</option>, the output also includes the + database's comment if any, and any configuration variable settings + that are specific to this database, that is, + any <command>ALTER DATABASE ... SET ...</command> + and <command>ALTER ROLE ... IN DATABASE ... SET ...</command> + commands that mention this database. + Access privileges for the database itself are also dumped, + unless <option>--no-acl</option> is specified. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--extension=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Dump only extensions matching <replaceable + class="parameter">pattern</replaceable>. When this option is not + specified, all non-system extensions in the target database will be + dumped. Multiple extensions can be selected by writing multiple + <option>-e</option> switches. The <replaceable + class="parameter">pattern</replaceable> parameter is interpreted as a + pattern according to the same rules used by + <application>psql</application>'s <literal>\d</literal> commands (see + <xref linkend="app-psql-patterns"/>), so multiple extensions can also + be selected by writing wildcard characters in the pattern. When using + wildcards, be careful to quote the pattern if needed to prevent the + shell from expanding the wildcards. + </para> + + <para> + Any configuration relation registered by + <function>pg_extension_config_dump</function> is included in the + dump if its extension is specified by <option>--extension</option>. + </para> + + <note> + <para> + When <option>-e</option> is specified, + <application>pg_dump</application> makes no attempt to dump any other + database objects that the selected extension(s) might depend upon. + Therefore, there is no guarantee that the results of a + specific-extension dump can be successfully restored by themselves + into a clean database. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E <replaceable class="parameter">encoding</replaceable></option></term> + <term><option>--encoding=<replaceable class="parameter">encoding</replaceable></option></term> + <listitem> + <para> + Create the dump in the specified character set encoding. By default, + the dump is created in the database encoding. (Another way to get the + same result is to set the <envar>PGCLIENTENCODING</envar> environment + variable to the desired dump encoding.) The supported encodings are + described in <xref linkend="multibyte-charset-supported"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable class="parameter">file</replaceable></option></term> + <term><option>--file=<replaceable class="parameter">file</replaceable></option></term> + <listitem> + <para> + Send output to the specified file. This parameter can be omitted for + file based output formats, in which case the standard output is used. + It must be given for the directory output format however, where it + specifies the target directory instead of a file. In this case the + directory is created by <command>pg_dump</command> and must not exist + before. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable class="parameter">format</replaceable></option></term> + <term><option>--format=<replaceable class="parameter">format</replaceable></option></term> + <listitem> + <para> + Selects the format of the output. + <replaceable>format</replaceable> can be one of the following: + + <variablelist> + <varlistentry> + <term><literal>p</literal></term> + <term><literal>plain</literal></term> + <listitem> + <para> + Output a plain-text <acronym>SQL</acronym> script file (the default). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>c</literal></term> + <term><literal>custom</literal></term> + <listitem> + <para> + Output a custom-format archive suitable for input into + <application>pg_restore</application>. + Together with the directory output format, this is the most flexible + output format in that it allows manual selection and reordering of + archived items during restore. This format is also compressed by + default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>d</literal></term> + <term><literal>directory</literal></term> + <listitem> + <para> + Output a directory-format archive suitable for input into + <application>pg_restore</application>. This will create a directory + with one file for each table and blob being dumped, plus a + so-called Table of Contents file describing the dumped objects in a + machine-readable format that <application>pg_restore</application> + can read. A directory format archive can be manipulated with + standard Unix tools; for example, files in an uncompressed archive + can be compressed with the <application>gzip</application> tool. + This format is compressed by default and also supports parallel + dumps. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>t</literal></term> + <term><literal>tar</literal></term> + <listitem> + <para> + Output a <command>tar</command>-format archive suitable for input + into <application>pg_restore</application>. The tar format is + compatible with the directory format: extracting a tar-format + archive produces a valid directory-format archive. + However, the tar format does not support compression. Also, when + using tar format the relative order of table data items cannot be + changed during restore. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">njobs</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">njobs</replaceable></option></term> + <listitem> + <para> + Run the dump in parallel by dumping <replaceable class="parameter">njobs</replaceable> + tables simultaneously. This option may reduce the time needed to perform the dump but it also + increases the load on the database server. You can only use this option with the + directory output format because this is the only output format where multiple processes + can write their data at the same time. + </para> + <para><application>pg_dump</application> will open <replaceable class="parameter">njobs</replaceable> + + 1 connections to the database, so make sure your <xref linkend="guc-max-connections"/> + setting is high enough to accommodate all connections. + </para> + <para> + Requesting exclusive locks on database objects while running a parallel dump could + cause the dump to fail. The reason is that the <application>pg_dump</application> leader process + requests shared locks (<link linkend="locking-tables">ACCESS SHARE</link>) on the + objects that the worker processes are going to dump later in order to + make sure that nobody deletes them and makes them go away while the dump is running. + If another client then requests an exclusive lock on a table, that lock will not be + granted but will be queued waiting for the shared lock of the leader process to be + released. Consequently any other access to the table will not be granted either and + will queue after the exclusive lock request. This includes the worker process trying + to dump the table. Without any precautions this would be a classic deadlock situation. + To detect this conflict, the <application>pg_dump</application> worker process requests another + shared lock using the <literal>NOWAIT</literal> option. If the worker process is not granted + this shared lock, somebody else must have requested an exclusive lock in the meantime + and there is no way to continue with the dump, so <application>pg_dump</application> has no choice + but to abort the dump. + </para> + <para> + To perform a parallel dump, the database server needs to support + synchronized snapshots, a feature that was introduced in + <productname>PostgreSQL</productname> 9.2 for primary servers and 10 + for standbys. With this feature, database clients can ensure they see + the same data set even though they use different connections. + <command>pg_dump -j</command> uses multiple database connections; it + connects to the database once with the leader process and once again + for each worker job. Without the synchronized snapshot feature, the + different worker jobs wouldn't be guaranteed to see the same data in + each connection, which could lead to an inconsistent backup. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--schema=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Dump only schemas matching <replaceable + class="parameter">pattern</replaceable>; this selects both the + schema itself, and all its contained objects. When this option is + not specified, all non-system schemas in the target database will be + dumped. Multiple schemas can be + selected by writing multiple <option>-n</option> switches. The + <replaceable class="parameter">pattern</replaceable> parameter is + interpreted as a pattern according to the same rules used by + <application>psql</application>'s <literal>\d</literal> commands + (see <xref linkend="app-psql-patterns"/> below), + so multiple schemas can also be selected by writing wildcard characters + in the pattern. When using wildcards, be careful to quote the pattern + if needed to prevent the shell from expanding the wildcards; see + <xref linkend="pg-dump-examples"/> below. + </para> + + <note> + <para> + When <option>-n</option> is specified, <application>pg_dump</application> + makes no attempt to dump any other database objects that the selected + schema(s) might depend upon. Therefore, there is no guarantee + that the results of a specific-schema dump can be successfully + restored by themselves into a clean database. + </para> + </note> + + <note> + <para> + Non-schema objects such as blobs are not dumped when <option>-n</option> is + specified. You can add blobs back to the dump with the + <option>--blobs</option> switch. + </para> + </note> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-schema=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Do not dump any schemas matching <replaceable + class="parameter">pattern</replaceable>. The pattern is + interpreted according to the same rules as for <option>-n</option>. + <option>-N</option> can be given more than once to exclude schemas + matching any of several patterns. + </para> + + <para> + When both <option>-n</option> and <option>-N</option> are given, the behavior + is to dump just the schemas that match at least one <option>-n</option> + switch but no <option>-N</option> switches. If <option>-N</option> appears + without <option>-n</option>, then schemas matching <option>-N</option> are + excluded from what is otherwise a normal dump. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O</option></term> + <term><option>--no-owner</option></term> + <listitem> + <para> + Do not output commands to set + ownership of objects to match the original database. + By default, <application>pg_dump</application> issues + <command>ALTER OWNER</command> or + <command>SET SESSION AUTHORIZATION</command> + statements to set ownership of created database objects. + These statements + will fail when the script is run unless it is started by a superuser + (or the same user that owns all of the objects in the script). + To make a script that can be restored by any user, but will give + that user ownership of all the objects, specify <option>-O</option>. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option></term> + <term><option>--no-reconnect</option></term> + <listitem> + <para> + This option is obsolete but still accepted for backwards + compatibility. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--schema-only</option></term> + <listitem> + <para> + Dump only the object definitions (schema), not data. + </para> + <para> + This option is the inverse of <option>--data-only</option>. + It is similar to, but for historical reasons not identical to, + specifying + <option>--section=pre-data --section=post-data</option>. + </para> + <para> + (Do not confuse this with the <option>--schema</option> option, which + uses the word <quote>schema</quote> in a different meaning.) + </para> + <para> + To exclude table data for only a subset of tables in the database, + see <option>--exclude-table-data</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">username</replaceable></option></term> + <term><option>--superuser=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Specify the superuser user name to use when disabling triggers. + This is relevant only if <option>--disable-triggers</option> is used. + (Usually, it's better to leave this out, and instead start the + resulting script as superuser.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--table=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Dump only tables with names matching + <replaceable class="parameter">pattern</replaceable>. Multiple tables + can be selected by writing multiple <option>-t</option> switches. The + <replaceable class="parameter">pattern</replaceable> parameter is + interpreted as a pattern according to the same rules used by + <application>psql</application>'s <literal>\d</literal> commands + (see <xref linkend="app-psql-patterns"/> below), + so multiple tables can also be selected by writing wildcard characters + in the pattern. When using wildcards, be careful to quote the pattern + if needed to prevent the shell from expanding the wildcards; see + <xref linkend="pg-dump-examples"/> below. + </para> + + <para> + As well as tables, this option can be used to dump the definition of matching + views, materialized views, foreign tables, and sequences. It will not dump the + contents of views or materialized views, and the contents of foreign tables will + only be dumped if the corresponding foreign server is specified with + <option>--include-foreign-data</option>. + </para> + + <para> + The <option>-n</option> and <option>-N</option> switches have no effect when + <option>-t</option> is used, because tables selected by <option>-t</option> will + be dumped regardless of those switches, and non-table objects will not + be dumped. + </para> + + <note> + <para> + When <option>-t</option> is specified, <application>pg_dump</application> + makes no attempt to dump any other database objects that the selected + table(s) might depend upon. Therefore, there is no guarantee + that the results of a specific-table dump can be successfully + restored by themselves into a clean database. + </para> + </note> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">pattern</replaceable></option></term> + <term><option>--exclude-table=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Do not dump any tables matching <replaceable + class="parameter">pattern</replaceable>. The pattern is + interpreted according to the same rules as for <option>-t</option>. + <option>-T</option> can be given more than once to exclude tables + matching any of several patterns. + </para> + + <para> + When both <option>-t</option> and <option>-T</option> are given, the behavior + is to dump just the tables that match at least one <option>-t</option> + switch but no <option>-T</option> switches. If <option>-T</option> appears + without <option>-t</option>, then tables matching <option>-T</option> are + excluded from what is otherwise a normal dump. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Specifies verbose mode. This will cause + <application>pg_dump</application> to output detailed object + comments and start/stop times to the dump file, and progress + messages to standard error. + Repeating the option causes additional debug-level messages + to appear on standard error. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_dump</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option></term> + <term><option>--no-privileges</option></term> + <term><option>--no-acl</option></term> + <listitem> + <para> + Prevent dumping of access privileges (grant/revoke commands). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Z <replaceable class="parameter">0..9</replaceable></option></term> + <term><option>--compress=<replaceable class="parameter">0..9</replaceable></option></term> + <listitem> + <para> + Specify the compression level to use. Zero means no compression. + For the custom and directory archive formats, this specifies compression of + individual table-data segments, and the default is to compress + at a moderate level. + For plain text output, setting a nonzero compression level causes + the entire output file to be compressed, as though it had been + fed through <application>gzip</application>; but the default is not to compress. + The tar archive format currently does not support compression at all. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--binary-upgrade</option></term> + <listitem> + <para> + This option is for use by in-place upgrade utilities. Its use + for other purposes is not recommended or supported. The + behavior of the option may change in future releases without + notice. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--column-inserts</option></term> + <term><option>--attribute-inserts</option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands with explicit + column names (<literal>INSERT INTO + <replaceable>table</replaceable> + (<replaceable>column</replaceable>, ...) VALUES + ...</literal>). This will make restoration very slow; it is mainly + useful for making dumps that can be loaded into + non-<productname>PostgreSQL</productname> databases. + Any error during restoring will cause only rows that are part of the + problematic <command>INSERT</command> to be lost, rather than the + entire table contents. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-dollar-quoting</option></term> + <listitem> + <para> + This option disables the use of dollar quoting for function bodies, + and forces them to be quoted using SQL standard string syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-triggers</option></term> + <listitem> + <para> + This option is relevant only when creating a data-only dump. + It instructs <application>pg_dump</application> to include commands + to temporarily disable triggers on the target tables while + the data is restored. Use this if you have referential + integrity checks or other triggers on the tables that you + do not want to invoke during data restore. + </para> + + <para> + Presently, the commands emitted for <option>--disable-triggers</option> + must be done as superuser. So, you should also specify + a superuser name with <option>-S</option>, or preferably be careful to + start the resulting script as a superuser. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--enable-row-security</option></term> + <listitem> + <para> + This option is relevant only when dumping the contents of a table + which has row security. By default, <application>pg_dump</application> will set + <xref linkend="guc-row-security"/> to off, to ensure + that all data is dumped from the table. If the user does not have + sufficient privileges to bypass row security, then an error is thrown. + This parameter instructs <application>pg_dump</application> to set + <xref linkend="guc-row-security"/> to on instead, allowing the user + to dump the parts of the contents of the table that they have access to. + </para> + + <para> + Note that if you use this option currently, you probably also want + the dump be in <command>INSERT</command> format, as the + <command>COPY FROM</command> during restore does not support row security. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--exclude-table-data=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Do not dump data for any tables matching <replaceable + class="parameter">pattern</replaceable>. The pattern is + interpreted according to the same rules as for <option>-t</option>. + <option>--exclude-table-data</option> can be given more than once to + exclude tables matching any of several patterns. This option is + useful when you need the definition of a particular table even + though you do not need the data in it. + </para> + <para> + To exclude data for all tables in the database, see <option>--schema-only</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--extra-float-digits=<replaceable class="parameter">ndigits</replaceable></option></term> + <listitem> + <para> + Use the specified value of <option>extra_float_digits</option> when dumping + floating-point data, instead of the maximum available precision. + Routine dumps made for backup purposes should not use this option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-exists</option></term> + <listitem> + <para> + Use <literal>DROP ... IF EXISTS</literal> commands to drop objects + in <option>--clean</option> mode. This suppresses <quote>does not + exist</quote> errors that might otherwise be reported. This + option is not valid unless <option>--clean</option> is also + specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--include-foreign-data=<replaceable class="parameter">foreignserver</replaceable></option></term> + <listitem> + <para> + Dump the data for any foreign table with a foreign server + matching <replaceable class="parameter">foreignserver</replaceable> + pattern. Multiple foreign servers can be selected by writing multiple + <option>--include-foreign-data</option> switches. + Also, the <replaceable class="parameter">foreignserver</replaceable> parameter is + interpreted as a pattern according to the same rules used by + <application>psql</application>'s <literal>\d</literal> commands + (see <xref linkend="app-psql-patterns"/> below), + so multiple foreign servers can also be selected by writing wildcard characters + in the pattern. When using wildcards, be careful to quote the pattern + if needed to prevent the shell from expanding the wildcards; see + <xref linkend="pg-dump-examples"/> below. + The only exception is that an empty pattern is disallowed. + </para> + + <note> + <para> + When <option>--include-foreign-data</option> is specified, + <application>pg_dump</application> does not check that the foreign + table is writable. Therefore, there is no guarantee that the + results of a foreign table dump can be successfully restored. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--inserts</option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands (rather + than <command>COPY</command>). This will make restoration very slow; + it is mainly useful for making dumps that can be loaded into + non-<productname>PostgreSQL</productname> databases. + Any error during restoring will cause only rows that are part of the + problematic <command>INSERT</command> to be lost, rather than the + entire table contents. Note that the restore might fail altogether if + you have rearranged column order. The + <option>--column-inserts</option> option is safe against column order + changes, though even slower. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--load-via-partition-root</option></term> + <listitem> + <para> + When dumping data for a table partition, make + the <command>COPY</command> or <command>INSERT</command> statements + target the root of the partitioning hierarchy that contains it, rather + than the partition itself. This causes the appropriate partition to + be re-determined for each row when the data is loaded. This may be + useful when restoring data on a server where rows do not always fall + into the same partitions as they did on the original server. That + could happen, for example, if the partitioning column is of type text + and the two systems have different definitions of the collation used + to sort the partitioning column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--lock-wait-timeout=<replaceable class="parameter">timeout</replaceable></option></term> + <listitem> + <para> + Do not wait forever to acquire shared table locks at the beginning of + the dump. Instead fail if unable to lock a table within the specified + <replaceable class="parameter">timeout</replaceable>. The timeout may be + specified in any of the formats accepted by <command>SET + statement_timeout</command>. (Allowed formats vary depending on the server + version you are dumping from, but an integer number of milliseconds + is accepted by all versions.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-comments</option></term> + <listitem> + <para> + Do not dump comments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-publications</option></term> + <listitem> + <para> + Do not dump publications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-security-labels</option></term> + <listitem> + <para> + Do not dump security labels. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-subscriptions</option></term> + <listitem> + <para> + Do not dump subscriptions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_dump</command> will wait for all files + to be written safely to disk. This option causes + <command>pg_dump</command> to return without waiting, which is + faster, but means that a subsequent operating system crash can leave + the dump corrupt. Generally, this option is useful for testing + but should not be used when dumping data from production installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-table-access-method</option></term> + <listitem> + <para> + Do not output commands to select table access methods. + With this option, all objects will be created with whichever + table access method is the default during restore. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-tablespaces</option></term> + <listitem> + <para> + Do not output commands to select tablespaces. + With this option, all objects will be created in whichever + tablespace is the default during restore. + </para> + + <para> + This option is ignored when emitting an archive (non-text) output + file. For the archive formats, you can specify the option when you + call <command>pg_restore</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-toast-compression</option></term> + <listitem> + <para> + Do not output commands to set <acronym>TOAST</acronym> compression + methods. + With this option, all columns will be restored with the default + compression setting. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-unlogged-table-data</option></term> + <listitem> + <para> + Do not dump the contents of unlogged tables and sequences. This + option has no effect on whether or not the table and sequence + definitions (schema) are dumped; it only suppresses dumping the table + and sequence data. Data in unlogged tables and sequences + is always excluded when dumping from a standby server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--on-conflict-do-nothing</option></term> + <listitem> + <para> + Add <literal>ON CONFLICT DO NOTHING</literal> to + <command>INSERT</command> commands. + This option is not valid unless <option>--inserts</option>, + <option>--column-inserts</option> or + <option>--rows-per-insert</option> is also specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--quote-all-identifiers</option></term> + <listitem> + <para> + Force quoting of all identifiers. This option is recommended when + dumping a database from a server whose <productname>PostgreSQL</productname> + major version is different from <application>pg_dump</application>'s, or when + the output is intended to be loaded into a server of a different + major version. By default, <application>pg_dump</application> quotes only + identifiers that are reserved words in its own major version. + This sometimes results in compatibility issues when dealing with + servers of other versions that may have slightly different sets + of reserved words. Using <option>--quote-all-identifiers</option> prevents + such issues, at the price of a harder-to-read dump script. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--rows-per-insert=<replaceable class="parameter">nrows</replaceable></option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands (rather than + <command>COPY</command>). Controls the maximum number of rows per + <command>INSERT</command> command. The value specified must be a + number greater than zero. Any error during restoring will cause only + rows that are part of the problematic <command>INSERT</command> to be + lost, rather than the entire table contents. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--section=<replaceable class="parameter">sectionname</replaceable></option></term> + <listitem> + <para> + Only dump the named section. The section name can be + <option>pre-data</option>, <option>data</option>, or <option>post-data</option>. + This option can be specified more than once to select multiple + sections. The default is to dump all sections. + </para> + <para> + The data section contains actual table data, large-object + contents, and sequence values. + Post-data items include definitions of indexes, triggers, rules, + and constraints other than validated check constraints. + Pre-data items include all other data definition items. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--serializable-deferrable</option></term> + <listitem> + <para> + Use a <literal>serializable</literal> transaction for the dump, to + ensure that the snapshot used is consistent with later database + states; but do this by waiting for a point in the transaction stream + at which no anomalies can be present, so that there isn't a risk of + the dump failing or causing other transactions to roll back with a + <literal>serialization_failure</literal>. See <xref linkend="mvcc"/> + for more information about transaction isolation and concurrency + control. + </para> + + <para> + This option is not beneficial for a dump which is intended only for + disaster recovery. It could be useful for a dump used to load a + copy of the database for reporting or other read-only load sharing + while the original database continues to be updated. Without it the + dump may reflect a state which is not consistent with any serial + execution of the transactions eventually committed. For example, if + batch processing techniques are used, a batch may show as closed in + the dump without all of the items which are in the batch appearing. + </para> + + <para> + This option will make no difference if there are no read-write + transactions active when pg_dump is started. If read-write + transactions are active, the start of the dump may be delayed for an + indeterminate length of time. Once running, performance with or + without the switch is the same. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--snapshot=<replaceable class="parameter">snapshotname</replaceable></option></term> + <listitem> + <para> + Use the specified synchronized snapshot when making a dump of the + database (see + <xref linkend="functions-snapshot-synchronization-table"/> for more + details). + </para> + <para> + This option is useful when needing to synchronize the dump with + a logical replication slot (see <xref linkend="logicaldecoding"/>) + or with a concurrent session. + </para> + <para> + In the case of a parallel dump, the snapshot name defined by this + option is used rather than taking a new snapshot. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--strict-names</option></term> + <listitem> + <para> + Require that each + extension (<option>-e</option>/<option>--extension</option>), + schema (<option>-n</option>/<option>--schema</option>) and + table (<option>-t</option>/<option>--table</option>) qualifier + match at least one extension/schema/table in the database to be dumped. + Note that if none of the extension/schema/table qualifiers find + matches, <application>pg_dump</application> will generate an error + even without <option>--strict-names</option>. + </para> + <para> + This option has no effect + on <option>-N</option>/<option>--exclude-schema</option>, + <option>-T</option>/<option>--exclude-table</option>, + or <option>--exclude-table-data</option>. An exclude pattern failing + to match any objects is not considered an error. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--use-set-session-authorization</option></term> + <listitem> + <para> + Output SQL-standard <command>SET SESSION AUTHORIZATION</command> commands + instead of <command>ALTER OWNER</command> commands to determine object + ownership. This makes the dump more standards-compatible, but + depending on the history of the objects in the dump, might not restore + properly. Also, a dump using <command>SET SESSION AUTHORIZATION</command> + will certainly require superuser privileges to restore correctly, + whereas <command>ALTER OWNER</command> requires lesser privileges. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_dump</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + The following command-line options control the database connection parameters. + + <variablelist> + <varlistentry> + <term><option>-d <replaceable class="parameter">dbname</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to. This is + equivalent to specifying <replaceable + class="parameter">dbname</replaceable> as the first non-option + argument on the command line. The <replaceable>dbname</replaceable> + can be a <link linkend="libpq-connstring">connection string</link>. + If so, connection string parameters will override any conflicting + command line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. The default is taken + from the <envar>PGHOST</envar> environment variable, if set, + else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_dump</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>pg_dump</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_dump</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--role=<replaceable class="parameter">rolename</replaceable></option></term> + <listitem> + <para> + Specifies a role name to be used to create the dump. + This option causes <application>pg_dump</application> to issue a + <command>SET ROLE</command> <replaceable class="parameter">rolename</replaceable> + command after connecting to the database. It is useful when the + authenticated user (specified by <option>-U</option>) lacks privileges + needed by <application>pg_dump</application>, but can switch to a role with + the required rights. Some installations have a policy against + logging in directly as a superuser, and use of this option allows + dumps to be made without violating the policy. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGOPTIONS</envar></term> + <term><envar>PGPORT</envar></term> + + <term><envar>PGUSER</envar></term> + <listitem> + <para> + Default connection parameters. + </para> + </listitem> + + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + <refsect1 id="app-pgdump-diagnostics"> + <title>Diagnostics</title> + + <para> + <application>pg_dump</application> internally executes + <command>SELECT</command> statements. If you have problems running + <application>pg_dump</application>, make sure you are able to + select information from the database using, for example, <xref + linkend="app-psql"/>. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + <para> + The database activity of <application>pg_dump</application> is + normally collected by the cumulative statistics system. If this is + undesirable, you can set parameter <varname>track_counts</varname> + to false via <envar>PGOPTIONS</envar> or the <literal>ALTER + USER</literal> command. + </para> + + </refsect1> + + + <refsect1 id="pg-dump-notes"> + <title>Notes</title> + + <para> + If your database cluster has any local additions to the <literal>template1</literal> database, + be careful to restore the output of <application>pg_dump</application> into a + truly empty database; otherwise you are likely to get errors due to + duplicate definitions of the added objects. To make an empty database + without any local additions, copy from <literal>template0</literal> not <literal>template1</literal>, + for example: +<programlisting> +CREATE DATABASE foo WITH TEMPLATE template0; +</programlisting> + </para> + + <para> + When a data-only dump is chosen and the option <option>--disable-triggers</option> + is used, <application>pg_dump</application> emits commands + to disable triggers on user tables before inserting the data, + and then commands to re-enable them after the data has been + inserted. If the restore is stopped in the middle, the system + catalogs might be left in the wrong state. + </para> + + <para> + The dump file produced by <application>pg_dump</application> + does not contain the statistics used by the optimizer to make + query planning decisions. Therefore, it is wise to run + <command>ANALYZE</command> after restoring from a dump file + to ensure optimal performance; see <xref linkend="vacuum-for-statistics"/> + and <xref linkend="autovacuum"/> for more information. + </para> + + <para> + Because <application>pg_dump</application> is used to transfer data + to newer versions of <productname>PostgreSQL</productname>, the output of + <application>pg_dump</application> can be expected to load into + <productname>PostgreSQL</productname> server versions newer than + <application>pg_dump</application>'s version. <application>pg_dump</application> can also + dump from <productname>PostgreSQL</productname> servers older than its own version. + (Currently, servers back to version 9.2 are supported.) + However, <application>pg_dump</application> cannot dump from + <productname>PostgreSQL</productname> servers newer than its own major version; + it will refuse to even try, rather than risk making an invalid dump. + Also, it is not guaranteed that <application>pg_dump</application>'s output can + be loaded into a server of an older major version — not even if the + dump was taken from a server of that version. Loading a dump file + into an older server may require manual editing of the dump file + to remove syntax not understood by the older server. + Use of the <option>--quote-all-identifiers</option> option is recommended + in cross-version cases, as it can prevent problems arising from varying + reserved-word lists in different <productname>PostgreSQL</productname> versions. + </para> + + <para> + When dumping logical replication subscriptions, + <application>pg_dump</application> will generate <command>CREATE + SUBSCRIPTION</command> commands that use the <literal>connect = false</literal> + option, so that restoring the subscription does not make remote connections + for creating a replication slot or for initial table copy. That way, the + dump can be restored without requiring network access to the remote + servers. It is then up to the user to reactivate the subscriptions in a + suitable way. If the involved hosts have changed, the connection + information might have to be changed. It might also be appropriate to + truncate the target tables before initiating a new full table copy. If users + intend to copy initial data during refresh they must create the slot with + <literal>two_phase = false</literal>. After the initial sync, the + <literal>two_phase</literal> option will be automatically enabled by the + subscriber if the subscription had been originally created with + <literal>two_phase = true</literal> option. + </para> + </refsect1> + + <refsect1 id="pg-dump-examples" xreflabel="Examples"> + <title>Examples</title> + + <para> + To dump a database called <literal>mydb</literal> into an SQL-script file: +<screen> +<prompt>$</prompt> <userinput>pg_dump mydb > db.sql</userinput> +</screen> + </para> + + <para> + To reload such a script into a (freshly created) database named + <literal>newdb</literal>: + +<screen> +<prompt>$</prompt> <userinput>psql -d newdb -f db.sql</userinput> +</screen> + </para> + + <para> + To dump a database into a custom-format archive file: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -Fc mydb > db.dump</userinput> +</screen> + </para> + + <para> + To dump a database into a directory-format archive: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -Fd mydb -f dumpdir</userinput> +</screen> + </para> + + <para> + To dump a database into a directory-format archive in parallel with + 5 worker jobs: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -Fd mydb -j 5 -f dumpdir</userinput> +</screen> + </para> + + <para> + To reload an archive file into a (freshly created) database named + <literal>newdb</literal>: + +<screen> +<prompt>$</prompt> <userinput>pg_restore -d newdb db.dump</userinput> +</screen> + </para> + + <para> + To reload an archive file into the same database it was dumped from, + discarding the current contents of that database: + +<screen> +<prompt>$</prompt> <userinput>pg_restore -d postgres --clean --create db.dump</userinput> +</screen> + </para> + + <para> + To dump a single table named <literal>mytab</literal>: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -t mytab mydb > db.sql</userinput> +</screen> + </para> + + <para> + To dump all tables whose names start with <literal>emp</literal> in the + <literal>detroit</literal> schema, except for the table named + <literal>employee_log</literal>: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -t 'detroit.emp*' -T detroit.employee_log mydb > db.sql</userinput> +</screen> + </para> + + <para> + To dump all schemas whose names start with <literal>east</literal> or + <literal>west</literal> and end in <literal>gsm</literal>, excluding any schemas whose + names contain the word <literal>test</literal>: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -n 'east*gsm' -n 'west*gsm' -N '*test*' mydb > db.sql</userinput> +</screen> + </para> + + <para> + The same, using regular expression notation to consolidate the switches: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -n '(east|west)*gsm' -N '*test*' mydb > db.sql</userinput> +</screen> + </para> + + <para> + To dump all database objects except for tables whose names begin with + <literal>ts_</literal>: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -T 'ts_*' mydb > db.sql</userinput> +</screen> + </para> + + <para> + To specify an upper-case or mixed-case name in <option>-t</option> and related + switches, you need to double-quote the name; else it will be folded to + lower case (see <xref linkend="app-psql-patterns"/> below). But + double quotes are special to the shell, so in turn they must be quoted. + Thus, to dump a single table with a mixed-case name, you need something + like + +<screen> +<prompt>$</prompt> <userinput>pg_dump -t "\"MixedCaseName\"" mydb > mytab.sql</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pg-dumpall"/></member> + <member><xref linkend="app-pgrestore"/></member> + <member><xref linkend="app-psql"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_dumpall.sgml b/doc/src/sgml/ref/pg_dumpall.sgml new file mode 100644 index 0000000..a1fae39 --- /dev/null +++ b/doc/src/sgml/ref/pg_dumpall.sgml @@ -0,0 +1,826 @@ +<!-- +doc/src/sgml/ref/pg_dumpall.sgml +PostgreSQL documentation +--> + +<refentry id="app-pg-dumpall"> + <indexterm zone="app-pg-dumpall"> + <primary>pg_dumpall</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_dumpall</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_dumpall</refname> + <refpurpose>extract a <productname>PostgreSQL</productname> database cluster into a script file</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_dumpall</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="app-pg-dumpall-description"> + <title>Description</title> + + <para> + <application>pg_dumpall</application> is a utility for writing out + (<quote>dumping</quote>) all <productname>PostgreSQL</productname> databases + of a cluster into one script file. The script file contains + <acronym>SQL</acronym> commands that can be used as input to <xref + linkend="app-psql"/> to restore the databases. It does this by + calling <xref linkend="app-pgdump"/> for each database in the cluster. + <application>pg_dumpall</application> also dumps global objects + that are common to all databases, namely database roles, tablespaces, + and privilege grants for configuration parameters. + (<application>pg_dump</application> does not save these objects.) + </para> + + <para> + Since <application>pg_dumpall</application> reads tables from all + databases you will most likely have to connect as a database + superuser in order to produce a complete dump. Also you will need + superuser privileges to execute the saved script in order to be + allowed to add roles and create databases. + </para> + + <para> + The SQL script will be written to the standard output. Use the + <option>-f</option>/<option>--file</option> option or shell operators to + redirect it into a file. + </para> + + <para> + <application>pg_dumpall</application> needs to connect several + times to the <productname>PostgreSQL</productname> server (once per + database). If you use password authentication it will ask for + a password each time. It is convenient to have a + <filename>~/.pgpass</filename> file in such cases. See <xref + linkend="libpq-pgpass"/> for more information. + </para> + + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following command-line options control the content and + format of the output. + + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--data-only</option></term> + <listitem> + <para> + Dump only the data, not the schema (data definitions). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--clean</option></term> + <listitem> + <para> + Emit SQL commands to <command>DROP</command> all the dumped + databases, roles, and tablespaces before recreating them. + This option is useful when the restore is to overwrite an existing + cluster. If any of the objects do not exist in the destination + cluster, ignorable error messages will be reported during + restore, unless <option>--if-exists</option> is also specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E <replaceable class="parameter">encoding</replaceable></option></term> + <term><option>--encoding=<replaceable class="parameter">encoding</replaceable></option></term> + <listitem> + <para> + Create the dump in the specified character set encoding. By default, + the dump is created in the database encoding. (Another way to get the + same result is to set the <envar>PGCLIENTENCODING</envar> environment + variable to the desired dump encoding.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable class="parameter">filename</replaceable></option></term> + <term><option>--file=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Send output to the specified file. If this is omitted, the + standard output is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-g</option></term> + <term><option>--globals-only</option></term> + <listitem> + <para> + Dump only global objects (roles and tablespaces), no databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O</option></term> + <term><option>--no-owner</option></term> + <listitem> + <para> + Do not output commands to set + ownership of objects to match the original database. + By default, <application>pg_dumpall</application> issues + <command>ALTER OWNER</command> or + <command>SET SESSION AUTHORIZATION</command> + statements to set ownership of created schema elements. + These statements + will fail when the script is run unless it is started by a superuser + (or the same user that owns all of the objects in the script). + To make a script that can be restored by any user, but will give + that user ownership of all the objects, specify <option>-O</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r</option></term> + <term><option>--roles-only</option></term> + <listitem> + <para> + Dump only roles, no databases or tablespaces. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--schema-only</option></term> + <listitem> + <para> + Dump only the object definitions (schema), not data. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">username</replaceable></option></term> + <term><option>--superuser=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Specify the superuser user name to use when disabling triggers. + This is relevant only if <option>--disable-triggers</option> is used. + (Usually, it's better to leave this out, and instead start the + resulting script as superuser.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option></term> + <term><option>--tablespaces-only</option></term> + <listitem> + <para> + Dump only tablespaces, no databases or roles. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Specifies verbose mode. This will cause + <application>pg_dumpall</application> to output start/stop + times to the dump file, and progress messages to standard error. + Repeating the option causes additional debug-level messages + to appear on standard error. + The option is also passed down to <application>pg_dump</application>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_dumpall</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option></term> + <term><option>--no-privileges</option></term> + <term><option>--no-acl</option></term> + <listitem> + <para> + Prevent dumping of access privileges (grant/revoke commands). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--binary-upgrade</option></term> + <listitem> + <para> + This option is for use by in-place upgrade utilities. Its use + for other purposes is not recommended or supported. The + behavior of the option may change in future releases without + notice. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--column-inserts</option></term> + <term><option>--attribute-inserts</option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands with explicit + column names (<literal>INSERT INTO + <replaceable>table</replaceable> + (<replaceable>column</replaceable>, ...) VALUES + ...</literal>). This will make restoration very slow; it is mainly + useful for making dumps that can be loaded into + non-<productname>PostgreSQL</productname> databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-dollar-quoting</option></term> + <listitem> + <para> + This option disables the use of dollar quoting for function bodies, + and forces them to be quoted using SQL standard string syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-triggers</option></term> + <listitem> + <para> + This option is relevant only when creating a data-only dump. + It instructs <application>pg_dumpall</application> to include commands + to temporarily disable triggers on the target tables while + the data is restored. Use this if you have referential + integrity checks or other triggers on the tables that you + do not want to invoke during data restore. + </para> + + <para> + Presently, the commands emitted for <option>--disable-triggers</option> + must be done as superuser. So, you should also specify + a superuser name with <option>-S</option>, or preferably be careful to + start the resulting script as a superuser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--exclude-database=<replaceable class="parameter">pattern</replaceable></option></term> + <listitem> + <para> + Do not dump databases whose name matches + <replaceable class="parameter">pattern</replaceable>. + Multiple patterns can be excluded by writing multiple + <option>--exclude-database</option> switches. The + <replaceable class="parameter">pattern</replaceable> parameter is + interpreted as a pattern according to the same rules used by + <application>psql</application>'s <literal>\d</literal> + commands (see <xref linkend="app-psql-patterns"/> below), + so multiple databases can also be excluded by writing wildcard + characters in the pattern. When using wildcards, be careful to + quote the pattern if needed to prevent shell wildcard expansion. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--extra-float-digits=<replaceable class="parameter">ndigits</replaceable></option></term> + <listitem> + <para> + Use the specified value of extra_float_digits when dumping + floating-point data, instead of the maximum available precision. + Routine dumps made for backup purposes should not use this option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-exists</option></term> + <listitem> + <para> + Use <literal>DROP ... IF EXISTS</literal> commands to drop objects + in <option>--clean</option> mode. This suppresses <quote>does not + exist</quote> errors that might otherwise be reported. This + option is not valid unless <option>--clean</option> is also + specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--inserts</option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands (rather + than <command>COPY</command>). This will make restoration very slow; + it is mainly useful for making dumps that can be loaded into + non-<productname>PostgreSQL</productname> databases. Note that + the restore might fail altogether if you have rearranged column order. + The <option>--column-inserts</option> option is safer, though even + slower. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--load-via-partition-root</option></term> + <listitem> + <para> + When dumping data for a table partition, make + the <command>COPY</command> or <command>INSERT</command> statements + target the root of the partitioning hierarchy that contains it, rather + than the partition itself. This causes the appropriate partition to + be re-determined for each row when the data is loaded. This may be + useful when restoring data on a server where rows do not always fall + into the same partitions as they did on the original server. That + could happen, for example, if the partitioning column is of type text + and the two systems have different definitions of the collation used + to sort the partitioning column. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--lock-wait-timeout=<replaceable class="parameter">timeout</replaceable></option></term> + <listitem> + <para> + Do not wait forever to acquire shared table locks at the beginning of + the dump. Instead, fail if unable to lock a table within the specified + <replaceable class="parameter">timeout</replaceable>. The timeout may be + specified in any of the formats accepted by <command>SET + statement_timeout</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-comments</option></term> + <listitem> + <para> + Do not dump comments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-publications</option></term> + <listitem> + <para> + Do not dump publications. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-role-passwords</option></term> + <listitem> + <para> + Do not dump passwords for roles. When restored, roles will have a + null password, and password authentication will always fail until the + password is set. Since password values aren't needed when this option + is specified, the role information is read from the catalog + view <structname>pg_roles</structname> instead + of <structname>pg_authid</structname>. Therefore, this option also + helps if access to <structname>pg_authid</structname> is restricted by + some security policy. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-security-labels</option></term> + <listitem> + <para> + Do not dump security labels. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-subscriptions</option></term> + <listitem> + <para> + Do not dump subscriptions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_dumpall</command> will wait for all files + to be written safely to disk. This option causes + <command>pg_dumpall</command> to return without waiting, which is + faster, but means that a subsequent operating system crash can leave + the dump corrupt. Generally, this option is useful for testing + but should not be used when dumping data from production installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-table-access-method</option></term> + <listitem> + <para> + Do not output commands to select table access methods. + With this option, all objects will be created with whichever + table access method is the default during restore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-tablespaces</option></term> + <listitem> + <para> + Do not output commands to create tablespaces nor select tablespaces + for objects. + With this option, all objects will be created in whichever + tablespace is the default during restore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-toast-compression</option></term> + <listitem> + <para> + Do not output commands to set <acronym>TOAST</acronym> compression + methods. + With this option, all columns will be restored with the default + compression setting. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-unlogged-table-data</option></term> + <listitem> + <para> + Do not dump the contents of unlogged tables. This option has no + effect on whether or not the table definitions (schema) are dumped; + it only suppresses dumping the table data. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--on-conflict-do-nothing</option></term> + <listitem> + <para> + Add <literal>ON CONFLICT DO NOTHING</literal> to + <command>INSERT</command> commands. + This option is not valid unless <option>--inserts</option> or + <option>--column-inserts</option> is also specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--quote-all-identifiers</option></term> + <listitem> + <para> + Force quoting of all identifiers. This option is recommended when + dumping a database from a server whose <productname>PostgreSQL</productname> + major version is different from <application>pg_dumpall</application>'s, or when + the output is intended to be loaded into a server of a different + major version. By default, <application>pg_dumpall</application> quotes only + identifiers that are reserved words in its own major version. + This sometimes results in compatibility issues when dealing with + servers of other versions that may have slightly different sets + of reserved words. Using <option>--quote-all-identifiers</option> prevents + such issues, at the price of a harder-to-read dump script. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--rows-per-insert=<replaceable class="parameter">nrows</replaceable></option></term> + <listitem> + <para> + Dump data as <command>INSERT</command> commands (rather than + <command>COPY</command>). Controls the maximum number of rows per + <command>INSERT</command> command. The value specified must be a + number greater than zero. Any error during restoring will cause only + rows that are part of the problematic <command>INSERT</command> to be + lost, rather than the entire table contents. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--use-set-session-authorization</option></term> + <listitem> + <para> + Output SQL-standard <command>SET SESSION AUTHORIZATION</command> commands + instead of <command>ALTER OWNER</command> commands to determine object + ownership. This makes the dump more standards compatible, but + depending on the history of the objects in the dump, might not restore + properly. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_dumpall</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + The following command-line options control the database connection parameters. + + <variablelist> + <varlistentry> + <term><option>-d <replaceable class="parameter">connstr</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">connstr</replaceable></option></term> + <listitem> + <para> + Specifies parameters used to connect to the server, as a <link + linkend="libpq-connstring">connection string</link>; these + will override any conflicting command line options. + </para> + <para> + The option is called <literal>--dbname</literal> for consistency with other + client applications, but because <application>pg_dumpall</application> + needs to connect to many databases, the database name in the + connection string will be ignored. Use the <literal>-l</literal> + option to specify the name of the database used for the initial + connection, which will dump global objects and discover what other + databases should be dumped. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable>host</replaceable></option></term> + <term><option>--host=<replaceable>host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the database + server is running. If the value begins with a slash, it is + used as the directory for the Unix domain socket. The default + is taken from the <envar>PGHOST</envar> environment variable, + if set, else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l <replaceable>dbname</replaceable></option></term> + <term><option>--database=<replaceable>dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to for dumping global + objects and discovering what other databases should be dumped. If + not specified, the <literal>postgres</literal> database will be used, + and if that does not exist, <literal>template1</literal> will be used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable>port</replaceable></option></term> + <term><option>--port=<replaceable>port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>username</replaceable></option></term> + <term><option>--username=<replaceable>username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_dumpall</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>pg_dumpall</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_dumpall</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + + <para> + Note that the password prompt will occur again for each database + to be dumped. Usually, it's better to set up a + <filename>~/.pgpass</filename> file than to rely on manual password entry. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--role=<replaceable class="parameter">rolename</replaceable></option></term> + <listitem> + <para> + Specifies a role name to be used to create the dump. + This option causes <application>pg_dumpall</application> to issue a + <command>SET ROLE</command> <replaceable class="parameter">rolename</replaceable> + command after connecting to the database. It is useful when the + authenticated user (specified by <option>-U</option>) lacks privileges + needed by <application>pg_dumpall</application>, but can switch to a role with + the required rights. Some installations have a policy against + logging in directly as a superuser, and use of this option allows + dumps to be made without violating the policy. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGOPTIONS</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Notes</title> + + <para> + Since <application>pg_dumpall</application> calls + <application>pg_dump</application> internally, some diagnostic + messages will refer to <application>pg_dump</application>. + </para> + + <para> + The <option>--clean</option> option can be useful even when your + intention is to restore the dump script into a fresh cluster. Use of + <option>--clean</option> authorizes the script to drop and re-create the + built-in <literal>postgres</literal> and <literal>template1</literal> + databases, ensuring that those databases will retain the same properties + (for instance, locale and encoding) that they had in the source cluster. + Without the option, those databases will retain their existing + database-level properties, as well as any pre-existing contents. + </para> + + <para> + Once restored, it is wise to run <command>ANALYZE</command> on each + database so the optimizer has useful statistics. You + can also run <command>vacuumdb -a -z</command> to analyze all + databases. + </para> + + <para> + The dump script should not be expected to run completely without errors. + In particular, because the script will issue <command>CREATE ROLE</command> + for every role existing in the source cluster, it is certain to get a + <quote>role already exists</quote> error for the bootstrap superuser, + unless the destination cluster was initialized with a different bootstrap + superuser name. This error is harmless and should be ignored. Use of + the <option>--clean</option> option is likely to produce additional + harmless error messages about non-existent objects, although you can + minimize those by adding <option>--if-exists</option>. + </para> + + <para> + <application>pg_dumpall</application> requires all needed + tablespace directories to exist before the restore; otherwise, + database creation will fail for databases in non-default + locations. + </para> + </refsect1> + + + <refsect1 id="app-pg-dumpall-ex"> + <title>Examples</title> + <para> + To dump all databases: + +<screen> +<prompt>$</prompt> <userinput>pg_dumpall > db.out</userinput> +</screen> + </para> + + <para> + To restore database(s) from this file, you can use: +<screen> +<prompt>$</prompt> <userinput>psql -f db.out postgres</userinput> +</screen> + It is not important to which database you connect here since the + script file created by <application>pg_dumpall</application> will + contain the appropriate commands to create and connect to the saved + databases. An exception is that if you specified <option>--clean</option>, + you must connect to the <literal>postgres</literal> database initially; + the script will attempt to drop other databases immediately, and that + will fail for the database you are connected to. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + Check <xref linkend="app-pgdump"/> for details on possible + error conditions. + </para> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_isready.sgml b/doc/src/sgml/ref/pg_isready.sgml new file mode 100644 index 0000000..ba25ca6 --- /dev/null +++ b/doc/src/sgml/ref/pg_isready.sgml @@ -0,0 +1,217 @@ +<!-- +doc/src/sgml/ref/pg_isready.sgml +PostgreSQL documentation +--> + +<refentry id="app-pg-isready"> + <indexterm zone="app-pg-isready"> + <primary>pg_isready</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_isready</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_isready</refname> + <refpurpose>check the connection status of a <productname>PostgreSQL</productname> server</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_isready</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="app-pg-isready-description"> + <title>Description</title> + <para> + <application>pg_isready</application> is a utility for checking the connection + status of a <productname>PostgreSQL</productname> database server. The exit + status specifies the result of the connection check. + </para> + </refsect1> + + <refsect1 id="app-pg-isready-options"> + <title>Options</title> + + <variablelist> + + <varlistentry> + <term><option>-d <replaceable class="parameter">dbname</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to. The + <replaceable>dbname</replaceable> can be a <link + linkend="libpq-connstring">connection string</link>. If so, + connection string parameters will override any conflicting command + line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">hostname</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">hostname</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server is running. If the value begins + with a slash, it is used as the directory for the Unix-domain + socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or the local Unix-domain + socket file extension on which the server is listening for + connections. Defaults to the value of the <envar>PGPORT</envar> + environment variable or, if not set, to the port specified at + compile time, usually 5432. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Do not display status message. This is useful when scripting. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">seconds</replaceable></option></term> + <term><option>--timeout=<replaceable class="parameter">seconds</replaceable></option></term> + <listitem> + <para> + The maximum number of seconds to wait when attempting connection before + returning that the server is not responding. Setting to 0 disables. The + default is 3 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Connect to the database as the user <replaceable + class="parameter">username</replaceable> instead of the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_isready</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_isready</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Exit Status</title> + + <para> + <application>pg_isready</application> returns <literal>0</literal> to the shell if the server + is accepting connections normally, <literal>1</literal> if the server is rejecting + connections (for example during startup), <literal>2</literal> if there was no response to the + connection attempt, and <literal>3</literal> if no attempt was made (for example due to invalid + parameters). + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + <command>pg_isready</command>, like most other <productname>PostgreSQL</productname> + utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1 id="app-pg-isready-notes"> + <title>Notes</title> + + <para> + It is not necessary to supply correct user name, password, or database + name values to obtain the server status; however, if incorrect values + are provided, the server will log a failed connection attempt. + </para> + </refsect1> + + <refsect1 id="app-pg-isready-examples"> + <title>Examples</title> + + <para> + Standard Usage: +<screen> +<prompt>$</prompt> <userinput>pg_isready</userinput> +<computeroutput>/tmp:5432 - accepting connections</computeroutput> +<prompt>$</prompt> <userinput>echo $?</userinput> +<computeroutput>0</computeroutput> +</screen> + </para> + + <para> + Running with connection parameters to a <productname>PostgreSQL</productname> cluster in startup: +<screen> +<prompt>$ </prompt><userinput>pg_isready -h localhost -p 5433</userinput> +<computeroutput>localhost:5433 - rejecting connections</computeroutput> +<prompt>$</prompt> <userinput>echo $?</userinput> +<computeroutput>1</computeroutput> +</screen> + </para> + + <para> + Running with connection parameters to a non-responsive <productname>PostgreSQL</productname> cluster: +<screen> +<prompt>$ </prompt><userinput>pg_isready -h someremotehost</userinput> +<computeroutput>someremotehost:5432 - no response</computeroutput> +<prompt>$</prompt> <userinput>echo $?</userinput> +<computeroutput>2</computeroutput> +</screen> + </para> + + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_receivewal.sgml b/doc/src/sgml/ref/pg_receivewal.sgml new file mode 100644 index 0000000..409e502 --- /dev/null +++ b/doc/src/sgml/ref/pg_receivewal.sgml @@ -0,0 +1,530 @@ +<!-- +doc/src/sgml/ref/pg_receivewal.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgreceivewal"> + <indexterm zone="app-pgreceivewal"> + <primary>pg_receivewal</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_receivewal</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_receivewal</refname> + <refpurpose>stream write-ahead logs from a <productname>PostgreSQL</productname> server</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_receivewal</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + <application>pg_receivewal</application> is used to stream the write-ahead log + from a running <productname>PostgreSQL</productname> cluster. The write-ahead + log is streamed using the streaming replication protocol, and is written + to a local directory of files. This directory can be used as the archive + location for doing a restore using point-in-time recovery (see + <xref linkend="continuous-archiving"/>). + </para> + + <para> + <application>pg_receivewal</application> streams the write-ahead + log in real time as it's being generated on the server, and does not wait + for segments to complete like <xref linkend="guc-archive-command"/> and + <xref linkend="guc-archive-library"/> do. + For this reason, it is not necessary to set + <xref linkend="guc-archive-timeout"/> when using + <application>pg_receivewal</application>. + </para> + + <para> + Unlike the WAL receiver of a PostgreSQL standby server, <application>pg_receivewal</application> + by default flushes WAL data only when a WAL file is closed. + The option <option>--synchronous</option> must be specified to flush WAL data + in real time. Since <application>pg_receivewal</application> does not + apply WAL, you should not allow it to become a synchronous standby when + <xref linkend="guc-synchronous-commit"/> equals + <literal>remote_apply</literal>. If it does, it will appear to be a + standby that never catches up, and will cause transaction commits to + block. To avoid this, you should either configure an appropriate value + for <xref linkend="guc-synchronous-standby-names"/>, or specify + <varname>application_name</varname> for + <application>pg_receivewal</application> that does not match it, or + change the value of <varname>synchronous_commit</varname> to + something other than <literal>remote_apply</literal>. + </para> + + <para> + The write-ahead log is streamed over a regular + <productname>PostgreSQL</productname> connection and uses the replication + protocol. The connection must be made with a user having + <literal>REPLICATION</literal> permissions (see + <xref linkend="role-attributes"/>) or a superuser, and + <filename>pg_hba.conf</filename> must permit the replication connection. + The server must also be configured with + <xref linkend="guc-max-wal-senders"/> set high enough to leave at least + one session available for the stream. + </para> + + <para> + The starting point of the write-ahead log streaming is calculated when + <application>pg_receivewal</application> starts: + <orderedlist> + <listitem> + <para> + First, scan the directory where the WAL segment files are written and + find the newest completed segment file, using as the starting point the + beginning of the next WAL segment file. + </para> + </listitem> + + <listitem> + <para> + If a starting point cannot be calculated with the previous method, + and if a replication slot is used, an extra + <command>READ_REPLICATION_SLOT</command> command is issued to retrieve + the slot's <literal>restart_lsn</literal> to use as the starting point. + This option is only available when streaming write-ahead logs from + <productname>PostgreSQL</productname> 15 and up. + </para> + </listitem> + + <listitem> + <para> + If a starting point cannot be calculated with the previous method, + the latest WAL flush location is used as reported by the server from + an <literal>IDENTIFY_SYSTEM</literal> command. + </para> + </listitem> + </orderedlist> + </para> + + <para> + If the connection is lost, or if it cannot be initially established, + with a non-fatal error, <application>pg_receivewal</application> will + retry the connection indefinitely, and reestablish streaming as soon + as possible. To avoid this behavior, use the <literal>-n</literal> + parameter. + </para> + + <para> + In the absence of fatal errors, <application>pg_receivewal</application> + will run until terminated by the <systemitem>SIGINT</systemitem> signal + (<keycombo action="simul"><keycap>Control</keycap><keycap>C</keycap></keycombo>). + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <variablelist> + <varlistentry> + <term><option>-D <replaceable class="parameter">directory</replaceable></option></term> + <term><option>--directory=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Directory to write the output to. + </para> + <para> + This parameter is required. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E <replaceable>lsn</replaceable></option></term> + <term><option>--endpos=<replaceable>lsn</replaceable></option></term> + <listitem> + <para> + Automatically stop replication and exit with normal exit status 0 when + receiving reaches the specified LSN. + </para> + + <para> + If there is a record with LSN exactly equal to <replaceable>lsn</replaceable>, + the record will be processed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-not-exists</option></term> + <listitem> + <para> + Do not error out when <option>--create-slot</option> is specified + and a slot with the specified name already exists. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-loop</option></term> + <listitem> + <para> + Don't loop on connection errors. Instead, exit right away with + an error. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-sync</option></term> + <listitem> + <para> + This option causes <command>pg_receivewal</command> to not force WAL + data to be flushed to disk. This is faster, but means that a + subsequent operating system crash can leave the WAL segments corrupt. + Generally, this option is useful for testing but should not be used + when doing WAL archiving on a production deployment. + </para> + + <para> + This option is incompatible with <literal>--synchronous</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s <replaceable class="parameter">interval</replaceable></option></term> + <term><option>--status-interval=<replaceable class="parameter">interval</replaceable></option></term> + <listitem> + <para> + Specifies the number of seconds between status packets sent back to the + server. This allows for easier monitoring of the progress from server. + A value of zero disables the periodic status updates completely, + although an update will still be sent when requested by the server, to + avoid timeout disconnect. The default value is 10 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable>slotname</replaceable></option></term> + <term><option>--slot=<replaceable class="parameter">slotname</replaceable></option></term> + <listitem> + <para> + Require <application>pg_receivewal</application> to use an existing + replication slot (see <xref linkend="streaming-replication-slots"/>). + When this option is used, <application>pg_receivewal</application> will report + a flush position to the server, indicating when each segment has been + synchronized to disk so that the server can remove that segment if it + is not otherwise needed. + </para> + + <para> + When the replication client + of <application>pg_receivewal</application> is configured on the + server as a synchronous standby, then using a replication slot will + report the flush position to the server, but only when a WAL file is + closed. Therefore, that configuration will cause transactions on the + primary to wait for a long time and effectively not work + satisfactorily. The option <literal>--synchronous</literal> (see + below) must be specified in addition to make this work correctly. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--synchronous</option></term> + <listitem> + <para> + Flush the WAL data to disk immediately after it has been received. Also + send a status packet back to the server immediately after flushing, + regardless of <literal>--status-interval</literal>. + </para> + + <para> + This option should be specified if the replication client + of <application>pg_receivewal</application> is configured on the + server as a synchronous standby, to ensure that timely feedback is + sent to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Enables verbose mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Z <replaceable class="parameter">level</replaceable></option></term> + <term><option>-Z <replaceable class="parameter">method</replaceable>[:<replaceable>detail</replaceable>]</option></term> + <term><option>--compress=<replaceable class="parameter">level</replaceable></option></term> + <term><option>--compress=<replaceable class="parameter">method</replaceable>[:<replaceable>detail</replaceable>]</option></term> + <listitem> + <para> + Enables compression of write-ahead logs. + </para> + <para> + The compression method can be set to <literal>gzip</literal>, + <literal>lz4</literal> (if <productname>PostgreSQL</productname> + was compiled with <option>--with-lz4</option>) or + <literal>none</literal> for no compression. + A compression detail string can optionally be specified. If the + detail string is an integer, it specifies the compression level. + Otherwise, it should be a comma-separated list of items, each of the + form <literal>keyword</literal> or <literal>keyword=value</literal>. + Currently, the only supported keyword is <literal>level</literal>. + </para> + <para> + If no compression level is specified, the default compression level + will be used. If only a level is specified without mentioning an + algorithm, <literal>gzip</literal> compression will be used if the + level is greater than 0, and no compression will be used if the level + is 0. + </para> + <para> + The suffix <filename>.gz</filename> will automatically be added to + all filenames when using <literal>gzip</literal>, and the suffix + <filename>.lz4</filename> is added when using <literal>lz4</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + The following command-line options control the database connection parameters. + + <variablelist> + <varlistentry> + <term><option>-d <replaceable class="parameter">connstr</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">connstr</replaceable></option></term> + <listitem> + <para> + Specifies parameters used to connect to the server, as a <link + linkend="libpq-connstring">connection string</link>; these + will override any conflicting command line options. + </para> + <para> + The option is called <literal>--dbname</literal> for consistency with other + client applications, but because <application>pg_receivewal</application> + doesn't connect to any particular database in the cluster, database + name in the connection string will be ignored. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. The default is taken + from the <envar>PGHOST</envar> environment variable, if set, + else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_receivewal</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>pg_receivewal</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_receivewal</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + <application>pg_receivewal</application> can perform one of the two + following actions in order to control physical replication slots: + + <variablelist> + <varlistentry> + <term><option>--create-slot</option></term> + <listitem> + <para> + Create a new physical replication slot with the name specified in + <option>--slot</option>, then exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--drop-slot</option></term> + <listitem> + <para> + Drop the replication slot with the name specified in + <option>--slot</option>, then exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other options are also available: + + <variablelist> + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_receivewal</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_receivewal</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Exit Status</title> + + <para> + <application>pg_receivewal</application> will exit with status 0 when + terminated by the <systemitem>SIGINT</systemitem> signal. (That is the + normal way to end it. Hence it is not an error.) For fatal errors or + other signals, the exit status will be nonzero. + </para> + + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + When using <application>pg_receivewal</application> instead of + <xref linkend="guc-archive-command"/> or + <xref linkend="guc-archive-library"/> as the main WAL backup method, it is + strongly recommended to use replication slots. Otherwise, the server is + free to recycle or remove write-ahead log files before they are backed up, + because it does not have any information, either + from <xref linkend="guc-archive-command"/> or + <xref linkend="guc-archive-library"/> or the replication slots, about + how far the WAL stream has been archived. Note, however, that a + replication slot will fill up the server's disk space if the receiver does + not keep up with fetching the WAL data. + </para> + + <para> + <application>pg_receivewal</application> will preserve group permissions on + the received WAL files if group permissions are enabled on the source + cluster. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To stream the write-ahead log from the server at + <literal>mydbserver</literal> and store it in the local directory + <filename>/usr/local/pgsql/archive</filename>: +<screen> +<prompt>$</prompt> <userinput>pg_receivewal -h mydbserver -D /usr/local/pgsql/archive</userinput> +</screen></para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgbasebackup"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_recvlogical.sgml b/doc/src/sgml/ref/pg_recvlogical.sgml new file mode 100644 index 0000000..7c01a5c --- /dev/null +++ b/doc/src/sgml/ref/pg_recvlogical.sgml @@ -0,0 +1,453 @@ +<!-- +doc/src/sgml/ref/pg_recvlogical.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgrecvlogical"> + <indexterm zone="app-pgrecvlogical"> + <primary>pg_recvlogical</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_recvlogical</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_recvlogical</refname> + <refpurpose>control <productname>PostgreSQL</productname> logical decoding streams</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_recvlogical</command> + <arg rep="repeat" choice="opt"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + <command>pg_recvlogical</command> controls logical decoding replication + slots and streams data from such replication slots. + </para> + + <para> + It creates a replication-mode connection, so it is subject to the same + constraints as <xref linkend="app-pgreceivewal"/>, plus those for logical + replication (see <xref linkend="logicaldecoding"/>). + </para> + + <para> + <command>pg_recvlogical</command> has no equivalent to the logical decoding + SQL interface's peek and get modes. It sends replay confirmations for + data lazily as it receives it and on clean exit. To examine pending data on + a slot without consuming it, use + <link linkend="functions-replication"><function>pg_logical_slot_peek_changes</function></link>. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + At least one of the following options must be specified to select an action: + + <variablelist> + + <varlistentry> + <term><option>--create-slot</option></term> + <listitem> + <para> + Create a new logical replication slot with the name specified by + <option>--slot</option>, using the output plugin specified by + <option>--plugin</option>, for the database specified + by <option>--dbname</option>. + </para> + + <para> + The <option>--two-phase</option> can be specified with + <option>--create-slot</option> to enable decoding of prepared transactions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--drop-slot</option></term> + <listitem> + <para> + Drop the replication slot with the name specified + by <option>--slot</option>, then exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--start</option></term> + <listitem> + <para> + Begin streaming changes from the logical replication slot specified + by <option>--slot</option>, continuing until terminated by a + signal. If the server side change stream ends with a server shutdown + or disconnect, retry in a loop unless + <option>--no-loop</option> is specified. + </para> + + <para> + The stream format is determined by the output plugin specified when + the slot was created. + </para> + + <para> + The connection must be to the same database used to create the slot. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + <option>--create-slot</option> and <option>--start</option> can be + specified together. <option>--drop-slot</option> cannot be combined with + another action. + </para> + + <para> + The following command-line options control the location and format of the + output and other replication behavior: + + <variablelist> + <varlistentry> + <term><option>-E <replaceable>lsn</replaceable></option></term> + <term><option>--endpos=<replaceable>lsn</replaceable></option></term> + <listitem> + <para> + In <option>--start</option> mode, automatically stop replication + and exit with normal exit status 0 when receiving reaches the + specified LSN. If specified when not in <option>--start</option> + mode, an error is raised. + </para> + + <para> + If there's a record with LSN exactly equal to <replaceable>lsn</replaceable>, + the record will be output. + </para> + + <para> + The <option>--endpos</option> option is not aware of transaction + boundaries and may truncate output partway through a transaction. + Any partially output transaction will not be consumed and will be + replayed again when the slot is next read from. Individual messages + are never truncated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable>filename</replaceable></option></term> + <term><option>--file=<replaceable>filename</replaceable></option></term> + <listitem> + <para> + Write received and decoded transaction data into this + file. Use <literal>-</literal> for <systemitem>stdout</systemitem>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable>interval_seconds</replaceable></option></term> + <term><option>--fsync-interval=<replaceable>interval_seconds</replaceable></option></term> + <listitem> + <para> + Specifies how often <application>pg_recvlogical</application> should + issue <function>fsync()</function> calls to ensure the output file is + safely flushed to disk. + </para> + + <para> + The server will occasionally request the client to perform a flush and + report the flush position to the server. This setting is in addition + to that, to perform flushes more frequently. + </para> + + <para> + Specifying an interval of <literal>0</literal> disables + issuing <function>fsync()</function> calls altogether, while still + reporting progress to the server. In this case, data could be lost in + the event of a crash. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I <replaceable>lsn</replaceable></option></term> + <term><option>--startpos=<replaceable>lsn</replaceable></option></term> + <listitem> + <para> + In <option>--start</option> mode, start replication from the given + LSN. For details on the effect of this, see the documentation + in <xref linkend="logicaldecoding"/> + and <xref linkend="protocol-replication"/>. Ignored in other modes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-not-exists</option></term> + <listitem> + <para> + Do not error out when <option>--create-slot</option> is specified + and a slot with the specified name already exists. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-loop</option></term> + <listitem> + <para> + When the connection to the server is lost, do not retry in a loop, just exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable>name</replaceable>[=<replaceable>value</replaceable>]</option></term> + <term><option>--option=<replaceable>name</replaceable>[=<replaceable>value</replaceable>]</option></term> + <listitem> + <para> + Pass the option <replaceable>name</replaceable> to the output plugin with, + if specified, the option value <replaceable>value</replaceable>. Which + options exist and their effects depends on the used output plugin. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P <replaceable>plugin</replaceable></option></term> + <term><option>--plugin=<replaceable>plugin</replaceable></option></term> + <listitem> + <para> + When creating a slot, use the specified logical decoding output + plugin. See <xref linkend="logicaldecoding"/>. This option has no + effect if the slot already exists. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s <replaceable>interval_seconds</replaceable></option></term> + <term><option>--status-interval=<replaceable>interval_seconds</replaceable></option></term> + <listitem> + <para> + This option has the same effect as the option of the same name + in <xref linkend="app-pgreceivewal"/>. See the description there. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable>slot_name</replaceable></option></term> + <term><option>--slot=<replaceable>slot_name</replaceable></option></term> + <listitem> + <para> + In <option>--start</option> mode, use the existing logical replication slot named + <replaceable>slot_name</replaceable>. In <option>--create-slot</option> + mode, create the slot with this name. In <option>--drop-slot</option> + mode, delete the slot with this name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option></term> + <term><option>--two-phase</option></term> + <listitem> + <para> + Enables decoding of prepared transactions. This option may only be specified with + <option>--create-slot</option> + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Enables verbose mode. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following command-line options control the database connection parameters. + + <variablelist> + <varlistentry> + <term><option>-d <replaceable>dbname</replaceable></option></term> + <term><option>--dbname=<replaceable>dbname</replaceable></option></term> + <listitem> + <para> + The database to connect to. See the description + of the actions for what this means in detail. + The <replaceable>dbname</replaceable> can be a <link + linkend="libpq-connstring">connection string</link>. If so, + connection string parameters will override any conflicting + command line options. Defaults to the user name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable>hostname-or-ip</replaceable></option></term> + <term><option>--host=<replaceable>hostname-or-ip</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. The default is taken + from the <envar>PGHOST</envar> environment variable, if set, + else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable>port</replaceable></option></term> + <term><option>--port=<replaceable>port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>user</replaceable></option></term> + <term><option>--username=<replaceable>user</replaceable></option></term> + <listitem> + <para> + User name to connect as. Defaults to current operating system user + name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_recvlogical</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>pg_recvlogical</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_recvlogical</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + The following additional options are available: + + <variablelist> + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_recvlogical</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_recvlogical</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <application>pg_recvlogical</application> will preserve group permissions on + the received WAL files if group permissions are enabled on the source + cluster. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + See <xref linkend="logicaldecoding-example"/> for an example. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgreceivewal"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_resetwal.sgml b/doc/src/sgml/ref/pg_resetwal.sgml new file mode 100644 index 0000000..fd539f5 --- /dev/null +++ b/doc/src/sgml/ref/pg_resetwal.sgml @@ -0,0 +1,386 @@ +<!-- +doc/src/sgml/ref/pg_resetwal.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgresetwal"> + <indexterm zone="app-pgresetwal"> + <primary>pg_resetwal</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_resetwal</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_resetwal</refname> + <refpurpose>reset the write-ahead log and other control information of a <productname>PostgreSQL</productname> database cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_resetwal</command> + <group choice="opt"> + <arg choice="plain"><option>-f</option></arg> + <arg choice="plain"><option>--force</option></arg> + </group> + <group choice="opt"> + <arg choice="plain"><option>-n</option></arg> + <arg choice="plain"><option>--dry-run</option></arg> + </group> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <group choice="plain"> + <group choice="opt"> + <arg choice="plain"><option>-D</option></arg> + <arg choice="plain"><option>--pgdata</option></arg> + </group> + <replaceable class="parameter">datadir</replaceable> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="r1-app-pgresetwal-1"> + <title>Description</title> + <para> + <command>pg_resetwal</command> clears the write-ahead log (WAL) and + optionally resets some other control information stored in the + <filename>pg_control</filename> file. This function is sometimes needed + if these files have become corrupted. It should be used only as a + last resort, when the server will not start due to such corruption. + </para> + + <para> + After running this command, it should be possible to start the server, + but bear in mind that the database might contain inconsistent data due to + partially-committed transactions. You should immediately dump your data, + run <command>initdb</command>, and restore. After restore, check for + inconsistencies and repair as needed. + </para> + + <para> + This utility can only be run by the user who installed the server, because + it requires read/write access to the data directory. + For safety reasons, you must specify the data directory on the command line. + <command>pg_resetwal</command> does not use the environment variable + <envar>PGDATA</envar>. + </para> + + <para> + If <command>pg_resetwal</command> complains that it cannot determine + valid data for <filename>pg_control</filename>, you can force it to proceed anyway + by specifying the <option>-f</option> (force) option. In this case plausible + values will be substituted for the missing data. Most of the fields can be + expected to match, but manual assistance might be needed for the next OID, + next transaction ID and epoch, next multitransaction ID and offset, and + WAL starting location fields. These fields can be set using the options + discussed below. If you are not able to determine correct values for all + these fields, <option>-f</option> can still be used, but + the recovered database must be treated with even more suspicion than + usual: an immediate dump and restore is imperative. <emphasis>Do not</emphasis> + execute any data-modifying operations in the database before you dump, + as any such action is likely to make the corruption worse. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <variablelist> + <varlistentry> + <term><option>-f</option></term> + <term><option>--force</option></term> + <listitem> + <para> + Force <command>pg_resetwal</command> to proceed even if it cannot determine + valid data for <filename>pg_control</filename>, as explained above. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--dry-run</option></term> + <listitem> + <para> + The <option>-n</option>/<option>--dry-run</option> option instructs + <command>pg_resetwal</command> to print the values reconstructed from + <filename>pg_control</filename> and values about to be changed, and then exit + without modifying anything. This is mainly a debugging tool, but can be + useful as a sanity check before allowing <command>pg_resetwal</command> + to proceed for real. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem><para>Display version information, then exit.</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem><para>Show help, then exit.</para></listitem> + </varlistentry> + </variablelist> + + <para> + The following options are only needed when + <command>pg_resetwal</command> is unable to determine appropriate values + by reading <filename>pg_control</filename>. Safe values can be determined as + described below. For values that take numeric arguments, hexadecimal + values can be specified by using the prefix <literal>0x</literal>. + </para> + + <variablelist> + <varlistentry> + <term><option>-c <replaceable class="parameter">xid</replaceable>,<replaceable class="parameter">xid</replaceable></option></term> + <term><option>--commit-timestamp-ids=<replaceable class="parameter">xid</replaceable>,<replaceable class="parameter">xid</replaceable></option></term> + <listitem> + <para> + Manually set the oldest and newest transaction IDs for which the commit + time can be retrieved. + </para> + + <para> + A safe value for the oldest transaction ID for which the commit time can + be retrieved (first part) can be determined by looking + for the numerically smallest file name in the directory + <filename>pg_commit_ts</filename> under the data directory. Conversely, a safe + value for the newest transaction ID for which the commit time can be + retrieved (second part) can be determined by looking for the numerically + greatest file name in the same directory. The file names are in + hexadecimal. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e <replaceable class="parameter">xid_epoch</replaceable></option></term> + <term><option>--epoch=<replaceable class="parameter">xid_epoch</replaceable></option></term> + <listitem> + <para> + Manually set the next transaction ID's epoch. + </para> + + <para> + The transaction ID epoch is not actually stored anywhere in the database + except in the field that is set by <command>pg_resetwal</command>, + so any value will work so far as the database itself is concerned. + You might need to adjust this value to ensure that replication + systems such as <application>Slony-I</application> and + <application>Skytools</application> work correctly — + if so, an appropriate value should be obtainable from the state of + the downstream replicated database. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l <replaceable class="parameter">walfile</replaceable></option></term> + <term><option>--next-wal-file=<replaceable class="parameter">walfile</replaceable></option></term> + <listitem> + <para> + Manually set the WAL starting location by specifying the name of the + next WAL segment file. + </para> + + <para> + The name of next WAL segment file should be + larger than any WAL segment file name currently existing in + the directory <filename>pg_wal</filename> under the data directory. + These names are also in hexadecimal and have three parts. The first + part is the <quote>timeline ID</quote> and should usually be kept the same. + For example, if <filename>00000001000000320000004A</filename> is the + largest entry in <filename>pg_wal</filename>, use <literal>-l 00000001000000320000004B</literal> or higher. + </para> + + <para> + Note that when using nondefault WAL segment sizes, the numbers in the WAL + file names are different from the LSNs that are reported by system + functions and system views. This option takes a WAL file name, not an + LSN. + </para> + + <note> + <para> + <command>pg_resetwal</command> itself looks at the files in + <filename>pg_wal</filename> and chooses a default <option>-l</option> setting + beyond the last existing file name. Therefore, manual adjustment of + <option>-l</option> should only be needed if you are aware of WAL segment + files that are not currently present in <filename>pg_wal</filename>, such as + entries in an offline archive; or if the contents of + <filename>pg_wal</filename> have been lost entirely. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-m <replaceable class="parameter">mxid</replaceable>,<replaceable class="parameter">mxid</replaceable></option></term> + <term><option>--multixact-ids=<replaceable class="parameter">mxid</replaceable>,<replaceable class="parameter">mxid</replaceable></option></term> + <listitem> + <para> + Manually set the next and oldest multitransaction ID. + </para> + + <para> + A safe value for the next multitransaction ID (first part) can be + determined by looking for the numerically largest file name in the + directory <filename>pg_multixact/offsets</filename> under the data directory, + adding one, and then multiplying by 65536 (0x10000). Conversely, a safe + value for the oldest multitransaction ID (second part of + <option>-m</option>) can be determined by looking for the numerically smallest + file name in the same directory and multiplying by 65536. The file + names are in hexadecimal, so the easiest way to do this is to specify + the option value in hexadecimal and append four zeroes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable class="parameter">oid</replaceable></option></term> + <term><option>--next-oid=<replaceable class="parameter">oid</replaceable></option></term> + <listitem> + <para> + Manually set the next OID. + </para> + + <para> + There is no comparably easy way to determine a next OID that's beyond + the largest one in the database, but fortunately it is not critical to + get the next-OID setting right. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O <replaceable class="parameter">mxoff</replaceable></option></term> + <term><option>--multixact-offset=<replaceable class="parameter">mxoff</replaceable></option></term> + <listitem> + <para> + Manually set the next multitransaction offset. + </para> + + <para> + A safe value can be determined by looking for the numerically largest + file name in the directory <filename>pg_multixact/members</filename> under the + data directory, adding one, and then multiplying by 52352 (0xCC80). + The file names are in hexadecimal. There is no simple recipe such as + the ones for other options of appending zeroes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--wal-segsize=<replaceable class="parameter">wal_segment_size</replaceable></option></term> + <listitem> + <para> + Set the new WAL segment size, in megabytes. The value must be set to a + power of 2 between 1 and 1024 (megabytes). See the same option of <xref + linkend="app-initdb"/> for more information. + </para> + + <note> + <para> + While <command>pg_resetwal</command> will set the WAL starting address + beyond the latest existing WAL segment file, some segment size changes + can cause previous WAL file names to be reused. It is recommended to + use <option>-l</option> together with this option to manually set the + WAL starting address if WAL file name overlap will cause problems with + your archiving strategy. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-u <replaceable class="parameter">xid</replaceable></option></term> + <term><option>--oldest-transaction-id=<replaceable class="parameter">xid</replaceable></option></term> + <listitem> + <para> + Manually set the oldest unfrozen transaction ID. + </para> + + <para> + A safe value can be determined by looking for the numerically smallest + file name in the directory <filename>pg_xact</filename> under the data directory + and then multiplying by 1048576 (0x100000). Note that the file names are in + hexadecimal. It is usually easiest to specify the option value in + hexadecimal too. For example, if <filename>0007</filename> is the smallest entry + in <filename>pg_xact</filename>, <literal>-u 0x700000</literal> will work (five + trailing zeroes provide the proper multiplier). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x <replaceable class="parameter">xid</replaceable></option></term> + <term><option>--next-transaction-id=<replaceable class="parameter">xid</replaceable></option></term> + <listitem> + <para> + Manually set the next transaction ID. + </para> + + <para> + A safe value can be determined by looking for the numerically largest + file name in the directory <filename>pg_xact</filename> under the data directory, + adding one, + and then multiplying by 1048576 (0x100000). Note that the file names are in + hexadecimal. It is usually easiest to specify the option value in + hexadecimal too. For example, if <filename>0011</filename> is the largest entry + in <filename>pg_xact</filename>, <literal>-x 0x1200000</literal> will work (five + trailing zeroes provide the proper multiplier). + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + This command must not be used when the server is + running. <command>pg_resetwal</command> will refuse to start up if + it finds a server lock file in the data directory. If the + server crashed then a lock file might have been left + behind; in that case you can remove the lock file to allow + <command>pg_resetwal</command> to run. But before you do + so, make doubly certain that there is no server process still alive. + </para> + + <para> + <command>pg_resetwal</command> works only with servers of the same + major version. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgcontroldata"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_restore.sgml b/doc/src/sgml/ref/pg_restore.sgml new file mode 100644 index 0000000..a815831 --- /dev/null +++ b/doc/src/sgml/ref/pg_restore.sgml @@ -0,0 +1,1048 @@ +<!-- +doc/src/sgml/ref/pg_restore.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgrestore"> + <indexterm zone="app-pgrestore"> + <primary>pg_restore</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_restore</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_restore</refname> + + <refpurpose> + restore a <productname>PostgreSQL</productname> database from an + archive file created by <application>pg_dump</application> + </refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_restore</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>filename</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1 id="app-pgrestore-description"> + <title>Description</title> + + <para> + <application>pg_restore</application> is a utility for restoring a + <productname>PostgreSQL</productname> database from an archive + created by <xref linkend="app-pgdump"/> in one of the non-plain-text + formats. It will issue the commands necessary to reconstruct the + database to the state it was in at the time it was saved. The + archive files also allow <application>pg_restore</application> to + be selective about what is restored, or even to reorder the items + prior to being restored. The archive files are designed to be + portable across architectures. + </para> + + <para> + <application>pg_restore</application> can operate in two modes. + If a database name is specified, <application>pg_restore</application> + connects to that database and restores archive contents directly into + the database. Otherwise, a script containing the SQL + commands necessary to rebuild the database is created and written + to a file or standard output. This script output is equivalent to + the plain text output format of <application>pg_dump</application>. + Some of the options controlling the output are therefore analogous to + <application>pg_dump</application> options. + </para> + + <para> + Obviously, <application>pg_restore</application> cannot restore information + that is not present in the archive file. For instance, if the + archive was made using the <quote>dump data as + <command>INSERT</command> commands</quote> option, + <application>pg_restore</application> will not be able to load the data + using <command>COPY</command> statements. + </para> + </refsect1> + + <refsect1 id="app-pgrestore-options"> + <title>Options</title> + + <para> + <application>pg_restore</application> accepts the following command + line arguments. + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">filename</replaceable></term> + <listitem> + <para> + Specifies the location of the archive file (or directory, for a + directory-format archive) to be restored. + If not specified, the standard input is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-a</option></term> + <term><option>--data-only</option></term> + <listitem> + <para> + Restore only the data, not the schema (data definitions). + Table data, large objects, and sequence values are restored, + if present in the archive. + </para> + + <para> + This option is similar to, but for historical reasons not identical + to, specifying <option>--section=data</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--clean</option></term> + <listitem> + <para> + Before restoring database objects, issue commands + to <command>DROP</command> all the objects that will be restored. + This option is useful for overwriting an existing database. + If any of the objects do not exist in the destination database, + ignorable error messages will be reported, + unless <option>--if-exists</option> is also specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C</option></term> + <term><option>--create</option></term> + <listitem> + <para> + Create the database before restoring into it. + If <option>--clean</option> is also specified, drop and + recreate the target database before connecting to it. + </para> + + <para> + With <option>--create</option>, <application>pg_restore</application> + also restores the database's comment if any, and any configuration + variable settings that are specific to this database, that is, + any <command>ALTER DATABASE ... SET ...</command> + and <command>ALTER ROLE ... IN DATABASE ... SET ...</command> + commands that mention this database. + Access privileges for the database itself are also restored, + unless <option>--no-acl</option> is specified. + </para> + + <para> + When this option is used, the database named with <option>-d</option> + is used only to issue the initial <command>DROP DATABASE</command> and + <command>CREATE DATABASE</command> commands. All data is restored into the + database name that appears in the archive. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d <replaceable class="parameter">dbname</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Connect to database <replaceable + class="parameter">dbname</replaceable> and restore directly + into the database. The <replaceable>dbname</replaceable> can + be a <link linkend="libpq-connstring">connection string</link>. + If so, connection string parameters will override any conflicting + command line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--exit-on-error</option></term> + <listitem> + <para> + Exit if an error is encountered while sending SQL commands to + the database. The default is to continue and to display a count of + errors at the end of the restoration. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable>filename</replaceable></option></term> + <term><option>--file=<replaceable>filename</replaceable></option></term> + <listitem> + <para> + Specify output file for generated script, or for the listing + when used with <option>-l</option>. Use <literal>-</literal> + for <systemitem>stdout</systemitem>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable class="parameter">format</replaceable></option></term> + <term><option>--format=<replaceable class="parameter">format</replaceable></option></term> + <listitem> + <para> + Specify format of the archive. It is not necessary to specify + the format, since <application>pg_restore</application> will + determine the format automatically. If specified, it can be + one of the following: + + <variablelist> + <varlistentry> + <term><literal>c</literal></term> + <term><literal>custom</literal></term> + <listitem> + <para> + The archive is in the custom format of + <application>pg_dump</application>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>d</literal></term> + <term><literal>directory</literal></term> + <listitem> + <para> + The archive is a directory archive. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>t</literal></term> + <term><literal>tar</literal></term> + <listitem> + <para> + The archive is a <command>tar</command> archive. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I <replaceable class="parameter">index</replaceable></option></term> + <term><option>--index=<replaceable class="parameter">index</replaceable></option></term> + <listitem> + <para> + Restore definition of named index only. Multiple indexes + may be specified with multiple <option>-I</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">number-of-jobs</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">number-of-jobs</replaceable></option></term> + <listitem> + <para> + Run the most time-consuming steps + of <application>pg_restore</application> — those that load data, + create indexes, or create constraints — concurrently, using up + to <replaceable class="parameter">number-of-jobs</replaceable> + concurrent sessions. This option can dramatically reduce the time + to restore a large database to a server running on a + multiprocessor machine. This option is ignored when emitting a script + rather than connecting directly to a database server. + </para> + + <para> + Each job is one process or one thread, depending on the + operating system, and uses a separate connection to the + server. + </para> + + <para> + The optimal value for this option depends on the hardware + setup of the server, of the client, and of the network. + Factors include the number of CPU cores and the disk setup. A + good place to start is the number of CPU cores on the server, + but values larger than that can also lead to faster restore + times in many cases. Of course, values that are too high will + lead to decreased performance because of thrashing. + </para> + + <para> + Only the custom and directory archive formats are supported + with this option. + The input must be a regular file or directory (not, for example, a + pipe or standard input). Also, multiple + jobs cannot be used together with the + option <option>--single-transaction</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <term><option>--list</option></term> + <listitem> + <para> + List the table of contents of the archive. The output of this operation + can be used as input to the <option>-L</option> option. Note that + if filtering switches such as <option>-n</option> or <option>-t</option> are + used with <option>-l</option>, they will restrict the items listed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-L <replaceable class="parameter">list-file</replaceable></option></term> + <term><option>--use-list=<replaceable class="parameter">list-file</replaceable></option></term> + <listitem> + <para> + Restore only those archive elements that are listed in <replaceable + class="parameter">list-file</replaceable>, and restore them in the + order they appear in the file. Note that + if filtering switches such as <option>-n</option> or <option>-t</option> are + used with <option>-L</option>, they will further restrict the items restored. + </para> + <para><replaceable class="parameter">list-file</replaceable> is normally created by + editing the output of a previous <option>-l</option> operation. + Lines can be moved or removed, and can also + be commented out by placing a semicolon (<literal>;</literal>) at the + start of the line. See below for examples. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n <replaceable class="parameter">schema</replaceable></option></term> + <term><option>--schema=<replaceable class="parameter">schema</replaceable></option></term> + <listitem> + <para> + Restore only objects that are in the named schema. Multiple schemas + may be specified with multiple <option>-n</option> switches. This can be + combined with the <option>-t</option> option to restore just a + specific table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N <replaceable class="parameter">schema</replaceable></option></term> + <term><option>--exclude-schema=<replaceable class="parameter">schema</replaceable></option></term> + <listitem> + <para> + Do not restore objects that are in the named schema. Multiple schemas + to be excluded may be specified with multiple <option>-N</option> switches. + </para> + + <para> + When both <option>-n</option> and <option>-N</option> are given for the same + schema name, the <option>-N</option> switch wins and the schema is excluded. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O</option></term> + <term><option>--no-owner</option></term> + <listitem> + <para> + Do not output commands to set + ownership of objects to match the original database. + By default, <application>pg_restore</application> issues + <command>ALTER OWNER</command> or + <command>SET SESSION AUTHORIZATION</command> + statements to set ownership of created schema elements. + These statements will fail unless the initial connection to the + database is made by a superuser + (or the same user that owns all of the objects in the script). + With <option>-O</option>, any user name can be used for the + initial connection, and this user will own all the created objects. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P <replaceable class="parameter">function-name(argtype [, ...])</replaceable></option></term> + <term><option>--function=<replaceable class="parameter">function-name(argtype [, ...])</replaceable></option></term> + <listitem> + <para> + Restore the named function only. Be careful to spell the function + name and arguments exactly as they appear in the dump file's table + of contents. Multiple functions may be specified with multiple + <option>-P</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option></term> + <term><option>--no-reconnect</option></term> + <listitem> + <para> + This option is obsolete but still accepted for backwards + compatibility. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--schema-only</option></term> + <listitem> + <para> + Restore only the schema (data definitions), not data, + to the extent that schema entries are present in the archive. + </para> + <para> + This option is the inverse of <option>--data-only</option>. + It is similar to, but for historical reasons not identical to, + specifying + <option>--section=pre-data --section=post-data</option>. + </para> + <para> + (Do not confuse this with the <option>--schema</option> option, which + uses the word <quote>schema</quote> in a different meaning.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">username</replaceable></option></term> + <term><option>--superuser=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Specify the superuser user name to use when disabling triggers. + This is relevant only if <option>--disable-triggers</option> is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">table</replaceable></option></term> + <term><option>--table=<replaceable class="parameter">table</replaceable></option></term> + <listitem> + <para> + Restore definition and/or data of only the named table. + For this purpose, <quote>table</quote> includes views, materialized views, + sequences, and foreign tables. Multiple tables + can be selected by writing multiple <option>-t</option> switches. + This option can be combined with the <option>-n</option> option to + specify table(s) in a particular schema. + </para> + + <note> + <para> + When <option>-t</option> is specified, <application>pg_restore</application> + makes no attempt to restore any other database objects that the + selected table(s) might depend upon. Therefore, there is no + guarantee that a specific-table restore into a clean database will + succeed. + </para> + </note> + + <note> + <para> + This flag does not behave identically to the <option>-t</option> + flag of <application>pg_dump</application>. There is not currently + any provision for wild-card matching in <application>pg_restore</application>, + nor can you include a schema name within its <option>-t</option>. + And, while <application>pg_dump</application>'s <option>-t</option> + flag will also dump subsidiary objects (such as indexes) of the + selected table(s), + <application>pg_restore</application>'s <option>-t</option> + flag does not include such subsidiary objects. + </para> + </note> + + <note> + <para> + In versions prior to <productname>PostgreSQL</productname> 9.6, this flag + matched only tables, not any other type of relation. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">trigger</replaceable></option></term> + <term><option>--trigger=<replaceable class="parameter">trigger</replaceable></option></term> + <listitem> + <para> + Restore named trigger only. Multiple triggers may be specified with + multiple <option>-T</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Specifies verbose mode. This will cause + <application>pg_restore</application> to output detailed object + comments and start/stop times to the output file, and progress + messages to standard error. + Repeating the option causes additional debug-level messages + to appear on standard error. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_restore</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option></term> + <term><option>--no-privileges</option></term> + <term><option>--no-acl</option></term> + <listitem> + <para> + Prevent restoration of access privileges (grant/revoke commands). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-1</option></term> + <term><option>--single-transaction</option></term> + <listitem> + <para> + Execute the restore as a single transaction (that is, wrap the + emitted commands in <command>BEGIN</command>/<command>COMMIT</command>). This + ensures that either all the commands complete successfully, or no + changes are applied. This option implies + <option>--exit-on-error</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-triggers</option></term> + <listitem> + <para> + This option is relevant only when performing a data-only restore. + It instructs <application>pg_restore</application> to execute commands + to temporarily disable triggers on the target tables while + the data is restored. Use this if you have referential + integrity checks or other triggers on the tables that you + do not want to invoke during data restore. + </para> + + <para> + Presently, the commands emitted for + <option>--disable-triggers</option> must be done as superuser. So you + should also specify a superuser name with <option>-S</option> or, + preferably, run <application>pg_restore</application> as a + <productname>PostgreSQL</productname> superuser. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--enable-row-security</option></term> + <listitem> + <para> + This option is relevant only when restoring the contents of a table + which has row security. By default, <application>pg_restore</application> will set + <xref linkend="guc-row-security"/> to off, to ensure + that all data is restored in to the table. If the user does not have + sufficient privileges to bypass row security, then an error is thrown. + This parameter instructs <application>pg_restore</application> to set + <xref linkend="guc-row-security"/> to on instead, allowing the user to attempt to restore + the contents of the table with row security enabled. This might still + fail if the user does not have the right to insert the rows from the + dump into the table. + </para> + + <para> + Note that this option currently also requires the dump be in <command>INSERT</command> + format, as <command>COPY FROM</command> does not support row security. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--if-exists</option></term> + <listitem> + <para> + Use <literal>DROP ... IF EXISTS</literal> commands to drop objects + in <option>--clean</option> mode. This suppresses <quote>does not + exist</quote> errors that might otherwise be reported. This + option is not valid unless <option>--clean</option> is also + specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-comments</option></term> + <listitem> + <para> + Do not output commands to restore comments, even if the archive + contains them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-data-for-failed-tables</option></term> + <listitem> + <para> + By default, table data is restored even if the creation command + for the table failed (e.g., because it already exists). + With this option, data for such a table is skipped. + This behavior is useful if the target database already + contains the desired table contents. For example, + auxiliary tables for <productname>PostgreSQL</productname> extensions + such as <productname>PostGIS</productname> might already be loaded in + the target database; specifying this option prevents duplicate + or obsolete data from being loaded into them. + </para> + + <para> + This option is effective only when restoring directly into a + database, not when producing SQL script output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-publications</option></term> + <listitem> + <para> + Do not output commands to restore publications, even if the archive + contains them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-security-labels</option></term> + <listitem> + <para> + Do not output commands to restore security labels, + even if the archive contains them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-subscriptions</option></term> + <listitem> + <para> + Do not output commands to restore subscriptions, even if the archive + contains them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-table-access-method</option></term> + <listitem> + <para> + Do not output commands to select table access methods. + With this option, all objects will be created with whichever + access method is the default during restore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-tablespaces</option></term> + <listitem> + <para> + Do not output commands to select tablespaces. + With this option, all objects will be created in whichever + tablespace is the default during restore. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--section=<replaceable class="parameter">sectionname</replaceable></option></term> + <listitem> + <para> + Only restore the named section. The section name can be + <option>pre-data</option>, <option>data</option>, or <option>post-data</option>. + This option can be specified more than once to select multiple + sections. The default is to restore all sections. + </para> + <para> + The data section contains actual table data as well as large-object + definitions. + Post-data items consist of definitions of indexes, triggers, rules + and constraints other than validated check constraints. + Pre-data items consist of all other data definition items. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--strict-names</option></term> + <listitem> + <para> + Require that each schema + (<option>-n</option>/<option>--schema</option>) and table + (<option>-t</option>/<option>--table</option>) qualifier match at + least one schema/table in the backup file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--use-set-session-authorization</option></term> + <listitem> + <para> + Output SQL-standard <command>SET SESSION AUTHORIZATION</command> commands + instead of <command>ALTER OWNER</command> commands to determine object + ownership. This makes the dump more standards-compatible, but + depending on the history of the objects in the dump, might not restore + properly. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_restore</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + <application>pg_restore</application> also accepts + the following command line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. The default is taken + from the <envar>PGHOST</envar> environment variable, if set, + else a Unix domain socket connection is attempted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server is listening for connections. + Defaults to the <envar>PGPORT</envar> environment variable, if + set, or a compiled-in default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable>username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>pg_restore</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>pg_restore</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>pg_restore</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--role=<replaceable class="parameter">rolename</replaceable></option></term> + <listitem> + <para> + Specifies a role name to be used to perform the restore. + This option causes <application>pg_restore</application> to issue a + <command>SET ROLE</command> <replaceable class="parameter">rolename</replaceable> + command after connecting to the database. It is useful when the + authenticated user (specified by <option>-U</option>) lacks privileges + needed by <application>pg_restore</application>, but can switch to a role with + the required rights. Some installations have a policy against + logging in directly as a superuser, and use of this option allows + restores to be performed without violating the policy. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGHOST</envar></term> + <term><envar>PGOPTIONS</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). However, it does not read + <envar>PGDATABASE</envar> when a database name is not supplied. + </para> + + </refsect1> + + + <refsect1 id="app-pgrestore-diagnostics"> + <title>Diagnostics</title> + + <para> + When a direct database connection is specified using the + <option>-d</option> option, <application>pg_restore</application> + internally executes <acronym>SQL</acronym> statements. If you have + problems running <application>pg_restore</application>, make sure + you are able to select information from the database using, for + example, <xref linkend="app-psql"/>. Also, any default connection + settings and environment variables used by the + <application>libpq</application> front-end library will apply. + </para> + </refsect1> + + + <refsect1 id="app-pgrestore-notes"> + <title>Notes</title> + + <para> + If your installation has any local additions to the + <literal>template1</literal> database, be careful to load the output of + <application>pg_restore</application> into a truly empty database; + otherwise you are likely to get errors due to duplicate definitions + of the added objects. To make an empty database without any local + additions, copy from <literal>template0</literal> not <literal>template1</literal>, for example: +<programlisting> +CREATE DATABASE foo WITH TEMPLATE template0; +</programlisting> + </para> + + <para> + The limitations of <application>pg_restore</application> are detailed below. + + <itemizedlist> + <listitem> + <para> + When restoring data to a pre-existing table and the option + <option>--disable-triggers</option> is used, + <application>pg_restore</application> emits commands + to disable triggers on user tables before inserting the data, then emits commands to + re-enable them after the data has been inserted. If the restore is stopped in the + middle, the system catalogs might be left in the wrong state. + </para> + </listitem> + + <listitem> + <para><application>pg_restore</application> cannot restore large objects + selectively; for instance, only those for a specific table. If + an archive contains large objects, then all large objects will be + restored, or none of them if they are excluded via <option>-L</option>, + <option>-t</option>, or other options. + </para> + </listitem> + + </itemizedlist> + </para> + + <para> + See also the <xref linkend="app-pgdump"/> documentation for details on + limitations of <application>pg_dump</application>. + </para> + + <para> + Once restored, it is wise to run <command>ANALYZE</command> on each + restored table so the optimizer has useful statistics; see + <xref linkend="vacuum-for-statistics"/> and + <xref linkend="autovacuum"/> for more information. + </para> + + </refsect1> + + + <refsect1 id="app-pgrestore-examples"> + <title>Examples</title> + + <para> + Assume we have dumped a database called <literal>mydb</literal> into a + custom-format dump file: + +<screen> +<prompt>$</prompt> <userinput>pg_dump -Fc mydb > db.dump</userinput> +</screen> + </para> + + <para> + To drop the database and recreate it from the dump: + +<screen> +<prompt>$</prompt> <userinput>dropdb mydb</userinput> +<prompt>$</prompt> <userinput>pg_restore -C -d postgres db.dump</userinput> +</screen> + + The database named in the <option>-d</option> switch can be any database existing + in the cluster; <application>pg_restore</application> only uses it to issue the + <command>CREATE DATABASE</command> command for <literal>mydb</literal>. With + <option>-C</option>, data is always restored into the database name that appears + in the dump file. + </para> + + <para> + To restore the dump into a new database called <literal>newdb</literal>: + +<screen> +<prompt>$</prompt> <userinput>createdb -T template0 newdb</userinput> +<prompt>$</prompt> <userinput>pg_restore -d newdb db.dump</userinput> +</screen> + + Notice we don't use <option>-C</option>, and instead connect directly to the + database to be restored into. Also note that we clone the new database + from <literal>template0</literal> not <literal>template1</literal>, to ensure it is + initially empty. + </para> + + <para> + To reorder database items, it is first necessary to dump the table of + contents of the archive: +<screen> +<prompt>$</prompt> <userinput>pg_restore -l db.dump > db.list</userinput> +</screen> + The listing file consists of a header and one line for each item, e.g.: +<programlisting> +; +; Archive created at Mon Sep 14 13:55:39 2009 +; dbname: DBDEMOS +; TOC Entries: 81 +; Compression: 9 +; Dump Version: 1.10-0 +; Format: CUSTOM +; Integer: 4 bytes +; Offset: 8 bytes +; Dumped from database version: 8.3.5 +; Dumped by pg_dump version: 8.3.8 +; +; +; Selected TOC Entries: +; +3; 2615 2200 SCHEMA - public pasha +1861; 0 0 COMMENT - SCHEMA public pasha +1862; 0 0 ACL - public pasha +317; 1247 17715 TYPE public composite pasha +319; 1247 25899 DOMAIN public domain0 pasha +</programlisting> + Semicolons start a comment, and the numbers at the start of lines refer to the + internal archive ID assigned to each item. + </para> + + <para> + Lines in the file can be commented out, deleted, and reordered. For example: +<programlisting> +10; 145433 TABLE map_resolutions postgres +;2; 145344 TABLE species postgres +;4; 145359 TABLE nt_header postgres +6; 145402 TABLE species_records postgres +;8; 145416 TABLE ss_old postgres +</programlisting> + could be used as input to <application>pg_restore</application> and would only restore + items 10 and 6, in that order: +<screen> +<prompt>$</prompt> <userinput>pg_restore -L db.list db.dump</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgdump"/></member> + <member><xref linkend="app-pg-dumpall"/></member> + <member><xref linkend="app-psql"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pg_rewind.sgml b/doc/src/sgml/ref/pg_rewind.sgml new file mode 100644 index 0000000..69d6924 --- /dev/null +++ b/doc/src/sgml/ref/pg_rewind.sgml @@ -0,0 +1,418 @@ +<!-- +doc/src/sgml/ref/pg_rewind.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgrewind"> + <indexterm zone="app-pgrewind"> + <primary>pg_rewind</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_rewind</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_rewind</refname> + <refpurpose>synchronize a <productname>PostgreSQL</productname> data directory with another data directory that was forked from it</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_rewind</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <group choice="plain"> + <group choice="req"> + <arg choice="plain"><option>-D</option></arg> + <arg choice="plain"><option>--target-pgdata</option></arg> + </group> + <replaceable> directory</replaceable> + <group choice="req"> + <arg choice="plain"><option>--source-pgdata=<replaceable>directory</replaceable></option></arg> + <arg choice="plain"><option>--source-server=<replaceable>connstr</replaceable></option></arg> + </group> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_rewind</application> is a tool for synchronizing a PostgreSQL cluster + with another copy of the same cluster, after the clusters' timelines have + diverged. A typical scenario is to bring an old primary server back online + after failover as a standby that follows the new primary. + </para> + + <para> + After a successful rewind, the state of the target data directory is + analogous to a base backup of the source data directory. Unlike taking + a new base backup or using a tool like <application>rsync</application>, + <application>pg_rewind</application> does not require comparing or copying + unchanged relation blocks in the cluster. Only changed blocks from existing + relation files are copied; all other files, including new relation files, + configuration files, and WAL segments, are copied in full. As such the + rewind operation is significantly faster than other approaches when the + database is large and only a small fraction of blocks differ between the + clusters. + </para> + + <para> + <application>pg_rewind</application> examines the timeline histories of the source + and target clusters to determine the point where they diverged, and + expects to find WAL in the target cluster's <filename>pg_wal</filename> directory + reaching all the way back to the point of divergence. The point of divergence + can be found either on the target timeline, the source timeline, or their common + ancestor. In the typical failover scenario where the target cluster was + shut down soon after the divergence, this is not a problem, but if the + target cluster ran for a long time after the divergence, its old WAL + files might no longer be present. In this case, you can manually copy them + from the WAL archive to the <filename>pg_wal</filename> directory, or run + <application>pg_rewind</application> with the <literal>-c</literal> option to + automatically retrieve them from the WAL archive. The use of + <application>pg_rewind</application> is not limited to failover, e.g., a standby + server can be promoted, run some write transactions, and then rewound + to become a standby again. + </para> + + <para> + After running <application>pg_rewind</application>, WAL replay needs to + complete for the data directory to be in a consistent state. When the + target server is started again it will enter archive recovery and replay + all WAL generated in the source server from the last checkpoint before + the point of divergence. If some of the WAL was no longer available in the + source server when <application>pg_rewind</application> was run, and + therefore could not be copied by the <application>pg_rewind</application> + session, it must be made available when the target server is started. + This can be done by creating a <filename>recovery.signal</filename> file + in the target data directory and by configuring a suitable + <xref linkend="guc-restore-command"/> in + <filename>postgresql.conf</filename>. + </para> + + <para> + <application>pg_rewind</application> requires that the target server either has + the <xref linkend="guc-wal-log-hints"/> option enabled + in <filename>postgresql.conf</filename> or data checksums enabled when + the cluster was initialized with <application>initdb</application>. Neither of these + are currently on by default. <xref linkend="guc-full-page-writes"/> + must also be set to <literal>on</literal>, but is enabled by default. + </para> + + <warning> + <para> + If <application>pg_rewind</application> fails while processing, then + the data folder of the target is likely not in a state that can be + recovered. In such a case, taking a new fresh backup is recommended. + </para> + + <para> + As <application>pg_rewind</application> copies configuration files + entirely from the source, it may be required to correct the configuration + used for recovery before restarting the target server, especially if + the target is reintroduced as a standby of the source. If you restart + the server after the rewind operation has finished but without configuring + recovery, the target may again diverge from the primary. + </para> + + <para> + <application>pg_rewind</application> will fail immediately if it finds + files it cannot write directly to. This can happen for example when + the source and the target server use the same file mapping for read-only + SSL keys and certificates. If such files are present on the target server + it is recommended to remove them before running + <application>pg_rewind</application>. After doing the rewind, some of + those files may have been copied from the source, in which case it may + be necessary to remove the data copied and restore back the set of links + used before the rewind. + </para> + </warning> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_rewind</application> accepts the following command-line + arguments: + + <variablelist> + <varlistentry> + <term><option>-D <replaceable class="parameter">directory</replaceable></option></term> + <term><option>--target-pgdata=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + This option specifies the target data directory that is synchronized + with the source. The target server must be shut down cleanly before + running <application>pg_rewind</application> + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--source-pgdata=<replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Specifies the file system path to the data directory of the source + server to synchronize the target with. This option requires the + source server to be cleanly shut down. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--source-server=<replaceable class="parameter">connstr</replaceable></option></term> + <listitem> + <para> + Specifies a libpq connection string to connect to the source + <productname>PostgreSQL</productname> server to synchronize the target + with. The connection must be a normal (non-replication) connection + with a role having sufficient permissions to execute the functions + used by <application>pg_rewind</application> on the source server + (see Notes section for details) or a superuser role. This option + requires the source server to be running and accepting connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option></term> + <term><option>--write-recovery-conf</option></term> + <listitem> + <para> + Create <filename>standby.signal</filename> and append connection + settings to <filename>postgresql.auto.conf</filename> in the output + directory. <literal>--source-server</literal> is mandatory with + this option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--dry-run</option></term> + <listitem> + <para> + Do everything except actually modifying the target directory. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_rewind</command> will wait for all files + to be written safely to disk. This option causes + <command>pg_rewind</command> to return without waiting, which is + faster, but means that a subsequent operating system crash can leave + the data directory corrupt. Generally, this option is useful for + testing but should not be used on a production + installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <term><option>--progress</option></term> + <listitem> + <para> + Enables progress reporting. Turning this on will deliver an approximate + progress report while copying data from the source cluster. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--restore-target-wal</option></term> + <listitem> + <para> + Use <varname>restore_command</varname> defined in the target cluster + configuration to retrieve WAL files from the WAL archive if these + files are no longer available in the <filename>pg_wal</filename> + directory. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--config-file=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Use the specified main server configuration file for the target + cluster. This affects <application>pg_rewind</application> when + it uses internally the <application>postgres</application> command + for the rewind operation on this cluster (when retrieving + <varname>restore_command</varname> with the option + <option>-c/--restore-target-wal</option> and when forcing a + completion of crash recovery). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--debug</option></term> + <listitem> + <para> + Print verbose debugging output that is mostly useful for developers + debugging <application>pg_rewind</application>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-ensure-shutdown</option></term> + <listitem> + <para> + <application>pg_rewind</application> requires that the target server + is cleanly shut down before rewinding. By default, if the target server + is not shut down cleanly, <application>pg_rewind</application> starts + the target server in single-user mode to complete crash recovery first, + and stops it. + By passing this option, <application>pg_rewind</application> skips + this and errors out immediately if the server is not cleanly shut + down. Users are expected to handle the situation themselves in that + case. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem><para>Display version information, then exit.</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem><para>Show help, then exit.</para></listitem> + </varlistentry> + + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + When <option>--source-server</option> option is used, + <application>pg_rewind</application> also uses the environment variables + supported by <application>libpq</application> (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + When executing <application>pg_rewind</application> using an online + cluster as source, a role having sufficient permissions to execute the + functions used by <application>pg_rewind</application> on the source + cluster can be used instead of a superuser. Here is how to create such + a role, named <literal>rewind_user</literal> here: +<programlisting> +CREATE USER rewind_user LOGIN; +GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text, boolean, boolean) TO rewind_user; +GRANT EXECUTE ON function pg_catalog.pg_stat_file(text, boolean) TO rewind_user; +GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text) TO rewind_user; +GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text, bigint, bigint, boolean) TO rewind_user; +</programlisting> + </para> + + <para> + When executing <application>pg_rewind</application> using an online + cluster as source which has been recently promoted, it is necessary + to execute a <command>CHECKPOINT</command> after promotion such that its + control file reflects up-to-date timeline information, which is used by + <application>pg_rewind</application> to check if the target cluster + can be rewound using the designated source cluster. + </para> + + <refsect2> + <title>How It Works</title> + + <para> + The basic idea is to copy all file system-level changes from the source + cluster to the target cluster: + </para> + + <procedure> + <step> + <para> + Scan the WAL log of the target cluster, starting from the last + checkpoint before the point where the source cluster's timeline + history forked off from the target cluster. For each WAL record, + record each data block that was touched. This yields a list of all + the data blocks that were changed in the target cluster, after the + source cluster forked off. If some of the WAL files are no longer + available, try re-running <application>pg_rewind</application> with + the <option>-c</option> option to search for the missing files in + the WAL archive. + </para> + </step> + <step> + <para> + Copy all those changed blocks from the source cluster to + the target cluster, either using direct file system access + (<option>--source-pgdata</option>) or SQL (<option>--source-server</option>). + Relation files are now in a state equivalent to the moment of the last + completed checkpoint prior to the point at which the WAL timelines of the + source and target diverged plus the current state on the source of any + blocks changed on the target after that divergence. + </para> + </step> + <step> + <para> + Copy all other files, including new relation files, WAL segments, + <filename>pg_xact</filename>, and configuration files from the source + cluster to the target cluster. Similarly to base backups, the contents + of the directories <filename>pg_dynshmem/</filename>, + <filename>pg_notify/</filename>, <filename>pg_replslot/</filename>, + <filename>pg_serial/</filename>, <filename>pg_snapshots/</filename>, + <filename>pg_stat_tmp/</filename>, and <filename>pg_subtrans/</filename> + are omitted from the data copied from the source cluster. The files + <filename>backup_label</filename>, + <filename>tablespace_map</filename>, + <filename>pg_internal.init</filename>, + <filename>postmaster.opts</filename>, and + <filename>postmaster.pid</filename>, as well as any file or directory + beginning with <filename>pgsql_tmp</filename>, are omitted. + </para> + </step> + <step> + <para> + Create a <filename>backup_label</filename> file to begin WAL replay at + the checkpoint created at failover and configure the + <filename>pg_control</filename> file with a minimum consistency LSN + defined as the result of <literal>pg_current_wal_insert_lsn()</literal> + when rewinding from a live source or the last checkpoint LSN when + rewinding from a stopped source. + </para> + </step> + <step> + <para> + When starting the target, <productname>PostgreSQL</productname> replays + all the required WAL, resulting in a data directory in a consistent + state. + </para> + </step> + </procedure> + </refsect2> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_verifybackup.sgml b/doc/src/sgml/ref/pg_verifybackup.sgml new file mode 100644 index 0000000..5f83c98 --- /dev/null +++ b/doc/src/sgml/ref/pg_verifybackup.sgml @@ -0,0 +1,289 @@ +<!-- +doc/src/sgml/ref/pg_verifybackup.sgml +PostgreSQL documentation +--> + +<refentry id="app-pgverifybackup"> + <indexterm zone="app-pgverifybackup"> + <primary>pg_verifybackup</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_verifybackup</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_verifybackup</refname> + <refpurpose>verify the integrity of a base backup of a + <productname>PostgreSQL</productname> cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_verifybackup</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + <application>pg_verifybackup</application> is used to check the + integrity of a database cluster backup taken using + <command>pg_basebackup</command> against a + <literal>backup_manifest</literal> generated by the server at the time + of the backup. The backup must be stored in the "plain" + format; a "tar" format backup can be checked after extracting it. + </para> + + <para> + It is important to note that the validation which is performed by + <application>pg_verifybackup</application> does not and cannot include + every check which will be performed by a running server when attempting + to make use of the backup. Even if you use this tool, you should still + perform test restores and verify that the resulting databases work as + expected and that they appear to contain the correct data. However, + <application>pg_verifybackup</application> can detect many problems + that commonly occur due to storage problems or user error. + </para> + + <para> + Backup verification proceeds in four stages. First, + <literal>pg_verifybackup</literal> reads the + <literal>backup_manifest</literal> file. If that file + does not exist, cannot be read, is malformed, or fails verification + against its own internal checksum, <literal>pg_verifybackup</literal> + will terminate with a fatal error. + </para> + + <para> + Second, <literal>pg_verifybackup</literal> will attempt to verify that + the data files currently stored on disk are exactly the same as the data + files which the server intended to send, with some exceptions that are + described below. Extra and missing files will be detected, with a few + exceptions. This step will ignore the presence or absence of, or any + modifications to, <literal>postgresql.auto.conf</literal>, + <literal>standby.signal</literal>, and <literal>recovery.signal</literal>, + because it is expected that these files may have been created or modified + as part of the process of taking the backup. It also won't complain about + a <literal>backup_manifest</literal> file in the target directory or + about anything inside <literal>pg_wal</literal>, even though these + files won't be listed in the backup manifest. Only files are checked; + the presence or absence of directories is not verified, except + indirectly: if a directory is missing, any files it should have contained + will necessarily also be missing. + </para> + + <para> + Next, <literal>pg_verifybackup</literal> will checksum all the files, + compare the checksums against the values in the manifest, and emit errors + for any files for which the computed checksum does not match the + checksum stored in the manifest. This step is not performed for any files + which produced errors in the previous step, since they are already known + to have problems. Files which were ignored in the previous step are also + ignored in this step. + </para> + + <para> + Finally, <literal>pg_verifybackup</literal> will use the manifest to + verify that the write-ahead log records which will be needed to recover + the backup are present and that they can be read and parsed. The + <literal>backup_manifest</literal> contains information about which + write-ahead log records will be needed, and + <literal>pg_verifybackup</literal> will use that information to + invoke <literal>pg_waldump</literal> to parse those write-ahead log + records. The <literal>--quiet</literal> flag will be used, so that + <literal>pg_waldump</literal> will only report errors, without producing + any other output. While this level of verification is sufficient to + detect obvious problems such as a missing file or one whose internal + checksums do not match, they aren't extensive enough to detect every + possible problem that might occur when attempting to recover. For + instance, a server bug that produces write-ahead log records that have + the correct checksums but specify nonsensical actions can't be detected + by this method. + </para> + + <para> + Note that if extra WAL files which are not required to recover the backup + are present, they will not be checked by this tool, although + a separate invocation of <literal>pg_waldump</literal> could be used for + that purpose. Also note that WAL verification is version-specific: you + must use the version of <literal>pg_verifybackup</literal>, and thus of + <literal>pg_waldump</literal>, which pertains to the backup being checked. + In contrast, the data file integrity checks should work with any version + of the server that generates a <literal>backup_manifest</literal> file. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_verifybackup</application> accepts the following + command-line arguments: + + <variablelist> + <varlistentry> + <term><option>-e</option></term> + <term><option>--exit-on-error</option></term> + <listitem> + <para> + Exit as soon as a problem with the backup is detected. If this option + is not specified, <literal>pg_verifybackup</literal> will continue + checking the backup even after a problem has been detected, and will + report all problems detected as errors. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i <replaceable class="parameter">path</replaceable></option></term> + <term><option>--ignore=<replaceable class="parameter">path</replaceable></option></term> + <listitem> + <para> + Ignore the specified file or directory, which should be expressed + as a relative path name, when comparing the list of data files + actually present in the backup to those listed in the + <literal>backup_manifest</literal> file. If a directory is + specified, this option affects the entire subtree rooted at that + location. Complaints about extra files, missing files, file size + differences, or checksum mismatches will be suppressed if the + relative path name matches the specified path name. This option + can be specified multiple times. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-m <replaceable class="parameter">path</replaceable></option></term> + <term><option>--manifest-path=<replaceable class="parameter">path</replaceable></option></term> + <listitem> + <para> + Use the manifest file at the specified path, rather than one located + in the root of the backup directory. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-parse-wal</option></term> + <listitem> + <para> + Don't attempt to parse write-ahead log data that will be needed + to recover from this backup. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Don't print anything when a backup is successfully verified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--skip-checksums</option></term> + <listitem> + <para> + Do not verify data file checksums. The presence or absence of + files and the sizes of those files will still be checked. This is + much faster, because the files themselves do not need to be read. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w <replaceable class="parameter">path</replaceable></option></term> + <term><option>--wal-directory=<replaceable class="parameter">path</replaceable></option></term> + <listitem> + <para> + Try to parse WAL files stored in the specified directory, rather than + in <literal>pg_wal</literal>. This may be useful if the backup is + stored in a separate location from the WAL archive. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Other options are also available: + + <variablelist> + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_verifybackup</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_verifybackup</application> command + line arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To create a base backup of the server at <literal>mydbserver</literal> and + verify the integrity of the backup: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -h mydbserver -D /usr/local/pgsql/data</userinput> +<prompt>$</prompt> <userinput>pg_verifybackup /usr/local/pgsql/data</userinput> +</screen> + </para> + + <para> + To create a base backup of the server at <literal>mydbserver</literal>, move + the manifest somewhere outside the backup directory, and verify the + backup: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -h mydbserver -D /usr/local/pgsql/backup1234</userinput> +<prompt>$</prompt> <userinput>mv /usr/local/pgsql/backup1234/backup_manifest /my/secure/location/backup_manifest.1234</userinput> +<prompt>$</prompt> <userinput>pg_verifybackup -m /my/secure/location/backup_manifest.1234 /usr/local/pgsql/backup1234</userinput> +</screen> + </para> + + <para> + To verify a backup while ignoring a file that was added manually to the + backup directory, and also skipping checksum verification: +<screen> +<prompt>$</prompt> <userinput>pg_basebackup -h mydbserver -D /usr/local/pgsql/data</userinput> +<prompt>$</prompt> <userinput>edit /usr/local/pgsql/data/note.to.self</userinput> +<prompt>$</prompt> <userinput>pg_verifybackup --ignore=note.to.self --skip-checksums /usr/local/pgsql/data</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-pgbasebackup"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pg_waldump.sgml b/doc/src/sgml/ref/pg_waldump.sgml new file mode 100644 index 0000000..c887ac1 --- /dev/null +++ b/doc/src/sgml/ref/pg_waldump.sgml @@ -0,0 +1,340 @@ +<!-- +doc/src/sgml/ref/pg_waldump.sgml +PostgreSQL documentation +--> + +<refentry id="pgwaldump"> + <indexterm zone="pgwaldump"> + <primary>pg_waldump</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_waldump</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_waldump</refname> + <refpurpose>display a human-readable rendering of the write-ahead log of a <productname>PostgreSQL</productname> database cluster</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_waldump</command> + <arg rep="repeat" choice="opt"><option>option</option></arg> + <arg choice="opt"><option>startseg</option><arg choice="opt"><option>endseg</option></arg></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1 id="r1-app-pgwaldump-1"> + <title>Description</title> + <para> + <command>pg_waldump</command> displays the write-ahead log (WAL) and is mainly + useful for debugging or educational purposes. + </para> + + <para> + This utility can only be run by the user who installed the server, because + it requires read-only access to the data directory. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following command-line options control the location and format of the + output: + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">startseg</replaceable></term> + <listitem> + <para> + Start reading at the specified log segment file. This implicitly determines + the path in which files will be searched for, and the timeline to use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">endseg</replaceable></term> + <listitem> + <para> + Stop after reading the specified log segment file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-b</option></term> + <term><option>--bkp-details</option></term> + <listitem> + <para> + Output detailed information about backup blocks. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-B <replaceable>block</replaceable></option></term> + <term><option>--block=<replaceable>block</replaceable></option></term> + <listitem> + <para> + Only display records that modify the given block. The relation must + also be provided with <option>--relation</option> or + <option>-R</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e <replaceable>end</replaceable></option></term> + <term><option>--end=<replaceable>end</replaceable></option></term> + <listitem> + <para> + Stop reading at the specified WAL location, instead of reading to the + end of the log stream. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f</option></term> + <term><option>--follow</option></term> + <listitem> + <para> + After reaching the end of valid WAL, keep polling once per second for + new WAL to appear. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable>fork</replaceable></option></term> + <term><option>--fork=<replaceable>fork</replaceable></option></term> + <listitem> + <para> + If provided, only display records that modify blocks in the given fork. + The valid values are <literal>main</literal> for the main fork, + <literal>fsm</literal> for the free space map, + <literal>vm</literal> for the visibility map, + and <literal>init</literal> for the init fork. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n <replaceable>limit</replaceable></option></term> + <term><option>--limit=<replaceable>limit</replaceable></option></term> + <listitem> + <para> + Display the specified number of records, then stop. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable>path</replaceable></option></term> + <term><option>--path=<replaceable>path</replaceable></option></term> + <listitem> + <para> + Specifies a directory to search for log segment files or a + directory with a <literal>pg_wal</literal> subdirectory that + contains such files. The default is to search in the current + directory, the <literal>pg_wal</literal> subdirectory of the + current directory, and the <literal>pg_wal</literal> subdirectory + of <envar>PGDATA</envar>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Do not print any output, except for errors. This option can be useful + when you want to know whether a range of WAL records can be + successfully parsed but don't care about the record contents. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r <replaceable>rmgr</replaceable></option></term> + <term><option>--rmgr=<replaceable>rmgr</replaceable></option></term> + <listitem> + <para> + Only display records generated by the specified resource manager. You can + specify the option multiple times to select multiple resource managers. + If <literal>list</literal> is passed as name, print a list of valid resource manager + names, and exit. + </para> + <para> + Extensions may define custom resource managers, but pg_waldump does + not load the extension module and therefore does not recognize custom + resource managers by name. Instead, you can specify the custom + resource managers as <literal>custom###</literal> where + "<literal>###</literal>" is the three-digit resource manager ID. Names + of this form will always be considered valid. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R <replaceable>tblspc</replaceable>/<replaceable>db</replaceable>/<replaceable>rel</replaceable></option></term> + <term><option>--relation=<replaceable>tblspc</replaceable>/<replaceable>db</replaceable>/<replaceable>rel</replaceable></option></term> + <listitem> + <para> + Only display records that modify blocks in the given relation. The + relation is specified with tablespace OID, database OID, and relfilenode + separated by slashes, for example <literal>1234/12345/12345</literal>. + This is the same format used for relations in the program's output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s <replaceable>start</replaceable></option></term> + <term><option>--start=<replaceable>start</replaceable></option></term> + <listitem> + <para> + WAL location at which to start reading. The default is to start reading + the first valid log record found in the earliest file found. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable>timeline</replaceable></option></term> + <term><option>--timeline=<replaceable>timeline</replaceable></option></term> + <listitem> + <para> + Timeline from which to read log records. The default is to use the + value in <replaceable>startseg</replaceable>, if that is specified; otherwise, the + default is 1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_waldump</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--fullpage</option></term> + <listitem> + <para> + Only display records that include full page images. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x <replaceable>xid</replaceable></option></term> + <term><option>--xid=<replaceable>xid</replaceable></option></term> + <listitem> + <para> + Only display records marked with the given transaction ID. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-z</option></term> + <term><option>--stats[=record]</option></term> + <listitem> + <para> + Display summary statistics (number and size of records and + full-page images) instead of individual records. Optionally + generate statistics per-record instead of per-rmgr. + </para> + + <para> + If <application>pg_waldump</application> is terminated by signal + <systemitem>SIGINT</systemitem> + (<keycombo action="simul"><keycap>Control</keycap><keycap>C</keycap></keycombo>), + the summary of the statistics computed is displayed up to the + termination point. This operation is not supported on + <productname>Windows</productname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_waldump</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATA</envar></term> + <listitem> + <para> + Data directory; see also the <option>-p</option> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + <para> + Can give wrong results when the server is running. + </para> + + <para> + Only the specified timeline is displayed (or the default, if none is + specified). Records in other timelines are ignored. + </para> + + <para> + <application>pg_waldump</application> cannot read WAL files with suffix + <literal>.partial</literal>. If those files need to be read, <literal>.partial</literal> + suffix needs to be removed from the file name. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="wal-internals"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pgarchivecleanup.sgml b/doc/src/sgml/ref/pgarchivecleanup.sgml new file mode 100644 index 0000000..635e7c7 --- /dev/null +++ b/doc/src/sgml/ref/pgarchivecleanup.sgml @@ -0,0 +1,207 @@ +<!-- +doc/src/sgml/ref/pgarchivecleanup.sgml +PostgreSQL documentation +--> + +<refentry id="pgarchivecleanup"> + <indexterm zone="pgarchivecleanup"> + <primary>pg_archivecleanup</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_archivecleanup</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_archivecleanup</refname> + <refpurpose>clean up <productname>PostgreSQL</productname> WAL archive files</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_archivecleanup</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="plain"><replaceable>archivelocation</replaceable></arg> + <arg choice="plain"><replaceable>oldestkeptwalfile</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_archivecleanup</application> is designed to be used as an + <literal>archive_cleanup_command</literal> to clean up WAL file archives when + running as a standby server (see <xref linkend="warm-standby"/>). + <application>pg_archivecleanup</application> can also be used as a standalone program to + clean WAL file archives. + </para> + + <para> + To configure a standby + server to use <application>pg_archivecleanup</application>, put this into its + <filename>postgresql.conf</filename> configuration file: +<programlisting> +archive_cleanup_command = 'pg_archivecleanup <replaceable>archivelocation</replaceable> %r' +</programlisting> + where <replaceable>archivelocation</replaceable> is the directory from which WAL segment + files should be removed. + </para> + <para> + When used within <xref linkend="guc-archive-cleanup-command"/>, all WAL files + logically preceding the value of the <literal>%r</literal> argument will be removed + from <replaceable>archivelocation</replaceable>. This minimizes the number of files + that need to be retained, while preserving crash-restart capability. Use of + this parameter is appropriate if the <replaceable>archivelocation</replaceable> is a + transient staging area for this particular standby server, but + <emphasis>not</emphasis> when the <replaceable>archivelocation</replaceable> is intended as a + long-term WAL archive area, or when multiple standby servers are recovering + from the same archive location. + </para> + <para> + When used as a standalone program all WAL files logically preceding the + <replaceable>oldestkeptwalfile</replaceable> will be removed from <replaceable>archivelocation</replaceable>. + In this mode, if you specify a <filename>.partial</filename> or <filename>.backup</filename> + file name, then only the file prefix will be used as the + <replaceable>oldestkeptwalfile</replaceable>. This treatment of <filename>.backup</filename> + file name allows you to remove + all WAL files archived prior to a specific base backup without error. + For example, the following example will remove all files older than + WAL file name <filename>000000010000003700000010</filename>: +<programlisting> +pg_archivecleanup -d archive 000000010000003700000010.00000020.backup + +pg_archivecleanup: keep WAL file "archive/000000010000003700000010" and later +pg_archivecleanup: removing file "archive/00000001000000370000000F" +pg_archivecleanup: removing file "archive/00000001000000370000000E" +</programlisting> + </para> + <para> + <application>pg_archivecleanup</application> assumes that + <replaceable>archivelocation</replaceable> is a directory readable and writable by the + server-owning user. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_archivecleanup</application> accepts the following command-line arguments: + + <variablelist> + + <varlistentry> + <term><option>-d</option></term> + <listitem> + <para> + Print lots of debug logging output on <filename>stderr</filename>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <listitem> + <para> + Print the names of the files that would have been removed on <filename>stdout</filename> (performs a dry run). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_archivecleanup</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option> <replaceable>extension</replaceable></term> + <listitem> + <para> + Provide an extension + that will be stripped from all file names before deciding if they + should be deleted. This is typically useful for cleaning up archives + that have been compressed during storage, and therefore have had an + extension added by the compression program. For example: <literal>-x + .gz</literal>. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_archivecleanup</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <application>pg_archivecleanup</application> is designed to work with + <productname>PostgreSQL</productname> 8.0 and later when used as a standalone utility, + or with <productname>PostgreSQL</productname> 9.0 and later when used as an + archive cleanup command. + </para> + + <para> + <application>pg_archivecleanup</application> is written in C and has an + easy-to-modify source code, with specifically designated sections to modify + for your own needs + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>On Linux or Unix systems, you might use: +<programlisting> +archive_cleanup_command = 'pg_archivecleanup -d /mnt/standby/archive %r 2>>cleanup.log' +</programlisting> + where the archive directory is physically located on the standby server, + so that the <varname>archive_command</varname> is accessing it across NFS, + but the files are local to the standby. + This will: + </para> + <itemizedlist> + <listitem> + <para> + produce debugging output in <filename>cleanup.log</filename> + </para> + </listitem> + <listitem> + <para> + remove no-longer-needed files from the archive directory + </para> + </listitem> + </itemizedlist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/pgbench.sgml b/doc/src/sgml/ref/pgbench.sgml new file mode 100644 index 0000000..7d66679 --- /dev/null +++ b/doc/src/sgml/ref/pgbench.sgml @@ -0,0 +1,2950 @@ +<!-- +doc/src/sgml/ref/pgbench.sgml +PostgreSQL documentation +--> + +<refentry id="pgbench"> + <indexterm zone="pgbench"> + <primary>pgbench</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pgbench</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pgbench</refname> + <refpurpose>run a benchmark test on <productname>PostgreSQL</productname></refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pgbench</command> + <arg choice="plain"><option>-i</option></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + <cmdsynopsis> + <command>pgbench</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para> + <application>pgbench</application> is a simple program for running benchmark + tests on <productname>PostgreSQL</productname>. It runs the same sequence of SQL + commands over and over, possibly in multiple concurrent database sessions, + and then calculates the average transaction rate (transactions per second). + By default, <application>pgbench</application> tests a scenario that is + loosely based on TPC-B, involving five <command>SELECT</command>, + <command>UPDATE</command>, and <command>INSERT</command> commands per transaction. + However, it is easy to test other cases by writing your own transaction + script files. + </para> + + <para> + Typical output from <application>pgbench</application> looks like: + +<screen> +transaction type: <builtin: TPC-B (sort of)> +scaling factor: 10 +query mode: simple +number of clients: 10 +number of threads: 1 +maximum number of tries: 1 +number of transactions per client: 1000 +number of transactions actually processed: 10000/10000 +number of failed transactions: 0 (0.000%) +latency average = 11.013 ms +latency stddev = 7.351 ms +initial connection time = 45.758 ms +tps = 896.967014 (without initial connection time) +</screen> + + The first seven lines report some of the most important parameter + settings. + The sixth line reports the maximum number of tries for transactions with + serialization or deadlock errors (see <xref linkend="failures-and-retries"/> + for more information). + The eighth line reports the number of transactions completed + and intended (the latter being just the product of number of clients + and number of transactions per client); these will be equal unless the run + failed before completion or some SQL command(s) failed. (In + <option>-T</option> mode, only the actual number of transactions is printed.) + The next line reports the number of failed transactions due to + serialization or deadlock errors (see <xref linkend="failures-and-retries"/> + for more information). + The last line reports the number of transactions per second. + </para> + + <para> + The default TPC-B-like transaction test requires specific tables to be + set up beforehand. <application>pgbench</application> should be invoked with + the <option>-i</option> (initialize) option to create and populate these + tables. (When you are testing a custom script, you don't need this + step, but will instead need to do whatever setup your test needs.) + Initialization looks like: + +<programlisting> +pgbench -i <optional> <replaceable>other-options</replaceable> </optional> <replaceable>dbname</replaceable> +</programlisting> + + where <replaceable>dbname</replaceable> is the name of the already-created + database to test in. (You may also need <option>-h</option>, + <option>-p</option>, and/or <option>-U</option> options to specify how to + connect to the database server.) + </para> + + <caution> + <para> + <literal>pgbench -i</literal> creates four tables <structname>pgbench_accounts</structname>, + <structname>pgbench_branches</structname>, <structname>pgbench_history</structname>, and + <structname>pgbench_tellers</structname>, + destroying any existing tables of these names. + Be very careful to use another database if you have tables having these + names! + </para> + </caution> + + <para> + At the default <quote>scale factor</quote> of 1, the tables initially + contain this many rows: +<screen> +table # of rows +--------------------------------- +pgbench_branches 1 +pgbench_tellers 10 +pgbench_accounts 100000 +pgbench_history 0 +</screen> + You can (and, for most purposes, probably should) increase the number + of rows by using the <option>-s</option> (scale factor) option. The + <option>-F</option> (fillfactor) option might also be used at this point. + </para> + + <para> + Once you have done the necessary setup, you can run your benchmark + with a command that doesn't include <option>-i</option>, that is + +<programlisting> +pgbench <optional> <replaceable>options</replaceable> </optional> <replaceable>dbname</replaceable> +</programlisting> + + In nearly all cases, you'll need some options to make a useful test. + The most important options are <option>-c</option> (number of clients), + <option>-t</option> (number of transactions), <option>-T</option> (time limit), + and <option>-f</option> (specify a custom script file). + See below for a full list. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + The following is divided into three subsections. Different options are + used during database initialization and while running benchmarks, but some + options are useful in both cases. + </para> + + <refsect2 id="pgbench-init-options"> + <title>Initialization Options</title> + + <para> + <application>pgbench</application> accepts the following command-line + initialization arguments: + + <variablelist> + + <varlistentry> + <term><replaceable class="parameter">dbname</replaceable></term> + <listitem> + <para> + Specifies the name of the database to test in. If this is + not specified, the environment variable + <envar>PGDATABASE</envar> is used. If that is not set, the + user name specified for the connection is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <term><option>--initialize</option></term> + <listitem> + <para> + Required to invoke initialization mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-I <replaceable>init_steps</replaceable></option></term> + <term><option>--init-steps=<replaceable>init_steps</replaceable></option></term> + <listitem> + <para> + Perform just a selected set of the normal initialization steps. + <replaceable>init_steps</replaceable> specifies the + initialization steps to be performed, using one character per step. + Each step is invoked in the specified order. + The default is <literal>dtgvp</literal>. + The available steps are: + + <variablelist> + <varlistentry> + <term><literal>d</literal> (Drop)</term> + <listitem> + <para> + Drop any existing <application>pgbench</application> tables. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>t</literal> (create Tables)</term> + <listitem> + <para> + Create the tables used by the + standard <application>pgbench</application> scenario, namely + <structname>pgbench_accounts</structname>, + <structname>pgbench_branches</structname>, + <structname>pgbench_history</structname>, and + <structname>pgbench_tellers</structname>. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>g</literal> or <literal>G</literal> (Generate data, client-side or server-side)</term> + <listitem> + <para> + Generate data and load it into the standard tables, + replacing any data already present. + </para> + <para> + With <literal>g</literal> (client-side data generation), + data is generated in <command>pgbench</command> client and then + sent to the server. This uses the client/server bandwidth + extensively through a <command>COPY</command>. + <command>pgbench</command> uses the FREEZE option with version 14 or later + of <productname>PostgreSQL</productname> to speed up + subsequent <command>VACUUM</command>, unless partitions are enabled. + Using <literal>g</literal> causes logging to print one message + every 100,000 rows while generating data for the + <structname>pgbench_accounts</structname> table. + </para> + <para> + With <literal>G</literal> (server-side data generation), + only small queries are sent from the <command>pgbench</command> + client and then data is actually generated in the server. + No significant bandwidth is required for this variant, but + the server will do more work. + Using <literal>G</literal> causes logging not to print any progress + message while generating data. + </para> + <para> + The default initialization behavior uses client-side data + generation (equivalent to <literal>g</literal>). + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>v</literal> (Vacuum)</term> + <listitem> + <para> + Invoke <command>VACUUM</command> on the standard tables. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>p</literal> (create Primary keys)</term> + <listitem> + <para> + Create primary key indexes on the standard tables. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>f</literal> (create Foreign keys)</term> + <listitem> + <para> + Create foreign key constraints between the standard tables. + (Note that this step is not performed by default.) + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F</option> <replaceable>fillfactor</replaceable></term> + <term><option>--fillfactor=</option><replaceable>fillfactor</replaceable></term> + <listitem> + <para> + Create the <structname>pgbench_accounts</structname>, + <structname>pgbench_tellers</structname> and + <structname>pgbench_branches</structname> tables with the given fillfactor. + Default is 100. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-vacuum</option></term> + <listitem> + <para> + Perform no vacuuming during initialization. + (This option suppresses the <literal>v</literal> initialization step, + even if it was specified in <option>-I</option>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Switch logging to quiet mode, producing only one progress message per 5 + seconds. The default logging prints one message each 100,000 rows, which + often outputs many lines per second (especially on good hardware). + </para> + <para> + This setting has no effect if <literal>G</literal> is specified + in <option>-I</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option> <replaceable>scale_factor</replaceable></term> + <term><option>--scale=</option><replaceable>scale_factor</replaceable></term> + <listitem> + <para> + Multiply the number of rows generated by the scale factor. + For example, <literal>-s 100</literal> will create 10,000,000 rows + in the <structname>pgbench_accounts</structname> table. Default is 1. + When the scale is 20,000 or larger, the columns used to + hold account identifiers (<structfield>aid</structfield> columns) + will switch to using larger integers (<type>bigint</type>), + in order to be big enough to hold the range of account + identifiers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--foreign-keys</option></term> + <listitem> + <para> + Create foreign key constraints between the standard tables. + (This option adds the <literal>f</literal> step to the initialization + step sequence, if it is not already present.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--index-tablespace=<replaceable>index_tablespace</replaceable></option></term> + <listitem> + <para> + Create indexes in the specified tablespace, rather than the default + tablespace. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--partition-method=<replaceable>NAME</replaceable></option></term> + <listitem> + <para> + Create a partitioned <literal>pgbench_accounts</literal> table with + <replaceable>NAME</replaceable> method. + Expected values are <literal>range</literal> or <literal>hash</literal>. + This option requires that <option>--partitions</option> is set to non-zero. + If unspecified, default is <literal>range</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--partitions=<replaceable>NUM</replaceable></option></term> + <listitem> + <para> + Create a partitioned <literal>pgbench_accounts</literal> table with + <replaceable>NUM</replaceable> partitions of nearly equal size for + the scaled number of accounts. + Default is <literal>0</literal>, meaning no partitioning. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--tablespace=<replaceable>tablespace</replaceable></option></term> + <listitem> + <para> + Create tables in the specified tablespace, rather than the default + tablespace. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--unlogged-tables</option></term> + <listitem> + <para> + Create all tables as unlogged tables, rather than permanent tables. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect2> + + <refsect2 id="pgbench-run-options"> + <title>Benchmarking Options</title> + + <para> + <application>pgbench</application> accepts the following command-line + benchmarking arguments: + + <variablelist> + <varlistentry> + <term><option>-b</option> <replaceable>scriptname[@weight]</replaceable></term> + <term><option>--builtin</option>=<replaceable>scriptname[@weight]</replaceable></term> + <listitem> + <para> + Add the specified built-in script to the list of scripts to be executed. + Available built-in scripts are: <literal>tpcb-like</literal>, + <literal>simple-update</literal> and <literal>select-only</literal>. + Unambiguous prefixes of built-in names are accepted. + With the special name <literal>list</literal>, show the list of built-in scripts + and exit immediately. + </para> + <para> + Optionally, write an integer weight after <literal>@</literal> to + adjust the probability of selecting this script versus other ones. + The default weight is 1. + See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option> <replaceable>clients</replaceable></term> + <term><option>--client=</option><replaceable>clients</replaceable></term> + <listitem> + <para> + Number of clients simulated, that is, number of concurrent database + sessions. Default is 1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C</option></term> + <term><option>--connect</option></term> + <listitem> + <para> + Establish a new connection for each transaction, rather than + doing it just once per client session. + This is useful to measure the connection overhead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d</option></term> + <term><option>--debug</option></term> + <listitem> + <para> + Print debugging output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D</option> <replaceable>varname</replaceable><literal>=</literal><replaceable>value</replaceable></term> + <term><option>--define=</option><replaceable>varname</replaceable><literal>=</literal><replaceable>value</replaceable></term> + <listitem> + <para> + Define a variable for use by a custom script (see below). + Multiple <option>-D</option> options are allowed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f</option> <replaceable>filename[@weight]</replaceable></term> + <term><option>--file=</option><replaceable>filename[@weight]</replaceable></term> + <listitem> + <para> + Add a transaction script read from <replaceable>filename</replaceable> + to the list of scripts to be executed. + </para> + <para> + Optionally, write an integer weight after <literal>@</literal> to + adjust the probability of selecting this script versus other ones. + The default weight is 1. + (To use a script file name that includes an <literal>@</literal> + character, append a weight so that there is no ambiguity, for + example <literal>filen@me@1</literal>.) + See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j</option> <replaceable>threads</replaceable></term> + <term><option>--jobs=</option><replaceable>threads</replaceable></term> + <listitem> + <para> + Number of worker threads within <application>pgbench</application>. + Using more than one thread can be helpful on multi-CPU machines. + Clients are distributed as evenly as possible among available threads. + Default is 1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <term><option>--log</option></term> + <listitem> + <para> + Write information about each transaction to a log file. + See below for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-L</option> <replaceable>limit</replaceable></term> + <term><option>--latency-limit=</option><replaceable>limit</replaceable></term> + <listitem> + <para> + Transactions that last more than <replaceable>limit</replaceable> milliseconds + are counted and reported separately, as <firstterm>late</firstterm>. + </para> + <para> + When throttling is used (<option>--rate=...</option>), transactions that + lag behind schedule by more than <replaceable>limit</replaceable> ms, and thus + have no hope of meeting the latency limit, are not sent to the server + at all. They are counted and reported separately as + <firstterm>skipped</firstterm>. + </para> + <para> + When the <option>--max-tries</option> option is used, a transaction + which fails due to a serialization anomaly or from a deadlock will not + be retried if the total time of all its tries is greater than + <replaceable>limit</replaceable> ms. To limit only the time of tries + and not their number, use <literal>--max-tries=0</literal>. By + default, the option <option>--max-tries</option> is set to 1 and + transactions with serialization/deadlock errors are not retried. See + <xref linkend="failures-and-retries"/> for more information about + retrying such transactions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-M</option> <replaceable>querymode</replaceable></term> + <term><option>--protocol=</option><replaceable>querymode</replaceable></term> + <listitem> + <para> + Protocol to use for submitting queries to the server: + <itemizedlist> + <listitem> + <para><literal>simple</literal>: use simple query protocol.</para> + </listitem> + <listitem> + <para><literal>extended</literal>: use extended query protocol.</para> + </listitem> + <listitem> + <para><literal>prepared</literal>: use extended query protocol with prepared statements.</para> + </listitem> + </itemizedlist> + + In the <literal>prepared</literal> mode, <application>pgbench</application> + reuses the parse analysis result starting from the second query + iteration, so <application>pgbench</application> runs faster + than in other modes. + </para> + <para> + The default is simple query protocol. (See <xref linkend="protocol"/> + for more information.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-vacuum</option></term> + <listitem> + <para> + Perform no vacuuming before running the test. + This option is <emphasis>necessary</emphasis> + if you are running a custom test scenario that does not include + the standard tables <structname>pgbench_accounts</structname>, + <structname>pgbench_branches</structname>, <structname>pgbench_history</structname>, and + <structname>pgbench_tellers</structname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--skip-some-updates</option></term> + <listitem> + <para> + Run built-in simple-update script. + Shorthand for <option>-b simple-update</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option> <replaceable>sec</replaceable></term> + <term><option>--progress=</option><replaceable>sec</replaceable></term> + <listitem> + <para> + Show progress report every <replaceable>sec</replaceable> seconds. The report + includes the time since the beginning of the run, the TPS since the + last report, and the transaction latency average, standard deviation, + and the number of failed transactions since the last report. Under + throttling (<option>-R</option>), the latency is computed with respect + to the transaction scheduled start time, not the actual transaction + beginning time, thus it also includes the average schedule lag time. + When <option>--max-tries</option> is used to enable transaction retries + after serialization/deadlock errors, the report includes the number of + retried transactions and the sum of all retries. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r</option></term> + <term><option>--report-per-command</option></term> + <listitem> + <para> + Report the following statistics for each command after the benchmark + finishes: the average per-statement latency (execution time from the + perspective of the client), the number of failures, and the number of + retries after serialization or deadlock errors in this command. The + report displays retry statistics only if the + <option>--max-tries</option> option is not equal to 1. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R</option> <replaceable>rate</replaceable></term> + <term><option>--rate=</option><replaceable>rate</replaceable></term> + <listitem> + <para> + Execute transactions targeting the specified rate instead of running + as fast as possible (the default). The rate is given in transactions + per second. If the targeted rate is above the maximum possible rate, + the rate limit won't impact the results. + </para> + <para> + The rate is targeted by starting transactions along a + Poisson-distributed schedule time line. The expected start time + schedule moves forward based on when the client first started, not + when the previous transaction ended. That approach means that when + transactions go past their original scheduled end time, it is + possible for later ones to catch up again. + </para> + <para> + When throttling is active, the transaction latency reported at the + end of the run is calculated from the scheduled start times, so it + includes the time each transaction had to wait for the previous + transaction to finish. The wait time is called the schedule lag time, + and its average and maximum are also reported separately. The + transaction latency with respect to the actual transaction start time, + i.e., the time spent executing the transaction in the database, can be + computed by subtracting the schedule lag time from the reported + latency. + </para> + + <para> + If <option>--latency-limit</option> is used together with <option>--rate</option>, + a transaction can lag behind so much that it is already over the + latency limit when the previous transaction ends, because the latency + is calculated from the scheduled start time. Such transactions are + not sent to the server, but are skipped altogether and counted + separately. + </para> + + <para> + A high schedule lag time is an indication that the system cannot + process transactions at the specified rate, with the chosen number of + clients and threads. When the average transaction execution time is + longer than the scheduled interval between each transaction, each + successive transaction will fall further behind, and the schedule lag + time will keep increasing the longer the test run is. When that + happens, you will have to reduce the specified transaction rate. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option> <replaceable>scale_factor</replaceable></term> + <term><option>--scale=</option><replaceable>scale_factor</replaceable></term> + <listitem> + <para> + Report the specified scale factor in <application>pgbench</application>'s + output. With the built-in tests, this is not necessary; the + correct scale factor will be detected by counting the number of + rows in the <structname>pgbench_branches</structname> table. + However, when testing only custom benchmarks (<option>-f</option> option), + the scale factor will be reported as 1 unless this option is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S</option></term> + <term><option>--select-only</option></term> + <listitem> + <para> + Run built-in select-only script. + Shorthand for <option>-b select-only</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option> <replaceable>transactions</replaceable></term> + <term><option>--transactions=</option><replaceable>transactions</replaceable></term> + <listitem> + <para> + Number of transactions each client runs. Default is 10. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T</option> <replaceable>seconds</replaceable></term> + <term><option>--time=</option><replaceable>seconds</replaceable></term> + <listitem> + <para> + Run the test for this many seconds, rather than a fixed number of + transactions per client. <option>-t</option> and + <option>-T</option> are mutually exclusive. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--vacuum-all</option></term> + <listitem> + <para> + Vacuum all four standard tables before running the test. + With neither <option>-n</option> nor <option>-v</option>, <application>pgbench</application> will vacuum the + <structname>pgbench_tellers</structname> and <structname>pgbench_branches</structname> + tables, and will truncate <structname>pgbench_history</structname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--aggregate-interval=<replaceable>seconds</replaceable></option></term> + <listitem> + <para> + Length of aggregation interval (in seconds). May be used only + with <option>-l</option> option. With this option, the log contains + per-interval summary data, as described below. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--failures-detailed</option></term> + <listitem> + <para> + Report failures in per-transaction and aggregation logs, as well as in + the main and per-script reports, grouped by the following types: + <itemizedlist> + <listitem> + <para>serialization failures;</para> + </listitem> + <listitem> + <para>deadlock failures;</para> + </listitem> + </itemizedlist> + See <xref linkend="failures-and-retries"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--log-prefix=<replaceable>prefix</replaceable></option></term> + <listitem> + <para> + Set the filename prefix for the log files created by + <option>--log</option>. The default is <literal>pgbench_log</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--max-tries=<replaceable>number_of_tries</replaceable></option></term> + <listitem> + <para> + Enable retries for transactions with serialization/deadlock errors and + set the maximum number of these tries. This option can be combined with + the <option>--latency-limit</option> option which limits the total time + of all transaction tries; moreover, you cannot use an unlimited number + of tries (<literal>--max-tries=0</literal>) without + <option>--latency-limit</option> or <option>--time</option>. + The default value is 1 and transactions with serialization/deadlock + errors are not retried. See <xref linkend="failures-and-retries"/> + for more information about retrying such transactions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--progress-timestamp</option></term> + <listitem> + <para> + When showing progress (option <option>-P</option>), use a timestamp + (Unix epoch) instead of the number of seconds since the + beginning of the run. The unit is in seconds, with millisecond + precision after the dot. + This helps compare logs generated by various tools. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--random-seed=</option><replaceable>seed</replaceable></term> + <listitem> + <para> + Set random generator seed. Seeds the system random number generator, + which then produces a sequence of initial generator states, one for + each thread. + Values for <replaceable>seed</replaceable> may be: + <literal>time</literal> (the default, the seed is based on the current time), + <literal>rand</literal> (use a strong random source, failing if none + is available), or an unsigned decimal integer value. + The random generator is invoked explicitly from a pgbench script + (<literal>random...</literal> functions) or implicitly (for instance option + <option>--rate</option> uses it to schedule transactions). + When explicitly set, the value used for seeding is shown on the terminal. + Any value allowed for <replaceable>seed</replaceable> may also be + provided through the environment variable + <literal>PGBENCH_RANDOM_SEED</literal>. + To ensure that the provided seed impacts all possible uses, put this option + first or use the environment variable. + </para> + <para> + Setting the seed explicitly allows to reproduce a <command>pgbench</command> + run exactly, as far as random numbers are concerned. + As the random state is managed per thread, this means the exact same + <command>pgbench</command> run for an identical invocation if there is one + client per thread and there are no external or data dependencies. + From a statistical viewpoint reproducing runs exactly is a bad idea because + it can hide the performance variability or improve performance unduly, + e.g., by hitting the same pages as a previous run. + However, it may also be of great help for debugging, for instance + re-running a tricky case which leads to an error. + Use wisely. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--sampling-rate=<replaceable>rate</replaceable></option></term> + <listitem> + <para> + Sampling rate, used when writing data into the log, to reduce the + amount of log generated. If this option is given, only the specified + fraction of transactions are logged. 1.0 means all transactions will + be logged, 0.05 means only 5% of the transactions will be logged. + </para> + <para> + Remember to take the sampling rate into account when processing the + log file. For example, when computing TPS values, you need to multiply + the numbers accordingly (e.g., with 0.01 sample rate, you'll only get + 1/100 of the actual TPS). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--show-script=</option><replaceable>scriptname</replaceable></term> + <listitem> + <para> + Show the actual code of builtin script <replaceable>scriptname</replaceable> + on stderr, and exit immediately. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--verbose-errors</option></term> + <listitem> + <para> + Print messages about all errors and failures (errors without retrying) + including which limit for retries was exceeded and how far it was + exceeded for the serialization/deadlock failures. (Note that in this + case the output can be significantly increased.). + See <xref linkend="failures-and-retries"/> for more information. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect2> + + <refsect2 id="pgbench-common-options"> + <title>Common Options</title> + + <para> + <application>pgbench</application> also accepts the following common command-line + arguments for connection parameters: + + <variablelist> + + <varlistentry> + <term><option>-h</option> <replaceable>hostname</replaceable></term> + <term><option>--host=</option><replaceable>hostname</replaceable></term> + <listitem> + <para> + The database server's host name + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p</option> <replaceable>port</replaceable></term> + <term><option>--port=</option><replaceable>port</replaceable></term> + <listitem> + <para> + The database server's port number + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U</option> <replaceable>login</replaceable></term> + <term><option>--username=</option><replaceable>login</replaceable></term> + <listitem> + <para> + The user name to connect as + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pgbench</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pgbench</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + </refsect2> + </refsect1> + + <refsect1> + <title>Exit Status</title> + + <para> + A successful run will exit with status 0. Exit status 1 indicates static + problems such as invalid command-line options or internal errors which + are supposed to never occur. Early errors that occur when starting + benchmark such as initial connection failures also exit with status 1. + Errors during the run such as database errors or problems in the script + will result in exit status 2. In the latter case, + <application>pgbench</application> will print partial results. + </para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <refsect2 id="transactions-and-scripts" xreflabel="What Is the "Transaction" Actually Performed in pgbench?"> + <title>What Is the <quote>Transaction</quote> Actually Performed in <application>pgbench</application>?</title> + + <para> + <application>pgbench</application> executes test scripts chosen randomly + from a specified list. + The scripts may include built-in scripts specified with <option>-b</option> + and user-provided scripts specified with <option>-f</option>. + Each script may be given a relative weight specified after an + <literal>@</literal> so as to change its selection probability. + The default weight is <literal>1</literal>. + Scripts with a weight of <literal>0</literal> are ignored. + </para> + + <para> + The default built-in transaction script (also invoked with <option>-b tpcb-like</option>) + issues seven commands per transaction over randomly chosen <literal>aid</literal>, + <literal>tid</literal>, <literal>bid</literal> and <literal>delta</literal>. + The scenario is inspired by the TPC-B benchmark, but is not actually TPC-B, + hence the name. + </para> + + <orderedlist> + <listitem><para><literal>BEGIN;</literal></para></listitem> + <listitem><para><literal>UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;</literal></para></listitem> + <listitem><para><literal>SELECT abalance FROM pgbench_accounts WHERE aid = :aid;</literal></para></listitem> + <listitem><para><literal>UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;</literal></para></listitem> + <listitem><para><literal>UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;</literal></para></listitem> + <listitem><para><literal>INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);</literal></para></listitem> + <listitem><para><literal>END;</literal></para></listitem> + </orderedlist> + + <para> + If you select the <literal>simple-update</literal> built-in (also <option>-N</option>), + steps 4 and 5 aren't included in the transaction. + This will avoid update contention on these tables, but + it makes the test case even less like TPC-B. + </para> + + <para> + If you select the <literal>select-only</literal> built-in (also <option>-S</option>), + only the <command>SELECT</command> is issued. + </para> + </refsect2> + + <refsect2> + <title>Custom Scripts</title> + + <para> + <application>pgbench</application> has support for running custom + benchmark scenarios by replacing the default transaction script + (described above) with a transaction script read from a file + (<option>-f</option> option). In this case a <quote>transaction</quote> + counts as one execution of a script file. + </para> + + <para> + A script file contains one or more SQL commands terminated by + semicolons. Empty lines and lines beginning with + <literal>--</literal> are ignored. Script files can also contain + <quote>meta commands</quote>, which are interpreted by <application>pgbench</application> + itself, as described below. + </para> + + <note> + <para> + Before <productname>PostgreSQL</productname> 9.6, SQL commands in script files + were terminated by newlines, and so they could not be continued across + lines. Now a semicolon is <emphasis>required</emphasis> to separate consecutive + SQL commands (though an SQL command does not need one if it is followed + by a meta command). If you need to create a script file that works with + both old and new versions of <application>pgbench</application>, be sure to write + each SQL command on a single line ending with a semicolon. + </para> + <para> + It is assumed that pgbench scripts do not contain incomplete blocks of SQL + transactions. If at runtime the client reaches the end of the script without + completing the last transaction block, it will be aborted. + </para> + </note> + + <para> + There is a simple variable-substitution facility for script files. + Variable names must consist of letters (including non-Latin letters), + digits, and underscores, with the first character not being a digit. + Variables can be set by the command-line <option>-D</option> option, + explained above, or by the meta commands explained below. + In addition to any variables preset by <option>-D</option> command-line options, + there are a few variables that are preset automatically, listed in + <xref linkend="pgbench-automatic-variables"/>. A value specified for these + variables using <option>-D</option> takes precedence over the automatic presets. + Once set, a variable's + value can be inserted into an SQL command by writing + <literal>:</literal><replaceable>variablename</replaceable>. When running more than + one client session, each session has its own set of variables. + <application>pgbench</application> supports up to 255 variable uses in one + statement. + </para> + + <table id="pgbench-automatic-variables"> + <title>pgbench Automatic Variables</title> + <tgroup cols="2"> + <colspec colname="col1" colwidth="1*"/> + <colspec colname="col2" colwidth="2*"/> + <thead> + <row> + <entry>Variable</entry> + <entry>Description</entry> + </row> + </thead> + + <tbody> + <row> + <entry> <literal>client_id</literal> </entry> + <entry>unique number identifying the client session (starts from zero)</entry> + </row> + + <row> + <entry> <literal>default_seed</literal> </entry> + <entry>seed used in hash and pseudorandom permutation functions by default</entry> + </row> + + <row> + <entry> <literal>random_seed</literal> </entry> + <entry>random generator seed (unless overwritten with <option>-D</option>)</entry> + </row> + + <row> + <entry> <literal>scale</literal> </entry> + <entry>current scale factor</entry> + </row> + </tbody> + </tgroup> + </table> + + <para> + Script file meta commands begin with a backslash (<literal>\</literal>) and + normally extend to the end of the line, although they can be continued + to additional lines by writing backslash-return. + Arguments to a meta command are separated by white space. + These meta commands are supported: + </para> + + <variablelist> + <varlistentry id='pgbench-metacommand-gset'> + <term> + <literal>\gset [<replaceable>prefix</replaceable>]</literal> + <literal>\aset [<replaceable>prefix</replaceable>]</literal> + </term> + + <listitem> + <para> + These commands may be used to end SQL queries, taking the place of the + terminating semicolon (<literal>;</literal>). + </para> + + <para> + When the <literal>\gset</literal> command is used, the preceding SQL query is + expected to return one row, the columns of which are stored into variables + named after column names, and prefixed with <replaceable>prefix</replaceable> + if provided. + </para> + + <para> + When the <literal>\aset</literal> command is used, all combined SQL queries + (separated by <literal>\;</literal>) have their columns stored into variables + named after column names, and prefixed with <replaceable>prefix</replaceable> + if provided. If a query returns no row, no assignment is made and the variable + can be tested for existence to detect this. If a query returns more than one + row, the last value is kept. + </para> + + <para> + <literal>\gset</literal> and <literal>\aset</literal> cannot be used in + pipeline mode, since the query results are not yet available by the time + the commands would need them. + </para> + + <para> + The following example puts the final account balance from the first query + into variable <replaceable>abalance</replaceable>, and fills variables + <replaceable>p_two</replaceable> and <replaceable>p_three</replaceable> + with integers from the third query. + The result of the second query is discarded. + The result of the two last combined queries are stored in variables + <replaceable>four</replaceable> and <replaceable>five</replaceable>. +<programlisting> +UPDATE pgbench_accounts + SET abalance = abalance + :delta + WHERE aid = :aid + RETURNING abalance \gset +-- compound of two queries +SELECT 1 \; +SELECT 2 AS two, 3 AS three \gset p_ +SELECT 4 AS four \; SELECT 5 AS five \aset +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\if</literal> <replaceable class="parameter">expression</replaceable></term> + <term><literal>\elif</literal> <replaceable class="parameter">expression</replaceable></term> + <term><literal>\else</literal></term> + <term><literal>\endif</literal></term> + <listitem> + <para> + This group of commands implements nestable conditional blocks, + similarly to <literal>psql</literal>'s <xref linkend="psql-metacommand-if"/>. + Conditional expressions are identical to those with <literal>\set</literal>, + with non-zero values interpreted as true. + </para> + </listitem> + </varlistentry> + + <varlistentry id='pgbench-metacommand-set'> + <term> + <literal>\set <replaceable>varname</replaceable> <replaceable>expression</replaceable></literal> + </term> + + <listitem> + <para> + Sets variable <replaceable>varname</replaceable> to a value calculated + from <replaceable>expression</replaceable>. + The expression may contain the <literal>NULL</literal> constant, + Boolean constants <literal>TRUE</literal> and <literal>FALSE</literal>, + integer constants such as <literal>5432</literal>, + double constants such as <literal>3.14159</literal>, + references to variables <literal>:</literal><replaceable>variablename</replaceable>, + <link linkend="pgbench-builtin-operators">operators</link> + with their usual SQL precedence and associativity, + <link linkend="pgbench-builtin-functions">function calls</link>, + SQL <link linkend="functions-case"><token>CASE</token> generic conditional + expressions</link> and parentheses. + </para> + + <para> + Functions and most operators return <literal>NULL</literal> on + <literal>NULL</literal> input. + </para> + + <para> + For conditional purposes, non zero numerical values are + <literal>TRUE</literal>, zero numerical values and <literal>NULL</literal> + are <literal>FALSE</literal>. + </para> + + <para> + Too large or small integer and double constants, as well as + integer arithmetic operators (<literal>+</literal>, + <literal>-</literal>, <literal>*</literal> and <literal>/</literal>) + raise errors on overflows. + </para> + + <para> + When no final <token>ELSE</token> clause is provided to a + <token>CASE</token>, the default value is <literal>NULL</literal>. + </para> + + <para> + Examples: +<programlisting> +\set ntellers 10 * :scale +\set aid (1021 * random(1, 100000 * :scale)) % \ + (100000 * :scale) + 1 +\set divx CASE WHEN :x <> 0 THEN :y/:x ELSE NULL END +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\sleep <replaceable>number</replaceable> [ us | ms | s ]</literal> + </term> + + <listitem> + <para> + Causes script execution to sleep for the specified duration in + microseconds (<literal>us</literal>), milliseconds (<literal>ms</literal>) or seconds + (<literal>s</literal>). If the unit is omitted then seconds are the default. + <replaceable>number</replaceable> can be either an integer constant or a + <literal>:</literal><replaceable>variablename</replaceable> reference to a variable + having an integer value. + </para> + + <para> + Example: +<programlisting> +\sleep 10 ms +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\setshell <replaceable>varname</replaceable> <replaceable>command</replaceable> [ <replaceable>argument</replaceable> ... ]</literal> + </term> + + <listitem> + <para> + Sets variable <replaceable>varname</replaceable> to the result of the shell command + <replaceable>command</replaceable> with the given <replaceable>argument</replaceable>(s). + The command must return an integer value through its standard output. + </para> + + <para> + <replaceable>command</replaceable> and each <replaceable>argument</replaceable> can be either + a text constant or a <literal>:</literal><replaceable>variablename</replaceable> reference + to a variable. If you want to use an <replaceable>argument</replaceable> starting + with a colon, write an additional colon at the beginning of + <replaceable>argument</replaceable>. + </para> + + <para> + Example: +<programlisting> +\setshell variable_to_be_assigned command literal_argument :variable ::literal_starting_with_colon +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\shell <replaceable>command</replaceable> [ <replaceable>argument</replaceable> ... ]</literal> + </term> + + <listitem> + <para> + Same as <literal>\setshell</literal>, but the result of the command + is discarded. + </para> + + <para> + Example: +<programlisting> +\shell command literal_argument :variable ::literal_starting_with_colon +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry id='pgbench-metacommand-pipeline'> + <term><literal>\startpipeline</literal></term> + <term><literal>\endpipeline</literal></term> + + <listitem> + <para> + These commands delimit the start and end of a pipeline of SQL + statements. In pipeline mode, statements are sent to the server + without waiting for the results of previous statements. See + <xref linkend="libpq-pipeline-mode"/> for more details. + Pipeline mode requires the use of extended query protocol. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect2> + + <refsect2 id="pgbench-builtin-operators"> + <title>Built-in Operators</title> + + <para> + The arithmetic, bitwise, comparison and logical operators listed in + <xref linkend="pgbench-operators"/> are built into <application>pgbench</application> + and may be used in expressions appearing in + <link linkend="pgbench-metacommand-set"><literal>\set</literal></link>. + The operators are listed in increasing precedence order. + Except as noted, operators taking two numeric inputs will produce + a double value if either input is double, otherwise they produce + an integer result. + </para> + + <table id="pgbench-operators"> + <title>pgbench Operators</title> + <tgroup cols="1"> + <thead> + <row> + <entry role="func_table_entry"><para role="func_signature"> + Operator + </para> + <para> + Description + </para> + <para> + Example(s) + </para></entry> + </row> + </thead> + + <tbody> + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>boolean</replaceable> <literal>OR</literal> <replaceable>boolean</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Logical OR + </para> + <para> + <literal>5 or 0</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>boolean</replaceable> <literal>AND</literal> <replaceable>boolean</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Logical AND + </para> + <para> + <literal>3 and 0</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <literal>NOT</literal> <replaceable>boolean</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Logical NOT + </para> + <para> + <literal>not false</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>boolean</replaceable> <literal>IS [NOT] (NULL|TRUE|FALSE)</literal> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Boolean value tests + </para> + <para> + <literal>1 is null</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>value</replaceable> <literal>ISNULL|NOTNULL</literal> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Nullness tests + </para> + <para> + <literal>1 notnull</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>=</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Equal + </para> + <para> + <literal>5 = 4</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal><></literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Not equal + </para> + <para> + <literal>5 <> 4</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>!=</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Not equal + </para> + <para> + <literal>5 != 5</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal><</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Less than + </para> + <para> + <literal>5 < 4</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal><=</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Less than or equal to + </para> + <para> + <literal>5 <= 4</literal> + <returnvalue>FALSE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>></literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Greater than + </para> + <para> + <literal>5 > 4</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>>=</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>boolean</replaceable></returnvalue> + </para> + <para> + Greater than or equal to + </para> + <para> + <literal>5 >= 4</literal> + <returnvalue>TRUE</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal>|</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise OR + </para> + <para> + <literal>1 | 2</literal> + <returnvalue>3</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal>#</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise XOR + </para> + <para> + <literal>1 # 3</literal> + <returnvalue>2</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal>&</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise AND + </para> + <para> + <literal>1 & 3</literal> + <returnvalue>1</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <literal>~</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise NOT + </para> + <para> + <literal>~ 1</literal> + <returnvalue>-2</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal><<</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise shift left + </para> + <para> + <literal>1 << 2</literal> + <returnvalue>4</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal>>></literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Bitwise shift right + </para> + <para> + <literal>8 >> 2</literal> + <returnvalue>2</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>+</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>number</replaceable></returnvalue> + </para> + <para> + Addition + </para> + <para> + <literal>5 + 4</literal> + <returnvalue>9</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>-</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>number</replaceable></returnvalue> + </para> + <para> + Subtraction + </para> + <para> + <literal>3 - 2.0</literal> + <returnvalue>1.0</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>*</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>number</replaceable></returnvalue> + </para> + <para> + Multiplication + </para> + <para> + <literal>5 * 4</literal> + <returnvalue>20</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>number</replaceable> <literal>/</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>number</replaceable></returnvalue> + </para> + <para> + Division (truncates the result towards zero if both inputs are integers) + </para> + <para> + <literal>5 / 3</literal> + <returnvalue>1</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <replaceable>integer</replaceable> <literal>%</literal> <replaceable>integer</replaceable> + <returnvalue><replaceable>integer</replaceable></returnvalue> + </para> + <para> + Modulo (remainder) + </para> + <para> + <literal>3 % 2</literal> + <returnvalue>1</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <literal>-</literal> <replaceable>number</replaceable> + <returnvalue><replaceable>number</replaceable></returnvalue> + </para> + <para> + Negation + </para> + <para> + <literal>- 2.0</literal> + <returnvalue>-2.0</returnvalue> + </para></entry> + </row> + </tbody> + </tgroup> + </table> + </refsect2> + + <refsect2 id="pgbench-builtin-functions"> + <title>Built-In Functions</title> + + <para> + The functions listed in <xref linkend="pgbench-functions"/> are built + into <application>pgbench</application> and may be used in expressions appearing in + <link linkend="pgbench-metacommand-set"><literal>\set</literal></link>. + </para> + + <!-- list pgbench functions in alphabetical order --> + <table id="pgbench-functions"> + <title>pgbench Functions</title> + <tgroup cols="1"> + <thead> + <row> + <entry role="func_table_entry"><para role="func_signature"> + Function + </para> + <para> + Description + </para> + <para> + Example(s) + </para></entry> + </row> + </thead> + + <tbody> + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>abs</function> ( <replaceable>number</replaceable> ) + <returnvalue></returnvalue> same type as input + </para> + <para> + Absolute value + </para> + <para> + <literal>abs(-17)</literal> + <returnvalue>17</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>debug</function> ( <replaceable>number</replaceable> ) + <returnvalue></returnvalue> same type as input + </para> + <para> + Prints the argument to <systemitem>stderr</systemitem>, + and returns the argument. + </para> + <para> + <literal>debug(5432.1)</literal> + <returnvalue>5432.1</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>double</function> ( <replaceable>number</replaceable> ) + <returnvalue>double</returnvalue> + </para> + <para> + Casts to double. + </para> + <para> + <literal>double(5432)</literal> + <returnvalue>5432.0</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>exp</function> ( <replaceable>number</replaceable> ) + <returnvalue>double</returnvalue> + </para> + <para> + Exponential (<literal>e</literal> raised to the given power) + </para> + <para> + <literal>exp(1.0)</literal> + <returnvalue>2.718281828459045</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>greatest</function> ( <replaceable>number</replaceable> <optional>, <literal>...</literal> </optional> ) + <returnvalue></returnvalue> <type>double</type> if any argument is double, else <type>integer</type> + </para> + <para> + Selects the largest value among the arguments. + </para> + <para> + <literal>greatest(5, 4, 3, 2)</literal> + <returnvalue>5</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>hash</function> ( <parameter>value</parameter> <optional>, <parameter>seed</parameter> </optional> ) + <returnvalue>integer</returnvalue> + </para> + <para> + This is an alias for <function>hash_murmur2</function>. + </para> + <para> + <literal>hash(10, 5432)</literal> + <returnvalue>-5817877081768721676</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>hash_fnv1a</function> ( <parameter>value</parameter> <optional>, <parameter>seed</parameter> </optional> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes <ulink url="https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function">FNV-1a hash</ulink>. + </para> + <para> + <literal>hash_fnv1a(10, 5432)</literal> + <returnvalue>-7793829335365542153</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>hash_murmur2</function> ( <parameter>value</parameter> <optional>, <parameter>seed</parameter> </optional> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes <ulink url="https://en.wikipedia.org/wiki/MurmurHash">MurmurHash2 hash</ulink>. + </para> + <para> + <literal>hash_murmur2(10, 5432)</literal> + <returnvalue>-5817877081768721676</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>int</function> ( <replaceable>number</replaceable> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Casts to integer. + </para> + <para> + <literal>int(5.4 + 3.8)</literal> + <returnvalue>9</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>least</function> ( <replaceable>number</replaceable> <optional>, <literal>...</literal> </optional> ) + <returnvalue></returnvalue> <type>double</type> if any argument is double, else <type>integer</type> + </para> + <para> + Selects the smallest value among the arguments. + </para> + <para> + <literal>least(5, 4, 3, 2.1)</literal> + <returnvalue>2.1</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>ln</function> ( <replaceable>number</replaceable> ) + <returnvalue>double</returnvalue> + </para> + <para> + Natural logarithm + </para> + <para> + <literal>ln(2.718281828459045)</literal> + <returnvalue>1.0</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> +<function>mod</function> ( <replaceable>integer</replaceable>, <replaceable>integer</replaceable> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Modulo (remainder) + </para> + <para> + <literal>mod(54, 32)</literal> + <returnvalue>22</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>permute</function> ( <parameter>i</parameter>, <parameter>size</parameter> [, <parameter>seed</parameter> ] ) + <returnvalue>integer</returnvalue> + </para> + <para> + Permuted value of <parameter>i</parameter>, in the range + <literal>[0, size)</literal>. This is the new position of + <parameter>i</parameter> (modulo <parameter>size</parameter>) in a + pseudorandom permutation of the integers <literal>0...size-1</literal>, + parameterized by <parameter>seed</parameter>, see below. + </para> + <para> + <literal>permute(0, 4)</literal> + <returnvalue>an integer between 0 and 3</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>pi</function> () + <returnvalue>double</returnvalue> + </para> + <para> + Approximate value of <phrase role="symbol_font">π</phrase> + </para> + <para> + <literal>pi()</literal> + <returnvalue>3.14159265358979323846</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>pow</function> ( <parameter>x</parameter>, <parameter>y</parameter> ) + <returnvalue>double</returnvalue> + </para> + <para role="func_signature"> + <function>power</function> ( <parameter>x</parameter>, <parameter>y</parameter> ) + <returnvalue>double</returnvalue> + </para> + <para> + <parameter>x</parameter> raised to the power of <parameter>y</parameter> + </para> + <para> + <literal>pow(2.0, 10)</literal> + <returnvalue>1024.0</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>random</function> ( <parameter>lb</parameter>, <parameter>ub</parameter> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes a uniformly-distributed random integer in <literal>[lb, + ub]</literal>. + </para> + <para> + <literal>random(1, 10)</literal> + <returnvalue>an integer between 1 and 10</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>random_exponential</function> ( <parameter>lb</parameter>, <parameter>ub</parameter>, <parameter>parameter</parameter> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes an exponentially-distributed random integer in <literal>[lb, + ub]</literal>, see below. + </para> + <para> + <literal>random_exponential(1, 10, 3.0)</literal> + <returnvalue>an integer between 1 and 10</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>random_gaussian</function> ( <parameter>lb</parameter>, <parameter>ub</parameter>, <parameter>parameter</parameter> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes a Gaussian-distributed random integer in <literal>[lb, + ub]</literal>, see below. + </para> + <para> + <literal>random_gaussian(1, 10, 2.5)</literal> + <returnvalue>an integer between 1 and 10</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>random_zipfian</function> ( <parameter>lb</parameter>, <parameter>ub</parameter>, <parameter>parameter</parameter> ) + <returnvalue>integer</returnvalue> + </para> + <para> + Computes a Zipfian-distributed random integer in <literal>[lb, + ub]</literal>, see below. + </para> + <para> + <literal>random_zipfian(1, 10, 1.5)</literal> + <returnvalue>an integer between 1 and 10</returnvalue> + </para></entry> + </row> + + <row> + <entry role="func_table_entry"><para role="func_signature"> + <function>sqrt</function> ( <replaceable>number</replaceable> ) + <returnvalue>double</returnvalue> + </para> + <para> + Square root + </para> + <para> + <literal>sqrt(2.0)</literal> + <returnvalue>1.414213562</returnvalue> + </para></entry> + </row> + </tbody> + </tgroup> + </table> + + <para> + The <literal>random</literal> function generates values using a uniform + distribution, that is all the values are drawn within the specified + range with equal probability. The <literal>random_exponential</literal>, + <literal>random_gaussian</literal> and <literal>random_zipfian</literal> + functions require an additional double parameter which determines the precise + shape of the distribution. + </para> + + <itemizedlist> + <listitem> + <para> + For an exponential distribution, <replaceable>parameter</replaceable> + controls the distribution by truncating a quickly-decreasing + exponential distribution at <replaceable>parameter</replaceable>, and then + projecting onto integers between the bounds. + To be precise, with +<literallayout> +f(x) = exp(-parameter * (x - min) / (max - min + 1)) / (1 - exp(-parameter)) +</literallayout> + Then value <replaceable>i</replaceable> between <replaceable>min</replaceable> and + <replaceable>max</replaceable> inclusive is drawn with probability: + <literal>f(i) - f(i + 1)</literal>. + </para> + + <para> + Intuitively, the larger the <replaceable>parameter</replaceable>, the more + frequently values close to <replaceable>min</replaceable> are accessed, and the + less frequently values close to <replaceable>max</replaceable> are accessed. + The closer to 0 <replaceable>parameter</replaceable> is, the flatter (more + uniform) the access distribution. + A crude approximation of the distribution is that the most frequent 1% + values in the range, close to <replaceable>min</replaceable>, are drawn + <replaceable>parameter</replaceable>% of the time. + The <replaceable>parameter</replaceable> value must be strictly positive. + </para> + </listitem> + + <listitem> + <para> + For a Gaussian distribution, the interval is mapped onto a standard + normal distribution (the classical bell-shaped Gaussian curve) truncated + at <literal>-parameter</literal> on the left and <literal>+parameter</literal> + on the right. + Values in the middle of the interval are more likely to be drawn. + To be precise, if <literal>PHI(x)</literal> is the cumulative distribution + function of the standard normal distribution, with mean <literal>mu</literal> + defined as <literal>(max + min) / 2.0</literal>, with +<literallayout> +f(x) = PHI(2.0 * parameter * (x - mu) / (max - min + 1)) / + (2.0 * PHI(parameter) - 1) +</literallayout> + then value <replaceable>i</replaceable> between <replaceable>min</replaceable> and + <replaceable>max</replaceable> inclusive is drawn with probability: + <literal>f(i + 0.5) - f(i - 0.5)</literal>. + Intuitively, the larger the <replaceable>parameter</replaceable>, the more + frequently values close to the middle of the interval are drawn, and the + less frequently values close to the <replaceable>min</replaceable> and + <replaceable>max</replaceable> bounds. About 67% of values are drawn from the + middle <literal>1.0 / parameter</literal>, that is a relative + <literal>0.5 / parameter</literal> around the mean, and 95% in the middle + <literal>2.0 / parameter</literal>, that is a relative + <literal>1.0 / parameter</literal> around the mean; for instance, if + <replaceable>parameter</replaceable> is 4.0, 67% of values are drawn from the + middle quarter (1.0 / 4.0) of the interval (i.e., from + <literal>3.0 / 8.0</literal> to <literal>5.0 / 8.0</literal>) and 95% from + the middle half (<literal>2.0 / 4.0</literal>) of the interval (second and third + quartiles). The minimum allowed <replaceable>parameter</replaceable> + value is 2.0. + </para> + </listitem> + <listitem> + <para> + <literal>random_zipfian</literal> generates a bounded Zipfian + distribution. + <replaceable>parameter</replaceable> defines how skewed the distribution + is. The larger the <replaceable>parameter</replaceable>, the more + frequently values closer to the beginning of the interval are drawn. + The distribution is such that, assuming the range starts from 1, + the ratio of the probability of drawing <replaceable>k</replaceable> + versus drawing <replaceable>k+1</replaceable> is + <literal>((<replaceable>k</replaceable>+1)/<replaceable>k</replaceable>)**<replaceable>parameter</replaceable></literal>. + For example, <literal>random_zipfian(1, ..., 2.5)</literal> produces + the value <literal>1</literal> about <literal>(2/1)**2.5 = + 5.66</literal> times more frequently than <literal>2</literal>, which + itself is produced <literal>(3/2)**2.5 = 2.76</literal> times more + frequently than <literal>3</literal>, and so on. + </para> + <para> + <application>pgbench</application>'s implementation is based on + "Non-Uniform Random Variate Generation", Luc Devroye, p. 550-551, + Springer 1986. Due to limitations of that algorithm, + the <replaceable>parameter</replaceable> value is restricted to + the range [1.001, 1000]. + </para> + </listitem> + </itemizedlist> + + <note> + <para> + When designing a benchmark which selects rows non-uniformly, be aware + that the rows chosen may be correlated with other data such as IDs from + a sequence or the physical row ordering, which may skew performance + measurements. + </para> + <para> + To avoid this, you may wish to use the <function>permute</function> + function, or some other additional step with similar effect, to shuffle + the selected rows and remove such correlations. + </para> + </note> + + <para> + Hash functions <literal>hash</literal>, <literal>hash_murmur2</literal> and + <literal>hash_fnv1a</literal> accept an input value and an optional seed parameter. + In case the seed isn't provided the value of <literal>:default_seed</literal> + is used, which is initialized randomly unless set by the command-line + <literal>-D</literal> option. + </para> + + <para> + <literal>permute</literal> accepts an input value, a size, and an optional + seed parameter. It generates a pseudorandom permutation of integers in + the range <literal>[0, size)</literal>, and returns the index of the input + value in the permuted values. The permutation chosen is parameterized by + the seed, which defaults to <literal>:default_seed</literal>, if not + specified. Unlike the hash functions, <literal>permute</literal> ensures + that there are no collisions or holes in the output values. Input values + outside the interval are interpreted modulo the size. The function raises + an error if the size is not positive. <function>permute</function> can be + used to scatter the distribution of non-uniform random functions such as + <literal>random_zipfian</literal> or <literal>random_exponential</literal> + so that values drawn more often are not trivially correlated. For + instance, the following <application>pgbench</application> script + simulates a possible real world workload typical for social media and + blogging platforms where a few accounts generate excessive load: + +<programlisting> +\set size 1000000 +\set r random_zipfian(1, :size, 1.07) +\set k 1 + permute(:r, :size) +</programlisting> + + In some cases several distinct distributions are needed which don't correlate + with each other and this is when the optional seed parameter comes in handy: + +<programlisting> +\set k1 1 + permute(:r, :size, :default_seed + 123) +\set k2 1 + permute(:r, :size, :default_seed + 321) +</programlisting> + + A similar behavior can also be approximated with <function>hash</function>: + +<programlisting> +\set size 1000000 +\set r random_zipfian(1, 100 * :size, 1.07) +\set k 1 + abs(hash(:r)) % :size +</programlisting> + + However, since <function>hash</function> generates collisions, some values + will not be reachable and others will be more frequent than expected from + the original distribution. + </para> + + <para> + As an example, the full definition of the built-in TPC-B-like + transaction is: + +<programlisting> +\set aid random(1, 100000 * :scale) +\set bid random(1, 1 * :scale) +\set tid random(1, 10 * :scale) +\set delta random(-5000, 5000) +BEGIN; +UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid; +SELECT abalance FROM pgbench_accounts WHERE aid = :aid; +UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid; +UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid; +INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP); +END; +</programlisting> + + This script allows each iteration of the transaction to reference + different, randomly-chosen rows. (This example also shows why it's + important for each client session to have its own variables — + otherwise they'd not be independently touching different rows.) + </para> + + </refsect2> + + <refsect2> + <title>Per-Transaction Logging</title> + + <para> + With the <option>-l</option> option (but without + the <option>--aggregate-interval</option> option), + <application>pgbench</application> writes information about each transaction + to a log file. The log file will be named + <filename><replaceable>prefix</replaceable>.<replaceable>nnn</replaceable></filename>, + where <replaceable>prefix</replaceable> defaults to <literal>pgbench_log</literal>, and + <replaceable>nnn</replaceable> is the PID of the + <application>pgbench</application> process. + The prefix can be changed by using the <option>--log-prefix</option> option. + If the <option>-j</option> option is 2 or higher, so that there are multiple + worker threads, each will have its own log file. The first worker will + use the same name for its log file as in the standard single worker case. + The additional log files for the other workers will be named + <filename><replaceable>prefix</replaceable>.<replaceable>nnn</replaceable>.<replaceable>mmm</replaceable></filename>, + where <replaceable>mmm</replaceable> is a sequential number for each worker starting + with 1. + </para> + + <para> + Each line in a log file describes one transaction. + It contains the following space-separated fields: + + <variablelist> + <varlistentry> + <term><replaceable>client_id</replaceable></term> + <listitem> + <para> + identifies the client session that ran the transaction + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>transaction_no</replaceable></term> + <listitem> + <para> + counts how many transactions have been run by that session + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>time</replaceable></term> + <listitem> + <para> + transaction's elapsed time, in microseconds + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>script_no</replaceable></term> + <listitem> + <para> + identifies the script file that was used for the transaction + (useful when multiple scripts are specified + with <option>-f</option> or <option>-b</option>) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>time_epoch</replaceable></term> + <listitem> + <para> + transaction's completion time, as a Unix-epoch time stamp + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>time_us</replaceable></term> + <listitem> + <para> + fractional-second part of transaction's completion time, in + microseconds + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>schedule_lag</replaceable></term> + <listitem> + <para> + transaction start delay, that is the difference between the + transaction's scheduled start time and the time it actually + started, in microseconds + (present only if <option>--rate</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>retries</replaceable></term> + <listitem> + <para> + count of retries after serialization or deadlock errors during the + transaction + (present only if <option>--max-tries</option> is not equal to one) + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + When both <option>--rate</option> and <option>--latency-limit</option> are used, + the <replaceable>time</replaceable> for a skipped transaction will be reported as + <literal>skipped</literal>. + If the transaction ends with a failure, its <replaceable>time</replaceable> + will be reported as <literal>failed</literal>. If you use the + <option>--failures-detailed</option> option, the + <replaceable>time</replaceable> of the failed transaction will be reported as + <literal>serialization</literal> or + <literal>deadlock</literal> depending on the type of failure (see + <xref linkend="failures-and-retries"/> for more information). + </para> + + <para> + Here is a snippet of a log file generated in a single-client run: +<screen> +0 199 2241 0 1175850568 995598 +0 200 2465 0 1175850568 998079 +0 201 2513 0 1175850569 608 +0 202 2038 0 1175850569 2663 +</screen> + + Another example with <literal>--rate=100</literal> + and <literal>--latency-limit=5</literal> (note the additional + <replaceable>schedule_lag</replaceable> column): +<screen> +0 81 4621 0 1412881037 912698 3005 +0 82 6173 0 1412881037 914578 4304 +0 83 skipped 0 1412881037 914578 5217 +0 83 skipped 0 1412881037 914578 5099 +0 83 4722 0 1412881037 916203 3108 +0 84 4142 0 1412881037 918023 2333 +0 85 2465 0 1412881037 919759 740 +</screen> + In this example, transaction 82 was late, because its latency (6.173 ms) was + over the 5 ms limit. The next two transactions were skipped, because they + were already late before they were even started. + </para> + + <para> + The following example shows a snippet of a log file with failures and + retries, with the maximum number of tries set to 10 (note the additional + <replaceable>retries</replaceable> column): +<screen> +3 0 47423 0 1499414498 34501 3 +3 1 8333 0 1499414498 42848 0 +3 2 8358 0 1499414498 51219 0 +4 0 72345 0 1499414498 59433 6 +1 3 41718 0 1499414498 67879 4 +1 4 8416 0 1499414498 76311 0 +3 3 33235 0 1499414498 84469 3 +0 0 failed 0 1499414498 84905 9 +2 0 failed 0 1499414498 86248 9 +3 4 8307 0 1499414498 92788 0 +</screen> + </para> + + <para> + If the <option>--failures-detailed</option> option is used, the type of + failure is reported in the <replaceable>time</replaceable> like this: +<screen> +3 0 47423 0 1499414498 34501 3 +3 1 8333 0 1499414498 42848 0 +3 2 8358 0 1499414498 51219 0 +4 0 72345 0 1499414498 59433 6 +1 3 41718 0 1499414498 67879 4 +1 4 8416 0 1499414498 76311 0 +3 3 33235 0 1499414498 84469 3 +0 0 serialization 0 1499414498 84905 9 +2 0 serialization 0 1499414498 86248 9 +3 4 8307 0 1499414498 92788 0 +</screen> + </para> + + <para> + When running a long test on hardware that can handle a lot of transactions, + the log files can become very large. The <option>--sampling-rate</option> option + can be used to log only a random sample of transactions. + </para> + </refsect2> + + <refsect2> + <title>Aggregated Logging</title> + + <para> + With the <option>--aggregate-interval</option> option, a different + format is used for the log files. Each log line describes one + aggregation interval. It contains the following space-separated + fields: + + <variablelist> + <varlistentry> + <term><replaceable>interval_start</replaceable></term> + <listitem> + <para> + start time of the interval, as a Unix-epoch time stamp + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>num_transactions</replaceable></term> + <listitem> + <para> + number of transactions within the interval + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>sum_latency</replaceable></term> + <listitem> + <para> + sum of transaction latencies + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>sum_latency_2</replaceable></term> + <listitem> + <para> + sum of squares of transaction latencies + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>min_latency</replaceable></term> + <listitem> + <para> + minimum transaction latency + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>max_latency</replaceable></term> + <listitem> + <para> + maximum transaction latency + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>sum_lag</replaceable></term> + <listitem> + <para> + sum of transaction start delays + (zero unless <option>--rate</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>sum_lag_2</replaceable></term> + <listitem> + <para> + sum of squares of transaction start delays + (zero unless <option>--rate</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>min_lag</replaceable></term> + <listitem> + <para> + minimum transaction start delay + (zero unless <option>--rate</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>max_lag</replaceable></term> + <listitem> + <para> + maximum transaction start delay + (zero unless <option>--rate</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>skipped</replaceable></term> + <listitem> + <para> + number of transactions skipped because they would have started too late + (zero unless <option>--rate</option> + and <option>--latency-limit</option> are specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>retried</replaceable></term> + <listitem> + <para> + number of retried transactions + (zero unless <option>--max-tries</option> is not equal to one) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>retries</replaceable></term> + <listitem> + <para> + number of retries after serialization or deadlock errors + (zero unless <option>--max-tries</option> is not equal to one) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>serialization_failures</replaceable></term> + <listitem> + <para> + number of transactions that got a serialization error and were not + retried afterwards + (zero unless <option>--failures-detailed</option> is specified) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable>deadlock_failures</replaceable></term> + <listitem> + <para> + number of transactions that got a deadlock error and were not + retried afterwards + (zero unless <option>--failures-detailed</option> is specified) + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Here is some example output generated with these options: +<screen> +<userinput>pgbench --aggregate-interval=10 --time=20 --client=10 --log --rate=1000 --latency-limit=10 --failures-detailed --max-tries=10 test</userinput> + +1650260552 5178 26171317 177284491527 1136 44462 2647617 7321113867 0 9866 64 7564 28340 4148 0 +1650260562 4808 25573984 220121792172 1171 62083 3037380 9666800914 0 9998 598 7392 26621 4527 0 +</screen> + </para> + + <para> + Notice that while the plain (unaggregated) log format shows which script + was used for each transaction, the aggregated format does not. Therefore if + you need per-script data, you need to aggregate the data on your own. + </para> + + </refsect2> + + <refsect2> + <title>Per-Statement Report</title> + + <para> + With the <option>-r</option> option, <application>pgbench</application> + collects the following statistics for each statement: + <itemizedlist> + <listitem> + <para> + <literal>latency</literal> — elapsed transaction time for each + statement. <application>pgbench</application> reports an average value + of all successful runs of the statement. + </para> + </listitem> + <listitem> + <para> + The number of failures in this statement. See + <xref linkend="failures-and-retries"/> for more information. + </para> + </listitem> + <listitem> + <para> + The number of retries after a serialization or a deadlock error in this + statement. See <xref linkend="failures-and-retries"/> for more information. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + The report displays retry statistics only if the <option>--max-tries</option> + option is not equal to 1. + </para> + + <para> + All values are computed for each statement executed by every client and are + reported after the benchmark has finished. + </para> + + <para> + For the default script, the output will look similar to this: +<screen> +starting vacuum...end. +transaction type: <builtin: TPC-B (sort of)> +scaling factor: 1 +query mode: simple +number of clients: 10 +number of threads: 1 +maximum number of tries: 1 +number of transactions per client: 1000 +number of transactions actually processed: 10000/10000 +number of failed transactions: 0 (0.000%) +number of transactions above the 50.0 ms latency limit: 1311/10000 (13.110 %) +latency average = 28.488 ms +latency stddev = 21.009 ms +initial connection time = 69.068 ms +tps = 346.224794 (without initial connection time) +statement latencies in milliseconds and failures: + 0.012 0 \set aid random(1, 100000 * :scale) + 0.002 0 \set bid random(1, 1 * :scale) + 0.002 0 \set tid random(1, 10 * :scale) + 0.002 0 \set delta random(-5000, 5000) + 0.319 0 BEGIN; + 0.834 0 UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid; + 0.641 0 SELECT abalance FROM pgbench_accounts WHERE aid = :aid; + 11.126 0 UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid; + 12.961 0 UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid; + 0.634 0 INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP); + 1.957 0 END; +</screen> + + Another example of output for the default script using serializable default + transaction isolation level (<command>PGOPTIONS='-c + default_transaction_isolation=serializable' pgbench ...</command>): +<screen> +starting vacuum...end. +transaction type: <builtin: TPC-B (sort of)> +scaling factor: 1 +query mode: simple +number of clients: 10 +number of threads: 1 +maximum number of tries: 10 +number of transactions per client: 1000 +number of transactions actually processed: 6317/10000 +number of failed transactions: 3683 (36.830%) +number of transactions retried: 7667 (76.670%) +total number of retries: 45339 +number of transactions above the 50.0 ms latency limit: 106/6317 (1.678 %) +latency average = 17.016 ms +latency stddev = 13.283 ms +initial connection time = 45.017 ms +tps = 186.792667 (without initial connection time) +statement latencies in milliseconds, failures and retries: + 0.006 0 0 \set aid random(1, 100000 * :scale) + 0.001 0 0 \set bid random(1, 1 * :scale) + 0.001 0 0 \set tid random(1, 10 * :scale) + 0.001 0 0 \set delta random(-5000, 5000) + 0.385 0 0 BEGIN; + 0.773 0 1 UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid; + 0.624 0 0 SELECT abalance FROM pgbench_accounts WHERE aid = :aid; + 1.098 320 3762 UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid; + 0.582 3363 41576 UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid; + 0.465 0 0 INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP); + 1.933 0 0 END; +</screen></para> + + <para> + If multiple script files are specified, all statistics are reported + separately for each script file. + </para> + + <para> + Note that collecting the additional timing information needed for + per-statement latency computation adds some overhead. This will slow + average execution speed and lower the computed TPS. The amount + of slowdown varies significantly depending on platform and hardware. + Comparing average TPS values with and without latency reporting enabled + is a good way to measure if the timing overhead is significant. + </para> + </refsect2> + + <refsect2 id="failures-and-retries" xreflabel="Failures and Serialization/Deadlock Retries"> + <title>Failures and Serialization/Deadlock Retries</title> + + <para> + When executing <application>pgbench</application>, there are three main types + of errors: + <itemizedlist> + <listitem> + <para> + Errors of the main program. They are the most serious and always result + in an immediate exit from <application>pgbench</application> with the + corresponding error message. They include: + <itemizedlist> + <listitem> + <para> + errors at the beginning of <application>pgbench</application> + (e.g. an invalid option value); + </para> + </listitem> + <listitem> + <para> + errors in the initialization mode (e.g. the query to create + tables for built-in scripts fails); + </para> + </listitem> + <listitem> + <para> + errors before starting threads (e.g. could not connect to the + database server, syntax error in the meta command, thread + creation failure); + </para> + </listitem> + <listitem> + <para> + internal <application>pgbench</application> errors (which are + supposed to never occur...). + </para> + </listitem> + </itemizedlist></para> + </listitem> + <listitem> + <para> + Errors when the thread manages its clients (e.g. the client could not + start a connection to the database server / the socket for connecting + the client to the database server has become invalid). In such cases + all clients of this thread stop while other threads continue to work. + </para> + </listitem> + <listitem> + <para> + Direct client errors. They lead to immediate exit from + <application>pgbench</application> with the corresponding error message + only in the case of an internal <application>pgbench</application> + error (which are supposed to never occur...). Otherwise in the worst + case they only lead to the abortion of the failed client while other + clients continue their run (but some client errors are handled without + an abortion of the client and reported separately, see below). Later in + this section it is assumed that the discussed errors are only the + direct client errors and they are not internal + <application>pgbench</application> errors. + </para> + </listitem> + </itemizedlist> + </para> + + <para> + A client's run is aborted in case of a serious error; for example, the + connection with the database server was lost or the end of script was reached + without completing the last transaction. In addition, if execution of an SQL + or meta command fails for reasons other than serialization or deadlock errors, + the client is aborted. Otherwise, if an SQL command fails with serialization or + deadlock errors, the client is not aborted. In such cases, the current + transaction is rolled back, which also includes setting the client variables + as they were before the run of this transaction (it is assumed that one + transaction script contains only one transaction; see + <xref linkend="transactions-and-scripts"/> for more information). + Transactions with serialization or deadlock errors are repeated after + rollbacks until they complete successfully or reach the maximum + number of tries (specified by the <option>--max-tries</option> option) / the maximum + time of retries (specified by the <option>--latency-limit</option> option) / the end + of benchmark (specified by the <option>--time</option> option). If + the last trial run fails, this transaction will be reported as failed but + the client is not aborted and continues to work. + </para> + + <note> + <para> + Without specifying the <option>--max-tries</option> option, a transaction will + never be retried after a serialization or deadlock error because its default + value is 1. Use an unlimited number of tries (<literal>--max-tries=0</literal>) + and the <option>--latency-limit</option> option to limit only the maximum time + of tries. You can also use the <option>--time</option> option to limit the + benchmark duration under an unlimited number of tries. + </para> + <para> + Be careful when repeating scripts that contain multiple transactions: the + script is always retried completely, so successful transactions can be + performed several times. + </para> + <para> + Be careful when repeating transactions with shell commands. Unlike the + results of SQL commands, the results of shell commands are not rolled back, + except for the variable value of the <command>\setshell</command> command. + </para> + </note> + + <para> + The latency of a successful transaction includes the entire time of + transaction execution with rollbacks and retries. The latency is measured + only for successful transactions and commands but not for failed transactions + or commands. + </para> + + <para> + The main report contains the number of failed transactions. If the + <option>--max-tries</option> option is not equal to 1, the main report also + contains statistics related to retries: the total number of retried + transactions and total number of retries. The per-script report inherits all + these fields from the main report. The per-statement report displays retry + statistics only if the <option>--max-tries</option> option is not equal to 1. + </para> + + <para> + If you want to group failures by basic types in per-transaction and + aggregation logs, as well as in the main and per-script reports, use the + <option>--failures-detailed</option> option. If you also want to distinguish + all errors and failures (errors without retrying) by type including which + limit for retries was exceeded and how much it was exceeded by for the + serialization/deadlock failures, use the <option>--verbose-errors</option> + option. + </para> + </refsect2> + + <refsect2> + <title>Good Practices</title> + + <para> + It is very easy to use <application>pgbench</application> to produce completely + meaningless numbers. Here are some guidelines to help you get useful + results. + </para> + + <para> + In the first place, <emphasis>never</emphasis> believe any test that runs + for only a few seconds. Use the <option>-t</option> or <option>-T</option> option + to make the run last at least a few minutes, so as to average out noise. + In some cases you could need hours to get numbers that are reproducible. + It's a good idea to try the test run a few times, to find out if your + numbers are reproducible or not. + </para> + + <para> + For the default TPC-B-like test scenario, the initialization scale factor + (<option>-s</option>) should be at least as large as the largest number of + clients you intend to test (<option>-c</option>); else you'll mostly be + measuring update contention. There are only <option>-s</option> rows in + the <structname>pgbench_branches</structname> table, and every transaction wants to + update one of them, so <option>-c</option> values in excess of <option>-s</option> + will undoubtedly result in lots of transactions blocked waiting for + other transactions. + </para> + + <para> + The default test scenario is also quite sensitive to how long it's been + since the tables were initialized: accumulation of dead rows and dead space + in the tables changes the results. To understand the results you must keep + track of the total number of updates and when vacuuming happens. If + autovacuum is enabled it can result in unpredictable changes in measured + performance. + </para> + + <para> + A limitation of <application>pgbench</application> is that it can itself become + the bottleneck when trying to test a large number of client sessions. + This can be alleviated by running <application>pgbench</application> on a different + machine from the database server, although low network latency will be + essential. It might even be useful to run several <application>pgbench</application> + instances concurrently, on several client machines, against the same + database server. + </para> + </refsect2> + <refsect2> + <title>Security</title> + + <para> + If untrusted users have access to a database that has not adopted a + <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>, + do not run <application>pgbench</application> in that + database. <application>pgbench</application> uses unqualified names and + does not manipulate the search path. + </para> + </refsect2> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pgtestfsync.sgml b/doc/src/sgml/ref/pgtestfsync.sgml new file mode 100644 index 0000000..e811f80 --- /dev/null +++ b/doc/src/sgml/ref/pgtestfsync.sgml @@ -0,0 +1,127 @@ +<!-- +doc/src/sgml/ref/pgtestfsync.sgml +PostgreSQL documentation +--> + +<refentry id="pgtestfsync"> + <indexterm zone="pgtestfsync"> + <primary>pg_test_fsync</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_test_fsync</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_test_fsync</refname> + <refpurpose>determine fastest <varname>wal_sync_method</varname> for <productname>PostgreSQL</productname></refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_test_fsync</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_test_fsync</application> is intended to give you a reasonable + idea of what the fastest <xref linkend="guc-wal-sync-method"/> is on your + specific system, + as well as supplying diagnostic information in the event of an identified I/O + problem. However, differences shown by + <application>pg_test_fsync</application> might not make any significant + difference in real database throughput, especially since many database servers + are not speed-limited by their write-ahead logs. + <application>pg_test_fsync</application> reports average file sync operation + time in microseconds for each <literal>wal_sync_method</literal>, which can also be used to + inform efforts to optimize the value of <xref linkend="guc-commit-delay"/>. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_test_fsync</application> accepts the following + command-line options: + + <variablelist> + + <varlistentry> + <term><option>-f</option></term> + <term><option>--filename</option></term> + <listitem> + <para> + Specifies the file name to write test data in. + This file should be in the same file system that the + <filename>pg_wal</filename> directory is or will be placed in. + (<filename>pg_wal</filename> contains the <acronym>WAL</acronym> files.) + The default is <filename>pg_test_fsync.out</filename> in the current + directory. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--secs-per-test</option></term> + <listitem> + <para> + Specifies the number of seconds for each test. The more time + per test, the greater the test's accuracy, but the longer it takes + to run. The default is 5 seconds, which allows the program to + complete in under 2 minutes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_test_fsync</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_test_fsync</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Environment</title> + + <para> + The environment variable <envar>PG_COLOR</envar> specifies whether to use + color in diagnostic messages. Possible values are + <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-postgres"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pgtesttiming.sgml b/doc/src/sgml/ref/pgtesttiming.sgml new file mode 100644 index 0000000..a5eb3aa --- /dev/null +++ b/doc/src/sgml/ref/pgtesttiming.sgml @@ -0,0 +1,303 @@ +<!-- +doc/src/sgml/ref/pgtesttiming.sgml +PostgreSQL documentation +--> + +<refentry id="pgtesttiming"> + <indexterm zone="pgtesttiming"> + <primary>pg_test_timing</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_test_timing</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_test_timing</refname> + <refpurpose>measure timing overhead</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_test_timing</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_test_timing</application> is a tool to measure the timing overhead + on your system and confirm that the system time never moves backwards. + Systems that are slow to collect timing data can give less accurate + <command>EXPLAIN ANALYZE</command> results. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_test_timing</application> accepts the following + command-line options: + + <variablelist> + + <varlistentry> + <term><option>-d <replaceable class="parameter">duration</replaceable></option></term> + <term><option>--duration=<replaceable class="parameter">duration</replaceable></option></term> + <listitem> + <para> + Specifies the test duration, in seconds. Longer durations + give slightly better accuracy, and are more likely to discover + problems with the system clock moving backwards. The default + test duration is 3 seconds. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>pg_test_timing</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>pg_test_timing</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Usage</title> + + <refsect2> + <title>Interpreting Results</title> + + <para> + Good results will show most (>90%) individual timing calls take less than + one microsecond. Average per loop overhead will be even lower, below 100 + nanoseconds. This example from an Intel i7-860 system using a TSC clock + source shows excellent performance: + +<screen><![CDATA[ +Testing timing overhead for 3 seconds. +Per loop time including overhead: 35.96 ns +Histogram of timing durations: + < us % of total count + 1 96.40465 80435604 + 2 3.59518 2999652 + 4 0.00015 126 + 8 0.00002 13 + 16 0.00000 2 +]]></screen> + </para> + + <para> + Note that different units are used for the per loop time than the + histogram. The loop can have resolution within a few nanoseconds (ns), + while the individual timing calls can only resolve down to one microsecond + (us). + </para> + + </refsect2> + <refsect2> + <title>Measuring Executor Timing Overhead</title> + + <para> + When the query executor is running a statement using + <command>EXPLAIN ANALYZE</command>, individual operations are timed as well + as showing a summary. The overhead of your system can be checked by + counting rows with the <application>psql</application> program: + +<screen> +CREATE TABLE t AS SELECT * FROM generate_series(1,100000); +\timing +SELECT COUNT(*) FROM t; +EXPLAIN ANALYZE SELECT COUNT(*) FROM t; +</screen> + </para> + + <para> + The i7-860 system measured runs the count query in 9.8 ms while + the <command>EXPLAIN ANALYZE</command> version takes 16.6 ms, each + processing just over 100,000 rows. That 6.8 ms difference means the timing + overhead per row is 68 ns, about twice what pg_test_timing estimated it + would be. Even that relatively small amount of overhead is making the fully + timed count statement take almost 70% longer. On more substantial queries, + the timing overhead would be less problematic. + </para> + + </refsect2> + + <refsect2> + <title>Changing Time Sources</title> + <para> + On some newer Linux systems, it's possible to change the clock source used + to collect timing data at any time. A second example shows the slowdown + possible from switching to the slower acpi_pm time source, on the same + system used for the fast results above: + +<screen><![CDATA[ +# cat /sys/devices/system/clocksource/clocksource0/available_clocksource +tsc hpet acpi_pm +# echo acpi_pm > /sys/devices/system/clocksource/clocksource0/current_clocksource +# pg_test_timing +Per loop time including overhead: 722.92 ns +Histogram of timing durations: + < us % of total count + 1 27.84870 1155682 + 2 72.05956 2990371 + 4 0.07810 3241 + 8 0.01357 563 + 16 0.00007 3 +]]></screen> + </para> + + <para> + In this configuration, the sample <command>EXPLAIN ANALYZE</command> above + takes 115.9 ms. That's 1061 ns of timing overhead, again a small multiple + of what's measured directly by this utility. That much timing overhead + means the actual query itself is only taking a tiny fraction of the + accounted for time, most of it is being consumed in overhead instead. In + this configuration, any <command>EXPLAIN ANALYZE</command> totals involving + many timed operations would be inflated significantly by timing overhead. + </para> + + <para> + FreeBSD also allows changing the time source on the fly, and it logs + information about the timer selected during boot: + +<screen> +# dmesg | grep "Timecounter" +Timecounter "ACPI-fast" frequency 3579545 Hz quality 900 +Timecounter "i8254" frequency 1193182 Hz quality 0 +Timecounters tick every 10.000 msec +Timecounter "TSC" frequency 2531787134 Hz quality 800 +# sysctl kern.timecounter.hardware=TSC +kern.timecounter.hardware: ACPI-fast -> TSC +</screen> + </para> + + <para> + Other systems may only allow setting the time source on boot. On older + Linux systems the "clock" kernel setting is the only way to make this sort + of change. And even on some more recent ones, the only option you'll see + for a clock source is "jiffies". Jiffies are the older Linux software clock + implementation, which can have good resolution when it's backed by fast + enough timing hardware, as in this example: + +<screen><![CDATA[ +$ cat /sys/devices/system/clocksource/clocksource0/available_clocksource +jiffies +$ dmesg | grep time.c +time.c: Using 3.579545 MHz WALL PM GTOD PIT/TSC timer. +time.c: Detected 2400.153 MHz processor. +$ pg_test_timing +Testing timing overhead for 3 seconds. +Per timing duration including loop overhead: 97.75 ns +Histogram of timing durations: + < us % of total count + 1 90.23734 27694571 + 2 9.75277 2993204 + 4 0.00981 3010 + 8 0.00007 22 + 16 0.00000 1 + 32 0.00000 1 +]]></screen></para> + + </refsect2> + + <refsect2> + <title>Clock Hardware and Timing Accuracy</title> + + <para> + Collecting accurate timing information is normally done on computers using + hardware clocks with various levels of accuracy. With some hardware the + operating systems can pass the system clock time almost directly to + programs. A system clock can also be derived from a chip that simply + provides timing interrupts, periodic ticks at some known time interval. In + either case, operating system kernels provide a clock source that hides + these details. But the accuracy of that clock source and how quickly it can + return results varies based on the underlying hardware. + </para> + + <para> + Inaccurate time keeping can result in system instability. Test any change + to the clock source very carefully. Operating system defaults are sometimes + made to favor reliability over best accuracy. And if you are using a virtual + machine, look into the recommended time sources compatible with it. Virtual + hardware faces additional difficulties when emulating timers, and there are + often per operating system settings suggested by vendors. + </para> + + <para> + The Time Stamp Counter (TSC) clock source is the most accurate one available + on current generation CPUs. It's the preferred way to track the system time + when it's supported by the operating system and the TSC clock is + reliable. There are several ways that TSC can fail to provide an accurate + timing source, making it unreliable. Older systems can have a TSC clock that + varies based on the CPU temperature, making it unusable for timing. Trying + to use TSC on some older multicore CPUs can give a reported time that's + inconsistent among multiple cores. This can result in the time going + backwards, a problem this program checks for. And even the newest systems + can fail to provide accurate TSC timing with very aggressive power saving + configurations. + </para> + + <para> + Newer operating systems may check for the known TSC problems and switch to a + slower, more stable clock source when they are seen. If your system + supports TSC time but doesn't default to that, it may be disabled for a good + reason. And some operating systems may not detect all the possible problems + correctly, or will allow using TSC even in situations where it's known to be + inaccurate. + </para> + + <para> + The High Precision Event Timer (HPET) is the preferred timer on systems + where it's available and TSC is not accurate. The timer chip itself is + programmable to allow up to 100 nanosecond resolution, but you may not see + that much accuracy in your system clock. + </para> + + <para> + Advanced Configuration and Power Interface (ACPI) provides a Power + Management (PM) Timer, which Linux refers to as the acpi_pm. The clock + derived from acpi_pm will at best provide 300 nanosecond resolution. + </para> + + <para> + Timers used on older PC hardware include the 8254 Programmable Interval + Timer (PIT), the real-time clock (RTC), the Advanced Programmable Interrupt + Controller (APIC) timer, and the Cyclone timer. These timers aim for + millisecond resolution. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-explain"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/pgupgrade.sgml b/doc/src/sgml/ref/pgupgrade.sgml new file mode 100644 index 0000000..a38a8a9 --- /dev/null +++ b/doc/src/sgml/ref/pgupgrade.sgml @@ -0,0 +1,855 @@ +<!-- +doc/src/sgml/ref/pgupgrade.sgml +PostgreSQL documentation +--> + +<refentry id="pgupgrade"> + <indexterm zone="pgupgrade"> + <primary>pg_upgrade</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>pg_upgrade</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>pg_upgrade</refname> + <refpurpose>upgrade a <productname>PostgreSQL</productname> server instance</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>pg_upgrade</command> + <arg choice="plain"><option>-b</option></arg> + <arg choice="plain"><replaceable>oldbindir</replaceable></arg> + <arg choice="opt"><option>-B</option> <replaceable>newbindir</replaceable></arg> + <arg choice="plain"><option>-d</option></arg> + <arg choice="plain"><replaceable>oldconfigdir</replaceable></arg> + <arg choice="plain"><option>-D</option></arg> + <arg choice="plain"><replaceable>newconfigdir</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>pg_upgrade</application> (formerly called <application>pg_migrator</application>) allows data + stored in <productname>PostgreSQL</productname> data files to be upgraded to a later <productname>PostgreSQL</productname> + major version without the data dump/restore typically required for + major version upgrades, e.g., from 9.5.8 to 9.6.4 or from 10.7 to 11.2. + It is not required for minor version upgrades, e.g., from 9.6.2 to 9.6.3 + or from 10.1 to 10.2. + </para> + + <para> + Major PostgreSQL releases regularly add new features that often + change the layout of the system tables, but the internal data storage + format rarely changes. <application>pg_upgrade</application> uses this fact + to perform rapid upgrades by creating new system tables and simply + reusing the old user data files. If a future major release ever + changes the data storage format in a way that makes the old data + format unreadable, <application>pg_upgrade</application> will not be usable + for such upgrades. (The community will attempt to avoid such + situations.) + </para> + + <para> + <application>pg_upgrade</application> does its best to + make sure the old and new clusters are binary-compatible, e.g., by + checking for compatible compile-time settings, including 32/64-bit + binaries. It is important that + any external modules are also binary compatible, though this cannot + be checked by <application>pg_upgrade</application>. + </para> + + <para> + pg_upgrade supports upgrades from 9.2.X and later to the current + major release of <productname>PostgreSQL</productname>, including snapshot and beta releases. + </para> + </refsect1> + + <refsect1> + <title>Options</title> + + <para> + <application>pg_upgrade</application> accepts the following command-line arguments: + + <variablelist> + + <varlistentry> + <term><option>-b</option> <replaceable>bindir</replaceable></term> + <term><option>--old-bindir=</option><replaceable>bindir</replaceable></term> + <listitem><para>the old PostgreSQL executable directory; + environment variable <envar>PGBINOLD</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-B</option> <replaceable>bindir</replaceable></term> + <term><option>--new-bindir=</option><replaceable>bindir</replaceable></term> + <listitem><para>the new PostgreSQL executable directory; + default is the directory where <application>pg_upgrade</application> resides; + environment variable <envar>PGBINNEW</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <term><option>--check</option></term> + <listitem><para>check clusters only, don't change any data</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-d</option> <replaceable>configdir</replaceable></term> + <term><option>--old-datadir=</option><replaceable>configdir</replaceable></term> + <listitem><para>the old database cluster configuration directory; environment + variable <envar>PGDATAOLD</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-D</option> <replaceable>configdir</replaceable></term> + <term><option>--new-datadir=</option><replaceable>configdir</replaceable></term> + <listitem><para>the new database cluster configuration directory; environment + variable <envar>PGDATANEW</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">njobs</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">njobs</replaceable></option></term> + <listitem><para>number of simultaneous processes or threads to use + </para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-k</option></term> + <term><option>--link</option></term> + <listitem><para>use hard links instead of copying files to the new + cluster</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-N</option></term> + <term><option>--no-sync</option></term> + <listitem> + <para> + By default, <command>pg_upgrade</command> will wait for all files + of the upgraded cluster to be written safely to disk. This option + causes <command>pg_upgrade</command> to return without waiting, which + is faster, but means that a subsequent operating system crash can leave + the data directory corrupt. Generally, this option is + useful for testing but should not be used on a production + installation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o</option> <replaceable class="parameter">options</replaceable></term> + <term><option>--old-options</option> <replaceable class="parameter">options</replaceable></term> + <listitem><para>options to be passed directly to the + old <command>postgres</command> command; multiple + option invocations are appended</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-O</option> <replaceable class="parameter">options</replaceable></term> + <term><option>--new-options</option> <replaceable class="parameter">options</replaceable></term> + <listitem><para>options to be passed directly to the + new <command>postgres</command> command; multiple + option invocations are appended</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-p</option> <replaceable>port</replaceable></term> + <term><option>--old-port=</option><replaceable>port</replaceable></term> + <listitem><para>the old cluster port number; environment + variable <envar>PGPORTOLD</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option> <replaceable>port</replaceable></term> + <term><option>--new-port=</option><replaceable>port</replaceable></term> + <listitem><para>the new cluster port number; environment + variable <envar>PGPORTNEW</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-r</option></term> + <term><option>--retain</option></term> + <listitem><para>retain SQL and log files even after successful completion + </para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option> <replaceable>dir</replaceable></term> + <term><option>--socketdir=</option><replaceable>dir</replaceable></term> + <listitem><para>directory to use for postmaster sockets during upgrade; + default is current working directory; environment + variable <envar>PGSOCKETDIR</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-U</option> <replaceable>username</replaceable></term> + <term><option>--username=</option><replaceable>username</replaceable></term> + <listitem><para>cluster's install user name; environment + variable <envar>PGUSER</envar></para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem><para>enable verbose internal logging</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem><para>display version information, then exit</para></listitem> + </varlistentry> + + <varlistentry> + <term><option>--clone</option></term> + <listitem> + <para> + Use efficient file cloning (also known as <quote>reflinks</quote> on + some systems) instead of copying files to the new cluster. This can + result in near-instantaneous copying of the data files, giving the + speed advantages of <option>-k</option>/<option>--link</option> while + leaving the old cluster untouched. + </para> + + <para> + File cloning is only supported on some operating systems and file + systems. If it is selected but not supported, the + <application>pg_upgrade</application> run will error. At present, it + is supported on Linux (kernel 4.5 or later) with Btrfs and XFS (on + file systems created with reflink support), and on macOS with APFS. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem><para>show help, then exit</para></listitem> + </varlistentry> + + </variablelist> + </para> + + </refsect1> + + <refsect1> + <title>Usage</title> + + <para> + These are the steps to perform an upgrade + with <application>pg_upgrade</application>: + </para> + + <procedure> + <step performance="optional"> + <title>Optionally move the old cluster</title> + + <para> + If you are using a version-specific installation directory, e.g., + <filename>/opt/PostgreSQL/&majorversion;</filename>, you do not need to move the old cluster. The + graphical installers all use version-specific installation directories. + </para> + + <para> + If your installation directory is not version-specific, e.g., + <filename>/usr/local/pgsql</filename>, it is necessary to move the current PostgreSQL install + directory so it does not interfere with the new <productname>PostgreSQL</productname> installation. + Once the current <productname>PostgreSQL</productname> server is shut down, it is safe to rename the + PostgreSQL installation directory; assuming the old directory is + <filename>/usr/local/pgsql</filename>, you can do: + +<programlisting> +mv /usr/local/pgsql /usr/local/pgsql.old +</programlisting> + to rename the directory. + </para> + </step> + + <step> + <title>For source installs, build the new version</title> + + <para> + Build the new PostgreSQL source with <command>configure</command> flags that are compatible + with the old cluster. <application>pg_upgrade</application> will check <command>pg_controldata</command> to make + sure all settings are compatible before starting the upgrade. + </para> + </step> + + <step> + <title>Install the new PostgreSQL binaries</title> + + <para> + Install the new server's binaries and support + files. <application>pg_upgrade</application> is included in a default installation. + </para> + + <para> + For source installs, if you wish to install the new server in a custom + location, use the <literal>prefix</literal> variable: + +<programlisting> +make prefix=/usr/local/pgsql.new install +</programlisting></para> + </step> + + <step> + <title>Initialize the new PostgreSQL cluster</title> + + <para> + Initialize the new cluster using <command>initdb</command>. + Again, use compatible <command>initdb</command> + flags that match the old cluster. Many + prebuilt installers do this step automatically. There is no need to + start the new cluster. + </para> + </step> + + <step> + <title>Install extension shared object files</title> + + <para> + Many extensions and custom modules, whether from + <filename>contrib</filename> or another source, use shared object + files (or DLLs), e.g., <filename>pgcrypto.so</filename>. If the old + cluster used these, shared object files matching the new server binary + must be installed in the new cluster, usually via operating system + commands. Do not load the schema definitions, e.g., <command>CREATE + EXTENSION pgcrypto</command>, because these will be duplicated from + the old cluster. If extension updates are available, + <application>pg_upgrade</application> will report this and create + a script that can be run later to update them. + </para> + </step> + + <step> + <title>Copy custom full-text search files</title> + + <para> + Copy any custom full text search files (dictionary, synonym, + thesaurus, stop words) from the old to the new cluster. + </para> + </step> + + <step> + <title>Adjust authentication</title> + + <para> + <command>pg_upgrade</command> will connect to the old and new servers several + times, so you might want to set authentication to <literal>peer</literal> + in <filename>pg_hba.conf</filename> or use a <filename>~/.pgpass</filename> file + (see <xref linkend="libpq-pgpass"/>). + </para> + </step> + + <step> + <title>Stop both servers</title> + + <para> + Make sure both database servers are stopped using, on Unix, e.g.: + +<programlisting> +pg_ctl -D /opt/PostgreSQL/9.6 stop +pg_ctl -D /opt/PostgreSQL/&majorversion; stop +</programlisting> + + or on Windows, using the proper service names: + +<programlisting> +NET STOP postgresql-9.6 +NET STOP postgresql-&majorversion; +</programlisting> + </para> + + <para> + Streaming replication and log-shipping standby servers must be + running during this shutdown so they receive all changes. + </para> + </step> + + <step> + <title>Prepare for standby server upgrades</title> + + <para> + If you are upgrading standby servers using methods outlined in section <xref + linkend="pgupgrade-step-replicas"/>, verify that the old standby + servers are caught up by running <application>pg_controldata</application> + against the old primary and standby clusters. Verify that the + <quote>Latest checkpoint location</quote> values match in all clusters. + Also, make sure <varname>wal_level</varname> is not set to + <literal>minimal</literal> in the <filename>postgresql.conf</filename> file on the + new primary cluster. + </para> + </step> + + <step> + <title>Run <application>pg_upgrade</application></title> + + <para> + Always run the <application>pg_upgrade</application> binary of the new server, not the old one. + <application>pg_upgrade</application> requires the specification of the old and new cluster's + data and executable (<filename>bin</filename>) directories. You can also specify + user and port values, and whether you want the data files linked or cloned + instead of the default copy behavior. + </para> + + <para> + If you use link mode, the upgrade will be much faster (no file + copying) and use less disk space, but you will not be able to access + your old cluster + once you start the new cluster after the upgrade. Link mode also + requires that the old and new cluster data directories be in the + same file system. (Tablespaces and <filename>pg_wal</filename> can be on + different file systems.) + Clone mode provides the same speed and disk space advantages but + does not cause the old cluster to be unusable once the new cluster + is started. Clone mode also requires that the old and new data + directories be in the same file system. This mode is only available + on certain operating systems and file systems. + </para> + + <para> + The <option>--jobs</option> option allows multiple CPU cores to be used + for copying/linking of files and to dump and restore database schemas + in parallel; a good place to start is the maximum of the number of + CPU cores and tablespaces. This option can dramatically reduce the + time to upgrade a multi-database server running on a multiprocessor + machine. + </para> + + <para> + For Windows users, you must be logged into an administrative account, and + then start a shell as the <literal>postgres</literal> user and set the proper path: + +<programlisting> +RUNAS /USER:postgres "CMD.EXE" +SET PATH=%PATH%;C:\Program Files\PostgreSQL\&majorversion;\bin; +</programlisting> + + and then run <application>pg_upgrade</application> with quoted directories, e.g.: + +<programlisting> +pg_upgrade.exe + --old-datadir "C:/Program Files/PostgreSQL/9.6/data" + --new-datadir "C:/Program Files/PostgreSQL/&majorversion;/data" + --old-bindir "C:/Program Files/PostgreSQL/9.6/bin" + --new-bindir "C:/Program Files/PostgreSQL/&majorversion;/bin" +</programlisting> + + Once started, <command>pg_upgrade</command> will verify the two clusters are compatible + and then do the upgrade. You can use <command>pg_upgrade --check</command> + to perform only the checks, even if the old server is still + running. <command>pg_upgrade --check</command> will also outline any + manual adjustments you will need to make after the upgrade. If you + are going to be using link or clone mode, you should use the option + <option>--link</option> or <option>--clone</option> with + <option>--check</option> to enable mode-specific checks. + <command>pg_upgrade</command> requires write permission in the current directory. + </para> + + <para> + Obviously, no one should be accessing the clusters during the + upgrade. <application>pg_upgrade</application> defaults to running servers + on port 50432 to avoid unintended client connections. + You can use the same port number for both clusters when doing an + upgrade because the old and new clusters will not be running at the + same time. However, when checking an old running server, the old + and new port numbers must be different. + </para> + + <para> + If an error occurs while restoring the database schema, <command>pg_upgrade</command> will + exit and you will have to revert to the old cluster as outlined in <xref linkend="pgupgrade-step-revert"/> + below. To try <command>pg_upgrade</command> again, you will need to modify the old + cluster so the pg_upgrade schema restore succeeds. If the problem is a + <filename>contrib</filename> module, you might need to uninstall the <filename>contrib</filename> module from + the old cluster and install it in the new cluster after the upgrade, + assuming the module is not being used to store user data. + </para> + </step> + + <step id="pgupgrade-step-replicas"> + <title>Upgrade streaming replication and log-shipping standby servers</title> + + <para> + If you used link mode and have Streaming Replication (see <xref + linkend="streaming-replication"/>) or Log-Shipping (see <xref + linkend="warm-standby"/>) standby servers, you can follow these steps to + quickly upgrade them. You will not be running <application>pg_upgrade</application> on + the standby servers, but rather <application>rsync</application> on the primary. + Do not start any servers yet. + </para> + + <para> + If you did <emphasis>not</emphasis> use link mode, do not have or do not + want to use <application>rsync</application>, or want an easier solution, skip + the instructions in this section and simply recreate the standby + servers once <application>pg_upgrade</application> completes and the new primary + is running. + </para> + + <procedure> + + <step> + <title>Install the new PostgreSQL binaries on standby servers</title> + + <para> + Make sure the new binaries and support files are installed on all + standby servers. + </para> + </step> + + <step> + <title>Make sure the new standby data directories do <emphasis>not</emphasis> exist</title> + + <para> + Make sure the new standby data directories do <emphasis>not</emphasis> + exist or are empty. If <application>initdb</application> was run, delete + the standby servers' new data directories. + </para> + </step> + + <step> + <title>Install extension shared object files</title> + + <para> + Install the same extension shared object files on the new standbys + that you installed in the new primary cluster. + </para> + </step> + + <step> + <title>Stop standby servers</title> + + <para> + If the standby servers are still running, stop them now using the + above instructions. + </para> + </step> + + <step> + <title>Save configuration files</title> + + <para> + Save any configuration files from the old standbys' configuration + directories you need to keep, e.g., <filename>postgresql.conf</filename> + (and any files included by it), <filename>postgresql.auto.conf</filename>, + <literal>pg_hba.conf</literal>, because these will be overwritten + or removed in the next step. + </para> + </step> + + <step> + <title>Run <application>rsync</application></title> + + <para> + When using link mode, standby servers can be quickly upgraded using + <application>rsync</application>. To accomplish this, from a directory on + the primary server that is above the old and new database cluster + directories, run this on the <emphasis>primary</emphasis> for each standby + server: + +<programlisting> +rsync --archive --delete --hard-links --size-only --no-inc-recursive old_cluster new_cluster remote_dir +</programlisting> + + where <option>old_cluster</option> and <option>new_cluster</option> are relative + to the current directory on the primary, and <option>remote_dir</option> + is <emphasis>above</emphasis> the old and new cluster directories + on the standby. The directory structure under the specified + directories on the primary and standbys must match. Consult the + <application>rsync</application> manual page for details on specifying the + remote directory, e.g., + +<programlisting> +rsync --archive --delete --hard-links --size-only --no-inc-recursive /opt/PostgreSQL/9.5 \ + /opt/PostgreSQL/9.6 standby.example.com:/opt/PostgreSQL +</programlisting> + + You can verify what the command will do using + <application>rsync</application>'s <option>--dry-run</option> option. While + <application>rsync</application> must be run on the primary for at least one + standby, it is possible to run <application>rsync</application> on an upgraded + standby to upgrade other standbys, as long as the upgraded standby + has not been started. + </para> + + <para> + What this does is to record the links created by + <application>pg_upgrade</application>'s link mode that connect files in the + old and new clusters on the primary server. It then finds matching + files in the standby's old cluster and creates links for them in the + standby's new cluster. Files that were not linked on the primary + are copied from the primary to the standby. (They are usually + small.) This provides rapid standby upgrades. Unfortunately, + <application>rsync</application> needlessly copies files associated with + temporary and unlogged tables because these files don't normally + exist on standby servers. + </para> + + <para> + If you have tablespaces, you will need to run a similar + <application>rsync</application> command for each tablespace directory, e.g.: + +<programlisting> +rsync --archive --delete --hard-links --size-only --no-inc-recursive /vol1/pg_tblsp/PG_9.5_201510051 \ + /vol1/pg_tblsp/PG_9.6_201608131 standby.example.com:/vol1/pg_tblsp +</programlisting> + + If you have relocated <filename>pg_wal</filename> outside the data + directories, <application>rsync</application> must be run on those directories + too. + </para> + </step> + + <step> + <title>Configure streaming replication and log-shipping standby servers</title> + + <para> + Configure the servers for log shipping. (You do not need to run + <function>pg_backup_start()</function> and <function>pg_backup_stop()</function> + or take a file system backup as the standbys are still synchronized + with the primary.) Replication slots are not copied and must + be recreated. + </para> + </step> + + </procedure> + + </step> + + <step> + <title>Restore <filename>pg_hba.conf</filename></title> + + <para> + If you modified <filename>pg_hba.conf</filename>, restore its original settings. + It might also be necessary to adjust other configuration files in the new + cluster to match the old cluster, e.g., <filename>postgresql.conf</filename> + (and any files included by it), <filename>postgresql.auto.conf</filename>. + </para> + </step> + + <step> + <title>Start the new server</title> + + <para> + The new server can now be safely started, and then any + <application>rsync</application>'ed standby servers. + </para> + </step> + + <step> + <title>Post-upgrade processing</title> + + <para> + If any post-upgrade processing is required, pg_upgrade will issue + warnings as it completes. It will also generate script files that must + be run by the administrator. The script files will connect to each + database that needs post-upgrade processing. Each script should be + run using: + +<programlisting> +psql --username=postgres --file=script.sql postgres +</programlisting> + + The scripts can be run in any order and can be deleted once they have + been run. + </para> + + <caution> + <para> + In general it is unsafe to access tables referenced in rebuild scripts + until the rebuild scripts have run to completion; doing so could yield + incorrect results or poor performance. Tables not referenced in rebuild + scripts can be accessed immediately. + </para> + </caution> + </step> + + <step> + <title>Statistics</title> + + <para> + Because optimizer statistics are not transferred by <command>pg_upgrade</command>, you will + be instructed to run a command to regenerate that information at the end + of the upgrade. You might need to set connection parameters to + match your new cluster. + </para> + </step> + + <step> + <title>Delete old cluster</title> + + <para> + Once you are satisfied with the upgrade, you can delete the old + cluster's data directories by running the script mentioned when + <command>pg_upgrade</command> completes. (Automatic deletion is not + possible if you have user-defined tablespaces inside the old data + directory.) You can also delete the old installation directories + (e.g., <filename>bin</filename>, <filename>share</filename>). + </para> + </step> + + <step id="pgupgrade-step-revert" performance="optional"> + <title>Reverting to old cluster</title> + + <para> + If, after running <command>pg_upgrade</command>, you wish to revert to the old cluster, + there are several options: + + <itemizedlist> + <listitem> + <para> + If the <option>--check</option> option was used, the old cluster + was unmodified; it can be restarted. + </para> + </listitem> + + <listitem> + <para> + If the <option>--link</option> option was <emphasis>not</emphasis> + used, the old cluster was unmodified; it can be restarted. + </para> + </listitem> + + <listitem> + <para> + If the <option>--link</option> option was used, the data + files might be shared between the old and new cluster: + + <itemizedlist> + <listitem> + <para> + If <command>pg_upgrade</command> aborted before linking started, + the old cluster was unmodified; it can be restarted. + </para> + </listitem> + + <listitem> + <para> + If you did <emphasis>not</emphasis> start the new cluster, the old + cluster was unmodified except that, when linking started, a + <literal>.old</literal> suffix was appended to + <filename>$PGDATA/global/pg_control</filename>. To reuse the old + cluster, remove the <filename>.old</filename> suffix from + <filename>$PGDATA/global/pg_control</filename>; you can then restart + the old cluster. + </para> + </listitem> + + <listitem> + <para> + If you did start the new cluster, it has written to shared files + and it is unsafe to use the old cluster. The old cluster will + need to be restored from backup in this case. + </para> + </listitem> + + </itemizedlist></para> + </listitem> + </itemizedlist></para> + </step> + </procedure> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <application>pg_upgrade</application> creates various working files, such + as schema dumps, stored within <filename>pg_upgrade_output.d</filename> in + the directory of the new cluster. Each run creates a new subdirectory named + with a timestamp formatted as per ISO 8601 + (<literal>%Y%m%dT%H%M%S</literal>), where all its generated files are + stored. + <filename>pg_upgrade_output.d</filename> and its contained files will be + removed automatically if <application>pg_upgrade</application> completes + successfully; but in the event of trouble, the files there may provide + useful debugging information. + </para> + + <para> + <application>pg_upgrade</application> launches short-lived postmasters in + the old and new data directories. Temporary Unix socket files for + communication with these postmasters are, by default, made in the current + working directory. In some situations the path name for the current + directory might be too long to be a valid socket name. In that case you + can use the <option>-s</option> option to put the socket files in some + directory with a shorter path name. For security, be sure that that + directory is not readable or writable by any other users. + (This is not supported on Windows.) + </para> + + <para> + All failure, rebuild, and reindex cases will be reported by + <application>pg_upgrade</application> if they affect your installation; + post-upgrade scripts to rebuild tables and indexes will be + generated automatically. If you are trying to automate the upgrade + of many clusters, you should find that clusters with identical database + schemas require the same post-upgrade steps for all cluster upgrades; + this is because the post-upgrade steps are based on the database + schemas, and not user data. + </para> + + <para> + For deployment testing, create a schema-only copy of the old cluster, + insert dummy data, and upgrade that. + </para> + + <para> + <application>pg_upgrade</application> does not support upgrading of databases + containing table columns using these <type>reg*</type> OID-referencing system data types: + <simplelist> + <member><type>regcollation</type></member> + <member><type>regconfig</type></member> + <member><type>regdictionary</type></member> + <member><type>regnamespace</type></member> + <member><type>regoper</type></member> + <member><type>regoperator</type></member> + <member><type>regproc</type></member> + <member><type>regprocedure</type></member> + </simplelist> + (<type>regclass</type>, <type>regrole</type>, and <type>regtype</type> can be upgraded.) + </para> + + <para> + If you want to use link mode and you do not want your old cluster + to be modified when the new cluster is started, consider using the clone mode. + If that is not available, make a copy of the + old cluster and upgrade that in link mode. To make a valid copy + of the old cluster, use <command>rsync</command> to create a dirty + copy of the old cluster while the server is running, then shut down + the old server and run <command>rsync --checksum</command> again to update the + copy with any changes to make it consistent. (<option>--checksum</option> + is necessary because <command>rsync</command> only has file modification-time + granularity of one second.) You might want to exclude some + files, e.g., <filename>postmaster.pid</filename>, as documented in <xref + linkend="backup-lowlevel-base-backup"/>. If your file system supports + file system snapshots or copy-on-write file copies, you can use that + to make a backup of the old cluster and tablespaces, though the snapshot + and copies must be created simultaneously or while the database server + is down. + </para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-initdb"/></member> + <member><xref linkend="app-pg-ctl"/></member> + <member><xref linkend="app-pgdump"/></member> + <member><xref linkend="app-postgres"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/postgres-ref.sgml b/doc/src/sgml/ref/postgres-ref.sgml new file mode 100644 index 0000000..55a3f6c --- /dev/null +++ b/doc/src/sgml/ref/postgres-ref.sgml @@ -0,0 +1,845 @@ +<!-- +doc/src/sgml/ref/postgres-ref.sgml +PostgreSQL documentation +--> + +<refentry id="app-postgres"> + <indexterm zone="app-postgres"> + <primary>postgres</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>postgres</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>postgres</refname> + <refpurpose><productname>PostgreSQL</productname> database server</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>postgres</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>postgres</command> is the + <productname>PostgreSQL</productname> database server. In order + for a client application to access a database it connects (over a + network or locally) to a running <command>postgres</command> instance. + The <command>postgres</command> instance then starts a separate server + process to handle the connection. + </para> + + <para> + One <command>postgres</command> instance always manages the data of + exactly one database cluster. A database cluster is a collection + of databases that is stored at a common file system location (the + <quote>data area</quote>). More than one + <command>postgres</command> instance can run on a system at one + time, so long as they use different data areas and different + communication ports (see below). When + <command>postgres</command> starts it needs to know the location + of the data area. The location must be specified by the + <option>-D</option> option or the <envar>PGDATA</envar> environment + variable; there is no default. Typically, <option>-D</option> or + <envar>PGDATA</envar> points directly to the data area directory + created by <xref linkend="app-initdb"/>. Other possible file layouts are + discussed in <xref linkend="runtime-config-file-locations"/>. + </para> + + <para> + By default <command>postgres</command> starts in the + foreground and prints log messages to the standard error stream. In + practical applications <command>postgres</command> + should be started as a background process, perhaps at boot time. + </para> + + <para> + The <command>postgres</command> command can also be called in + single-user mode. The primary use for this mode is during + bootstrapping by <xref linkend="app-initdb"/>. Sometimes it is used + for debugging or disaster recovery; note that running a single-user + server is not truly suitable for debugging the server, since no + realistic interprocess communication and locking will happen. + When invoked in single-user + mode from the shell, the user can enter queries and the results + will be printed to the screen, but in a form that is more useful + for developers than end users. In the single-user mode, + the session user will be set to the user with ID 1, and implicit + superuser powers are granted to this user. + This user does not actually have to exist, so the single-user mode + can be used to manually recover from certain + kinds of accidental damage to the system catalogs. + </para> + </refsect1> + + <refsect1 id="app-postgres-options"> + <title>Options</title> + + <para> + <command>postgres</command> accepts the following command-line + arguments. For a detailed discussion of the options consult <xref + linkend="runtime-config"/>. You can save typing most of these + options by setting up a configuration file. Some (safe) options + can also be set from the connecting client in an + application-dependent way to apply only for that session. For + example, if the environment variable <envar>PGOPTIONS</envar> is + set, then <application>libpq</application>-based clients will pass that + string to the server, which will interpret it as + <command>postgres</command> command-line options. + </para> + + <refsect2> + <title>General Purpose</title> + + <variablelist> + <varlistentry> + <term><option>-B <replaceable class="parameter">nbuffers</replaceable></option></term> + <listitem> + <para> + Sets the number of shared buffers for use by the server + processes. The default value of this parameter is chosen + automatically by <application>initdb</application>. + Specifying this option is equivalent to setting the + <xref linkend="guc-shared-buffers"/> configuration parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c <replaceable>name</replaceable>=<replaceable>value</replaceable></option></term> + <listitem> + <para> + Sets a named run-time parameter. The configuration parameters + supported by <productname>PostgreSQL</productname> are + described in <xref linkend="runtime-config"/>. Most of the + other command line options are in fact short forms of such a + parameter assignment. <option>-c</option> can appear multiple times + to set multiple parameters. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-C <replaceable>name</replaceable></option></term> + <listitem> + <para> + Prints the value of the named run-time parameter, and exits. + (See the <option>-c</option> option above for details.) This + returns values from + <filename>postgresql.conf</filename>, modified by any parameters + supplied in this invocation. It does not reflect parameters + supplied when the cluster was started. + </para> + + <para> + This can be used on a running server for most parameters. However, + the server must be shut down for some runtime-computed parameters + (e.g., <xref linkend="guc-shared-memory-size"/>, + <xref linkend="guc-shared-memory-size-in-huge-pages"/>, and + <xref linkend="guc-wal-segment-size"/>). + </para> + + <para> + This option is meant for other programs that interact with a server + instance, such as <xref linkend="app-pg-ctl"/>, to query configuration + parameter values. User-facing applications should instead use <link + linkend="sql-show"><command>SHOW</command></link> or the <structname>pg_settings</structname> view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d <replaceable>debug-level</replaceable></option></term> + <listitem> + <para> + Sets the debug level. The higher this value is set, the more + debugging output is written to the server log. Values are + from 1 to 5. It is also possible to pass <literal>-d + 0</literal> for a specific session, which will prevent the + server log level of the parent <command>postgres</command> process from being + propagated to this session. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-D <replaceable class="parameter">datadir</replaceable></option></term> + <listitem> + <para> + Specifies the file system location of the database + configuration files. See + <xref linkend="runtime-config-file-locations"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <listitem> + <para> + Sets the default date style to <quote>European</quote>, that is + <literal>DMY</literal> ordering of input date fields. This also causes + the day to be printed before the month in certain date output formats. + See <xref linkend="datatype-datetime"/> for more information. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F</option></term> + <listitem> + <para> + Disables <function>fsync</function> calls for improved + performance, at the risk of data corruption in the event of a + system crash. Specifying this option is equivalent to + disabling the <xref linkend="guc-fsync"/> configuration + parameter. Read the detailed documentation before using this! + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">hostname</replaceable></option></term> + <listitem> + <para> + Specifies the IP host name or address on which + <command>postgres</command> is to listen for TCP/IP + connections from client applications. The value can also be a + comma-separated list of addresses, or <literal>*</literal> to specify + listening on all available interfaces. An empty value + specifies not listening on any IP addresses, in which case + only Unix-domain sockets can be used to connect to the + server. Defaults to listening only on + <systemitem class="systemname">localhost</systemitem>. + Specifying this option is equivalent to setting the <xref + linkend="guc-listen-addresses"/> configuration parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <listitem> + <para> + Allows remote clients to connect via TCP/IP (Internet domain) + connections. Without this option, only local connections are + accepted. This option is equivalent to setting + <varname>listen_addresses</varname> to <literal>*</literal> in + <filename>postgresql.conf</filename> or via <option>-h</option>. + </para> + <para> + This option is deprecated since it does not allow access to the + full functionality of <xref linkend="guc-listen-addresses"/>. + It's usually better to set <varname>listen_addresses</varname> directly. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-k <replaceable class="parameter">directory</replaceable></option></term> + <listitem> + <para> + Specifies the directory of the Unix-domain socket on which + <command>postgres</command> is to listen for + connections from client applications. The value can also be a + comma-separated list of directories. An empty value + specifies not listening on any Unix-domain sockets, in which case + only TCP/IP sockets can be used to connect to the server. + The default value is normally + <filename>/tmp</filename>, but that can be changed at build time. + Specifying this option is equivalent to setting the <xref + linkend="guc-unix-socket-directories"/> configuration parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <listitem> + <para> + Enables secure connections using <acronym>SSL</acronym>. + <productname>PostgreSQL</productname> must have been compiled with + support for <acronym>SSL</acronym> for this option to be + available. For more information on using <acronym>SSL</acronym>, + refer to <xref linkend="ssl-tcp"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-N <replaceable class="parameter">max-connections</replaceable></option></term> + <listitem> + <para> + Sets the maximum number of client connections that this + server will accept. The default value of this parameter is chosen + automatically by <application>initdb</application>. + Specifying this option is equivalent to setting the + <xref linkend="guc-max-connections"/> configuration parameter. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP/IP port or local Unix domain socket file + extension on which <command>postgres</command> + is to listen for connections from client applications. + Defaults to the value of the <envar>PGPORT</envar> environment + variable, or if <envar>PGPORT</envar> is not set, then + defaults to the value established during compilation (normally + 5432). If you specify a port other than the default port, + then all client applications must specify the same port using + either command-line options or <envar>PGPORT</envar>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <listitem> + <para> + Print time information and other statistics at the end of each command. + This is useful for benchmarking or for use in tuning the number of + buffers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S</option> <replaceable class="parameter">work-mem</replaceable></term> + <listitem> + <para> + Specifies the base amount of memory to be used by sorts and + hash tables before resorting to temporary disk files. See the + description of the <varname>work_mem</varname> configuration + parameter in <xref linkend="runtime-config-resource-memory"/>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>postgres</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--<replaceable>name</replaceable>=<replaceable>value</replaceable></option></term> + <listitem> + <para> + Sets a named run-time parameter; a shorter form of + <option>-c</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--describe-config</option></term> + <listitem> + <para> + This option dumps out the server's internal configuration variables, + descriptions, and defaults in tab-delimited <command>COPY</command> format. + It is designed primarily for use by administration tools. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>postgres</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + + <refsect2> + <title>Semi-Internal Options</title> + + <para> + The options described here are used + mainly for debugging purposes, and in some cases to assist with + recovery of severely damaged databases. There should be no reason + to use them in a production database setup. They are listed + here only for use by <productname>PostgreSQL</productname> + system developers. Furthermore, these options might + change or be removed in a future release without notice. + </para> + + <variablelist> + <varlistentry> + <term><option>-f</option> <literal>{ s | i | o | b | t | n | m | h }</literal></term> + <listitem> + <para> + Forbids the use of particular scan and join methods: + <literal>s</literal> and <literal>i</literal> + disable sequential and index scans respectively, + <literal>o</literal>, <literal>b</literal> and <literal>t</literal> + disable index-only scans, bitmap index scans, and TID scans + respectively, while + <literal>n</literal>, <literal>m</literal>, and <literal>h</literal> + disable nested-loop, merge and hash joins respectively. + </para> + + <para> + Neither sequential scans nor nested-loop joins can be disabled + completely; the <literal>-fs</literal> and + <literal>-fn</literal> options simply discourage the optimizer + from using those plan types if it has any other alternative. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <listitem> + <para> + This option is for debugging problems that cause a server + process to die abnormally. The ordinary strategy in this + situation is to notify all other server processes that they + must terminate and then reinitialize the shared memory and + semaphores. This is because an errant server process could + have corrupted some shared state before terminating. This + option specifies that <command>postgres</command> will + not reinitialize shared data structures. A knowledgeable + system programmer can then use a debugger to examine shared + memory and semaphore state. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-O</option></term> + <listitem> + <para> + Allows the structure of system tables to be modified. This is + used by <command>initdb</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P</option></term> + <listitem> + <para> + Ignore system indexes when reading system tables, but still update + the indexes when modifying the tables. This is useful when + recovering from damaged system indexes. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option> <literal>pa[rser] | pl[anner] | e[xecutor]</literal></term> + <listitem> + <para> + Print timing statistics for each query relating to each of the + major system modules. This option cannot be used together + with the <option>-s</option> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T</option></term> + <listitem> + <para> + This option is for debugging problems that cause a server + process to die abnormally. The ordinary strategy in this + situation is to notify all other server processes that they + must terminate and then reinitialize the shared memory and + semaphores. This is because an errant server process could + have corrupted some shared state before terminating. This + option specifies that <command>postgres</command> will + stop all other server processes by sending the signal + <literal>SIGSTOP</literal>, but will not cause them to + terminate. This permits system programmers to collect core + dumps from all server processes by hand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option> <replaceable class="parameter">protocol</replaceable></term> + <listitem> + <para> + Specifies the version number of the frontend/backend protocol + to be used for a particular session. This option is for + internal use only. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option> <replaceable class="parameter">seconds</replaceable></term> + <listitem> + <para> + A delay of this many seconds occurs when a new server process + is started, after it conducts the authentication procedure. + This is intended to give an opportunity to attach to the + server process with a debugger. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + + <refsect2> + <title>Options for Single-User Mode</title> + + <indexterm> + <primary>single-user mode</primary> + </indexterm> + + <para> + The following options only apply to the single-user mode + (see <xref linkend="app-postgres-single-user"/> below). + </para> + + <variablelist> + <varlistentry> + <term><option>--single</option></term> + <listitem> + <para> + Selects the single-user mode. This must be the first argument + on the command line. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">database</replaceable></term> + <listitem> + <para> + Specifies the name of the database to be accessed. This must be + the last argument on the command line. If it is + omitted it defaults to the user name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E</option></term> + <listitem> + <para> + Echo all commands to standard output before executing them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j</option></term> + <listitem> + <para> + Use semicolon followed by two newlines, rather than just newline, + as the command entry terminator. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-r</option> <replaceable class="parameter">filename</replaceable></term> + <listitem> + <para> + Send all server log output to <replaceable + class="parameter">filename</replaceable>. This option is only + honored when supplied as a command-line option. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect2> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGCLIENTENCODING</envar></term> + + <listitem> + <para> + Default character encoding used by clients. (The clients can + override this individually.) This value can also be set in the + configuration file. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGDATA</envar></term> + + <listitem> + <para> + Default data directory location + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGDATESTYLE</envar></term> + + <listitem> + <para> + Default value of the <xref linkend="guc-datestyle"/> run-time + parameter. (The use of this environment variable is deprecated.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGPORT</envar></term> + + <listitem> + <para> + Default port number (preferably set in the configuration file) + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <refsect1> + <title>Diagnostics</title> + + <para> + A failure message mentioning <literal>semget</literal> or + <literal>shmget</literal> probably indicates you need to configure your + kernel to provide adequate shared memory and semaphores. For more + discussion see <xref linkend="kernel-resources"/>. You might be able + to postpone reconfiguring your kernel by decreasing <xref + linkend="guc-shared-buffers"/> to reduce the shared memory + consumption of <productname>PostgreSQL</productname>, and/or by reducing + <xref linkend="guc-max-connections"/> to reduce the semaphore + consumption. + </para> + + <para> + A failure message suggesting that another server is already running + should be checked carefully, for example by using the command +<screen> +<prompt>$</prompt> <userinput>ps ax | grep postgres</userinput> +</screen> + or +<screen> +<prompt>$</prompt> <userinput>ps -ef | grep postgres</userinput> +</screen> + depending on your system. If you are certain that no conflicting + server is running, you can remove the lock file mentioned in the + message and try again. + </para> + + <para> + A failure message indicating inability to bind to a port might + indicate that that port is already in use by some + non-<productname>PostgreSQL</productname> process. You might also + get this error if you terminate <command>postgres</command> + and immediately restart it using the same port; in this case, you + must simply wait a few seconds until the operating system closes + the port before trying again. Finally, you might get this error if + you specify a port number that your operating system considers to + be reserved. For example, many versions of Unix consider port + numbers under 1024 to be <quote>trusted</quote> and only permit + the Unix superuser to access them. + </para> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The utility command <xref linkend="app-pg-ctl"/> can be used to + start and shut down the <command>postgres</command> server + safely and comfortably. + </para> + + <para> + If at all possible, <emphasis>do not</emphasis> use + <literal>SIGKILL</literal> to kill the main + <command>postgres</command> server. Doing so will prevent + <command>postgres</command> from freeing the system + resources (e.g., shared memory and semaphores) that it holds before + terminating. This might cause problems for starting a fresh + <command>postgres</command> run. + </para> + + <para> + To terminate the <command>postgres</command> server normally, the + signals <literal>SIGTERM</literal>, <literal>SIGINT</literal>, or + <literal>SIGQUIT</literal> can be used. The first will wait for + all clients to terminate before quitting, the second will + forcefully disconnect all clients, and the third will quit + immediately without proper shutdown, resulting in a recovery run + during restart. + </para> + + <para> + The <literal>SIGHUP</literal> signal will reload + the server configuration files. It is also possible to send + <literal>SIGHUP</literal> to an individual server process, but that + is usually not sensible. + </para> + + <para> + To cancel a running query, send the <literal>SIGINT</literal> signal + to the process running that command. To terminate a backend process + cleanly, send <literal>SIGTERM</literal> to that process. See + also <function>pg_cancel_backend</function> and <function>pg_terminate_backend</function> + in <xref linkend="functions-admin-signal"/> for the SQL-callable equivalents + of these two actions. + </para> + + <para> + The <command>postgres</command> server uses <literal>SIGQUIT</literal> + to tell subordinate server processes to terminate without normal + cleanup. + This signal <emphasis>should not</emphasis> be used by users. It + is also unwise to send <literal>SIGKILL</literal> to a server + process — the main <command>postgres</command> process will + interpret this as a crash and will force all the sibling processes + to quit as part of its standard crash-recovery procedure. + </para> + </refsect1> + + <refsect1 id="app-postgres-bugs"> + <title>Bugs</title> + <para> + The <option>--</option> options will not work on <systemitem + class="osname">FreeBSD</systemitem> or <systemitem class="osname">OpenBSD</systemitem>. + Use <option>-c</option> instead. This is a bug in the affected operating + systems; a future release of <productname>PostgreSQL</productname> + will provide a workaround if this is not fixed. + </para> + </refsect1> + + <refsect1 id="app-postgres-single-user" xreflabel="Single-User Mode"> + <title>Single-User Mode</title> + + <para> + To start a single-user mode server, use a command like +<screen> +<userinput>postgres --single -D /usr/local/pgsql/data <replaceable>other-options</replaceable> my_database</userinput> +</screen> + Provide the correct path to the database directory with <option>-D</option>, or + make sure that the environment variable <envar>PGDATA</envar> is set. + Also specify the name of the particular database you want to work in. + </para> + + <para> + Normally, the single-user mode server treats newline as the command + entry terminator; there is no intelligence about semicolons, + as there is in <application>psql</application>. To continue a command + across multiple lines, you must type backslash just before each + newline except the last one. The backslash and adjacent newline are + both dropped from the input command. Note that this will happen even + when within a string literal or comment. + </para> + + <para> + But if you use the <option>-j</option> command line switch, a single newline + does not terminate command entry; instead, the sequence + semicolon-newline-newline does. That is, type a semicolon immediately + followed by a completely empty line. Backslash-newline is not + treated specially in this mode. Again, there is no intelligence about + such a sequence appearing within a string literal or comment. + </para> + + <para> + In either input mode, if you type a semicolon that is not just before or + part of a command entry terminator, it is considered a command separator. + When you do type a command entry terminator, the multiple statements + you've entered will be executed as a single transaction. + </para> + + <para> + To quit the session, type <acronym>EOF</acronym> + (<keycombo action="simul"><keycap>Control</keycap><keycap>D</keycap></keycombo>, usually). + If you've entered any text since the last command entry terminator, + then <acronym>EOF</acronym> will be taken as a command entry terminator, + and another <acronym>EOF</acronym> will be needed to exit. + </para> + + <para> + Note that the single-user mode server does not provide sophisticated + line-editing features (no command history, for example). + Single-user mode also does not do any background processing, such as + automatic checkpoints or replication. + </para> + </refsect1> + + <refsect1 id="app-postgres-examples"> + <title>Examples</title> + + <para> + To start <command>postgres</command> in the background + using default values, type: + +<screen> +<prompt>$</prompt> <userinput>nohup postgres >logfile 2>&1 </dev/null &</userinput> +</screen> + </para> + + <para> + To start <command>postgres</command> with a specific + port, e.g., 1234: +<screen> +<prompt>$</prompt> <userinput>postgres -p 1234</userinput> +</screen> + To connect to this server using <application>psql</application>, specify this port with the -p option: +<screen> +<prompt>$</prompt> <userinput>psql -p 1234</userinput> +</screen> + or set the environment variable <envar>PGPORT</envar>: +<screen> +<prompt>$</prompt> <userinput>export PGPORT=1234</userinput> +<prompt>$</prompt> <userinput>psql</userinput> +</screen> + </para> + + <para> + Named run-time parameters can be set in either of these styles: +<screen> +<prompt>$</prompt> <userinput>postgres -c work_mem=1234</userinput> +<prompt>$</prompt> <userinput>postgres --work-mem=1234</userinput> +</screen> + Either form overrides whatever setting might exist for + <varname>work_mem</varname> in <filename>postgresql.conf</filename>. Notice that + underscores in parameter names can be written as either underscore + or dash on the command line. Except for short-term experiments, + it's probably better practice to edit the setting in + <filename>postgresql.conf</filename> than to rely on a command-line switch + to set a parameter. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <xref linkend="app-initdb"/>, + <xref linkend="app-pg-ctl"/> + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/postmaster.sgml b/doc/src/sgml/ref/postmaster.sgml new file mode 100644 index 0000000..7b544ed --- /dev/null +++ b/doc/src/sgml/ref/postmaster.sgml @@ -0,0 +1,44 @@ +<!-- +doc/src/sgml/ref/postmaster.sgml +PostgreSQL documentation +--> + +<refentry id="app-postmaster"> + <indexterm zone="app-postmaster"> + <primary>postmaster</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>postmaster</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>postmaster</refname> + <refpurpose><productname>PostgreSQL</productname> database server</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>postmaster</command> + <arg rep="repeat"><replaceable>option</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>postmaster</command> is a deprecated alias of <command>postgres</command>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <xref linkend="app-postgres"/> + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/prepare.sgml b/doc/src/sgml/ref/prepare.sgml new file mode 100644 index 0000000..d7b8539 --- /dev/null +++ b/doc/src/sgml/ref/prepare.sgml @@ -0,0 +1,258 @@ +<!-- +doc/src/sgml/ref/prepare.sgml +PostgreSQL documentation +--> + +<refentry id="sql-prepare"> + <indexterm zone="sql-prepare"> + <primary>PREPARE</primary> + </indexterm> + + <indexterm zone="sql-prepare"> + <primary>prepared statements</primary> + <secondary>creating</secondary> + </indexterm> + + <refmeta> + <refentrytitle>PREPARE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>PREPARE</refname> + <refpurpose>prepare a statement for execution</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +PREPARE <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">data_type</replaceable> [, ...] ) ] AS <replaceable class="parameter">statement</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>PREPARE</command> creates a prepared statement. A prepared + statement is a server-side object that can be used to optimize + performance. When the <command>PREPARE</command> statement is + executed, the specified statement is parsed, analyzed, and rewritten. + When an <command>EXECUTE</command> command is subsequently + issued, the prepared statement is planned and executed. This division + of labor avoids repetitive parse analysis work, while allowing + the execution plan to depend on the specific parameter values supplied. + </para> + + <para> + Prepared statements can take parameters: values that are + substituted into the statement when it is executed. When creating + the prepared statement, refer to parameters by position, using + <literal>$1</literal>, <literal>$2</literal>, etc. A corresponding list of + parameter data types can optionally be specified. When a + parameter's data type is not specified or is declared as + <literal>unknown</literal>, the type is inferred from the context + in which the parameter is first referenced (if possible). When executing the + statement, specify the actual values for these parameters in the + <command>EXECUTE</command> statement. Refer to <xref + linkend="sql-execute"/> for more + information about that. + </para> + + <para> + Prepared statements only last for the duration of the current + database session. When the session ends, the prepared statement is + forgotten, so it must be recreated before being used again. This + also means that a single prepared statement cannot be used by + multiple simultaneous database clients; however, each client can create + their own prepared statement to use. Prepared statements can be + manually cleaned up using the <link linkend="sql-deallocate"><command>DEALLOCATE</command></link> command. + </para> + + <para> + Prepared statements potentially have the largest performance advantage + when a single session is being used to execute a large number of similar + statements. The performance difference will be particularly + significant if the statements are complex to plan or rewrite, e.g., + if the query involves a join of many tables or requires + the application of several rules. If the statement is relatively simple + to plan and rewrite but relatively expensive to execute, the + performance advantage of prepared statements will be less noticeable. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + An arbitrary name given to this particular prepared + statement. It must be unique within a single session and is + subsequently used to execute or deallocate a previously prepared + statement. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">data_type</replaceable></term> + <listitem> + <para> + The data type of a parameter to the prepared statement. If the + data type of a particular parameter is unspecified or is + specified as <literal>unknown</literal>, it will be inferred + from the context in which the parameter is first referenced. To refer to the + parameters in the prepared statement itself, use + <literal>$1</literal>, <literal>$2</literal>, etc. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">statement</replaceable></term> + <listitem> + <para> + Any <command>SELECT</command>, <command>INSERT</command>, <command>UPDATE</command>, + <command>DELETE</command>, <command>MERGE</command>, or <command>VALUES</command> + statement. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1 id="sql-prepare-notes"> + <title>Notes</title> + + <para> + A prepared statement can be executed with either a <firstterm>generic + plan</firstterm> or a <firstterm>custom plan</firstterm>. A generic + plan is the same across all executions, while a custom plan is generated + for a specific execution using the parameter values given in that call. + Use of a generic plan avoids planning overhead, but in some situations + a custom plan will be much more efficient to execute because the planner + can make use of knowledge of the parameter values. (Of course, if the + prepared statement has no parameters, then this is moot and a generic + plan is always used.) + </para> + + <para> + By default (that is, when <xref linkend="guc-plan-cache_mode"/> is set + to <literal>auto</literal>), the server will automatically choose + whether to use a generic or custom plan for a prepared statement that + has parameters. The current rule for this is that the first five + executions are done with custom plans and the average estimated cost of + those plans is calculated. Then a generic plan is created and its + estimated cost is compared to the average custom-plan cost. Subsequent + executions use the generic plan if its cost is not so much higher than + the average custom-plan cost as to make repeated replanning seem + preferable. + </para> + + <para> + This heuristic can be overridden, forcing the server to use either + generic or custom plans, by setting <varname>plan_cache_mode</varname> + to <literal>force_generic_plan</literal> + or <literal>force_custom_plan</literal> respectively. + This setting is primarily useful if the generic plan's cost estimate + is badly off for some reason, allowing it to be chosen even though + its actual cost is much more than that of a custom plan. + </para> + + <para> + To examine the query plan <productname>PostgreSQL</productname> is using + for a prepared statement, use <link linkend="sql-explain"><command>EXPLAIN</command></link>, for example +<programlisting> +EXPLAIN EXECUTE <replaceable>name</replaceable>(<replaceable>parameter_values</replaceable>); +</programlisting> + If a generic plan is in use, it will contain parameter symbols + <literal>$<replaceable>n</replaceable></literal>, while a custom plan + will have the supplied parameter values substituted into it. + </para> + + <para> + For more information on query planning and the statistics collected + by <productname>PostgreSQL</productname> for that purpose, see + the <xref linkend="sql-analyze"/> + documentation. + </para> + + <para> + Although the main point of a prepared statement is to avoid repeated parse + analysis and planning of the statement, <productname>PostgreSQL</productname> will + force re-analysis and re-planning of the statement before using it + whenever database objects used in the statement have undergone + definitional (DDL) changes or their planner statistics have + been updated since the previous use of the prepared + statement. Also, if the value of <xref linkend="guc-search-path"/> changes + from one use to the next, the statement will be re-parsed using the new + <varname>search_path</varname>. (This latter behavior is new as of + <productname>PostgreSQL</productname> 9.3.) These rules make use of a + prepared statement semantically almost equivalent to re-submitting the + same query text over and over, but with a performance benefit if no object + definitions are changed, especially if the best plan remains the same + across uses. An example of a case where the semantic equivalence is not + perfect is that if the statement refers to a table by an unqualified name, + and then a new table of the same name is created in a schema appearing + earlier in the <varname>search_path</varname>, no automatic re-parse will occur + since no object used in the statement changed. However, if some other + change forces a re-parse, the new table will be referenced in subsequent + uses. + </para> + + <para> + You can see all prepared statements available in the session by querying the + <link linkend="view-pg-prepared-statements"><structname>pg_prepared_statements</structname></link> + system view. + </para> + </refsect1> + + <refsect1 id="sql-prepare-examples" xreflabel="Examples"> + <title>Examples</title> + <para> + Create a prepared statement for an <command>INSERT</command> + statement, and then execute it: +<programlisting> +PREPARE fooplan (int, text, bool, numeric) AS + INSERT INTO foo VALUES($1, $2, $3, $4); +EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00); +</programlisting> + </para> + + <para> + Create a prepared statement for a <command>SELECT</command> + statement, and then execute it: +<programlisting> +PREPARE usrrptplan (int) AS + SELECT * FROM users u, logs l WHERE u.usrid=$1 AND u.usrid=l.usrid + AND l.date = $2; +EXECUTE usrrptplan(1, current_date); +</programlisting> + + In this example, the data type of the second parameter is not specified, + so it is inferred from the context in which <literal>$2</literal> is used. + </para> + </refsect1> + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard includes a <command>PREPARE</command> statement, + but it is only for use in embedded SQL. This version of the + <command>PREPARE</command> statement also uses a somewhat different + syntax. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-deallocate"/></member> + <member><xref linkend="sql-execute"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/prepare_transaction.sgml b/doc/src/sgml/ref/prepare_transaction.sgml new file mode 100644 index 0000000..f4f6118 --- /dev/null +++ b/doc/src/sgml/ref/prepare_transaction.sgml @@ -0,0 +1,181 @@ +<!-- +doc/src/sgml/ref/prepare_transaction.sgml +PostgreSQL documentation +--> + +<refentry id="sql-prepare-transaction"> + <indexterm zone="sql-prepare-transaction"> + <primary>PREPARE TRANSACTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>PREPARE TRANSACTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>PREPARE TRANSACTION</refname> + <refpurpose>prepare the current transaction for two-phase commit</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +PREPARE TRANSACTION <replaceable class="parameter">transaction_id</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>PREPARE TRANSACTION</command> prepares the current transaction + for two-phase commit. After this command, the transaction is no longer + associated with the current session; instead, its state is fully stored on + disk, and there is a very high probability that it can be committed + successfully, even if a database crash occurs before the commit is + requested. + </para> + + <para> + Once prepared, a transaction can later be committed or rolled back + with <link linkend="sql-commit-prepared"><command>COMMIT PREPARED</command></link> + or <link linkend="sql-rollback-prepared"><command>ROLLBACK PREPARED</command></link>, + respectively. Those commands can be issued from any session, not + only the one that executed the original transaction. + </para> + + <para> + From the point of view of the issuing session, <command>PREPARE + TRANSACTION</command> is not unlike a <command>ROLLBACK</command> command: + after executing it, there is no active current transaction, and the + effects of the prepared transaction are no longer visible. (The effects + will become visible again if the transaction is committed.) + </para> + + <para> + If the <command>PREPARE TRANSACTION</command> command fails for any + reason, it becomes a <command>ROLLBACK</command>: the current transaction + is canceled. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">transaction_id</replaceable></term> + <listitem> + <para> + An arbitrary identifier that later identifies this transaction for + <command>COMMIT PREPARED</command> or <command>ROLLBACK PREPARED</command>. + The identifier must be written as a string literal, and must be + less than 200 bytes long. It must not be the same as the identifier + used for any currently prepared transaction. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>PREPARE TRANSACTION</command> is not intended for use in applications + or interactive sessions. Its purpose is to allow an external + transaction manager to perform atomic global transactions across multiple + databases or other transactional resources. Unless you're writing a + transaction manager, you probably shouldn't be using <command>PREPARE + TRANSACTION</command>. + </para> + + <para> + This command must be used inside a transaction block. Use <link + linkend="sql-begin"><command>BEGIN</command></link> to start one. + </para> + + <para> + It is not currently allowed to <command>PREPARE</command> a transaction that + has executed any operations involving temporary tables or the session's + temporary namespace, created any cursors <literal>WITH HOLD</literal>, or + executed <command>LISTEN</command>, <command>UNLISTEN</command>, or + <command>NOTIFY</command>. + Those features are too tightly + tied to the current session to be useful in a transaction to be prepared. + </para> + + <para> + If the transaction modified any run-time parameters with <command>SET</command> + (without the <literal>LOCAL</literal> option), + those effects persist after <command>PREPARE TRANSACTION</command>, and will not + be affected by any later <command>COMMIT PREPARED</command> or + <command>ROLLBACK PREPARED</command>. Thus, in this one respect + <command>PREPARE TRANSACTION</command> acts more like <command>COMMIT</command> than + <command>ROLLBACK</command>. + </para> + + <para> + All currently available prepared transactions are listed in the + <link linkend="view-pg-prepared-xacts"><structname>pg_prepared_xacts</structname></link> + system view. + </para> + + <caution> + <para> + It is unwise to leave transactions in the prepared state for a long time. + This will interfere with the ability of <command>VACUUM</command> to reclaim + storage, and in extreme cases could cause the database to shut down + to prevent transaction ID wraparound (see <xref + linkend="vacuum-for-wraparound"/>). Keep in mind also that the transaction + continues to hold whatever locks it held. The intended usage of the + feature is that a prepared transaction will normally be committed or + rolled back as soon as an external transaction manager has verified that + other databases are also prepared to commit. + </para> + + <para> + If you have not set up an external transaction manager to track prepared + transactions and ensure they get closed out promptly, it is best to keep + the prepared-transaction feature disabled by setting + <xref linkend="guc-max-prepared-transactions"/> to zero. This will + prevent accidental creation of prepared transactions that might then + be forgotten and eventually cause problems. + </para> + </caution> + </refsect1> + + <refsect1 id="sql-prepare-transaction-examples"> + <title>Examples</title> + <para> + Prepare the current transaction for two-phase commit, using + <literal>foobar</literal> as the transaction identifier: + +<programlisting> +PREPARE TRANSACTION 'foobar'; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>PREPARE TRANSACTION</command> is a + <productname>PostgreSQL</productname> extension. It is intended for use by + external transaction management systems, some of which are covered by + standards (such as X/Open XA), but the SQL side of those systems is not + standardized. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-commit-prepared"/></member> + <member><xref linkend="sql-rollback-prepared"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml new file mode 100644 index 0000000..d0bd119 --- /dev/null +++ b/doc/src/sgml/ref/psql-ref.sgml @@ -0,0 +1,5187 @@ +<!-- +doc/src/sgml/ref/psql-ref.sgml +PostgreSQL documentation +--> + +<refentry id="app-psql"> + <indexterm zone="app-psql"> + <primary>psql</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>psql</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname><application>psql</application></refname> + <refpurpose> + <productname>PostgreSQL</productname> interactive terminal + </refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>psql</command> + <arg rep="repeat"><replaceable class="parameter">option</replaceable></arg> + <arg choice="opt"><replaceable class="parameter">dbname</replaceable> + <arg choice="opt"><replaceable class="parameter">username</replaceable></arg></arg> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>psql</application> is a terminal-based front-end to + <productname>PostgreSQL</productname>. It enables you to type in + queries interactively, issue them to + <productname>PostgreSQL</productname>, and see the query results. + Alternatively, input can be from a file or from command line + arguments. In addition, <application>psql</application> provides a + number of meta-commands and various shell-like features to + facilitate writing scripts and automating a wide variety of tasks. + </para> + </refsect1> + + <refsect1 id="r1-app-psql-3"> + <title>Options</title> + + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--echo-all</option></term> + <listitem> + <para> + Print all nonempty input lines to standard output as they are read. + (This does not apply to lines read interactively.) This is + equivalent to setting the variable <varname>ECHO</varname> to + <literal>all</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-A</option></term> + <term><option>--no-align</option></term> + <listitem> + <para> + Switches to unaligned output mode. (The default output mode is + <literal>aligned</literal>.) This is equivalent to + <command>\pset format unaligned</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-b</option></term> + <term><option>--echo-errors</option></term> + <listitem> + <para> + Print failed SQL commands to standard error output. This is + equivalent to setting the variable <varname>ECHO</varname> to + <literal>errors</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c <replaceable class="parameter">command</replaceable></option></term> + <term><option>--command=<replaceable class="parameter">command</replaceable></option></term> + <listitem> + <para> + Specifies that <application>psql</application> is to execute the given + command string, <replaceable class="parameter">command</replaceable>. + This option can be repeated and combined in any order with + the <option>-f</option> option. When either <option>-c</option> + or <option>-f</option> is specified, <application>psql</application> + does not read commands from standard input; instead it terminates + after processing all the <option>-c</option> and <option>-f</option> + options in sequence. + </para> + <para> + <replaceable class="parameter">command</replaceable> must be either + a command string that is completely parsable by the server (i.e., + it contains no <application>psql</application>-specific features), + or a single backslash command. Thus you cannot mix + <acronym>SQL</acronym> and <application>psql</application> + meta-commands within a <option>-c</option> option. To achieve that, + you could use repeated <option>-c</option> options or pipe the string + into <application>psql</application>, for example: +<programlisting> +psql -c '\x' -c 'SELECT * FROM foo;' +</programlisting> + or +<programlisting> +echo '\x \\ SELECT * FROM foo;' | psql +</programlisting> + (<literal>\\</literal> is the separator meta-command.) + </para> + <para> + Each <acronym>SQL</acronym> command string passed + to <option>-c</option> is sent to the server as a single request. + Because of this, the server executes it as a single transaction even + if the string contains multiple <acronym>SQL</acronym> commands, + unless there are explicit <command>BEGIN</command>/<command>COMMIT</command> + commands included in the string to divide it into multiple + transactions. (See <xref linkend="protocol-flow-multi-statement"/> + for more details about how the server handles multi-query strings.) + </para> + <para> + If having several commands executed in one transaction is not desired, + use repeated <option>-c</option> commands or feed multiple commands to + <application>psql</application>'s standard input, + either using <application>echo</application> as illustrated above, or + via a shell here-document, for example: +<programlisting> +psql <<EOF +\x +SELECT * FROM foo; +EOF +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--csv</option></term> + <listitem> + <para> + Switches to <acronym>CSV</acronym> (Comma-Separated Values) output + mode. This is equivalent to <command>\pset format csv</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-d <replaceable class="parameter">dbname</replaceable></option></term> + <term><option>--dbname=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to. This is + equivalent to specifying <replaceable + class="parameter">dbname</replaceable> as the first non-option + argument on the command line. The <replaceable>dbname</replaceable> + can be a <link linkend="libpq-connstring">connection string</link>. + If so, connection string parameters will override any conflicting + command line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo-queries</option></term> + <listitem> + <para> + Copy all SQL commands sent to the server to standard output as well. + This is equivalent + to setting the variable <varname>ECHO</varname> to + <literal>queries</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-E</option></term> + <term><option>--echo-hidden</option></term> + <listitem> + <para> + Echo the actual queries generated by <command>\d</command> and other backslash + commands. You can use this to study <application>psql</application>'s + internal operations. This is equivalent to + setting the variable <varname>ECHO_HIDDEN</varname> to <literal>on</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f <replaceable class="parameter">filename</replaceable></option></term> + <term><option>--file=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Read commands from the + file <replaceable class="parameter">filename</replaceable>, + rather than standard input. + This option can be repeated and combined in any order with + the <option>-c</option> option. When either <option>-c</option> + or <option>-f</option> is specified, <application>psql</application> + does not read commands from standard input; instead it terminates + after processing all the <option>-c</option> and <option>-f</option> + options in sequence. + Except for that, this option is largely equivalent to the + meta-command <command>\i</command>. + </para> + + <para> + If <replaceable>filename</replaceable> is <literal>-</literal> + (hyphen), then standard input is read until an EOF indication + or <command>\q</command> meta-command. This can be used to intersperse + interactive input with input from files. Note however that Readline + is not used in this case (much as if <option>-n</option> had been + specified). + </para> + + <para> + Using this option is subtly different from writing <literal>psql + < <replaceable + class="parameter">filename</replaceable></literal>. In general, + both will do what you expect, but using <literal>-f</literal> + enables some nice features such as error messages with line + numbers. There is also a slight chance that using this option will + reduce the start-up overhead. On the other hand, the variant using + the shell's input redirection is (in theory) guaranteed to yield + exactly the same output you would have received had you entered + everything by hand. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F <replaceable class="parameter">separator</replaceable></option></term> + <term><option>--field-separator=<replaceable class="parameter">separator</replaceable></option></term> + <listitem> + <para> + Use <replaceable class="parameter">separator</replaceable> as the + field separator for unaligned output. This is equivalent to + <command>\pset fieldsep</command> or <command>\f</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-h <replaceable class="parameter">hostname</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">hostname</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the + server is running. If the value begins + with a slash, it is used as the directory for the Unix-domain + socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-H</option></term> + <term><option>--html</option></term> + <listitem> + <para> + Switches to <acronym>HTML</acronym> output mode. This is + equivalent to <command>\pset format html</command> or the + <command>\H</command> command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <term><option>--list</option></term> + <listitem> + <para> + List all available databases, then exit. Other non-connection + options are ignored. This is similar to the meta-command + <command>\list</command>. + </para> + + <para> + When this option is used, <application>psql</application> will connect + to the database <literal>postgres</literal>, unless a different database + is named on the command line (option <option>-d</option> or non-option + argument, possibly via a service entry, but not via an environment + variable). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-L <replaceable class="parameter">filename</replaceable></option></term> + <term><option>--log-file=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Write all query output into file <replaceable + class="parameter">filename</replaceable>, in addition to the + normal output destination. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-n</option></term> + <term><option>--no-readline</option></term> + <listitem> + <para> + Do not use <application>Readline</application> for line editing and + do not use the command history (see + <xref linkend="app-psql-readline"/> below). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-o <replaceable class="parameter">filename</replaceable></option></term> + <term><option>--output=<replaceable class="parameter">filename</replaceable></option></term> + <listitem> + <para> + Put all query output into file <replaceable + class="parameter">filename</replaceable>. This is equivalent to + the command <command>\o</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or the local Unix-domain + socket file extension on which the server is listening for + connections. Defaults to the value of the <envar>PGPORT</envar> + environment variable or, if not set, to the port specified at + compile time, usually 5432. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P <replaceable class="parameter">assignment</replaceable></option></term> + <term><option>--pset=<replaceable class="parameter">assignment</replaceable></option></term> + <listitem> + <para> + Specifies printing options, in the style of + <command>\pset</command>. Note that here you + have to separate name and value with an equal sign instead of a + space. For example, to set the output format to <application>LaTeX</application>, you could write + <literal>-P format=latex</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Specifies that <application>psql</application> should do its work + quietly. By default, it prints welcome messages and various + informational output. If this option is used, none of this + happens. This is useful with the <option>-c</option> option. + This is equivalent to setting the variable <varname>QUIET</varname> + to <literal>on</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-R <replaceable class="parameter">separator</replaceable></option></term> + <term><option>--record-separator=<replaceable class="parameter">separator</replaceable></option></term> + <listitem> + <para> + Use <replaceable class="parameter">separator</replaceable> as the + record separator for unaligned output. This is equivalent to + <command>\pset recordsep</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--single-step</option></term> + <listitem> + <para> + Run in single-step mode. That means the user is prompted before + each command is sent to the server, with the option to cancel + execution as well. Use this to debug scripts. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S</option></term> + <term><option>--single-line</option></term> + <listitem> + <para> + Runs in single-line mode where a newline terminates an SQL command, as a + semicolon does. + </para> + + <note> + <para> + This mode is provided for those who insist on it, but you are not + necessarily encouraged to use it. In particular, if you mix + <acronym>SQL</acronym> and meta-commands on a line the order of + execution might not always be clear to the inexperienced user. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t</option></term> + <term><option>--tuples-only</option></term> + <listitem> + <para> + Turn off printing of column names and result row count footers, + etc. This is equivalent to <command>\t</command> or + <command>\pset tuples_only</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-T <replaceable class="parameter">table_options</replaceable></option></term> + <term><option>--table-attr=<replaceable class="parameter">table_options</replaceable></option></term> + <listitem> + <para> + Specifies options to be placed within the + <acronym>HTML</acronym> <sgmltag>table</sgmltag> tag. See + <command>\pset tableattr</command> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + Connect to the database as the user <replaceable + class="parameter">username</replaceable> instead of the default. + (You must have permission to do so, of course.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v <replaceable class="parameter">assignment</replaceable></option></term> + <term><option>--set=<replaceable class="parameter">assignment</replaceable></option></term> + <term><option>--variable=<replaceable class="parameter">assignment</replaceable></option></term> + <listitem> + <para> + Perform a variable assignment, like the <command>\set</command> + meta-command. Note that you must separate name and value, if + any, by an equal sign on the command line. To unset a variable, + leave off the equal sign. To set a variable with an empty value, + use the equal sign but leave off the value. These assignments are + done during command line processing, so variables that reflect + connection state will get overwritten later. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>psql</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires password + authentication and a password is not available from other sources + such as a <filename>.pgpass</filename> file, the connection + attempt will fail. This option can be useful in batch jobs and + scripts where no user is present to enter a password. + </para> + + <para> + Note that this option will remain set for the entire session, + and so it affects uses of the meta-command + <command>\connect</command> as well as the initial connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>psql</application> to prompt for a + password before connecting to a database, even if the password will + not be used. + </para> + + <para> + If the server requires password authentication and a password is not + available from other sources such as a <filename>.pgpass</filename> + file, <application>psql</application> will prompt for a + password in any case. However, <application>psql</application> + will waste a connection attempt finding out that the server wants a + password. In some cases it is worth typing <option>-W</option> to avoid + the extra connection attempt. + </para> + + <para> + Note that this option will remain set for the entire session, + and so it affects uses of the meta-command + <command>\connect</command> as well as the initial connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option></term> + <term><option>--expanded</option></term> + <listitem> + <para> + Turn on the expanded table formatting mode. This is equivalent to + <command>\x</command> or <command>\pset expanded</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-X,</option></term> + <term><option>--no-psqlrc</option></term> + <listitem> + <para> + Do not read the start-up file (neither the system-wide + <filename>psqlrc</filename> file nor the user's + <filename>~/.psqlrc</filename> file). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-z</option></term> + <term><option>--field-separator-zero</option></term> + <listitem> + <para> + Set the field separator for unaligned output to a zero byte. This is + equivalent to <command>\pset fieldsep_zero</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-0</option></term> + <term><option>--record-separator-zero</option></term> + <listitem> + <para> + Set the record separator for unaligned output to a zero byte. This is + useful for interfacing, for example, with <literal>xargs -0</literal>. + This is equivalent to <command>\pset recordsep_zero</command>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-1</option></term> + <term><option>--single-transaction</option></term> + <listitem> + <para> + This option can only be used in combination with one or more + <option>-c</option> and/or <option>-f</option> options. It causes + <application>psql</application> to issue a <command>BEGIN</command> command + before the first such option and a <command>COMMIT</command> command after + the last one, thereby wrapping all the commands into a single + transaction. If any of the commands fails and the variable + <varname>ON_ERROR_STOP</varname> was set, a + <command>ROLLBACK</command> command is sent instead. This ensures that + either all the commands complete successfully, or no changes are + applied. + </para> + + <para> + If the commands themselves + contain <command>BEGIN</command>, <command>COMMIT</command>, + or <command>ROLLBACK</command>, this option will not have the desired + effects. Also, if an individual command cannot be executed inside a + transaction block, specifying this option will cause the whole + transaction to fail. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help[=<replaceable class="parameter">topic</replaceable>]</option></term> + <listitem> + <para> + Show help about <application>psql</application> and exit. The optional + <replaceable class="parameter">topic</replaceable> parameter (defaulting + to <literal>options</literal>) selects which part of <application>psql</application> is + explained: <literal>commands</literal> describes <application>psql</application>'s + backslash commands; <literal>options</literal> describes the command-line + options that can be passed to <application>psql</application>; + and <literal>variables</literal> shows help about <application>psql</application> configuration + variables. + </para> + </listitem> + </varlistentry> + + </variablelist> + </refsect1> + + + <refsect1> + <title>Exit Status</title> + + <para> + <application>psql</application> returns 0 to the shell if it + finished normally, 1 if a fatal error of its own occurs (e.g., out of memory, + file not found), 2 if the connection to the server went bad + and the session was not interactive, and 3 if an error occurred in a + script and the variable <varname>ON_ERROR_STOP</varname> was set. + </para> + </refsect1> + + + <refsect1> + <title>Usage</title> + + <refsect2 id="r2-app-psql-connecting"> + <title>Connecting to a Database</title> + + <para> + <application>psql</application> is a regular + <productname>PostgreSQL</productname> client application. In order + to connect to a database you need to know the name of your target + database, the host name and port number of the server, and what user + name you want to connect as. <application>psql</application> can be + told about those parameters via command line options, namely + <option>-d</option>, <option>-h</option>, <option>-p</option>, and + <option>-U</option> respectively. If an argument is found that does + not belong to any option it will be interpreted as the database name + (or the user name, if the database name is already given). Not all + of these options are required; there are useful defaults. If you omit the host + name, <application>psql</application> will connect via a Unix-domain socket + to a server on the local host, or via TCP/IP to <literal>localhost</literal> on + machines that don't have Unix-domain sockets. The default port number is + determined at compile time. + Since the database server uses the same default, you will not have + to specify the port in most cases. The default user name is your + operating-system user name, as is the default database name. + Note that you cannot + just connect to any database under any user name. Your database + administrator should have informed you about your access rights. + </para> + + <para> + When the defaults aren't quite right, you can save yourself + some typing by setting the environment variables + <envar>PGDATABASE</envar>, <envar>PGHOST</envar>, + <envar>PGPORT</envar> and/or <envar>PGUSER</envar> to appropriate + values. (For additional environment variables, see <xref + linkend="libpq-envars"/>.) It is also convenient to have a + <filename>~/.pgpass</filename> file to avoid regularly having to type in + passwords. See <xref linkend="libpq-pgpass"/> for more information. + </para> + + <para> + An alternative way to specify connection parameters is in a + <parameter>conninfo</parameter> string or + a <acronym>URI</acronym>, which is used instead of a database + name. This mechanism give you very wide control over the + connection. For example: +<programlisting> +$ <userinput>psql "service=myservice sslmode=require"</userinput> +$ <userinput>psql postgresql://dbmaster:5433/mydb?sslmode=require</userinput> +</programlisting> + This way you can also use <acronym>LDAP</acronym> for connection + parameter lookup as described in <xref linkend="libpq-ldap"/>. + See <xref linkend="libpq-paramkeywords"/> for more information on all the + available connection options. + </para> + + <para> + If the connection could not be made for any reason (e.g., insufficient + privileges, server is not running on the targeted host, etc.), + <application>psql</application> will return an error and terminate. + </para> + + <para> + If both standard input and standard output are a + terminal, then <application>psql</application> sets the client + encoding to <quote>auto</quote>, which will detect the + appropriate client encoding from the locale settings + (<envar>LC_CTYPE</envar> environment variable on Unix systems). + If this doesn't work out as expected, the client encoding can be + overridden using the environment + variable <envar>PGCLIENTENCODING</envar>. + </para> + </refsect2> + + <refsect2 id="r2-app-psql-4"> + <title>Entering SQL Commands</title> + + <para> + In normal operation, <application>psql</application> provides a + prompt with the name of the database to which + <application>psql</application> is currently connected, followed by + the string <literal>=></literal>. For example: +<programlisting> +$ <userinput>psql testdb</userinput> +psql (&version;) +Type "help" for help. + +testdb=> +</programlisting> + </para> + + <para> + At the prompt, the user can type in <acronym>SQL</acronym> commands. + Ordinarily, input lines are sent to the server when a + command-terminating semicolon is reached. An end of line does not + terminate a command. Thus commands can be spread over several lines for + clarity. If the command was sent and executed without error, the results + of the command are displayed on the screen. + </para> + + <para> + If untrusted users have access to a database that has not adopted a + <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>, + begin your session by removing publicly-writable schemas + from <varname>search_path</varname>. One can + add <literal>options=-csearch_path=</literal> to the connection string or + issue <literal>SELECT pg_catalog.set_config('search_path', '', + false)</literal> before other SQL commands. This consideration is not + specific to <application>psql</application>; it applies to every interface + for executing arbitrary SQL commands. + </para> + + <para> + Whenever a command is executed, <application>psql</application> also polls + for asynchronous notification events generated by + <link linkend="sql-listen"><command>LISTEN</command></link> and + <link linkend="sql-notify"><command>NOTIFY</command></link>. + </para> + + <para> + While C-style block comments are passed to the server for + processing and removal, SQL-standard comments are removed by + <application>psql</application>. + </para> + </refsect2> + + <refsect2 id="app-psql-meta-commands"> + <title>Meta-Commands</title> + + <para> + Anything you enter in <application>psql</application> that begins + with an unquoted backslash is a <application>psql</application> + meta-command that is processed by <application>psql</application> + itself. These commands make + <application>psql</application> more useful for administration or + scripting. Meta-commands are often called slash or backslash commands. + </para> + + <para> + The format of a <application>psql</application> command is the backslash, + followed immediately by a command verb, then any arguments. The arguments + are separated from the command verb and each other by any number of + whitespace characters. + </para> + + <para> + To include whitespace in an argument you can quote it with + single quotes. To include a single quote in an argument, + write two single quotes within single-quoted text. + Anything contained in single quotes is + furthermore subject to C-like substitutions for + <literal>\n</literal> (new line), <literal>\t</literal> (tab), + <literal>\b</literal> (backspace), <literal>\r</literal> (carriage return), + <literal>\f</literal> (form feed), + <literal>\</literal><replaceable>digits</replaceable> (octal), and + <literal>\x</literal><replaceable>digits</replaceable> (hexadecimal). + A backslash preceding any other character within single-quoted text + quotes that single character, whatever it is. + </para> + + <para> + If an unquoted colon (<literal>:</literal>) followed by a + <application>psql</application> variable name appears within an argument, it is + replaced by the variable's value, as described in <xref + linkend="app-psql-interpolation"/> below. + The forms <literal>:'<replaceable>variable_name</replaceable>'</literal> and + <literal>:"<replaceable>variable_name</replaceable>"</literal> described there + work as well. + The <literal>:{?<replaceable>variable_name</replaceable>}</literal> syntax allows + testing whether a variable is defined. It is substituted by + TRUE or FALSE. + Escaping the colon with a backslash protects it from substitution. + </para> + + <para> + Within an argument, text that is enclosed in backquotes + (<literal>`</literal>) is taken as a command line that is passed to the + shell. The output of the command (with any trailing newline removed) + replaces the backquoted text. Within the text enclosed in backquotes, + no special quoting or other processing occurs, except that appearances + of <literal>:<replaceable>variable_name</replaceable></literal> where + <replaceable>variable_name</replaceable> is a <application>psql</application> variable name + are replaced by the variable's value. Also, appearances of + <literal>:'<replaceable>variable_name</replaceable>'</literal> are replaced by the + variable's value suitably quoted to become a single shell command + argument. (The latter form is almost always preferable, unless you are + very sure of what is in the variable.) Because carriage return and line + feed characters cannot be safely quoted on all platforms, the + <literal>:'<replaceable>variable_name</replaceable>'</literal> form prints an + error message and does not substitute the variable value when such + characters appear in the value. + </para> + + <para> + Some commands take an <acronym>SQL</acronym> identifier (such as a + table name) as argument. These arguments follow the syntax rules + of <acronym>SQL</acronym>: Unquoted letters are forced to + lowercase, while double quotes (<literal>"</literal>) protect letters + from case conversion and allow incorporation of whitespace into + the identifier. Within double quotes, paired double quotes reduce + to a single double quote in the resulting name. For example, + <literal>FOO"BAR"BAZ</literal> is interpreted as <literal>fooBARbaz</literal>, + and <literal>"A weird"" name"</literal> becomes <literal>A weird" + name</literal>. + </para> + + <para> + Parsing for arguments stops at the end of the line, or when another + unquoted backslash is found. An unquoted backslash + is taken as the beginning of a new meta-command. The special + sequence <literal>\\</literal> (two backslashes) marks the end of + arguments and continues parsing <acronym>SQL</acronym> commands, if + any. That way <acronym>SQL</acronym> and + <application>psql</application> commands can be freely mixed on a + line. But in any case, the arguments of a meta-command cannot + continue beyond the end of the line. + </para> + + <para> + Many of the meta-commands act on the <firstterm>current query buffer</firstterm>. + This is simply a buffer holding whatever SQL command text has been typed + but not yet sent to the server for execution. This will include previous + input lines as well as any text appearing before the meta-command on the + same line. + </para> + + <para> + The following meta-commands are defined: + + <variablelist> + <varlistentry> + <term><literal>\a</literal></term> + <listitem> + <para> + If the current table output format is unaligned, it is switched to aligned. + If it is not unaligned, it is set to unaligned. This command is + kept for backwards compatibility. See <command>\pset</command> for a + more general solution. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\c</literal> or <literal>\connect [ -reuse-previous=<replaceable class="parameter">on|off</replaceable> ] [ <replaceable class="parameter">dbname</replaceable> [ <replaceable class="parameter">username</replaceable> ] [ <replaceable class="parameter">host</replaceable> ] [ <replaceable class="parameter">port</replaceable> ] | <replaceable class="parameter">conninfo</replaceable> ]</literal></term> + <listitem> + <para> + Establishes a new connection to a <productname>PostgreSQL</productname> + server. The connection parameters to use can be specified either + using a positional syntax (one or more of database name, user, + host, and port), or using a <replaceable>conninfo</replaceable> + connection string as detailed in + <xref linkend="libpq-connstring"/>. If no arguments are given, a + new connection is made using the same parameters as before. + </para> + + <para> + Specifying any + of <replaceable class="parameter">dbname</replaceable>, + <replaceable class="parameter">username</replaceable>, + <replaceable class="parameter">host</replaceable> or + <replaceable class="parameter">port</replaceable> + as <literal>-</literal> is equivalent to omitting that parameter. + </para> + + <para> + The new connection can re-use connection parameters from the previous + connection; not only database name, user, host, and port, but other + settings such as <replaceable>sslmode</replaceable>. By default, + parameters are re-used in the positional syntax, but not when + a <replaceable>conninfo</replaceable> string is given. Passing a + first argument of <literal>-reuse-previous=on</literal> + or <literal>-reuse-previous=off</literal> overrides that default. If + parameters are re-used, then any parameter not explicitly specified as + a positional parameter or in the <replaceable>conninfo</replaceable> + string is taken from the existing connection's parameters. An + exception is that if the <replaceable>host</replaceable> setting + is changed from its previous value using the positional syntax, + any <replaceable>hostaddr</replaceable> setting present in the + existing connection's parameters is dropped. + Also, any password used for the existing connection will be re-used + only if the user, host, and port settings are not changed. + When the command neither specifies nor reuses a particular parameter, + the <application>libpq</application> default is used. + </para> + + <para> + If the new connection is successfully made, the previous + connection is closed. + If the connection attempt fails (wrong user name, access + denied, etc.), the previous connection will be kept if + <application>psql</application> is in interactive mode. But when + executing a non-interactive script, the old connection is closed + and an error is reported. That may or may not terminate the + script; if it does not, all database-accessing commands will fail + until another <literal>\connect</literal> command is successfully + executed. This distinction was chosen as + a user convenience against typos on the one hand, and a safety + mechanism that scripts are not accidentally acting on the + wrong database on the other hand. + Note that whenever a <literal>\connect</literal> command attempts + to re-use parameters, the values re-used are those of the last + successful connection, not of any failed attempts made subsequently. + However, in the case of a + non-interactive <literal>\connect</literal> failure, no parameters + are allowed to be re-used later, since the script would likely be + expecting the values from the failed <literal>\connect</literal> + to be re-used. + </para> + + <para> + Examples: + </para> +<programlisting> +=> \c mydb myuser host.dom 6432 +=> \c service=foo +=> \c "host=localhost port=5432 dbname=mydb connect_timeout=10 sslmode=disable" +=> \c -reuse-previous=on sslmode=require -- changes only sslmode +=> \c postgresql://tom@localhost/mydb?application_name=myapp +</programlisting> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\C [ <replaceable class="parameter">title</replaceable> ]</literal></term> + <listitem> + <para> + Sets the title of any tables being printed as the result of a + query or unset any such title. This command is equivalent to + <literal>\pset title <replaceable + class="parameter">title</replaceable></literal>. (The name of + this command derives from <quote>caption</quote>, as it was + previously only used to set the caption in an + <acronym>HTML</acronym> table.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\cd [ <replaceable>directory</replaceable> ]</literal></term> + <listitem> + <para> + Changes the current working directory to + <replaceable>directory</replaceable>. Without argument, changes + to the current user's home directory. + </para> + + <tip> + <para> + To print your current working directory, use <literal>\! pwd</literal>. + </para> + </tip> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\conninfo</literal></term> + <listitem> + <para> + Outputs information about the current database connection. + </para> + </listitem> + </varlistentry> + + <varlistentry id="app-psql-meta-commands-copy"> + <term><literal>\copy { <replaceable class="parameter">table</replaceable> [ ( <replaceable class="parameter">column_list</replaceable> ) ] } + <literal>from</literal> + { <replaceable class="parameter">'filename'</replaceable> | program <replaceable class="parameter">'command'</replaceable> | stdin | pstdin } + [ [ with ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ] + [ where <replaceable class="parameter">condition</replaceable> ]</literal></term> + + <term><literal>\copy { <replaceable class="parameter">table</replaceable> [ ( <replaceable class="parameter">column_list</replaceable> ) ] | ( <replaceable class="parameter">query</replaceable> ) } + <literal>to</literal> + { <replaceable class="parameter">'filename'</replaceable> | program <replaceable class="parameter">'command'</replaceable> | stdout | pstdout } + [ [ with ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]</literal></term> + + <listitem> + <para> + Performs a frontend (client) copy. This is an operation that + runs an <acronym>SQL</acronym> <link linkend="sql-copy"><command>COPY</command></link> + command, but instead of the server + reading or writing the specified file, + <application>psql</application> reads or writes the file and + routes the data between the server and the local file system. + This means that file accessibility and privileges are those of + the local user, not the server, and no SQL superuser + privileges are required. + </para> + + <para> + When <literal>program</literal> is specified, + <replaceable class="parameter">command</replaceable> is + executed by <application>psql</application> and the data passed from + or to <replaceable class="parameter">command</replaceable> is + routed between the server and the client. + Again, the execution privileges are those of + the local user, not the server, and no SQL superuser + privileges are required. + </para> + + <para> + For <literal>\copy ... from stdin</literal>, data rows are read from the same + source that issued the command, continuing until <literal>\.</literal> + is read or the stream reaches <acronym>EOF</acronym>. This option is useful + for populating tables in-line within an SQL script file. + For <literal>\copy ... to stdout</literal>, output is sent to the same place + as <application>psql</application> command output, and + the <literal>COPY <replaceable>count</replaceable></literal> command status is + not printed (since it might be confused with a data row). + To read/write <application>psql</application>'s standard input or + output regardless of the current command source or <literal>\o</literal> + option, write <literal>from pstdin</literal> or <literal>to pstdout</literal>. + </para> + + <para> + The syntax of this command is similar to that of the + <acronym>SQL</acronym> <link linkend="sql-copy"><command>COPY</command></link> + command. All options other than the data source/destination are + as specified for <command>COPY</command>. + Because of this, special parsing rules apply to the <command>\copy</command> + meta-command. Unlike most other meta-commands, the entire remainder + of the line is always taken to be the arguments of <command>\copy</command>, + and neither variable interpolation nor backquote expansion are + performed in the arguments. + </para> + + <tip> + <para> + Another way to obtain the same result as <literal>\copy + ... to</literal> is to use the <acronym>SQL</acronym> <literal>COPY + ... TO STDOUT</literal> command and terminate it + with <literal>\g <replaceable>filename</replaceable></literal> + or <literal>\g |<replaceable>program</replaceable></literal>. + Unlike <literal>\copy</literal>, this method allows the command to + span multiple lines; also, variable interpolation and backquote + expansion can be used. + </para> + </tip> + + <tip> + <para> + These operations are not as efficient as the <acronym>SQL</acronym> + <command>COPY</command> command with a file or program data source or + destination, because all data must pass through the client/server + connection. For large amounts of data the <acronym>SQL</acronym> + command might be preferable. + Also, because of this pass-through method, <literal>\copy + ... from</literal> in <acronym>CSV</acronym> mode will erroneously + treat a <literal>\.</literal> data value alone on a line as an + end-of-input marker. + </para> + </tip> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\copyright</literal></term> + <listitem> + <para> + Shows the copyright and distribution terms of + <productname>PostgreSQL</productname>. + </para> + </listitem> + </varlistentry> + + + <varlistentry id="app-psql-meta-commands-crosstabview"> + <term><literal>\crosstabview [ + <replaceable class="parameter">colV</replaceable> + [ <replaceable class="parameter">colH</replaceable> + [ <replaceable class="parameter">colD</replaceable> + [ <replaceable class="parameter">sortcolH</replaceable> + ] ] ] ] </literal></term> + <listitem> + <para> + Executes the current query buffer (like <literal>\g</literal>) and + shows the results in a crosstab grid. + The query must return at least three columns. + The output column identified by <replaceable class="parameter">colV</replaceable> + becomes a vertical header and the output column identified by + <replaceable class="parameter">colH</replaceable> + becomes a horizontal header. + <replaceable class="parameter">colD</replaceable> identifies + the output column to display within the grid. + <replaceable class="parameter">sortcolH</replaceable> identifies + an optional sort column for the horizontal header. + </para> + + <para> + Each column specification can be a column number (starting at 1) or + a column name. The usual SQL case folding and quoting rules apply to + column names. If omitted, + <replaceable class="parameter">colV</replaceable> is taken as column 1 + and <replaceable class="parameter">colH</replaceable> as column 2. + <replaceable class="parameter">colH</replaceable> must differ from + <replaceable class="parameter">colV</replaceable>. + If <replaceable class="parameter">colD</replaceable> is not + specified, then there must be exactly three columns in the query + result, and the column that is neither + <replaceable class="parameter">colV</replaceable> nor + <replaceable class="parameter">colH</replaceable> + is taken to be <replaceable class="parameter">colD</replaceable>. + </para> + + <para> + The vertical header, displayed as the leftmost column, contains the + values found in column <replaceable class="parameter">colV</replaceable>, in the + same order as in the query results, but with duplicates removed. + </para> + + <para> + The horizontal header, displayed as the first row, contains the values + found in column <replaceable class="parameter">colH</replaceable>, + with duplicates removed. By default, these appear in the same order + as in the query results. But if the + optional <replaceable class="parameter">sortcolH</replaceable> argument is given, + it identifies a column whose values must be integer numbers, and the + values from <replaceable class="parameter">colH</replaceable> will + appear in the horizontal header sorted according to the + corresponding <replaceable class="parameter">sortcolH</replaceable> values. + </para> + + <para> + Inside the crosstab grid, for each distinct value <literal>x</literal> + of <replaceable class="parameter">colH</replaceable> and each distinct + value <literal>y</literal> + of <replaceable class="parameter">colV</replaceable>, the cell located + at the intersection <literal>(x,y)</literal> contains the value of + the <literal>colD</literal> column in the query result row for which + the value of <replaceable class="parameter">colH</replaceable> + is <literal>x</literal> and the value + of <replaceable class="parameter">colV</replaceable> + is <literal>y</literal>. If there is no such row, the cell is empty. If + there are multiple such rows, an error is reported. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\d[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + For each relation (table, view, materialized view, index, sequence, + or foreign table) + or composite type matching the + <replaceable class="parameter">pattern</replaceable>, show all + columns, their types, the tablespace (if not the default) and any + special attributes such as <literal>NOT NULL</literal> or defaults. + Associated indexes, constraints, rules, and triggers are + also shown. For foreign tables, the associated foreign + server is shown as well. + (<quote>Matching the pattern</quote> is defined in + <xref linkend="app-psql-patterns"/> below.) + </para> + + <para> + For some types of relation, <literal>\d</literal> shows additional information + for each column: column values for sequences, indexed expressions for + indexes, and foreign data wrapper options for foreign tables. + </para> + + <para> + The command form <literal>\d+</literal> is identical, except that + more information is displayed: any comments associated with the + columns of the table are shown, as is the presence of OIDs in the + table, the view definition if the relation is a view, a non-default + <link linkend="sql-altertable-replica-identity">replica + identity</link> setting and the + <link linkend="sql-create-access-method">access method</link> name + if the relation has an access method. + </para> + + <para> + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + </para> + + <note> + <para> + If <command>\d</command> is used without a + <replaceable class="parameter">pattern</replaceable> argument, it is + equivalent to <command>\dtvmsE</command> which will show a list of + all visible tables, views, materialized views, sequences and + foreign tables. + This is purely a convenience measure. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\da[S] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + Lists aggregate functions, together with their + return type and the data types they operate on. If <replaceable + class="parameter">pattern</replaceable> + is specified, only aggregates whose names match the pattern are shown. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dA[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + Lists access methods. If <replaceable + class="parameter">pattern</replaceable> is specified, only access + methods whose names match the pattern are shown. If + <literal>+</literal> is appended to the command name, each access + method is listed with its associated handler function and description. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\dAc[+] + [<link linkend="app-psql-patterns"><replaceable class="parameter">access-method-pattern</replaceable></link> + [<link linkend="app-psql-patterns"><replaceable class="parameter">input-type-pattern</replaceable></link>]] + </literal> + </term> + <listitem> + <para> + Lists operator classes + (see <xref linkend="xindex-opclass"/>). + If <replaceable class="parameter">access-method-pattern</replaceable> + is specified, only operator classes associated with access methods whose + names match that pattern are listed. + If <replaceable class="parameter">input-type-pattern</replaceable> + is specified, only operator classes associated with input types whose + names match that pattern are listed. + If <literal>+</literal> is appended to the command name, each operator + class is listed with its associated operator family and owner. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\dAf[+] + [<link linkend="app-psql-patterns"><replaceable class="parameter">access-method-pattern</replaceable></link> + [<link linkend="app-psql-patterns"><replaceable class="parameter">input-type-pattern</replaceable></link>]] + </literal> + </term> + <listitem> + <para> + Lists operator families + (see <xref linkend="xindex-opfamily"/>). + If <replaceable class="parameter">access-method-pattern</replaceable> + is specified, only operator families associated with access methods whose + names match that pattern are listed. + If <replaceable class="parameter">input-type-pattern</replaceable> + is specified, only operator families associated with input types whose + names match that pattern are listed. + If <literal>+</literal> is appended to the command name, each operator + family is listed with its owner. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\dAo[+] + [<link linkend="app-psql-patterns"><replaceable class="parameter">access-method-pattern</replaceable></link> + [<link linkend="app-psql-patterns"><replaceable class="parameter">operator-family-pattern</replaceable></link>]] + </literal> + </term> + + <listitem> + <para> + Lists operators associated with operator families + (see <xref linkend="xindex-strategies"/>). + If <replaceable class="parameter">access-method-pattern</replaceable> + is specified, only members of operator families associated with access + methods whose names match that pattern are listed. + If <replaceable class="parameter">operator-family-pattern</replaceable> + is specified, only members of operator families whose names match that + pattern are listed. + If <literal>+</literal> is appended to the command name, each operator + is listed with its sort operator family (if it is an ordering operator). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>\dAp[+] + [<link linkend="app-psql-patterns"><replaceable class="parameter">access-method-pattern</replaceable></link> + [<link linkend="app-psql-patterns"><replaceable class="parameter">operator-family-pattern</replaceable></link>]] + </literal> + </term> + <listitem> + <para> + Lists support functions associated with operator families + (see <xref linkend="xindex-support"/>). + If <replaceable class="parameter">access-method-pattern</replaceable> + is specified, only functions of operator families associated with + access methods whose names match that pattern are listed. + If <replaceable class="parameter">operator-family-pattern</replaceable> + is specified, only functions of operator families whose names match + that pattern are listed. + If <literal>+</literal> is appended to the command name, functions are + displayed verbosely, with their actual parameter lists. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\db[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + Lists tablespaces. If <replaceable + class="parameter">pattern</replaceable> + is specified, only tablespaces whose names match the pattern are shown. + If <literal>+</literal> is appended to the command name, each tablespace + is listed with its associated options, on-disk size, permissions and + description. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dc[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists conversions between character-set encodings. + If <replaceable class="parameter">pattern</replaceable> + is specified, only conversions whose names match the pattern are + listed. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + If <literal>+</literal> is appended to the command name, each object + is listed with its associated description. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dconfig[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists server configuration parameters and their values. + If <replaceable class="parameter">pattern</replaceable> is specified, + only parameters whose names match the pattern are listed. Without + a <replaceable class="parameter">pattern</replaceable>, only + parameters that are set to non-default values are listed. + (Use <literal>\dconfig *</literal> to see all parameters.) + If <literal>+</literal> is appended to the command name, each + parameter is listed with its data type, context in which the + parameter can be set, and access privileges (if non-default access + privileges have been granted). + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dC[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists type casts. + If <replaceable class="parameter">pattern</replaceable> + is specified, only casts whose source or target types match the + pattern are listed. + If <literal>+</literal> is appended to the command name, each object + is listed with its associated description. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dd[S] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Shows the descriptions of objects of type <literal>constraint</literal>, + <literal>operator class</literal>, <literal>operator family</literal>, + <literal>rule</literal>, and <literal>trigger</literal>. All + other comments may be viewed by the respective backslash commands for + those object types. + </para> + + <para><literal>\dd</literal> displays descriptions for objects matching the + <replaceable class="parameter">pattern</replaceable>, or of visible + objects of the appropriate type if no argument is given. But in either + case, only objects that have a description are listed. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + </para> + + <para> + Descriptions for objects can be created with the <link + linkend="sql-comment"><command>COMMENT</command></link> + <acronym>SQL</acronym> command. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dD[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists domains. If <replaceable + class="parameter">pattern</replaceable> + is specified, only domains whose names match the pattern are shown. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + If <literal>+</literal> is appended to the command name, each object + is listed with its associated permissions and description. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\ddp [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists default access privilege settings. An entry is shown for + each role (and schema, if applicable) for which the default + privilege settings have been changed from the built-in defaults. + If <replaceable class="parameter">pattern</replaceable> is + specified, only entries whose role name or schema name matches + the pattern are listed. + </para> + + <para> + The <link linkend="sql-alterdefaultprivileges"><command>ALTER DEFAULT + PRIVILEGES</command></link> command is used to set default access + privileges. The meaning of the privilege display is explained in + <xref linkend="ddl-priv"/>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dE[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <term><literal>\di[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <term><literal>\dm[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <term><literal>\ds[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <term><literal>\dt[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <term><literal>\dv[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + In this group of commands, the letters <literal>E</literal>, + <literal>i</literal>, <literal>m</literal>, <literal>s</literal>, + <literal>t</literal>, and <literal>v</literal> + stand for foreign table, index, materialized view, + sequence, table, and view, + respectively. + You can specify any or all of + these letters, in any order, to obtain a listing of objects + of these types. For example, <literal>\dti</literal> lists + tables and indexes. If <literal>+</literal> is + appended to the command name, each object is listed with its + persistence status (permanent, temporary, or unlogged), + physical size on disk, and associated description if any. + If <replaceable class="parameter">pattern</replaceable> is + specified, only objects whose names match the pattern are listed. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\des[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists foreign servers (mnemonic: <quote>external + servers</quote>). + If <replaceable class="parameter">pattern</replaceable> is + specified, only those servers whose name matches the pattern + are listed. If the form <literal>\des+</literal> is used, a + full description of each server is shown, including the + server's access privileges, type, version, options, and description. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\det[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists foreign tables (mnemonic: <quote>external tables</quote>). + If <replaceable class="parameter">pattern</replaceable> is + specified, only entries whose table name or schema name matches + the pattern are listed. If the form <literal>\det+</literal> + is used, generic options and the foreign table description + are also displayed. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\deu[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists user mappings (mnemonic: <quote>external + users</quote>). + If <replaceable class="parameter">pattern</replaceable> is + specified, only those mappings whose user names match the + pattern are listed. If the form <literal>\deu+</literal> is + used, additional information about each mapping is shown. + </para> + + <caution> + <para> + <literal>\deu+</literal> might also display the user name and + password of the remote user, so care should be taken not to + disclose them. + </para> + </caution> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dew[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists foreign-data wrappers (mnemonic: <quote>external + wrappers</quote>). + If <replaceable class="parameter">pattern</replaceable> is + specified, only those foreign-data wrappers whose name matches + the pattern are listed. If the form <literal>\dew+</literal> + is used, the access privileges, options, and description of the + foreign-data wrapper are also shown. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\df[anptwS+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> [ <replaceable class="parameter">arg_pattern</replaceable> ... ] ]</literal></term> + + <listitem> + <para> + Lists functions, together with their result data types, argument data + types, and function types, which are classified as <quote>agg</quote> + (aggregate), <quote>normal</quote>, <quote>procedure</quote>, <quote>trigger</quote>, or <quote>window</quote>. + To display only functions + of specific type(s), add the corresponding letters <literal>a</literal>, + <literal>n</literal>, <literal>p</literal>, <literal>t</literal>, or <literal>w</literal> to the command. + If <replaceable + class="parameter">pattern</replaceable> is specified, only + functions whose names match the pattern are shown. + Any additional arguments are type-name patterns, which are matched + to the type names of the first, second, and so on arguments of the + function. (Matching functions can have more arguments than what + you specify. To prevent that, write a dash <literal>-</literal> as + the last <replaceable class="parameter">arg_pattern</replaceable>.) + By default, only user-created + objects are shown; supply a pattern or the <literal>S</literal> + modifier to include system objects. + If the form <literal>\df+</literal> is used, additional information + about each function is shown, including volatility, + parallel safety, owner, security classification, access privileges, + language, source code and description. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dF[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists text search configurations. + If <replaceable class="parameter">pattern</replaceable> is specified, + only configurations whose names match the pattern are shown. + If the form <literal>\dF+</literal> is used, a full description of + each configuration is shown, including the underlying text search + parser and the dictionary list for each parser token type. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dFd[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists text search dictionaries. + If <replaceable class="parameter">pattern</replaceable> is specified, + only dictionaries whose names match the pattern are shown. + If the form <literal>\dFd+</literal> is used, additional information + is shown about each selected dictionary, including the underlying + text search template and the option values. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dFp[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists text search parsers. + If <replaceable class="parameter">pattern</replaceable> is specified, + only parsers whose names match the pattern are shown. + If the form <literal>\dFp+</literal> is used, a full description of + each parser is shown, including the underlying functions and the + list of recognized token types. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dFt[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists text search templates. + If <replaceable class="parameter">pattern</replaceable> is specified, + only templates whose names match the pattern are shown. + If the form <literal>\dFt+</literal> is used, additional information + is shown about each template, including the underlying function names. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dg[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists database roles. + (Since the concepts of <quote>users</quote> and <quote>groups</quote> have been + unified into <quote>roles</quote>, this command is now equivalent to + <literal>\du</literal>.) + By default, only user-created roles are shown; supply the + <literal>S</literal> modifier to include system roles. + If <replaceable class="parameter">pattern</replaceable> is specified, + only those roles whose names match the pattern are listed. + If the form <literal>\dg+</literal> is used, additional information + is shown about each role; currently this adds the comment for each + role. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dl[+]</literal></term> + <listitem> + <para> + This is an alias for <command>\lo_list</command>, which shows a + list of large objects. + If <literal>+</literal> is appended to the command name, + each large object is listed with its associated permissions, + if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dL[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists procedural languages. If <replaceable + class="parameter">pattern</replaceable> + is specified, only languages whose names match the pattern are listed. + By default, only user-created languages + are shown; supply the <literal>S</literal> modifier to include system + objects. If <literal>+</literal> is appended to the command name, each + language is listed with its call handler, validator, access privileges, + and whether it is a system object. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dn[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + + <listitem> + <para> + Lists schemas (namespaces). If <replaceable + class="parameter">pattern</replaceable> + is specified, only schemas whose names match the pattern are listed. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system objects. + If <literal>+</literal> is appended to the command name, each object + is listed with its associated permissions and description, if any. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\do[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> [ <replaceable class="parameter">arg_pattern</replaceable> [ <replaceable class="parameter">arg_pattern</replaceable> ] ] ]</literal></term> + <listitem> + <para> + Lists operators with their operand and result types. + If <replaceable class="parameter">pattern</replaceable> is + specified, only operators whose names match the pattern are listed. + If one <replaceable class="parameter">arg_pattern</replaceable> is + specified, only prefix operators whose right argument's type name + matches that pattern are listed. + If two <replaceable class="parameter">arg_pattern</replaceable>s + are specified, only binary operators whose argument type names match + those patterns are listed. (Alternatively, write <literal>-</literal> + for the unused argument of a unary operator.) + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + If <literal>+</literal> is appended to the command name, + additional information about each operator is shown, currently just + the name of the underlying function. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dO[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists collations. + If <replaceable class="parameter">pattern</replaceable> is + specified, only collations whose names match the pattern are + listed. By default, only user-created objects are shown; + supply a pattern or the <literal>S</literal> modifier to + include system objects. If <literal>+</literal> is appended + to the command name, each collation is listed with its associated + description, if any. + Note that only collations usable with the current database's encoding + are shown, so the results may vary in different databases of the + same installation. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dp [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists tables, views and sequences with their + associated access privileges. + If <replaceable class="parameter">pattern</replaceable> is + specified, only tables, views and sequences whose names match the + pattern are listed. + </para> + + <para> + The <link linkend="sql-grant"><command>GRANT</command></link> and + <link linkend="sql-revoke"><command>REVOKE</command></link> + commands are used to set access privileges. The meaning of the + privilege display is explained in + <xref linkend="ddl-priv"/>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\dP[itn+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists partitioned relations. + If <replaceable class="parameter">pattern</replaceable> + is specified, only entries whose name matches the pattern are listed. + The modifiers <literal>t</literal> (tables) and <literal>i</literal> + (indexes) can be appended to the command, filtering the kind of + relations to list. By default, partitioned tables and indexes are + listed. + </para> + + <para> + If the modifier <literal>n</literal> (<quote>nested</quote>) is used, + or a pattern is specified, then non-root partitioned relations are + included, and a column is shown displaying the parent of each + partitioned relation. + </para> + + <para> + If <literal>+</literal> is appended to the command name, the sum of the + sizes of each relation's partitions is also displayed, along with the + relation's description. + If <literal>n</literal> is combined with <literal>+</literal>, two + sizes are shown: one including the total size of directly-attached + leaf partitions, and another showing the total size of all partitions, + including indirectly attached sub-partitions. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\drds [ <link linkend="app-psql-patterns"><replaceable class="parameter">role-pattern</replaceable></link> [ <link linkend="app-psql-patterns"><replaceable class="parameter">database-pattern</replaceable></link> ] ]</literal></term> + <listitem> + <para> + Lists defined configuration settings. These settings can be + role-specific, database-specific, or both. + <replaceable>role-pattern</replaceable> and + <replaceable>database-pattern</replaceable> are used to select + specific roles and databases to list, respectively. If omitted, or if + <literal>*</literal> is specified, all settings are listed, including those + not role-specific or database-specific, respectively. + </para> + + <para> + The <link linkend="sql-alterrole"><command>ALTER ROLE</command></link> and + <link linkend="sql-alterdatabase"><command>ALTER DATABASE</command></link> + commands are used to define per-role and per-database configuration + settings. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dRp[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists replication publications. + If <replaceable class="parameter">pattern</replaceable> is + specified, only those publications whose names match the pattern are + listed. + If <literal>+</literal> is appended to the command name, the tables and + schemas associated with each publication are shown as well. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dRs[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists replication subscriptions. + If <replaceable class="parameter">pattern</replaceable> is + specified, only those subscriptions whose names match the pattern are + listed. + If <literal>+</literal> is appended to the command name, additional + properties of the subscriptions are shown. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dT[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists data types. + If <replaceable class="parameter">pattern</replaceable> is + specified, only types whose names match the pattern are listed. + If <literal>+</literal> is appended to the command name, each type is + listed with its internal name and size, its allowed values + if it is an <type>enum</type> type, and its associated permissions. + By default, only user-created objects are shown; supply a + pattern or the <literal>S</literal> modifier to include system + objects. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\du[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists database roles. + (Since the concepts of <quote>users</quote> and <quote>groups</quote> have been + unified into <quote>roles</quote>, this command is now equivalent to + <literal>\dg</literal>.) + By default, only user-created roles are shown; supply the + <literal>S</literal> modifier to include system roles. + If <replaceable class="parameter">pattern</replaceable> is specified, + only those roles whose names match the pattern are listed. + If the form <literal>\du+</literal> is used, additional information + is shown about each role; currently this adds the comment for each + role. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dx[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists installed extensions. + If <replaceable class="parameter">pattern</replaceable> + is specified, only those extensions whose names match the pattern + are listed. + If the form <literal>\dx+</literal> is used, all the objects belonging + to each matching extension are listed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dX [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists extended statistics. + If <replaceable class="parameter">pattern</replaceable> + is specified, only those extended statistics whose names match the + pattern are listed. + </para> + + <para> + The status of each kind of extended statistics is shown in a column + named after its statistic kind (e.g. Ndistinct). + <literal>defined</literal> means that it was requested when creating + the statistics, and NULL means it wasn't requested. + You can use <structname>pg_stats_ext</structname> if you'd like to + know whether <link linkend="sql-analyze"><command>ANALYZE</command></link> + was run and statistics are available to the planner. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\dy[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists event triggers. + If <replaceable class="parameter">pattern</replaceable> + is specified, only those event triggers whose names match the pattern + are listed. + If <literal>+</literal> is appended to the command name, each object + is listed with its associated description. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\e</literal> or <literal>\edit</literal> <literal> <optional> <replaceable class="parameter">filename</replaceable> </optional> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </literal></term> + + <listitem> + <para> + If <replaceable class="parameter">filename</replaceable> is + specified, the file is edited; after the editor exits, the file's + content is copied into the current query buffer. If no <replaceable + class="parameter">filename</replaceable> is given, the current query + buffer is copied to a temporary file which is then edited in the same + fashion. Or, if the current query buffer is empty, the most recently + executed query is copied to a temporary file and edited in the same + fashion. + </para> + + <para> + If you edit a file or the previous query, and you quit the editor without + modifying the file, the query buffer is cleared. + Otherwise, the new contents of the query buffer are re-parsed according to + the normal rules of <application>psql</application>, treating the + whole buffer as a single line. Any complete queries are immediately + executed; that is, if the query buffer contains or ends with a + semicolon, everything up to that point is executed and removed from + the query buffer. Whatever remains in the query buffer is + redisplayed. Type semicolon or <literal>\g</literal> to send it, + or <literal>\r</literal> to cancel it by clearing the query buffer. + </para> + + <para> + Treating the buffer as a single line primarily affects meta-commands: + whatever is in the buffer after a meta-command will be taken as + argument(s) to the meta-command, even if it spans multiple lines. + (Thus you cannot make meta-command-using scripts this way. + Use <command>\i</command> for that.) + </para> + + <para> + If a line number is specified, <application>psql</application> will + position the cursor on the specified line of the file or query buffer. + Note that if a single all-digits argument is given, + <application>psql</application> assumes it is a line number, + not a file name. + </para> + + <tip> + <para> + See <xref linkend="app-psql-environment"/>, below, for how to + configure and customize your editor. + </para> + </tip> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\echo <replaceable class="parameter">text</replaceable> [ ... ]</literal></term> + <listitem> + <para> + Prints the evaluated arguments to standard output, separated by + spaces and followed by a newline. This can be useful to + intersperse information in the output of scripts. For example: +<programlisting> +=> <userinput>\echo `date`</userinput> +Tue Oct 26 21:40:57 CEST 1999 +</programlisting> + If the first argument is an unquoted <literal>-n</literal> the trailing + newline is not written (nor is the first argument). + </para> + + <tip> + <para> + If you use the <command>\o</command> command to redirect your + query output you might wish to use <command>\qecho</command> + instead of this command. See also <command>\warn</command>. + </para> + </tip> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\ef <optional> <replaceable class="parameter">function_description</replaceable> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </optional> </literal></term> + + <listitem> + <para> + This command fetches and edits the definition of the named function or procedure, + in the form of a <command>CREATE OR REPLACE FUNCTION</command> or + <command>CREATE OR REPLACE PROCEDURE</command> command. + Editing is done in the same way as for <literal>\edit</literal>. + If you quit the editor without saving, the statement is discarded. + If you save and exit the editor, the updated command is executed immediately + if you added a semicolon to it. Otherwise it is redisplayed; + type semicolon or <literal>\g</literal> to send it, or <literal>\r</literal> + to cancel. + </para> + + <para> + The target function can be specified by name alone, or by name + and arguments, for example <literal>foo(integer, text)</literal>. + The argument types must be given if there is more + than one function of the same name. + </para> + + <para> + If no function is specified, a blank <command>CREATE FUNCTION</command> + template is presented for editing. + </para> + + <para> + If a line number is specified, <application>psql</application> will + position the cursor on the specified line of the function body. + (Note that the function body typically does not begin on the first + line of the file.) + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\ef</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. + </para> + + <tip> + <para> + See <xref linkend="app-psql-environment"/>, below, for how to + configure and customize your editor. + </para> + </tip> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\encoding [ <replaceable class="parameter">encoding</replaceable> ]</literal></term> + + <listitem> + <para> + Sets the client character set encoding. Without an argument, this command + shows the current encoding. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\errverbose</literal></term> + + <listitem> + <para> + Repeats the most recent server error message at maximum + verbosity, as though <varname>VERBOSITY</varname> were set + to <literal>verbose</literal> and <varname>SHOW_CONTEXT</varname> were + set to <literal>always</literal>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\ev <optional> <replaceable class="parameter">view_name</replaceable> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </optional> </literal></term> + + <listitem> + <para> + This command fetches and edits the definition of the named view, + in the form of a <command>CREATE OR REPLACE VIEW</command> command. + Editing is done in the same way as for <literal>\edit</literal>. + If you quit the editor without saving, the statement is discarded. + If you save and exit the editor, the updated command is executed immediately + if you added a semicolon to it. Otherwise it is redisplayed; + type semicolon or <literal>\g</literal> to send it, or <literal>\r</literal> + to cancel. + </para> + + <para> + If no view is specified, a blank <command>CREATE VIEW</command> + template is presented for editing. + </para> + + <para> + If a line number is specified, <application>psql</application> will + position the cursor on the specified line of the view definition. + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\ev</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\f [ <replaceable class="parameter">string</replaceable> ]</literal></term> + + <listitem> + <para> + Sets the field separator for unaligned query output. The default + is the vertical bar (<literal>|</literal>). It is equivalent to + <command>\pset fieldsep</command>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\g [ (<replaceable class="parameter">option</replaceable>=<replaceable class="parameter">value</replaceable> [...]) ] [ <replaceable class="parameter">filename</replaceable> ]</literal></term> + <term><literal>\g [ (<replaceable class="parameter">option</replaceable>=<replaceable class="parameter">value</replaceable> [...]) ] [ |<replaceable class="parameter">command</replaceable> ]</literal></term> + <listitem> + <para> + Sends the current query buffer to the server for execution. + </para> + <para> + If parentheses appear after <literal>\g</literal>, they surround a + space-separated list + of <replaceable class="parameter">option</replaceable><literal>=</literal><replaceable class="parameter">value</replaceable> + formatting-option clauses, which are interpreted in the same way + as <literal>\pset</literal> + <replaceable class="parameter">option</replaceable> + <replaceable class="parameter">value</replaceable> commands, but take + effect only for the duration of this query. In this list, spaces are + not allowed around <literal>=</literal> signs, but are required + between option clauses. + If <literal>=</literal><replaceable class="parameter">value</replaceable> + is omitted, the + named <replaceable class="parameter">option</replaceable> is changed + in the same way as for + <literal>\pset</literal> <replaceable class="parameter">option</replaceable> + with no explicit <replaceable class="parameter">value</replaceable>. + </para> + <para> + If a <replaceable class="parameter">filename</replaceable> + or <literal>|</literal><replaceable class="parameter">command</replaceable> + argument is given, the query's output is written to the named + file or piped to the given shell command, instead of displaying it as + usual. The file or command is written to only if the query + successfully returns zero or more tuples, not if the query fails or + is a non-data-returning SQL command. + </para> + <para> + If the current query buffer is empty, the most recently sent query is + re-executed instead. Except for that behavior, <literal>\g</literal> + without any arguments is essentially equivalent to a semicolon. + With arguments, <literal>\g</literal> provides + a <quote>one-shot</quote> alternative to the <command>\o</command> + command, and additionally allows one-shot adjustments of the + output formatting options normally set by <literal>\pset</literal>. + </para> + <para> + When the last argument begins with <literal>|</literal>, the entire + remainder of the line is taken to be + the <replaceable class="parameter">command</replaceable> to execute, + and neither variable interpolation nor backquote expansion are + performed in it. The rest of the line is simply passed literally to + the shell. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\gdesc</literal></term> + + <listitem> + <para> + Shows the description (that is, the column names and data types) + of the result of the current query buffer. The query is not + actually executed; however, if it contains some type of syntax + error, that error will be reported in the normal way. + </para> + + <para> + If the current query buffer is empty, the most recently sent query + is described instead. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\getenv <replaceable class="parameter">psql_var</replaceable> <replaceable class="parameter">env_var</replaceable></literal></term> + + <listitem> + <para> + Gets the value of the environment + variable <replaceable class="parameter">env_var</replaceable> + and assigns it to the <application>psql</application> + variable <replaceable class="parameter">psql_var</replaceable>. + If <replaceable class="parameter">env_var</replaceable> is + not defined in the <application>psql</application> process's + environment, <replaceable class="parameter">psql_var</replaceable> + is not changed. Example: +<programlisting> +=> <userinput>\getenv home HOME</userinput> +=> <userinput>\echo :home</userinput> +/home/postgres +</programlisting></para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\gexec</literal></term> + + <listitem> + <para> + Sends the current query buffer to the server, then treats + each column of each row of the query's output (if any) as an SQL + statement to be executed. For example, to create an index on each + column of <structname>my_table</structname>: +<programlisting> +=> <userinput>SELECT format('create index on my_table(%I)', attname)</userinput> +-> <userinput>FROM pg_attribute</userinput> +-> <userinput>WHERE attrelid = 'my_table'::regclass AND attnum > 0</userinput> +-> <userinput>ORDER BY attnum</userinput> +-> <userinput>\gexec</userinput> +CREATE INDEX +CREATE INDEX +CREATE INDEX +CREATE INDEX +</programlisting> + </para> + + <para> + The generated queries are executed in the order in which the rows + are returned, and left-to-right within each row if there is more + than one column. NULL fields are ignored. The generated queries + are sent literally to the server for processing, so they cannot be + <application>psql</application> meta-commands nor contain <application>psql</application> + variable references. If any individual query fails, execution of + the remaining queries continues + unless <varname>ON_ERROR_STOP</varname> is set. Execution of each + query is subject to <varname>ECHO</varname> processing. + (Setting <varname>ECHO</varname> to <literal>all</literal> + or <literal>queries</literal> is often advisable when + using <command>\gexec</command>.) Query logging, single-step mode, + timing, and other query execution features apply to each generated + query as well. + </para> + <para> + If the current query buffer is empty, the most recently sent query + is re-executed instead. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\gset [ <replaceable class="parameter">prefix</replaceable> ]</literal></term> + + <listitem> + <para> + Sends the current query buffer to the server and stores the + query's output into <application>psql</application> variables + (see <xref linkend="app-psql-variables"/> below). + The query to be executed must return exactly one row. Each column of + the row is stored into a separate variable, named the same as the + column. For example: +<programlisting> +=> <userinput>SELECT 'hello' AS var1, 10 AS var2</userinput> +-> <userinput>\gset</userinput> +=> <userinput>\echo :var1 :var2</userinput> +hello 10 +</programlisting> + </para> + <para> + If you specify a <replaceable class="parameter">prefix</replaceable>, + that string is prepended to the query's column names to create the + variable names to use: +<programlisting> +=> <userinput>SELECT 'hello' AS var1, 10 AS var2</userinput> +-> <userinput>\gset result_</userinput> +=> <userinput>\echo :result_var1 :result_var2</userinput> +hello 10 +</programlisting> + </para> + <para> + If a column result is NULL, the corresponding variable is unset + rather than being set. + </para> + <para> + If the query fails or does not return one row, + no variables are changed. + </para> + <para> + If the current query buffer is empty, the most recently sent query + is re-executed instead. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\gx [ (<replaceable class="parameter">option</replaceable>=<replaceable class="parameter">value</replaceable> [...]) ] [ <replaceable class="parameter">filename</replaceable> ]</literal></term> + <term><literal>\gx [ (<replaceable class="parameter">option</replaceable>=<replaceable class="parameter">value</replaceable> [...]) ] [ |<replaceable class="parameter">command</replaceable> ]</literal></term> + <listitem> + <para> + <literal>\gx</literal> is equivalent to <literal>\g</literal>, except + that it forces expanded output mode for this query, as + if <literal>expanded=on</literal> were included in the list of + <literal>\pset</literal> options. See also <literal>\x</literal>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\h</literal> or <literal>\help</literal> <literal>[ <replaceable class="parameter">command</replaceable> ]</literal></term> + <listitem> + <para> + Gives syntax help on the specified <acronym>SQL</acronym> + command. If <replaceable class="parameter">command</replaceable> + is not specified, then <application>psql</application> will list + all the commands for which syntax help is available. If + <replaceable class="parameter">command</replaceable> is an + asterisk (<literal>*</literal>), then syntax help on all + <acronym>SQL</acronym> commands is shown. + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\help</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. + </para> + + <note> + <para> + To simplify typing, commands that consists of several words do + not have to be quoted. Thus it is fine to type <userinput>\help + alter table</userinput>. + </para> + </note> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\H</literal> or <literal>\html</literal></term> + <listitem> + <para> + Turns on <acronym>HTML</acronym> query output format. If the + <acronym>HTML</acronym> format is already on, it is switched + back to the default aligned text format. This command is for + compatibility and convenience, but see <command>\pset</command> + about setting other output options. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\i</literal> or <literal>\include</literal> <replaceable class="parameter">filename</replaceable></term> + <listitem> + <para> + Reads input from the file <replaceable + class="parameter">filename</replaceable> and executes it as + though it had been typed on the keyboard. + </para> + <para> + If <replaceable>filename</replaceable> is <literal>-</literal> + (hyphen), then standard input is read until an EOF indication + or <command>\q</command> meta-command. This can be used to intersperse + interactive input with input from files. Note that Readline behavior + will be used only if it is active at the outermost level. + </para> + <note> + <para> + If you want to see the lines on the screen as they are read you + must set the variable <varname>ECHO</varname> to + <literal>all</literal>. + </para> + </note> + </listitem> + </varlistentry> + + + <varlistentry id="psql-metacommand-if"> + <term><literal>\if</literal> <replaceable class="parameter">expression</replaceable></term> + <term><literal>\elif</literal> <replaceable class="parameter">expression</replaceable></term> + <term><literal>\else</literal></term> + <term><literal>\endif</literal></term> + <listitem> + <para> + This group of commands implements nestable conditional blocks. + A conditional block must begin with an <command>\if</command> and end + with an <command>\endif</command>. In between there may be any number + of <command>\elif</command> clauses, which may optionally be followed + by a single <command>\else</command> clause. Ordinary queries and + other types of backslash commands may (and usually do) appear between + the commands forming a conditional block. + </para> + <para> + The <command>\if</command> and <command>\elif</command> commands read + their argument(s) and evaluate them as a Boolean expression. If the + expression yields <literal>true</literal> then processing continues + normally; otherwise, lines are skipped until a + matching <command>\elif</command>, <command>\else</command>, + or <command>\endif</command> is reached. Once + an <command>\if</command> or <command>\elif</command> test has + succeeded, the arguments of later <command>\elif</command> commands in + the same block are not evaluated but are treated as false. Lines + following an <command>\else</command> are processed only if no earlier + matching <command>\if</command> or <command>\elif</command> succeeded. + </para> + <para> + The <replaceable class="parameter">expression</replaceable> argument + of an <command>\if</command> or <command>\elif</command> command + is subject to variable interpolation and backquote expansion, just + like any other backslash command argument. After that it is evaluated + like the value of an on/off option variable. So a valid value + is any unambiguous case-insensitive match for one of: + <literal>true</literal>, <literal>false</literal>, <literal>1</literal>, + <literal>0</literal>, <literal>on</literal>, <literal>off</literal>, + <literal>yes</literal>, <literal>no</literal>. For example, + <literal>t</literal>, <literal>T</literal>, and <literal>tR</literal> + will all be considered to be <literal>true</literal>. + </para> + <para> + Expressions that do not properly evaluate to true or false will + generate a warning and be treated as false. + </para> + <para> + Lines being skipped are parsed normally to identify queries and + backslash commands, but queries are not sent to the server, and + backslash commands other than conditionals + (<command>\if</command>, <command>\elif</command>, + <command>\else</command>, <command>\endif</command>) are + ignored. Conditional commands are checked only for valid nesting. + Variable references in skipped lines are not expanded, and backquote + expansion is not performed either. + </para> + <para> + All the backslash commands of a given conditional block must appear in + the same source file. If EOF is reached on the main input file or an + <command>\include</command>-ed file before all local + <command>\if</command>-blocks have been closed, + then <application>psql</application> will raise an error. + </para> + <para> + Here is an example: + </para> +<programlisting> +-- check for the existence of two separate records in the database and store +-- the results in separate psql variables +SELECT + EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer, + EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee +\gset +\if :is_customer + SELECT * FROM customer WHERE customer_id = 123; +\elif :is_employee + \echo 'is not a customer but is an employee' + SELECT * FROM employee WHERE employee_id = 456; +\else + \if yes + \echo 'not a customer or employee' + \else + \echo 'this will never print' + \endif +\endif +</programlisting> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\ir</literal> or <literal>\include_relative</literal> <replaceable class="parameter">filename</replaceable></term> + <listitem> + <para> + The <literal>\ir</literal> command is similar to <literal>\i</literal>, but resolves + relative file names differently. When executing in interactive mode, + the two commands behave identically. However, when invoked from a + script, <literal>\ir</literal> interprets file names relative to the + directory in which the script is located, rather than the current + working directory. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\l[+]</literal> or <literal>\list[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + List the databases in the server and show their names, owners, + character set encodings, and access privileges. + If <replaceable class="parameter">pattern</replaceable> is specified, + only databases whose names match the pattern are listed. + If <literal>+</literal> is appended to the command name, database + sizes, default tablespaces, and descriptions are also displayed. + (Size information is only available for databases that the current + user can connect to.) + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\lo_export <replaceable class="parameter">loid</replaceable> <replaceable class="parameter">filename</replaceable></literal></term> + + <listitem> + <para> + Reads the large object with <acronym>OID</acronym> <replaceable + class="parameter">loid</replaceable> from the database and + writes it to <replaceable + class="parameter">filename</replaceable>. Note that this is + subtly different from the server function + <function>lo_export</function>, which acts with the permissions + of the user that the database server runs as and on the server's + file system. + </para> + <tip> + <para> + Use <command>\lo_list</command> to find out the large object's + <acronym>OID</acronym>. + </para> + </tip> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\lo_import <replaceable class="parameter">filename</replaceable> [ <replaceable class="parameter">comment</replaceable> ]</literal></term> + + <listitem> + <para> + Stores the file into a <productname>PostgreSQL</productname> + large object. Optionally, it associates the given + comment with the object. Example: +<programlisting> +foo=> <userinput>\lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'</userinput> +lo_import 152801 +</programlisting> + The response indicates that the large object received object + ID 152801, which can be used to access the newly-created large + object in the future. For the sake of readability, it is + recommended to always associate a human-readable comment with + every object. Both OIDs and comments can be viewed with the + <command>\lo_list</command> command. + </para> + + <para> + Note that this command is subtly different from the server-side + <function>lo_import</function> because it acts as the local user + on the local file system, rather than the server's user and file + system. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\lo_list[+]</literal></term> + <listitem> + <para> + Shows a list of all <productname>PostgreSQL</productname> + large objects currently stored in the database, + along with any comments provided for them. + If <literal>+</literal> is appended to the command name, + each large object is listed with its associated permissions, + if any. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\lo_unlink <replaceable class="parameter">loid</replaceable></literal></term> + + <listitem> + <para> + Deletes the large object with <acronym>OID</acronym> + <replaceable class="parameter">loid</replaceable> from the + database. + </para> + + <tip> + <para> + Use <command>\lo_list</command> to find out the large object's + <acronym>OID</acronym>. + </para> + </tip> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\o</literal> or <literal>\out [ <replaceable class="parameter">filename</replaceable> ]</literal></term> + <term><literal>\o</literal> or <literal>\out [ |<replaceable class="parameter">command</replaceable> ]</literal></term> + <listitem> + <para> + Arranges to save future query results to the file <replaceable + class="parameter">filename</replaceable> or pipe future results + to the shell command <replaceable + class="parameter">command</replaceable>. If no argument is + specified, the query output is reset to the standard output. + </para> + + <para> + If the argument begins with <literal>|</literal>, then the entire remainder + of the line is taken to be + the <replaceable class="parameter">command</replaceable> to execute, + and neither variable interpolation nor backquote expansion are + performed in it. The rest of the line is simply passed literally to + the shell. + </para> + + <para> + <quote>Query results</quote> includes all tables, command + responses, and notices obtained from the database server, as + well as output of various backslash commands that query the + database (such as <command>\d</command>); but not error + messages. + </para> + + <tip> + <para> + To intersperse text output in between query results, use + <command>\qecho</command>. + </para> + </tip> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\p</literal> or <literal>\print</literal></term> + <listitem> + <para> + Print the current query buffer to the standard output. + If the current query buffer is empty, the most recently executed query + is printed instead. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\password [ <replaceable class="parameter">username</replaceable> ]</literal></term> + <listitem> + <para> + Changes the password of the specified user (by default, the current + user). This command prompts for the new password, encrypts it, and + sends it to the server as an <command>ALTER ROLE</command> command. This + makes sure that the new password does not appear in cleartext in the + command history, the server log, or elsewhere. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\prompt [ <replaceable class="parameter">text</replaceable> ] <replaceable class="parameter">name</replaceable></literal></term> + <listitem> + <para> + Prompts the user to supply text, which is assigned to the variable + <replaceable class="parameter">name</replaceable>. + An optional prompt string, <replaceable + class="parameter">text</replaceable>, can be specified. (For multiword + prompts, surround the text with single quotes.) + </para> + + <para> + By default, <literal>\prompt</literal> uses the terminal for input and + output. However, if the <option>-f</option> command line switch was + used, <literal>\prompt</literal> uses standard input and standard output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\pset [ <replaceable class="parameter">option</replaceable> [ <replaceable class="parameter">value</replaceable> ] ]</literal></term> + + <listitem> + <para> + This command sets options affecting the output of query result tables. + <replaceable class="parameter">option</replaceable> + indicates which option is to be set. The semantics of + <replaceable class="parameter">value</replaceable> vary depending + on the selected option. For some options, omitting <replaceable + class="parameter">value</replaceable> causes the option to be toggled + or unset, as described under the particular option. If no such + behavior is mentioned, then omitting + <replaceable class="parameter">value</replaceable> just results in + the current setting being displayed. + </para> + + <para> + <command>\pset</command> without any arguments displays the current status + of all printing options. + </para> + + <para> + Adjustable printing options are: + <variablelist> + <varlistentry> + <term><literal>border</literal></term> + <listitem> + <para> + The <replaceable class="parameter">value</replaceable> must be a + number. In general, the higher + the number the more borders and lines the tables will have, + but details depend on the particular format. + In <acronym>HTML</acronym> format, this will translate directly + into the <literal>border=...</literal> attribute. + In most other formats only values 0 (no border), 1 (internal + dividing lines), and 2 (table frame) make sense, and values above 2 + will be treated the same as <literal>border = 2</literal>. + The <literal>latex</literal> and <literal>latex-longtable</literal> + formats additionally allow a value of 3 to add dividing lines + between data rows. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>columns</literal></term> + <listitem> + <para> + Sets the target width for the <literal>wrapped</literal> format, and also + the width limit for determining whether output is wide enough to + require the pager or switch to the vertical display in expanded auto + mode. + Zero (the default) causes the target width to be controlled by the + environment variable <envar>COLUMNS</envar>, or the detected screen width + if <envar>COLUMNS</envar> is not set. + In addition, if <literal>columns</literal> is zero then the + <literal>wrapped</literal> format only affects screen output. + If <literal>columns</literal> is nonzero then file and pipe output is + wrapped to that width as well. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>csv_fieldsep</literal></term> + <listitem> + <para> + Specifies the field separator to be used in + <acronym>CSV</acronym> output format. If the separator character + appears in a field's value, that field is output within double + quotes, following standard <acronym>CSV</acronym> rules. + The default is a comma. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>expanded</literal> (or <literal>x</literal>)</term> + <listitem> + <para> + If <replaceable class="parameter">value</replaceable> is specified it + must be either <literal>on</literal> or <literal>off</literal>, which + will enable or disable expanded mode, or <literal>auto</literal>. + If <replaceable class="parameter">value</replaceable> is omitted the + command toggles between the on and off settings. When expanded mode + is enabled, query results are displayed in two columns, with the + column name on the left and the data on the right. This mode is + useful if the data wouldn't fit on the screen in the + normal <quote>horizontal</quote> mode. In the auto setting, the + expanded mode is used whenever the query output has more than one + column and is wider than the screen; otherwise, the regular mode is + used. The auto setting is only + effective in the aligned and wrapped formats. In other formats, it + always behaves as if the expanded mode is off. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>fieldsep</literal></term> + <listitem> + <para> + Specifies the field separator to be used in unaligned output + format. That way one can create, for example, tab-separated + output, which other programs might prefer. To + set a tab as field separator, type <literal>\pset fieldsep + '\t'</literal>. The default field separator is + <literal>'|'</literal> (a vertical bar). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>fieldsep_zero</literal></term> + <listitem> + <para> + Sets the field separator to use in unaligned output format to a zero + byte. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>footer</literal></term> + <listitem> + <para> + If <replaceable class="parameter">value</replaceable> is specified + it must be either <literal>on</literal> or <literal>off</literal> + which will enable or disable display of the table footer + (the <literal>(<replaceable>n</replaceable> rows)</literal> count). + If <replaceable class="parameter">value</replaceable> is omitted the + command toggles footer display on or off. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>format</literal></term> + <listitem> + <para> + Sets the output format to one of <literal>aligned</literal>, + <literal>asciidoc</literal>, + <literal>csv</literal>, + <literal>html</literal>, + <literal>latex</literal>, + <literal>latex-longtable</literal>, <literal>troff-ms</literal>, + <literal>unaligned</literal>, or <literal>wrapped</literal>. + Unique abbreviations are allowed. + </para> + + <para><literal>aligned</literal> format is the standard, + human-readable, nicely formatted text output; this is the default. + </para> + + <para><literal>unaligned</literal> format writes all columns of a row on one + line, separated by the currently active field separator. This + is useful for creating output that might be intended to be read + in by other programs, for example, tab-separated or comma-separated + format. However, the field separator character is not treated + specially if it appears in a column's value; + so <acronym>CSV</acronym> format may be better suited for such + purposes. + </para> + + <para><literal>csv</literal> format + <indexterm> + <primary>CSV (Comma-Separated Values) format</primary> + <secondary>in psql</secondary> + </indexterm> + writes column values separated by commas, applying the quoting + rules described in + <ulink url="https://tools.ietf.org/html/rfc4180">RFC 4180</ulink>. + This output is compatible with the CSV format of the server's + <command>COPY</command> command. + A header line with column names is generated unless + the <literal>tuples_only</literal> parameter is + <literal>on</literal>. Titles and footers are not printed. + Each row is terminated by the system-dependent end-of-line character, + which is typically a single newline (<literal>\n</literal>) for + Unix-like systems or a carriage return and newline sequence + (<literal>\r\n</literal>) for Microsoft Windows. + Field separator characters other than comma can be selected with + <command>\pset csv_fieldsep</command>. + </para> + + <para><literal>wrapped</literal> format is like <literal>aligned</literal> but wraps + wide data values across lines to make the output fit in the target + column width. The target width is determined as described under + the <literal>columns</literal> option. Note that <application>psql</application> will + not attempt to wrap column header titles; therefore, + <literal>wrapped</literal> format behaves the same as <literal>aligned</literal> + if the total width needed for column headers exceeds the target. + </para> + + <para> + The <literal>asciidoc</literal>, <literal>html</literal>, + <literal>latex</literal>, <literal>latex-longtable</literal>, and + <literal>troff-ms</literal> formats put out tables that are intended + to be included in documents using the respective mark-up + language. They are not complete documents! This might not be + necessary in <acronym>HTML</acronym>, but in + <application>LaTeX</application> you must have a complete + document wrapper. + The <literal>latex</literal> format + uses <application>LaTeX</application>'s <literal>tabular</literal> + environment. + The <literal>latex-longtable</literal> format + requires the <application>LaTeX</application> + <literal>longtable</literal> and <literal>booktabs</literal> packages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>linestyle</literal></term> + <listitem> + <para> + Sets the border line drawing style to one + of <literal>ascii</literal>, <literal>old-ascii</literal>, + or <literal>unicode</literal>. + Unique abbreviations are allowed. (That would mean one + letter is enough.) + The default setting is <literal>ascii</literal>. + This option only affects the <literal>aligned</literal> and + <literal>wrapped</literal> output formats. + </para> + + <para><literal>ascii</literal> style uses plain <acronym>ASCII</acronym> + characters. Newlines in data are shown using + a <literal>+</literal> symbol in the right-hand margin. + When the <literal>wrapped</literal> format wraps data from + one line to the next without a newline character, a dot + (<literal>.</literal>) is shown in the right-hand margin of the first line, + and again in the left-hand margin of the following line. + </para> + + <para><literal>old-ascii</literal> style uses plain <acronym>ASCII</acronym> + characters, using the formatting style used + in <productname>PostgreSQL</productname> 8.4 and earlier. + Newlines in data are shown using a <literal>:</literal> + symbol in place of the left-hand column separator. + When the data is wrapped from one line + to the next without a newline character, a <literal>;</literal> + symbol is used in place of the left-hand column separator. + </para> + + <para><literal>unicode</literal> style uses Unicode box-drawing characters. + Newlines in data are shown using a carriage return symbol + in the right-hand margin. When the data is wrapped from one line + to the next without a newline character, an ellipsis symbol + is shown in the right-hand margin of the first line, and + again in the left-hand margin of the following line. + </para> + + <para> + When the <literal>border</literal> setting is greater than zero, + the <literal>linestyle</literal> option also determines the + characters with which the border lines are drawn. + Plain <acronym>ASCII</acronym> characters work everywhere, but + Unicode characters look nicer on displays that recognize them. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>null</literal></term> + <listitem> + <para> + Sets the string to be printed in place of a null value. + The default is to print nothing, which can easily be mistaken for + an empty string. For example, one might prefer <literal>\pset null + '(null)'</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>numericlocale</literal></term> + <listitem> + <para> + If <replaceable class="parameter">value</replaceable> is specified + it must be either <literal>on</literal> or <literal>off</literal> + which will enable or disable display of a locale-specific character + to separate groups of digits to the left of the decimal marker. + If <replaceable class="parameter">value</replaceable> is omitted the + command toggles between regular and locale-specific numeric output. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>pager</literal></term> + <listitem> + <para> + Controls use of a pager program for query and <application>psql</application> + help output. + When the <literal>pager</literal> option is <literal>off</literal>, the pager + program is not used. When the <literal>pager</literal> option is + <literal>on</literal>, the pager is used when appropriate, i.e., when the + output is to a terminal and will not fit on the screen. + The <literal>pager</literal> option can also be set to <literal>always</literal>, + which causes the pager to be used for all terminal output regardless + of whether it fits on the screen. <literal>\pset pager</literal> + without a <replaceable class="parameter">value</replaceable> + toggles pager use on and off. + </para> + + <para> + If the environment variable <envar>PSQL_PAGER</envar> + or <envar>PAGER</envar> is set, output to be paged is piped to the + specified program. Otherwise a platform-dependent default program + (such as <filename>more</filename>) is used. + </para> + + <para> + When using the <literal>\watch</literal> command to execute a query + repeatedly, the environment variable <envar>PSQL_WATCH_PAGER</envar> + is used to find the pager program instead, on Unix systems. This is + configured separately because it may confuse traditional pagers, but + can be used to send output to tools that understand + <application>psql</application>'s output format (such as + <filename>pspg --stream</filename>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>pager_min_lines</literal></term> + <listitem> + <para> + If <literal>pager_min_lines</literal> is set to a number greater than the + page height, the pager program will not be called unless there are + at least this many lines of output to show. The default setting + is 0. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>recordsep</literal></term> + <listitem> + <para> + Specifies the record (line) separator to use in unaligned + output format. The default is a newline character. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>recordsep_zero</literal></term> + <listitem> + <para> + Sets the record separator to use in unaligned output format to a zero + byte. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>tableattr</literal> (or <literal>T</literal>)</term> + <listitem> + <para> + In <acronym>HTML</acronym> format, this specifies attributes + to be placed inside the <sgmltag>table</sgmltag> tag. This + could for example be <literal>cellpadding</literal> or + <literal>bgcolor</literal>. Note that you probably don't want + to specify <literal>border</literal> here, as that is already + taken care of by <literal>\pset border</literal>. + If no + <replaceable class="parameter">value</replaceable> is given, + the table attributes are unset. + </para> + <para> + In <literal>latex-longtable</literal> format, this controls + the proportional width of each column containing a left-aligned + data type. It is specified as a whitespace-separated list of values, + e.g., <literal>'0.2 0.2 0.6'</literal>. Unspecified output columns + use the last specified value. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>title</literal> (or <literal>C</literal>)</term> + <listitem> + <para> + Sets the table title for any subsequently printed tables. This + can be used to give your output descriptive tags. If no + <replaceable class="parameter">value</replaceable> is given, + the title is unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>tuples_only</literal> (or <literal>t</literal>)</term> + <listitem> + <para> + If <replaceable class="parameter">value</replaceable> is specified + it must be either <literal>on</literal> or <literal>off</literal> + which will enable or disable tuples-only mode. + If <replaceable class="parameter">value</replaceable> is omitted the + command toggles between regular and tuples-only output. + Regular output includes extra information such + as column headers, titles, and various footers. In tuples-only + mode, only actual table data is shown. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>unicode_border_linestyle</literal></term> + <listitem> + <para> + Sets the border drawing style for the <literal>unicode</literal> + line style to one of <literal>single</literal> + or <literal>double</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>unicode_column_linestyle</literal></term> + <listitem> + <para> + Sets the column drawing style for the <literal>unicode</literal> + line style to one of <literal>single</literal> + or <literal>double</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>unicode_header_linestyle</literal></term> + <listitem> + <para> + Sets the header drawing style for the <literal>unicode</literal> + line style to one of <literal>single</literal> + or <literal>double</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Illustrations of how these different formats look can be seen in + <xref linkend="app-psql-examples"/>, below. + </para> + + <tip> + <para> + There are various shortcut commands for <command>\pset</command>. See + <command>\a</command>, <command>\C</command>, <command>\f</command>, + <command>\H</command>, <command>\t</command>, <command>\T</command>, + and <command>\x</command>. + </para> + </tip> + + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\q</literal> or <literal>\quit</literal></term> + <listitem> + <para> + Quits the <application>psql</application> program. + In a script file, only execution of that script is terminated. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\qecho <replaceable class="parameter">text</replaceable> [ ... ] </literal></term> + <listitem> + <para> + This command is identical to <command>\echo</command> except + that the output will be written to the query output channel, as + set by <command>\o</command>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\r</literal> or <literal>\reset</literal></term> + <listitem> + <para> + Resets (clears) the query buffer. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\s [ <replaceable class="parameter">filename</replaceable> ]</literal></term> + <listitem> + <para> + Print <application>psql</application>'s command line history + to <replaceable class="parameter">filename</replaceable>. + If <replaceable class="parameter">filename</replaceable> is omitted, + the history is written to the standard output (using the pager if + appropriate). This command is not available + if <application>psql</application> was built + without <application>Readline</application> support. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\set [ <replaceable class="parameter">name</replaceable> [ <replaceable class="parameter">value</replaceable> [ ... ] ] ]</literal></term> + + <listitem> + <para> + Sets the <application>psql</application> variable <replaceable + class="parameter">name</replaceable> to <replaceable + class="parameter">value</replaceable>, or if more than one value + is given, to the concatenation of all of them. If only one + argument is given, the variable is set to an empty-string value. To + unset a variable, use the <command>\unset</command> command. + </para> + + <para><command>\set</command> without any arguments displays the names and values + of all currently-set <application>psql</application> variables. + </para> + + <para> + Valid variable names can contain letters, digits, and + underscores. See <xref linkend="app-psql-variables"/> below for details. + Variable names are case-sensitive. + </para> + + <para> + Certain variables are special, in that they + control <application>psql</application>'s behavior or are + automatically set to reflect connection state. These variables are + documented in <xref linkend="app-psql-variables"/>, below. + </para> + + <note> + <para> + This command is unrelated to the <acronym>SQL</acronym> + command <link linkend="sql-set"><command>SET</command></link>. + </para> + </note> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\setenv <replaceable class="parameter">name</replaceable> [ <replaceable class="parameter">value</replaceable> ]</literal></term> + + <listitem> + <para> + Sets the environment variable <replaceable + class="parameter">name</replaceable> to <replaceable + class="parameter">value</replaceable>, or if the + <replaceable class="parameter">value</replaceable> is + not supplied, unsets the environment variable. Example: +<programlisting> +testdb=> <userinput>\setenv PAGER less</userinput> +testdb=> <userinput>\setenv LESS -imx4F</userinput> +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>\sf[+] <replaceable class="parameter">function_description</replaceable> </literal></term> + + <listitem> + <para> + This command fetches and shows the definition of the named function or procedure, + in the form of a <command>CREATE OR REPLACE FUNCTION</command> or + <command>CREATE OR REPLACE PROCEDURE</command> command. + The definition is printed to the current query output channel, + as set by <command>\o</command>. + </para> + + <para> + The target function can be specified by name alone, or by name + and arguments, for example <literal>foo(integer, text)</literal>. + The argument types must be given if there is more + than one function of the same name. + </para> + + <para> + If <literal>+</literal> is appended to the command name, then the + output lines are numbered, with the first line of the function body + being line 1. + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\sf</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\sv[+] <replaceable class="parameter">view_name</replaceable> </literal></term> + + <listitem> + <para> + This command fetches and shows the definition of the named view, + in the form of a <command>CREATE OR REPLACE VIEW</command> command. + The definition is printed to the current query output channel, + as set by <command>\o</command>. + </para> + + <para> + If <literal>+</literal> is appended to the command name, then the + output lines are numbered from 1. + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\sv</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\t</literal></term> + <listitem> + <para> + Toggles the display of output column name headings and row count + footer. This command is equivalent to <literal>\pset + tuples_only</literal> and is provided for convenience. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\T <replaceable class="parameter">table_options</replaceable></literal></term> + <listitem> + <para> + Specifies attributes to be placed within the + <sgmltag>table</sgmltag> tag in <acronym>HTML</acronym> + output format. This command is equivalent to <literal>\pset + tableattr <replaceable + class="parameter">table_options</replaceable></literal>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\timing [ <replaceable class="parameter">on</replaceable> | <replaceable class="parameter">off</replaceable> ]</literal></term> + <listitem> + <para> + With a parameter, turns displaying of how long each SQL statement + takes on or off. Without a parameter, toggles the display between + on and off. The display is in milliseconds; intervals longer than + 1 second are also shown in minutes:seconds format, with hours and + days fields added if needed. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\unset <replaceable class="parameter">name</replaceable></literal></term> + + <listitem> + <para> + Unsets (deletes) the <application>psql</application> variable <replaceable + class="parameter">name</replaceable>. + </para> + + <para> + Most variables that control <application>psql</application>'s behavior + cannot be unset; instead, an <literal>\unset</literal> command is interpreted + as setting them to their default values. + See <xref linkend="app-psql-variables"/> below. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\w</literal> or <literal>\write</literal> <replaceable class="parameter">filename</replaceable></term> + <term><literal>\w</literal> or <literal>\write</literal> <literal>|</literal><replaceable class="parameter">command</replaceable></term> + <listitem> + <para> + Writes the current query buffer to the file <replaceable + class="parameter">filename</replaceable> or pipes it to the shell + command <replaceable class="parameter">command</replaceable>. + If the current query buffer is empty, the most recently executed query + is written instead. + </para> + + <para> + If the argument begins with <literal>|</literal>, then the entire remainder + of the line is taken to be + the <replaceable class="parameter">command</replaceable> to execute, + and neither variable interpolation nor backquote expansion are + performed in it. The rest of the line is simply passed literally to + the shell. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\warn <replaceable class="parameter">text</replaceable> [ ... ]</literal></term> + <listitem> + <para> + This command is identical to <command>\echo</command> except + that the output will be written to <application>psql</application>'s + standard error channel, rather than standard output. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\watch [ <replaceable class="parameter">seconds</replaceable> ]</literal></term> + <listitem> + <para> + Repeatedly execute the current query buffer (as <literal>\g</literal> does) + until interrupted or the query fails. Wait the specified number of + seconds (default 2) between executions. Each query result is + displayed with a header that includes the <literal>\pset title</literal> + string (if any), the time as of query start, and the delay interval. + </para> + <para> + If the current query buffer is empty, the most recently sent query + is re-executed instead. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\x [ <replaceable class="parameter">on</replaceable> | <replaceable class="parameter">off</replaceable> | <replaceable class="parameter">auto</replaceable> ]</literal></term> + <listitem> + <para> + Sets or toggles expanded table formatting mode. As such it is equivalent to + <literal>\pset expanded</literal>. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\z [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term> + <listitem> + <para> + Lists tables, views and sequences with their + associated access privileges. + If a <replaceable class="parameter">pattern</replaceable> is + specified, only tables, views and sequences whose names match the + pattern are listed. + </para> + + <para> + This is an alias for <command>\dp</command> (<quote>display + privileges</quote>). + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\! [ <replaceable class="parameter">command</replaceable> ]</literal></term> + <listitem> + <para> + With no argument, escapes to a sub-shell; <application>psql</application> + resumes when the sub-shell exits. With an argument, executes the + shell command <replaceable class="parameter">command</replaceable>. + </para> + + <para> + Unlike most other meta-commands, the entire remainder of the line is + always taken to be the argument(s) of <command>\!</command>, and neither + variable interpolation nor backquote expansion are performed in the + arguments. The rest of the line is simply passed literally to the + shell. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\? [ <replaceable class="parameter">topic</replaceable> ]</literal></term> + <listitem> + <para> + Shows help information. The optional + <replaceable class="parameter">topic</replaceable> parameter + (defaulting to <literal>commands</literal>) selects which part of <application>psql</application> is + explained: <literal>commands</literal> describes <application>psql</application>'s + backslash commands; <literal>options</literal> describes the command-line + options that can be passed to <application>psql</application>; + and <literal>variables</literal> shows help about <application>psql</application> configuration + variables. + </para> + </listitem> + </varlistentry> + + + <varlistentry> + <term><literal>\;</literal></term> + <listitem> + <para> + Backslash-semicolon is not a meta-command in the same way as the + preceding commands; rather, it simply causes a semicolon to be + added to the query buffer without any further processing. + </para> + + <para> + Normally, <application>psql</application> will dispatch an SQL command to the + server as soon as it reaches the command-ending semicolon, even if + more input remains on the current line. Thus for example entering +<programlisting> +select 1; select 2; select 3; +</programlisting> + will result in the three SQL commands being individually sent to + the server, with each one's results being displayed before + continuing to the next command. However, a semicolon entered + as <literal>\;</literal> will not trigger command processing, so that the + command before it and the one after are effectively combined and + sent to the server in one request. So for example +<programlisting> +select 1\; select 2\; select 3; +</programlisting> + results in sending the three SQL commands to the server in a single + request, when the non-backslashed semicolon is reached. + The server executes such a request as a single transaction, + unless there are explicit <command>BEGIN</command>/<command>COMMIT</command> + commands included in the string to divide it into multiple + transactions. (See <xref linkend="protocol-flow-multi-statement"/> + for more details about how the server handles multi-query strings.) + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <refsect3 id="app-psql-patterns" xreflabel="Patterns"> + <title>Patterns</title> + + <indexterm> + <primary>patterns</primary> + <secondary>in psql and pg_dump</secondary> + </indexterm> + + <para> + The various <literal>\d</literal> commands accept a <replaceable + class="parameter">pattern</replaceable> parameter to specify the + object name(s) to be displayed. In the simplest case, a pattern + is just the exact name of the object. The characters within a + pattern are normally folded to lower case, just as in SQL names; + for example, <literal>\dt FOO</literal> will display the table named + <literal>foo</literal>. As in SQL names, placing double quotes around + a pattern stops folding to lower case. Should you need to include + an actual double quote character in a pattern, write it as a pair + of double quotes within a double-quote sequence; again this is in + accord with the rules for SQL quoted identifiers. For example, + <literal>\dt "FOO""BAR"</literal> will display the table named + <literal>FOO"BAR</literal> (not <literal>foo"bar</literal>). Unlike the normal + rules for SQL names, you can put double quotes around just part + of a pattern, for instance <literal>\dt FOO"FOO"BAR</literal> will display + the table named <literal>fooFOObar</literal>. + </para> + + <para> + Whenever the <replaceable class="parameter">pattern</replaceable> parameter + is omitted completely, the <literal>\d</literal> commands display all objects + that are visible in the current schema search path — this is + equivalent to using <literal>*</literal> as the pattern. + (An object is said to be <firstterm>visible</firstterm> if its + containing schema is in the search path and no object of the same + kind and name appears earlier in the search path. This is equivalent to the + statement that the object can be referenced by name without explicit + schema qualification.) + To see all objects in the database regardless of visibility, + use <literal>*.*</literal> as the pattern. + </para> + + <para> + Within a pattern, <literal>*</literal> matches any sequence of characters + (including no characters) and <literal>?</literal> matches any single character. + (This notation is comparable to Unix shell file name patterns.) + For example, <literal>\dt int*</literal> displays tables whose names + begin with <literal>int</literal>. But within double quotes, <literal>*</literal> + and <literal>?</literal> lose these special meanings and are just matched + literally. + </para> + + <para> + A relation pattern that contains a dot (<literal>.</literal>) is interpreted as a schema + name pattern followed by an object name pattern. For example, + <literal>\dt foo*.*bar*</literal> displays all tables whose table name + includes <literal>bar</literal> that are in schemas whose schema name + starts with <literal>foo</literal>. When no dot appears, then the pattern + matches only objects that are visible in the current schema search path. + Again, a dot within double quotes loses its special meaning and is matched + literally. A relation pattern that contains two dots (<literal>.</literal>) + is interpreted as a database name followed by a schema name pattern followed + by an object name pattern. The database name portion will not be treated as + a pattern and must match the name of the currently connected database, else + an error will be raised. + </para> + + <para> + A schema pattern that contains a dot (<literal>.</literal>) is interpreted + as a database name followed by a schema name pattern. For example, + <literal>\dn mydb.*foo*</literal> displays all schemas whose schema name + includes <literal>foo</literal>. The database name portion will not be + treated as a pattern and must match the name of the currently connected + database, else an error will be raised. + </para> + + <para> + Advanced users can use regular-expression notations such as character + classes, for example <literal>[0-9]</literal> to match any digit. All regular + expression special characters work as specified in + <xref linkend="functions-posix-regexp"/>, except for <literal>.</literal> which + is taken as a separator as mentioned above, <literal>*</literal> which is + translated to the regular-expression notation <literal>.*</literal>, + <literal>?</literal> which is translated to <literal>.</literal>, and + <literal>$</literal> which is matched literally. You can emulate + these pattern characters at need by writing + <literal>?</literal> for <literal>.</literal>, + <literal>(<replaceable class="parameter">R</replaceable>+|)</literal> for + <literal><replaceable class="parameter">R</replaceable>*</literal>, or + <literal>(<replaceable class="parameter">R</replaceable>|)</literal> for + <literal><replaceable class="parameter">R</replaceable>?</literal>. + <literal>$</literal> is not needed as a regular-expression character since + the pattern must match the whole name, unlike the usual + interpretation of regular expressions (in other words, <literal>$</literal> + is automatically appended to your pattern). Write <literal>*</literal> at the + beginning and/or end if you don't wish the pattern to be anchored. + Note that within double quotes, all regular expression special characters + lose their special meanings and are matched literally. Also, the regular + expression special characters are matched literally in operator name + patterns (i.e., the argument of <literal>\do</literal>). + </para> + </refsect3> + </refsect2> + + <refsect2> + <title>Advanced Features</title> + + <refsect3 id="app-psql-variables" xreflabel="Variables"> + <title>Variables</title> + + <para> + <application>psql</application> provides variable substitution + features similar to common Unix command shells. + Variables are simply name/value pairs, where the value + can be any string of any length. The name must consist of letters + (including non-Latin letters), digits, and underscores. + </para> + + <para> + To set a variable, use the <application>psql</application> meta-command + <command>\set</command>. For example, +<programlisting> +testdb=> <userinput>\set foo bar</userinput> +</programlisting> + sets the variable <literal>foo</literal> to the value + <literal>bar</literal>. To retrieve the content of the variable, precede + the name with a colon, for example: +<programlisting> +testdb=> <userinput>\echo :foo</userinput> +bar +</programlisting> + This works in both regular SQL commands and meta-commands; there is + more detail in <xref linkend="app-psql-interpolation"/>, below. + </para> + + <para> + If you call <command>\set</command> without a second argument, the + variable is set to an empty-string value. To unset (i.e., delete) + a variable, use the command <command>\unset</command>. To show the + values of all variables, call <command>\set</command> without any argument. + </para> + + <note> + <para> + The arguments of <command>\set</command> are subject to the same + substitution rules as with other commands. Thus you can construct + interesting references such as <literal>\set :foo + 'something'</literal> and get <quote>soft links</quote> or + <quote>variable variables</quote> of <productname>Perl</productname> + or <productname><acronym>PHP</acronym></productname> fame, + respectively. Unfortunately (or fortunately?), there is no way to do + anything useful with these constructs. On the other hand, + <literal>\set bar :foo</literal> is a perfectly valid way to copy a + variable. + </para> + </note> + + <para> + A number of these variables are treated specially + by <application>psql</application>. They represent certain option + settings that can be changed at run time by altering the value of + the variable, or in some cases represent changeable state of + <application>psql</application>. + By convention, all specially treated variables' names + consist of all upper-case ASCII letters (and possibly digits and + underscores). To ensure maximum compatibility in the future, avoid + using such variable names for your own purposes. + </para> + + <para> + Variables that control <application>psql</application>'s behavior + generally cannot be unset or set to invalid values. An <literal>\unset</literal> + command is allowed but is interpreted as setting the variable to its + default value. A <literal>\set</literal> command without a second argument is + interpreted as setting the variable to <literal>on</literal>, for control + variables that accept that value, and is rejected for others. Also, + control variables that accept the values <literal>on</literal> + and <literal>off</literal> will also accept other common spellings of Boolean + values, such as <literal>true</literal> and <literal>false</literal>. + </para> + + <para> + The specially treated variables are: + </para> + + <variablelist> + <varlistentry> + <term> + <varname>AUTOCOMMIT</varname> + <indexterm> + <primary>autocommit</primary> + <secondary>psql</secondary> + </indexterm> + </term> + <listitem> + <para> + When <literal>on</literal> (the default), each SQL command is automatically + committed upon successful completion. To postpone commit in this + mode, you must enter a <command>BEGIN</command> or <command>START + TRANSACTION</command> SQL command. When <literal>off</literal> or unset, SQL + commands are not committed until you explicitly issue + <command>COMMIT</command> or <command>END</command>. The autocommit-off + mode works by issuing an implicit <command>BEGIN</command> for you, just + before any command that is not already in a transaction block and + is not itself a <command>BEGIN</command> or other transaction-control + command, nor a command that cannot be executed inside a transaction + block (such as <command>VACUUM</command>). + </para> + + <note> + <para> + In autocommit-off mode, you must explicitly abandon any failed + transaction by entering <command>ABORT</command> or <command>ROLLBACK</command>. + Also keep in mind that if you exit the session + without committing, your work will be lost. + </para> + </note> + + <note> + <para> + The autocommit-on mode is <productname>PostgreSQL</productname>'s traditional + behavior, but autocommit-off is closer to the SQL spec. If you + prefer autocommit-off, you might wish to set it in the system-wide + <filename>psqlrc</filename> file or your + <filename>~/.psqlrc</filename> file. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>COMP_KEYWORD_CASE</varname></term> + <listitem> + <para> + Determines which letter case to use when completing an SQL key word. + If set to <literal>lower</literal> or <literal>upper</literal>, the + completed word will be in lower or upper case, respectively. If set + to <literal>preserve-lower</literal> + or <literal>preserve-upper</literal> (the default), the completed word + will be in the case of the word already entered, but words being + completed without anything entered will be in lower or upper case, + respectively. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>DBNAME</varname></term> + <listitem> + <para> + The name of the database you are currently connected to. This is + set every time you connect to a database (including program + start-up), but can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ECHO</varname></term> + <listitem> + <para> + If set to <literal>all</literal>, all nonempty input lines are printed + to standard output as they are read. (This does not apply to lines + read interactively.) To select this behavior on program + start-up, use the switch <option>-a</option>. If set to + <literal>queries</literal>, + <application>psql</application> prints each query to standard output + as it is sent to the server. The switch to select this behavior is + <option>-e</option>. If set to <literal>errors</literal>, then only + failed queries are displayed on standard error output. The switch + for this behavior is <option>-b</option>. If set to + <literal>none</literal> (the default), then no queries are displayed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ECHO_HIDDEN</varname></term> + <listitem> + <para> + When this variable is set to <literal>on</literal> and a backslash command + queries the database, the query is first shown. + This feature helps you to study + <productname>PostgreSQL</productname> internals and provide + similar functionality in your own programs. (To select this behavior + on program start-up, use the switch <option>-E</option>.) If you set + this variable to the value <literal>noexec</literal>, the queries are + just shown but are not actually sent to the server and executed. + The default value is <literal>off</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ENCODING</varname></term> + <listitem> + <para> + The current client character set encoding. + This is set every time you connect to a database (including + program start-up), and when you change the encoding + with <literal>\encoding</literal>, but it can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ERROR</varname></term> + <listitem> + <para> + <literal>true</literal> if the last SQL query failed, <literal>false</literal> if + it succeeded. See also <varname>SQLSTATE</varname>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>FETCH_COUNT</varname></term> + <listitem> + <para> + If this variable is set to an integer value greater than zero, + the results of <command>SELECT</command> queries are fetched + and displayed in groups of that many rows, rather than the + default behavior of collecting the entire result set before + display. Therefore only a + limited amount of memory is used, regardless of the size of + the result set. Settings of 100 to 1000 are commonly used + when enabling this feature. + Keep in mind that when using this feature, a query might + fail after having already displayed some rows. + </para> + + <tip> + <para> + Although you can use any output format with this feature, + the default <literal>aligned</literal> format tends to look bad + because each group of <varname>FETCH_COUNT</varname> rows + will be formatted separately, leading to varying column + widths across the row groups. The other output formats work better. + </para> + </tip> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HIDE_TABLEAM</varname></term> + <listitem> + <para> + If this variable is set to <literal>true</literal>, a table's access + method details are not displayed. This is mainly useful for + regression tests. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HIDE_TOAST_COMPRESSION</varname></term> + <listitem> + <para> + If this variable is set to <literal>true</literal>, column + compression method details are not displayed. This is mainly + useful for regression tests. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HISTCONTROL</varname></term> + <listitem> + <para> + If this variable is set to <literal>ignorespace</literal>, + lines which begin with a space are not entered into the history + list. If set to a value of <literal>ignoredups</literal>, lines + matching the previous history line are not entered. A value of + <literal>ignoreboth</literal> combines the two options. If + set to <literal>none</literal> (the default), all lines + read in interactive mode are saved on the history list. + </para> + <note> + <para> + This feature was shamelessly plagiarized from + <application>Bash</application>. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HISTFILE</varname></term> + <listitem> + <para> + The file name that will be used to store the history list. If unset, + the file name is taken from the <envar>PSQL_HISTORY</envar> + environment variable. If that is not set either, the default + is <filename>~/.psql_history</filename>, + or <filename>%APPDATA%\postgresql\psql_history</filename> on Windows. + For example, putting: +<programlisting> +\set HISTFILE ~/.psql_history-:DBNAME +</programlisting> + in <filename>~/.psqlrc</filename> will cause + <application>psql</application> to maintain a separate history for + each database. + </para> + <note> + <para> + This feature was shamelessly plagiarized from + <application>Bash</application>. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HISTSIZE</varname></term> + <listitem> + <para> + The maximum number of commands to store in the command history + (default 500). If set to a negative value, no limit is applied. + </para> + <note> + <para> + This feature was shamelessly plagiarized from + <application>Bash</application>. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>HOST</varname></term> + <listitem> + <para> + The database server host you are currently connected to. This is + set every time you connect to a database (including program + start-up), but can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>IGNOREEOF</varname></term> + <listitem> + <para> + If set to 1 or less, sending an <acronym>EOF</acronym> character (usually + <keycombo action="simul"><keycap>Control</keycap><keycap>D</keycap></keycombo>) + to an interactive session of <application>psql</application> + will terminate the application. If set to a larger numeric value, + that many consecutive <acronym>EOF</acronym> characters must be typed to + make an interactive session terminate. If the variable is set to a + non-numeric value, it is interpreted as 10. The default is 0. + </para> + <note> + <para> + This feature was shamelessly plagiarized from + <application>Bash</application>. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>LASTOID</varname></term> + <listitem> + <para> + The value of the last affected OID, as returned from an + <command>INSERT</command> or <command>\lo_import</command> + command. This variable is only guaranteed to be valid until + after the result of the next <acronym>SQL</acronym> command has + been displayed. + <productname>PostgreSQL</productname> servers since version 12 do not + support OID system columns anymore, thus LASTOID will always be 0 + following <command>INSERT</command> when targeting such servers. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>LAST_ERROR_MESSAGE</varname></term> + <term><varname>LAST_ERROR_SQLSTATE</varname></term> + <listitem> + <para> + The primary error message and associated SQLSTATE code for the most + recent failed query in the current <application>psql</application> session, or + an empty string and <literal>00000</literal> if no error has occurred in + the current session. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <varname>ON_ERROR_ROLLBACK</varname> + <indexterm> + <primary>rollback</primary> + <secondary>psql</secondary> + </indexterm> + </term> + <listitem> + <para> + When set to <literal>on</literal>, if a statement in a transaction block + generates an error, the error is ignored and the transaction + continues. When set to <literal>interactive</literal>, such errors are only + ignored in interactive sessions, and not when reading script + files. When set to <literal>off</literal> (the default), a statement in a + transaction block that generates an error aborts the entire + transaction. The error rollback mode works by issuing an + implicit <command>SAVEPOINT</command> for you, just before each command + that is in a transaction block, and then rolling back to the + savepoint if the command fails. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ON_ERROR_STOP</varname></term> + <listitem> + <para> + By default, command processing continues after an error. When this + variable is set to <literal>on</literal>, processing will instead stop + immediately. In interactive mode, + <application>psql</application> will return to the command prompt; + otherwise, <application>psql</application> will exit, returning + error code 3 to distinguish this case from fatal error + conditions, which are reported using error code 1. In either case, + any currently running scripts (the top-level script, if any, and any + other scripts which it may have in invoked) will be terminated + immediately. If the top-level command string contained multiple SQL + commands, processing will stop with the current command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>PORT</varname></term> + <listitem> + <para> + The database server port to which you are currently connected. + This is set every time you connect to a database (including + program start-up), but can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>PROMPT1</varname></term> + <term><varname>PROMPT2</varname></term> + <term><varname>PROMPT3</varname></term> + <listitem> + <para> + These specify what the prompts <application>psql</application> + issues should look like. See <xref + linkend="app-psql-prompting"/> below. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>QUIET</varname></term> + <listitem> + <para> + Setting this variable to <literal>on</literal> is equivalent to the command + line option <option>-q</option>. It is probably not too useful in + interactive mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>ROW_COUNT</varname></term> + <listitem> + <para> + The number of rows returned or affected by the last SQL query, or 0 + if the query failed or did not report a row count. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SERVER_VERSION_NAME</varname></term> + <term><varname>SERVER_VERSION_NUM</varname></term> + <listitem> + <para> + The server's version number as a string, for + example <literal>9.6.2</literal>, <literal>10.1</literal> or <literal>11beta1</literal>, + and in numeric form, for + example <literal>90602</literal> or <literal>100001</literal>. + These are set every time you connect to a database + (including program start-up), but can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SHOW_ALL_RESULTS</varname></term> + <listitem> + <para> + When this variable is set to <literal>off</literal>, only the last + result of a combined query (<literal>\;</literal>) is shown instead of + all of them. The default is <literal>on</literal>. The off behavior + is for compatibility with older versions of psql. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SHOW_CONTEXT</varname></term> + <listitem> + <para> + This variable can be set to the + values <literal>never</literal>, <literal>errors</literal>, or <literal>always</literal> + to control whether <literal>CONTEXT</literal> fields are displayed in + messages from the server. The default is <literal>errors</literal> (meaning + that context will be shown in error messages, but not in notice or + warning messages). This setting has no effect + when <varname>VERBOSITY</varname> is set to <literal>terse</literal> + or <literal>sqlstate</literal>. + (See also <command>\errverbose</command>, for use when you want a verbose + version of the error you just got.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SINGLELINE</varname></term> + <listitem> + <para> + Setting this variable to <literal>on</literal> is equivalent to the command + line option <option>-S</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SINGLESTEP</varname></term> + <listitem> + <para> + Setting this variable to <literal>on</literal> is equivalent to the command + line option <option>-s</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>SQLSTATE</varname></term> + <listitem> + <para> + The error code (see <xref linkend="errcodes-appendix"/>) associated + with the last SQL query's failure, or <literal>00000</literal> if it + succeeded. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>USER</varname></term> + <listitem> + <para> + The database user you are currently connected as. This is set + every time you connect to a database (including program + start-up), but can be changed or unset. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>VERBOSITY</varname></term> + <listitem> + <para> + This variable can be set to the values <literal>default</literal>, + <literal>verbose</literal>, <literal>terse</literal>, + or <literal>sqlstate</literal> to control the verbosity of error + reports. + (See also <command>\errverbose</command>, for use when you want a verbose + version of the error you just got.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><varname>VERSION</varname></term> + <term><varname>VERSION_NAME</varname></term> + <term><varname>VERSION_NUM</varname></term> + <listitem> + <para> + These variables are set at program start-up to reflect + <application>psql</application>'s version, respectively as a verbose string, + a short string (e.g., <literal>9.6.2</literal>, <literal>10.1</literal>, + or <literal>11beta1</literal>), and a number (e.g., <literal>90602</literal> + or <literal>100001</literal>). They can be changed or unset. + </para> + </listitem> + </varlistentry> + + </variablelist> + + </refsect3> + + <refsect3 id="app-psql-interpolation" xreflabel="SQL Interpolation"> + <title><acronym>SQL</acronym> Interpolation</title> + + <para> + A key feature of <application>psql</application> + variables is that you can substitute (<quote>interpolate</quote>) + them into regular <acronym>SQL</acronym> statements, as well as the + arguments of meta-commands. Furthermore, + <application>psql</application> provides facilities for + ensuring that variable values used as SQL literals and identifiers are + properly quoted. The syntax for interpolating a value without + any quoting is to prepend the variable name with a colon + (<literal>:</literal>). For example, +<programlisting> +testdb=> <userinput>\set foo 'my_table'</userinput> +testdb=> <userinput>SELECT * FROM :foo;</userinput> +</programlisting> + would query the table <literal>my_table</literal>. Note that this + may be unsafe: the value of the variable is copied literally, so it can + contain unbalanced quotes, or even backslash commands. You must make sure + that it makes sense where you put it. + </para> + + <para> + When a value is to be used as an SQL literal or identifier, it is + safest to arrange for it to be quoted. To quote the value of + a variable as an SQL literal, write a colon followed by the variable + name in single quotes. To quote the value as an SQL identifier, write + a colon followed by the variable name in double quotes. + These constructs deal correctly with quotes and other special + characters embedded within the variable value. + The previous example would be more safely written this way: +<programlisting> +testdb=> <userinput>\set foo 'my_table'</userinput> +testdb=> <userinput>SELECT * FROM :"foo";</userinput> +</programlisting> + </para> + + <para> + Variable interpolation will not be performed within quoted + <acronym>SQL</acronym> literals and identifiers. Therefore, a + construction such as <literal>':foo'</literal> doesn't work to produce a quoted + literal from a variable's value (and it would be unsafe if it did work, + since it wouldn't correctly handle quotes embedded in the value). + </para> + + <para> + One example use of this mechanism is to + copy the contents of a file into a table column. + First load the file into a variable and then interpolate the variable's + value as a quoted string: +<programlisting> +testdb=> <userinput>\set content `cat my_file.txt`</userinput> +testdb=> <userinput>INSERT INTO my_table VALUES (:'content');</userinput> +</programlisting> + (Note that this still won't work if <filename>my_file.txt</filename> contains NUL bytes. + <application>psql</application> does not support embedded NUL bytes in variable values.) + </para> + + <para> + Since colons can legally appear in SQL commands, an apparent attempt + at interpolation (that is, <literal>:name</literal>, + <literal>:'name'</literal>, or <literal>:"name"</literal>) is not + replaced unless the named variable is currently set. In any case, you + can escape a colon with a backslash to protect it from substitution. + </para> + + <para> + The <literal>:{?<replaceable>name</replaceable>}</literal> special syntax returns TRUE + or FALSE depending on whether the variable exists or not, and is thus + always substituted, unless the colon is backslash-escaped. + </para> + + <para> + The colon syntax for variables is standard <acronym>SQL</acronym> for + embedded query languages, such as <application>ECPG</application>. + The colon syntaxes for array slices and type casts are + <productname>PostgreSQL</productname> extensions, which can sometimes + conflict with the standard usage. The colon-quote syntax for escaping a + variable's value as an SQL literal or identifier is a + <application>psql</application> extension. + </para> + + </refsect3> + + <refsect3 id="app-psql-prompting" xreflabel="Prompting"> + <title>Prompting</title> + + <para> + The prompts <application>psql</application> issues can be customized + to your preference. The three variables <varname>PROMPT1</varname>, + <varname>PROMPT2</varname>, and <varname>PROMPT3</varname> contain strings + and special escape sequences that describe the appearance of the + prompt. Prompt 1 is the normal prompt that is issued when + <application>psql</application> requests a new command. Prompt 2 is + issued when more input is expected during command entry, for example + because the command was not terminated with a semicolon or a quote + was not closed. + Prompt 3 is issued when you are running an <acronym>SQL</acronym> + <command>COPY FROM STDIN</command> command and you need to type in + a row value on the terminal. + </para> + + <para> + The value of the selected prompt variable is printed literally, + except where a percent sign (<literal>%</literal>) is encountered. + Depending on the next character, certain other text is substituted + instead. Defined substitutions are: + + <variablelist> + <varlistentry> + <term><literal>%M</literal></term> + <listitem> + <para> + The full host name (with domain name) of the database server, + or <literal>[local]</literal> if the connection is over a Unix + domain socket, or + <literal>[local:<replaceable>/dir/name</replaceable>]</literal>, + if the Unix domain socket is not at the compiled in default + location. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%m</literal></term> + <listitem> + <para> + The host name of the database server, truncated at the + first dot, or <literal>[local]</literal> if the connection is + over a Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%></literal></term> + <listitem><para>The port number at which the database server is listening.</para></listitem> + </varlistentry> + + <varlistentry> + <term><literal>%n</literal></term> + <listitem> + <para> + The database session user name. (The expansion of this + value might change during a database session as the result + of the command <command>SET SESSION + AUTHORIZATION</command>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%/</literal></term> + <listitem><para>The name of the current database.</para></listitem> + </varlistentry> + + <varlistentry> + <term><literal>%~</literal></term> + <listitem><para>Like <literal>%/</literal>, but the output is <literal>~</literal> + (tilde) if the database is your default database.</para></listitem> + </varlistentry> + + <varlistentry> + <term><literal>%#</literal></term> + <listitem> + <para> + If the session user is a database superuser, then a + <literal>#</literal>, otherwise a <literal>></literal>. + (The expansion of this value might change during a database + session as the result of the command <command>SET SESSION + AUTHORIZATION</command>.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%p</literal></term> + <listitem> + <para>The process ID of the backend currently connected to.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%R</literal></term> + <listitem> + <para> + In prompt 1 normally <literal>=</literal>, + but <literal>@</literal> if the session is in an inactive branch of a + conditional block, or <literal>^</literal> if in single-line mode, + or <literal>!</literal> if the session is disconnected from the + database (which can happen if <command>\connect</command> fails). + In prompt 2 <literal>%R</literal> is replaced by a character that + depends on why <application>psql</application> expects more input: + <literal>-</literal> if the command simply wasn't terminated yet, + but <literal>*</literal> if there is an unfinished + <literal>/* ... */</literal> comment, + a single quote if there is an unfinished quoted string, + a double quote if there is an unfinished quoted identifier, + a dollar sign if there is an unfinished dollar-quoted string, + or <literal>(</literal> if there is an unmatched left parenthesis. + In prompt 3 <literal>%R</literal> doesn't produce anything. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%x</literal></term> + <listitem> + <para> + Transaction status: an empty string when not in a transaction + block, or <literal>*</literal> when in a transaction block, or + <literal>!</literal> when in a failed transaction block, or <literal>?</literal> + when the transaction state is indeterminate (for example, because + there is no connection). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%l</literal></term> + <listitem> + <para> + The line number inside the current statement, starting from <literal>1</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%</literal><replaceable class="parameter">digits</replaceable></term> + <listitem> + <para> + The character with the indicated octal code is substituted. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%:</literal><replaceable class="parameter">name</replaceable><literal>:</literal></term> + <listitem> + <para> + The value of the <application>psql</application> variable + <replaceable class="parameter">name</replaceable>. See + <xref linkend="app-psql-variables"/>, above, for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%`</literal><replaceable class="parameter">command</replaceable><literal>`</literal></term> + <listitem> + <para> + The output of <replaceable + class="parameter">command</replaceable>, similar to ordinary + <quote>back-tick</quote> substitution. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%[</literal> ... <literal>%]</literal></term> + <listitem> + <para> + Prompts can contain terminal control characters which, for + example, change the color, background, or style of the prompt + text, or change the title of the terminal window. In order for + the line editing features of <application>Readline</application> to work properly, these + non-printing control characters must be designated as invisible + by surrounding them with <literal>%[</literal> and + <literal>%]</literal>. Multiple pairs of these can occur within + the prompt. For example: +<programlisting> +testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# ' +</programlisting> + results in a boldfaced (<literal>1;</literal>) yellow-on-black + (<literal>33;40</literal>) prompt on VT100-compatible, color-capable + terminals. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>%w</literal></term> + <listitem> + <para> + Whitespace of the same width as the most recent output of + <varname>PROMPT1</varname>. This can be used as a + <varname>PROMPT2</varname> setting, so that multi-line statements are + aligned with the first line, but there is no visible secondary prompt. + </para> + </listitem> + </varlistentry> + + </variablelist> + + To insert a percent sign into your prompt, write + <literal>%%</literal>. The default prompts are + <literal>'%/%R%x%# '</literal> for prompts 1 and 2, and + <literal>'>> '</literal> for prompt 3. + </para> + + <note> + <para> + This feature was shamelessly plagiarized from + <application>tcsh</application>. + </para> + </note> + + </refsect3> + + <refsect3 id="app-psql-readline"> + <title>Command-Line Editing</title> + + <indexterm> + <primary>Readline</primary> + <secondary>in psql</secondary> + </indexterm> + <indexterm> + <primary>libedit</primary> + <secondary>in psql</secondary> + </indexterm> + + <para> + <application>psql</application> uses + the <application>Readline</application> + or <application>libedit</application> library, if available, for + convenient line editing and retrieval. The command history is + automatically saved when <application>psql</application> exits and is + reloaded when <application>psql</application> starts up. Type + up-arrow or control-P to retrieve previous lines. + </para> + + <para> + You can also use tab completion to fill in partially-typed keywords + and SQL object names in many (by no means all) contexts. For example, + at the start of a command, typing <literal>ins</literal> and pressing + TAB will fill in <literal>insert into </literal>. Then, typing a few + characters of a table or schema name and pressing <literal>TAB</literal> + will fill in the unfinished name, or offer a menu of possible completions + when there's more than one. (Depending on the library in use, you may need to + press <literal>TAB</literal> more than once to get a menu.) + </para> + + <para> + Tab completion for SQL object names requires sending queries to the + server to find possible matches. In some contexts this can interfere + with other operations. For example, after <command>BEGIN</command> + it will be too late to issue <command>SET TRANSACTION ISOLATION + LEVEL</command> if a tab-completion query is issued in between. + If you do not want tab completion at all, you + can turn it off permanently by putting this in a file named + <filename>.inputrc</filename> in your home directory: +<programlisting> +$if psql +set disable-completion on +$endif +</programlisting> + (This is not a <application>psql</application> but a + <application>Readline</application> feature. Read its documentation + for further details.) + </para> + + <para> + The <option>-n</option> (<option>--no-readline</option>) command line + option can also be useful to disable use + of <application>Readline</application> for a single run + of <application>psql</application>. This prevents tab completion, + use or recording of command line history, and editing of multi-line + commands. It is particularly useful when you need to copy-and-paste + text that contains <literal>TAB</literal> characters. + </para> + </refsect3> + </refsect2> + </refsect1> + + + <refsect1 id="app-psql-environment" xreflabel="Environment"> + <title>Environment</title> + + <variablelist> + + <varlistentry> + <term><envar>COLUMNS</envar></term> + + <listitem> + <para> + If <literal>\pset columns</literal> is zero, controls the + width for the <literal>wrapped</literal> format and width for determining + if wide output requires the pager or should be switched to the + vertical format in expanded auto mode. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters (see <xref linkend="libpq-envars"/>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQL_EDITOR</envar></term> + <term><envar>EDITOR</envar></term> + <term><envar>VISUAL</envar></term> + + <listitem> + <para> + Editor used by the <command>\e</command>, <command>\ef</command>, + and <command>\ev</command> commands. + These variables are examined in the order listed; + the first that is set is used. + If none of them is set, the default is to use <filename>vi</filename> + on Unix systems or <filename>notepad.exe</filename> on Windows systems. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQL_EDITOR_LINENUMBER_ARG</envar></term> + + <listitem> + <para> + When <command>\e</command>, <command>\ef</command>, or + <command>\ev</command> is used + with a line number argument, this variable specifies the + command-line argument used to pass the starting line number to + the user's editor. For editors such as <productname>Emacs</productname> or + <productname>vi</productname>, this is a plus sign. Include a trailing + space in the value of the variable if there needs to be space + between the option name and the line number. Examples: +<programlisting> +PSQL_EDITOR_LINENUMBER_ARG='+' +PSQL_EDITOR_LINENUMBER_ARG='--line ' +</programlisting> + </para> + + <para> + The default is <literal>+</literal> on Unix systems + (corresponding to the default editor <filename>vi</filename>, + and useful for many other common editors); but there is no + default on Windows systems. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQL_HISTORY</envar></term> + + <listitem> + <para> + Alternative location for the command history file. Tilde (<literal>~</literal>) expansion is performed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQL_PAGER</envar></term> + <term><envar>PAGER</envar></term> + + <listitem> + <para> + If a query's results do not fit on the screen, they are piped + through this command. Typical values are <literal>more</literal> + or <literal>less</literal>. + Use of the pager can be disabled by setting <envar>PSQL_PAGER</envar> + or <envar>PAGER</envar> to an empty string, or by adjusting the + pager-related options of the <command>\pset</command> command. + These variables are examined in the order listed; + the first that is set is used. + If neither of them is set, the default is to use <literal>more</literal> on most + platforms, but <literal>less</literal> on Cygwin. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQL_WATCH_PAGER</envar></term> + + <listitem> + <para> + When a query is executed repeatedly with the <command>\watch</command> + command, a pager is not used by default. This behavior can be changed + by setting <envar>PSQL_WATCH_PAGER</envar> to a pager command, on Unix + systems. The <literal>pspg</literal> pager (not part of + <productname>PostgreSQL</productname> but available in many open source + software distributions) can display the output of + <command>\watch</command> if started with the option + <literal>--stream</literal>. + </para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PSQLRC</envar></term> + + <listitem> + <para> + Alternative location of the user's <filename>.psqlrc</filename> file. Tilde (<literal>~</literal>) expansion is performed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>SHELL</envar></term> + + <listitem> + <para> + Command executed by the <command>\!</command> command. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>TMPDIR</envar></term> + + <listitem> + <para> + Directory for storing temporary files. The default is + <filename>/tmp</filename>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Files</title> + + <variablelist> + <varlistentry> + <term><filename>psqlrc</filename> and <filename>~/.psqlrc</filename></term> + <listitem> + <para> + Unless it is passed an <option>-X</option> option, + <application>psql</application> attempts to read and execute commands + from the system-wide startup file (<filename>psqlrc</filename>) and then + the user's personal startup file (<filename>~/.psqlrc</filename>), after + connecting to the database but before accepting normal commands. + These files can be used to set up the client and/or the server to taste, + typically with <command>\set</command> and <command>SET</command> + commands. + </para> + <para> + The system-wide startup file is named <filename>psqlrc</filename>. + By default it is + sought in the installation's <quote>system configuration</quote> directory, + which is most reliably identified by running <literal>pg_config + --sysconfdir</literal>. + Typically this directory will be <filename>../etc/</filename> + relative to the directory containing + the <productname>PostgreSQL</productname> executables. + The directory to look in can be set explicitly via + the <envar>PGSYSCONFDIR</envar> environment variable. + </para> + <para> + The user's personal startup file is named <filename>.psqlrc</filename> + and is sought in the invoking user's home directory. + On Windows the personal startup file is instead named + <filename>%APPDATA%\postgresql\psqlrc.conf</filename>. + In either case, this default file path can be overridden by setting + the <envar>PSQLRC</envar> environment variable. + </para> + <para> + Both the system-wide startup file and the user's personal startup file + can be made <application>psql</application>-version-specific + by appending a dash and the <productname>PostgreSQL</productname> + major or minor release identifier to the file name, + for example <filename>~/.psqlrc-&majorversion;</filename> or + <filename>~/.psqlrc-&version;</filename>. + The most specific version-matching file will be read in preference + to a non-version-specific file. + These version suffixes are added after determining the file path + as explained above. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.psql_history</filename></term> + <listitem> + <para> + The command-line history is stored in the file + <filename>~/.psql_history</filename>, or + <filename>%APPDATA%\postgresql\psql_history</filename> on Windows. + </para> + <para> + The location of the history file can be set explicitly via + the <varname>HISTFILE</varname> <application>psql</application> variable or + the <envar>PSQL_HISTORY</envar> environment variable. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + + <refsect1> + <title>Notes</title> + + <itemizedlist> + <listitem> + <para><application>psql</application> works best with servers of the same + or an older major version. Backslash commands are particularly likely + to fail if the server is of a newer version than <application>psql</application> + itself. However, backslash commands of the <literal>\d</literal> family should + work with servers of versions back to 9.2, though not necessarily with + servers newer than <application>psql</application> itself. The general + functionality of running SQL commands and displaying query results + should also work with servers of a newer major version, but this cannot + be guaranteed in all cases. + </para> + <para> + If you want to use <application>psql</application> to connect to several + servers of different major versions, it is recommended that you use the + newest version of <application>psql</application>. Alternatively, you + can keep around a copy of <application>psql</application> from each + major version and be sure to use the version that matches the + respective server. But in practice, this additional complication should + not be necessary. + </para> + </listitem> + + <listitem> + <para> + Before <productname>PostgreSQL</productname> 9.6, + the <option>-c</option> option implied <option>-X</option> + (<option>--no-psqlrc</option>); this is no longer the case. + </para> + </listitem> + + <listitem> + <para> + Before <productname>PostgreSQL</productname> 8.4, + <application>psql</application> allowed the + first argument of a single-letter backslash command to start + directly after the command, without intervening whitespace. + Now, some whitespace is required. + </para> + </listitem> + </itemizedlist> + </refsect1> + + + <refsect1> + <title>Notes for Windows Users</title> + + <para> + <application>psql</application> is built as a <quote>console + application</quote>. Since the Windows console windows use a different + encoding than the rest of the system, you must take special care + when using 8-bit characters within <application>psql</application>. + If <application>psql</application> detects a problematic + console code page, it will warn you at startup. To change the + console code page, two things are necessary: + + <itemizedlist> + <listitem> + <para> + Set the code page by entering <userinput>cmd.exe /c chcp + 1252</userinput>. (1252 is a code page that is appropriate for + German; replace it with your value.) If you are using Cygwin, + you can put this command in <filename>/etc/profile</filename>. + </para> + </listitem> + + <listitem> + <para> + Set the console font to <literal>Lucida Console</literal>, because the + raster font does not work with the ANSI code page. + </para> + </listitem> + </itemizedlist></para> + + </refsect1> + + + <refsect1 id="app-psql-examples" xreflabel="Examples"> + <title>Examples</title> + + <para> + The first example shows how to spread a command over several lines of + input. Notice the changing prompt: +<programlisting> +testdb=> <userinput>CREATE TABLE my_table (</userinput> +testdb(> <userinput> first integer not null default 0,</userinput> +testdb(> <userinput> second text)</userinput> +testdb-> <userinput>;</userinput> +CREATE TABLE +</programlisting> + Now look at the table definition again: +<programlisting> +testdb=> <userinput>\d my_table</userinput> + Table "public.my_table" + Column | Type | Collation | Nullable | Default +--------+---------+-----------+----------+--------- + first | integer | | not null | 0 + second | text | | | +</programlisting> + Now we change the prompt to something more interesting: +<programlisting> +testdb=> <userinput>\set PROMPT1 '%n@%m %~%R%# '</userinput> +peter@localhost testdb=> +</programlisting> + Let's assume you have filled the table with data and want to take a + look at it: +<programlisting> +peter@localhost testdb=> SELECT * FROM my_table; + first | second +-------+-------- + 1 | one + 2 | two + 3 | three + 4 | four +(4 rows) +</programlisting> + You can display tables in different ways by using the + <command>\pset</command> command: +<programlisting> +peter@localhost testdb=> <userinput>\pset border 2</userinput> +Border style is 2. +peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput> ++-------+--------+ +| first | second | ++-------+--------+ +| 1 | one | +| 2 | two | +| 3 | three | +| 4 | four | ++-------+--------+ +(4 rows) + +peter@localhost testdb=> <userinput>\pset border 0</userinput> +Border style is 0. +peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput> +first second +----- ------ + 1 one + 2 two + 3 three + 4 four +(4 rows) + +peter@localhost testdb=> <userinput>\pset border 1</userinput> +Border style is 1. +peter@localhost testdb=> <userinput>\pset format csv</userinput> +Output format is csv. +peter@localhost testdb=> <userinput>\pset tuples_only</userinput> +Tuples only is on. +peter@localhost testdb=> <userinput>SELECT second, first FROM my_table;</userinput> +one,1 +two,2 +three,3 +four,4 +peter@localhost testdb=> <userinput>\pset format unaligned</userinput> +Output format is unaligned. +peter@localhost testdb=> <userinput>\pset fieldsep '\t'</userinput> +Field separator is " ". +peter@localhost testdb=> <userinput>SELECT second, first FROM my_table;</userinput> +one 1 +two 2 +three 3 +four 4 +</programlisting> + Alternatively, use the short commands: +<programlisting> +peter@localhost testdb=> <userinput>\a \t \x</userinput> +Output format is aligned. +Tuples only is off. +Expanded display is on. +peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput> +-[ RECORD 1 ]- +first | 1 +second | one +-[ RECORD 2 ]- +first | 2 +second | two +-[ RECORD 3 ]- +first | 3 +second | three +-[ RECORD 4 ]- +first | 4 +second | four +</programlisting> + </para> + + <para> + Also, these output format options can be set for just one query by using + <literal>\g</literal>: +<programlisting> +peter@localhost testdb=> <userinput>SELECT * FROM my_table</userinput> +peter@localhost testdb-> <userinput>\g (format=aligned tuples_only=off expanded=on)</userinput> +-[ RECORD 1 ]- +first | 1 +second | one +-[ RECORD 2 ]- +first | 2 +second | two +-[ RECORD 3 ]- +first | 3 +second | three +-[ RECORD 4 ]- +first | 4 +second | four +</programlisting> + </para> + + <para> + Here is an example of using the <command>\df</command> command to + find only functions with names matching <literal>int*pl</literal> + and whose second argument is of type <type>bigint</type>: +<programlisting> +testdb=> <userinput>\df int*pl * bigint</userinput> + List of functions + Schema | Name | Result data type | Argument data types | Type +------------+---------+------------------+---------------------+------ + pg_catalog | int28pl | bigint | smallint, bigint | func + pg_catalog | int48pl | bigint | integer, bigint | func + pg_catalog | int8pl | bigint | bigint, bigint | func +(3 rows) +</programlisting> + </para> + + <para> + When suitable, query results can be shown in a crosstab representation + with the <command>\crosstabview</command> command: +<programlisting> +testdb=> <userinput>SELECT first, second, first > 2 AS gt2 FROM my_table;</userinput> + first | second | gt2 +-------+--------+----- + 1 | one | f + 2 | two | f + 3 | three | t + 4 | four | t +(4 rows) + +testdb=> <userinput>\crosstabview first second</userinput> + first | one | two | three | four +-------+-----+-----+-------+------ + 1 | f | | | + 2 | | f | | + 3 | | | t | + 4 | | | | t +(4 rows) +</programlisting> + +This second example shows a multiplication table with rows sorted in reverse +numerical order and columns with an independent, ascending numerical order. +<programlisting> +testdb=> <userinput>SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as "AxB",</userinput> +testdb(> <userinput>row_number() over(order by t2.first) AS ord</userinput> +testdb(> <userinput>FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC</userinput> +testdb(> <userinput>\crosstabview "A" "B" "AxB" ord</userinput> + A | 101 | 102 | 103 | 104 +---+-----+-----+-----+----- + 4 | 404 | 408 | 412 | 416 + 3 | 303 | 306 | 309 | 312 + 2 | 202 | 204 | 206 | 208 + 1 | 101 | 102 | 103 | 104 +(4 rows) +</programlisting></para> + + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/reassign_owned.sgml b/doc/src/sgml/ref/reassign_owned.sgml new file mode 100644 index 0000000..ab692bd --- /dev/null +++ b/doc/src/sgml/ref/reassign_owned.sgml @@ -0,0 +1,123 @@ +<!-- +doc/src/sgml/ref/reassign_owned.sgml +PostgreSQL documentation +--> + +<refentry id="sql-reassign-owned"> + <indexterm zone="sql-reassign-owned"> + <primary>REASSIGN OWNED</primary> + </indexterm> + + <refmeta> + <refentrytitle>REASSIGN OWNED</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>REASSIGN OWNED</refname> + <refpurpose>change the ownership of database objects owned by a database role</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +REASSIGN OWNED BY { <replaceable class="parameter">old_role</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } [, ...] + TO { <replaceable class="parameter">new_role</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>REASSIGN OWNED</command> instructs the system to change + the ownership of database objects owned by any of the + <replaceable class="parameter">old_roles</replaceable> to + <replaceable class="parameter">new_role</replaceable>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">old_role</replaceable></term> + <listitem> + <para> + The name of a role. The ownership of all the objects within the + current database, and of all shared objects (databases, tablespaces), + owned by this role will be reassigned to + <replaceable class="parameter">new_role</replaceable>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_role</replaceable></term> + <listitem> + <para> + The name of the role that will be made the new owner of the + affected objects. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>REASSIGN OWNED</command> is often used to prepare for the + removal of one or more roles. Because <command>REASSIGN + OWNED</command> does not affect objects within other databases, + it is usually necessary to execute this command in each database + that contains objects owned by a role that is to be removed. + </para> + + <para> + <command>REASSIGN OWNED</command> requires membership on both the + source role(s) and the target role. + </para> + + <para> + The <link linkend="sql-drop-owned"><command>DROP OWNED</command></link> command is an alternative that + simply drops all the database objects owned by one or more roles. + </para> + + <para> + The <command>REASSIGN OWNED</command> command does not affect any + privileges granted to + the <replaceable class="parameter">old_roles</replaceable> on objects + that are not owned by them. Likewise, it does not affect default + privileges created with <command>ALTER DEFAULT PRIVILEGES</command>. + Use <command>DROP OWNED</command> to revoke such privileges. + </para> + + <para> + See <xref linkend="role-removal"/> for more discussion. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>REASSIGN OWNED</command> command is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-drop-owned"/></member> + <member><xref linkend="sql-droprole"/></member> + <member><xref linkend="sql-alterdatabase"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/refresh_materialized_view.sgml b/doc/src/sgml/ref/refresh_materialized_view.sgml new file mode 100644 index 0000000..675d609 --- /dev/null +++ b/doc/src/sgml/ref/refresh_materialized_view.sgml @@ -0,0 +1,143 @@ +<!-- +doc/src/sgml/ref/refresh_materialized_view.sgml +PostgreSQL documentation +--> + +<refentry id="sql-refreshmaterializedview"> + <indexterm zone="sql-refreshmaterializedview"> + <primary>REFRESH MATERIALIZED VIEW</primary> + </indexterm> + + <refmeta> + <refentrytitle>REFRESH MATERIALIZED VIEW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>REFRESH MATERIALIZED VIEW</refname> + <refpurpose>replace the contents of a materialized view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] <replaceable class="parameter">name</replaceable> + [ WITH [ NO ] DATA ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>REFRESH MATERIALIZED VIEW</command> completely replaces the + contents of a materialized view. To execute this command you must be the + owner of the materialized view. The old contents are discarded. If + <literal>WITH DATA</literal> is specified (or defaults) the backing query + is executed to provide the new data, and the materialized view is left in a + scannable state. If <literal>WITH NO DATA</literal> is specified no new + data is generated and the materialized view is left in an unscannable + state. + </para> + <para> + <literal>CONCURRENTLY</literal> and <literal>WITH NO DATA</literal> may not + be specified together. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>CONCURRENTLY</literal></term> + <listitem> + <para> + Refresh the materialized view without locking out concurrent selects on + the materialized view. Without this option a refresh which affects a + lot of rows will tend to use fewer resources and complete more quickly, + but could block other connections which are trying to read from the + materialized view. This option may be faster in cases where a small + number of rows are affected. + </para> + <para> + This option is only allowed if there is at least one + <literal>UNIQUE</literal> index on the materialized view which uses only + column names and includes all rows; that is, it must not be an + expression index or include a <literal>WHERE</literal> clause. + </para> + <para> + This option may not be used when the materialized view is not already + populated. + </para> + <para> + Even with this option only one <literal>REFRESH</literal> at a time may + run against any one materialized view. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the materialized view to + refresh. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If there is an <literal>ORDER BY</literal> clause in the materialized + view's defining query, the original contents of the materialized view + will be ordered that way; but <command>REFRESH MATERIALIZED + VIEW</command> does not guarantee to preserve that ordering. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + This command will replace the contents of the materialized view called + <literal>order_summary</literal> using the query from the materialized + view's definition, and leave it in a scannable state: +<programlisting> +REFRESH MATERIALIZED VIEW order_summary; +</programlisting> + </para> + + <para> + This command will free storage associated with the materialized view + <literal>annual_statistics_basis</literal> and leave it in an unscannable + state: +<programlisting> +REFRESH MATERIALIZED VIEW annual_statistics_basis WITH NO DATA; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>REFRESH MATERIALIZED VIEW</command> is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-creatematerializedview"/></member> + <member><xref linkend="sql-altermaterializedview"/></member> + <member><xref linkend="sql-dropmaterializedview"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/reindex.sgml b/doc/src/sgml/ref/reindex.sgml new file mode 100644 index 0000000..336ca24 --- /dev/null +++ b/doc/src/sgml/ref/reindex.sgml @@ -0,0 +1,560 @@ +<!-- +doc/src/sgml/ref/reindex.sgml +PostgreSQL documentation +--> + +<refentry id="sql-reindex"> + <indexterm zone="sql-reindex"> + <primary>REINDEX</primary> + </indexterm> + + <refmeta> + <refentrytitle>REINDEX</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>REINDEX</refname> + <refpurpose>rebuild indexes</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +REINDEX [ ( <replaceable class="parameter">option</replaceable> [, ...] ) ] { INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } [ CONCURRENTLY ] <replaceable class="parameter">name</replaceable> + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + CONCURRENTLY [ <replaceable class="parameter">boolean</replaceable> ] + TABLESPACE <replaceable class="parameter">new_tablespace</replaceable> + VERBOSE [ <replaceable class="parameter">boolean</replaceable> ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>REINDEX</command> rebuilds an index using the data + stored in the index's table, replacing the old copy of the index. There are + several scenarios in which to use <command>REINDEX</command>: + + <itemizedlist> + <listitem> + <para> + An index has become corrupted, and no longer contains valid + data. Although in theory this should never happen, in + practice indexes can become corrupted due to software bugs or + hardware failures. <command>REINDEX</command> provides a + recovery method. + </para> + </listitem> + + <listitem> + <para> + An index has become <quote>bloated</quote>, that is it contains many + empty or nearly-empty pages. This can occur with B-tree indexes in + <productname>PostgreSQL</productname> under certain uncommon access + patterns. <command>REINDEX</command> provides a way to reduce + the space consumption of the index by writing a new version of + the index without the dead pages. See <xref + linkend="routine-reindex"/> for more information. + </para> + </listitem> + + <listitem> + <para> + You have altered a storage parameter (such as fillfactor) + for an index, and wish to ensure that the change has taken full effect. + </para> + </listitem> + + <listitem> + <para> + If an index build fails with the <literal>CONCURRENTLY</literal> option, + this index is left as <quote>invalid</quote>. Such indexes are useless + but it can be convenient to use <command>REINDEX</command> to rebuild + them. Note that only <command>REINDEX INDEX</command> is able + to perform a concurrent build on an invalid index. + </para> + </listitem> + + </itemizedlist></para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>INDEX</literal></term> + <listitem> + <para> + Recreate the specified index. This form of <command>REINDEX</command> + cannot be executed inside a transaction block when used with a + partitioned index. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TABLE</literal></term> + <listitem> + <para> + Recreate all indexes of the specified table. If the table has a + secondary <quote>TOAST</quote> table, that is reindexed as well. + This form of <command>REINDEX</command> cannot be executed inside a + transaction block when used with a partitioned table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SCHEMA</literal></term> + <listitem> + <para> + Recreate all indexes of the specified schema. If a table of this + schema has a secondary <quote>TOAST</quote> table, that is reindexed as + well. Indexes on shared system catalogs are also processed. + This form of <command>REINDEX</command> cannot be executed inside a + transaction block. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DATABASE</literal></term> + <listitem> + <para> + Recreate all indexes within the current database. + Indexes on shared system catalogs are also processed. + This form of <command>REINDEX</command> cannot be executed inside a + transaction block. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SYSTEM</literal></term> + <listitem> + <para> + Recreate all indexes on system catalogs within the current database. + Indexes on shared system catalogs are included. + Indexes on user tables are not processed. + This form of <command>REINDEX</command> cannot be executed inside a + transaction block. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of the specific index, table, or database to be + reindexed. Index and table names can be schema-qualified. + Presently, <command>REINDEX DATABASE</command> and <command>REINDEX SYSTEM</command> + can only reindex the current database, so their parameter must match + the current database's name. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONCURRENTLY</literal></term> + <listitem> + <para> + When this option is used, <productname>PostgreSQL</productname> will rebuild the + index without taking any locks that prevent concurrent inserts, + updates, or deletes on the table; whereas a standard index rebuild + locks out writes (but not reads) on the table until it's done. + There are several caveats to be aware of when using this option + — see <xref linkend="sql-reindex-concurrently"/> below. + </para> + <para> + For temporary tables, <command>REINDEX</command> is always + non-concurrent, as no other session can access them, and + non-concurrent reindex is cheaper. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TABLESPACE</literal></term> + <listitem> + <para> + Specifies that indexes will be rebuilt on a new tablespace. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VERBOSE</literal></term> + <listitem> + <para> + Prints a progress report as each index is reindexed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_tablespace</replaceable></term> + <listitem> + <para> + The tablespace where indexes will be rebuilt. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If you suspect corruption of an index on a user table, you can + simply rebuild that index, or all indexes on the table, using + <command>REINDEX INDEX</command> or <command>REINDEX TABLE</command>. + </para> + + <para> + Things are more difficult if you need to recover from corruption of + an index on a system table. In this case it's important for the + system to not have used any of the suspect indexes itself. + (Indeed, in this sort of scenario you might find that server + processes are crashing immediately at start-up, due to reliance on + the corrupted indexes.) To recover safely, the server must be started + with the <option>-P</option> option, which prevents it from using + indexes for system catalog lookups. + </para> + + <para> + One way to do this is to shut down the server and start a single-user + <productname>PostgreSQL</productname> server + with the <option>-P</option> option included on its command line. + Then, <command>REINDEX DATABASE</command>, <command>REINDEX SYSTEM</command>, + <command>REINDEX TABLE</command>, or <command>REINDEX INDEX</command> can be + issued, depending on how much you want to reconstruct. If in + doubt, use <command>REINDEX SYSTEM</command> to select + reconstruction of all system indexes in the database. Then quit + the single-user server session and restart the regular server. + See the <xref linkend="app-postgres"/> reference page for more + information about how to interact with the single-user server + interface. + </para> + + <para> + Alternatively, a regular server session can be started with + <option>-P</option> included in its command line options. + The method for doing this varies across clients, but in all + <application>libpq</application>-based clients, it is possible to set + the <envar>PGOPTIONS</envar> environment variable to <literal>-P</literal> + before starting the client. Note that while this method does not + require locking out other clients, it might still be wise to prevent + other users from connecting to the damaged database until repairs + have been completed. + </para> + + <para> + <command>REINDEX</command> is similar to a drop and recreate of the index + in that the index contents are rebuilt from scratch. However, the locking + considerations are rather different. <command>REINDEX</command> locks out writes + but not reads of the index's parent table. It also takes an + <literal>ACCESS EXCLUSIVE</literal> lock on the specific index being processed, + which will block reads that attempt to use that index. In particular, + the query planner tries to take an <literal>ACCESS SHARE</literal> + lock on every index of the table, regardless of the query, and so + <command>REINDEX</command> blocks virtually any queries except for some + prepared queries whose plan has been cached and which don't use this very + index. In contrast, + <command>DROP INDEX</command> momentarily takes an + <literal>ACCESS EXCLUSIVE</literal> lock on the parent table, blocking both + writes and reads. The subsequent <command>CREATE INDEX</command> locks out + writes but not reads; since the index is not there, no read will attempt to + use it, meaning that there will be no blocking but reads might be forced + into expensive sequential scans. + </para> + + <para> + Reindexing a single index or table requires being the owner of that + index or table. Reindexing a schema or database requires being the + owner of that schema or database. Note specifically that it's thus + possible for non-superusers to rebuild indexes of tables owned by + other users. However, as a special exception, when + <command>REINDEX DATABASE</command>, <command>REINDEX SCHEMA</command> + or <command>REINDEX SYSTEM</command> is issued by a non-superuser, + indexes on shared catalogs will be skipped unless the user owns the + catalog (which typically won't be the case). Of course, superusers + can always reindex anything. + </para> + + <para> + Reindexing partitioned indexes or partitioned tables is supported + with <command>REINDEX INDEX</command> or <command>REINDEX TABLE</command>, + respectively. Each partition of the specified partitioned relation is + reindexed in a separate transaction. Those commands cannot be used inside + a transaction block when working on a partitioned table or index. + </para> + + <para> + When using the <literal>TABLESPACE</literal> clause with + <command>REINDEX</command> on a partitioned index or table, only the + tablespace references of the leaf partitions are updated. As partitioned + indexes are not updated, it is recommended to separately use + <command>ALTER TABLE ONLY</command> on them so as any new partitions + attached inherit the new tablespace. On failure, it may not have moved + all the indexes to the new tablespace. Re-running the command will rebuild + all the leaf partitions and move previously-unprocessed indexes to the new + tablespace. + </para> + + <para> + If <literal>SCHEMA</literal>, <literal>DATABASE</literal> or + <literal>SYSTEM</literal> is used with <literal>TABLESPACE</literal>, + system relations are skipped and a single <literal>WARNING</literal> + will be generated. Indexes on TOAST tables are rebuilt, but not moved + to the new tablespace. + </para> + + <refsect2 id="sql-reindex-concurrently" xreflabel="Rebuilding Indexes Concurrently"> + <title>Rebuilding Indexes Concurrently</title> + + <indexterm zone="sql-reindex-concurrently"> + <primary>index</primary> + <secondary>rebuilding concurrently</secondary> + </indexterm> + + <para> + Rebuilding an index can interfere with regular operation of a database. + Normally <productname>PostgreSQL</productname> locks the table whose index is rebuilt + against writes and performs the entire index build with a single scan of the + table. Other transactions can still read the table, but if they try to + insert, update, or delete rows in the table they will block until the + index rebuild is finished. This could have a severe effect if the system is + a live production database. Very large tables can take many hours to be + indexed, and even for smaller tables, an index rebuild can lock out writers + for periods that are unacceptably long for a production system. + </para> + + <para> + <productname>PostgreSQL</productname> supports rebuilding indexes with minimum locking + of writes. This method is invoked by specifying the + <literal>CONCURRENTLY</literal> option of <command>REINDEX</command>. When this option + is used, <productname>PostgreSQL</productname> must perform two scans of the table + for each index that needs to be rebuilt and wait for termination of + all existing transactions that could potentially use the index. + This method requires more total work than a standard index + rebuild and takes significantly longer to complete as it needs to wait + for unfinished transactions that might modify the index. However, since + it allows normal operations to continue while the index is being rebuilt, this + method is useful for rebuilding indexes in a production environment. Of + course, the extra CPU, memory and I/O load imposed by the index rebuild + may slow down other operations. + </para> + + <para> + The following steps occur in a concurrent reindex. Each step is run in a + separate transaction. If there are multiple indexes to be rebuilt, then + each step loops through all the indexes before moving to the next step. + + <orderedlist> + <listitem> + <para> + A new transient index definition is added to the catalog + <literal>pg_index</literal>. This definition will be used to replace + the old index. A <literal>SHARE UPDATE EXCLUSIVE</literal> lock at + session level is taken on the indexes being reindexed as well as their + associated tables to prevent any schema modification while processing. + </para> + </listitem> + + <listitem> + <para> + A first pass to build the index is done for each new index. Once the + index is built, its flag <literal>pg_index.indisready</literal> is + switched to <quote>true</quote> to make it ready for inserts, making it + visible to other sessions once the transaction that performed the build + is finished. This step is done in a separate transaction for each + index. + </para> + </listitem> + + <listitem> + <para> + Then a second pass is performed to add tuples that were added while the + first pass was running. This step is also done in a separate + transaction for each index. + </para> + </listitem> + + <listitem> + <para> + All the constraints that refer to the index are changed to refer to the + new index definition, and the names of the indexes are changed. At + this point, <literal>pg_index.indisvalid</literal> is switched to + <quote>true</quote> for the new index and to <quote>false</quote> for + the old, and a cache invalidation is done causing all sessions that + referenced the old index to be invalidated. + </para> + </listitem> + + <listitem> + <para> + The old indexes have <literal>pg_index.indisready</literal> switched to + <quote>false</quote> to prevent any new tuple insertions, after waiting + for running queries that might reference the old index to complete. + </para> + </listitem> + + <listitem> + <para> + The old indexes are dropped. The <literal>SHARE UPDATE + EXCLUSIVE</literal> session locks for the indexes and the table are + released. + </para> + </listitem> + </orderedlist> + </para> + + <para> + If a problem arises while rebuilding the indexes, such as a + uniqueness violation in a unique index, the <command>REINDEX</command> + command will fail but leave behind an <quote>invalid</quote> new index in addition to + the pre-existing one. This index will be ignored for querying purposes + because it might be incomplete; however it will still consume update + overhead. The <application>psql</application> <command>\d</command> command will report + such an index as <literal>INVALID</literal>: + +<programlisting> +postgres=# \d tab + Table "public.tab" + Column | Type | Modifiers +--------+---------+----------- + col | integer | +Indexes: + "idx" btree (col) + "idx_ccnew" btree (col) INVALID +</programlisting> + + If the index marked <literal>INVALID</literal> is suffixed + <literal>ccnew</literal>, then it corresponds to the transient + index created during the concurrent operation, and the recommended + recovery method is to drop it using <literal>DROP INDEX</literal>, + then attempt <command>REINDEX CONCURRENTLY</command> again. + If the invalid index is instead suffixed <literal>ccold</literal>, + it corresponds to the original index which could not be dropped; + the recommended recovery method is to just drop said index, since the + rebuild proper has been successful. + </para> + + <para> + Regular index builds permit other regular index builds on the same table + to occur simultaneously, but only one concurrent index build can occur on a + table at a time. In both cases, no other types of schema modification on + the table are allowed meanwhile. Another difference is that a regular + <command>REINDEX TABLE</command> or <command>REINDEX INDEX</command> + command can be performed within a transaction block, but <command>REINDEX + CONCURRENTLY</command> cannot. + </para> + + <para> + Like any long-running transaction, <command>REINDEX</command> on a table + can affect which tuples can be removed by concurrent + <command>VACUUM</command> on any other table. + </para> + + <para> + <command>REINDEX SYSTEM</command> does not support + <command>CONCURRENTLY</command> since system catalogs cannot be reindexed + concurrently. + </para> + + <para> + Furthermore, indexes for exclusion constraints cannot be reindexed + concurrently. If such an index is named directly in this command, an + error is raised. If a table or database with exclusion constraint indexes + is reindexed concurrently, those indexes will be skipped. (It is possible + to reindex such indexes without the <command>CONCURRENTLY</command> option.) + </para> + + <para> + Each backend running <command>REINDEX</command> will report its progress + in the <structname>pg_stat_progress_create_index</structname> view. See + <xref linkend="create-index-progress-reporting"/> for details. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Rebuild a single index: + +<programlisting> +REINDEX INDEX my_index; +</programlisting> + </para> + + <para> + Rebuild all the indexes on the table <literal>my_table</literal>: + +<programlisting> +REINDEX TABLE my_table; +</programlisting> + </para> + + <para> + Rebuild all indexes in a particular database, without trusting the + system indexes to be valid already: + +<programlisting> +$ <userinput>export PGOPTIONS="-P"</userinput> +$ <userinput>psql broken_db</userinput> +... +broken_db=> REINDEX DATABASE broken_db; +broken_db=> \q +</programlisting></para> + + <para> + Rebuild indexes for a table, without blocking read and write operations + on involved relations while reindexing is in progress: + +<programlisting> +REINDEX TABLE CONCURRENTLY my_broken_table; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>REINDEX</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createindex"/></member> + <member><xref linkend="sql-dropindex"/></member> + <member><xref linkend="app-reindexdb"/></member> + <member><xref linkend="create-index-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/reindexdb.sgml b/doc/src/sgml/ref/reindexdb.sgml new file mode 100644 index 0000000..8cb8bf4 --- /dev/null +++ b/doc/src/sgml/ref/reindexdb.sgml @@ -0,0 +1,476 @@ +<!-- +doc/src/sgml/ref/reindexdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-reindexdb"> + <indexterm zone="app-reindexdb"> + <primary>reindexdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>reindexdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>reindexdb</refname> + <refpurpose>reindex a <productname>PostgreSQL</productname> database</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>reindexdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + + <arg choice="plain" rep="repeat"> + <arg choice="opt"> + <group choice="plain"> + <arg choice="plain"><option>-S</option></arg> + <arg choice="plain"><option>--schema</option></arg> + </group> + <replaceable>schema</replaceable> + </arg> + </arg> + + <arg choice="plain" rep="repeat"> + <arg choice="opt"> + <group choice="plain"> + <arg choice="plain"><option>-t</option></arg> + <arg choice="plain"><option>--table</option></arg> + </group> + <replaceable>table</replaceable> + </arg> + </arg> + + <arg choice="plain" rep="repeat"> + <arg choice="opt"> + <group choice="plain"> + <arg choice="plain"><option>-i</option></arg> + <arg choice="plain"><option>--index</option></arg> + </group> + <replaceable>index</replaceable> + </arg> + </arg> + + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>reindexdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + + <group choice="plain"> + <arg choice="plain"><option>-a</option></arg> + <arg choice="plain"><option>--all</option></arg> + </group> + </cmdsynopsis> + + <cmdsynopsis> + <command>reindexdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + + <group choice="plain"> + <arg choice="plain"><option>-s</option></arg> + <arg choice="plain"><option>--system</option></arg> + </group> + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + </refsynopsisdiv> + + + <refsect1> + <title>Description</title> + + <para> + <application>reindexdb</application> is a utility for rebuilding indexes + in a <productname>PostgreSQL</productname> database. + </para> + + <para> + <application>reindexdb</application> is a wrapper around the SQL + command <link linkend="sql-reindex"><command>REINDEX</command></link>. + There is no effective difference between reindexing databases via + this utility and via other methods for accessing the server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>reindexdb</application> accepts the following command-line arguments: + + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--all</option></term> + <listitem> + <para> + Reindex all databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--concurrently</option></term> + <listitem> + <para> + Use the <literal>CONCURRENTLY</literal> option. See + <xref linkend="sql-reindex"/>, where all the caveats of this option + are explained in detail. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option><optional>-d</optional> <replaceable class="parameter">dbname</replaceable></option></term> + <term><option><optional>--dbname=</optional><replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to be reindexed, + when <option>-a</option>/<option>--all</option> is not used. + If this is not specified, the database name is read + from the environment variable <envar>PGDATABASE</envar>. If + that is not set, the user name specified for the connection is + used. The <replaceable>dbname</replaceable> can be a <link + linkend="libpq-connstring">connection string</link>. If so, + connection string parameters will override any conflicting command + line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>reindexdb</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i <replaceable class="parameter">index</replaceable></option></term> + <term><option>--index=<replaceable class="parameter">index</replaceable></option></term> + <listitem> + <para> + Recreate <replaceable class="parameter">index</replaceable> only. + Multiple indexes can be recreated by writing multiple + <option>-i</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">njobs</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">njobs</replaceable></option></term> + <listitem> + <para> + Execute the reindex commands in parallel by running + <replaceable class="parameter">njobs</replaceable> + commands simultaneously. This option may reduce the processing time + but it also increases the load on the database server. + </para> + <para> + <application>reindexdb</application> will open + <replaceable class="parameter">njobs</replaceable> connections to the + database, so make sure your <xref linkend="guc-max-connections"/> + setting is high enough to accommodate all connections. + </para> + <para> + Note that this option is incompatible with the <option>--index</option> + and <option>--system</option> options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Do not display progress messages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <term><option>--system</option></term> + <listitem> + <para> + Reindex database's system catalogs only. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-S <replaceable class="parameter">schema</replaceable></option></term> + <term><option>--schema=<replaceable class="parameter">schema</replaceable></option></term> + <listitem> + <para> + Reindex <replaceable class="parameter">schema</replaceable> only. + Multiple schemas can be reindexed by writing multiple + <option>-S</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">table</replaceable></option></term> + <term><option>--table=<replaceable class="parameter">table</replaceable></option></term> + <listitem> + <para> + Reindex <replaceable class="parameter">table</replaceable> only. + Multiple tables can be reindexed by writing multiple + <option>-t</option> switches. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--tablespace=<replaceable class="parameter">tablespace</replaceable></option></term> + <listitem> + <para> + Specifies the tablespace where indexes are rebuilt. (This name is + processed as a double-quoted identifier.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Print detailed information during processing. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>reindexdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>reindexdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + + </para> + + <para> + <application>reindexdb</application> also accepts + the following command-line arguments for connection parameters: + + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server is + running. If the value begins with a slash, it is used as the + directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>reindexdb</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>reindexdb</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>reindexdb</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to to discover which + databases should be reindexed, + when <option>-a</option>/<option>--all</option> is used. + If not specified, the <literal>postgres</literal> database will be used, + or if that does not exist, <literal>template1</literal> will be used. + This can be a <link linkend="libpq-connstring">connection + string</link>. If so, connection string parameters will override any + conflicting command line options. Also, connection string parameters + other than the database name itself will be re-used when connecting + to other databases. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-reindex"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Notes</title> + + <para> + <application>reindexdb</application> might need to connect several + times to the <productname>PostgreSQL</productname> server, asking + for a password each time. It is convenient to have a + <filename>~/.pgpass</filename> file in such cases. See <xref + linkend="libpq-pgpass"/> for more information. + </para> + </refsect1> + + + <refsect1> + <title>Examples</title> + + <para> + To reindex the database <literal>test</literal>: +<screen> +<prompt>$ </prompt><userinput>reindexdb test</userinput> +</screen> + </para> + + <para> + To reindex the table <literal>foo</literal> and the index + <literal>bar</literal> in a database named <literal>abcd</literal>: +<screen> +<prompt>$ </prompt><userinput>reindexdb --table=foo --index=bar abcd</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-reindex"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/release_savepoint.sgml b/doc/src/sgml/ref/release_savepoint.sgml new file mode 100644 index 0000000..daf8eb9 --- /dev/null +++ b/doc/src/sgml/ref/release_savepoint.sgml @@ -0,0 +1,131 @@ +<!-- +doc/src/sgml/ref/release_savepoint.sgml +PostgreSQL documentation +--> + +<refentry id="sql-release-savepoint"> + <indexterm zone="sql-release-savepoint"> + <primary>RELEASE SAVEPOINT</primary> + </indexterm> + + <indexterm zone="sql-release-savepoint"> + <primary>savepoints</primary> + <secondary>releasing</secondary> + </indexterm> + + <refmeta> + <refentrytitle>RELEASE SAVEPOINT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>RELEASE SAVEPOINT</refname> + <refpurpose>destroy a previously defined savepoint</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +RELEASE [ SAVEPOINT ] <replaceable>savepoint_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>RELEASE SAVEPOINT</command> destroys a savepoint previously defined + in the current transaction. + </para> + + <para> + Destroying a savepoint makes it unavailable as a rollback point, + but it has no other user visible behavior. It does not undo the + effects of commands executed after the savepoint was established. + (To do that, see <xref linkend="sql-rollback-to"/>.) + Destroying a savepoint when + it is no longer needed allows the system to reclaim some resources + earlier than transaction end. + </para> + + <para> + <command>RELEASE SAVEPOINT</command> also destroys all savepoints that were + established after the named savepoint was established. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>savepoint_name</replaceable></term> + <listitem> + <para> + The name of the savepoint to destroy. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Specifying a savepoint name that was not previously defined is an error. + </para> + + <para> + It is not possible to release a savepoint when the transaction is in + an aborted state. + </para> + + <para> + If multiple savepoints have the same name, only the most recently defined + unreleased one is released. Repeated commands will release progressively + older savepoints. + </para> + + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To establish and later destroy a savepoint: +<programlisting> +BEGIN; + INSERT INTO table1 VALUES (3); + SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (4); + RELEASE SAVEPOINT my_savepoint; +COMMIT; +</programlisting> + The above transaction will insert both 3 and 4. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to the <acronym>SQL</acronym> standard. The standard + specifies that the key word <literal>SAVEPOINT</literal> is + mandatory, but <productname>PostgreSQL</productname> allows it to + be omitted. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback"/></member> + <member><xref linkend="sql-rollback-to"/></member> + <member><xref linkend="sql-savepoint"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/reset.sgml b/doc/src/sgml/ref/reset.sgml new file mode 100644 index 0000000..9559907 --- /dev/null +++ b/doc/src/sgml/ref/reset.sgml @@ -0,0 +1,113 @@ +<!-- +doc/src/sgml/ref/reset.sgml +PostgreSQL documentation +--> + +<refentry id="sql-reset"> + <indexterm zone="sql-reset"> + <primary>RESET</primary> + </indexterm> + + <refmeta> + <refentrytitle>RESET</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>RESET</refname> + <refpurpose>restore the value of a run-time parameter to the default value</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +RESET <replaceable class="parameter">configuration_parameter</replaceable> +RESET ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>RESET</command> restores run-time parameters to their + default values. <command>RESET</command> is an alternative + spelling for +<synopsis> +SET <replaceable class="parameter">configuration_parameter</replaceable> TO DEFAULT +</synopsis> + Refer to <xref linkend="sql-set"/> for + details. + </para> + + <para> + The default value is defined as the value that the parameter would + have had, if no <command>SET</command> had ever been issued for it in the + current session. The actual source of this value might be a + compiled-in default, the configuration file, command-line options, + or per-database or per-user default settings. This is subtly different + from defining it as <quote>the value that the parameter had at session + start</quote>, because if the value came from the configuration file, it + will be reset to whatever is specified by the configuration file now. + See <xref linkend="runtime-config"/> for details. + </para> + + <para> + The transactional behavior of <command>RESET</command> is the same as + <command>SET</command>: its effects will be undone by transaction rollback. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">configuration_parameter</replaceable></term> + <listitem> + <para> + Name of a settable run-time parameter. Available parameters are + documented in <xref linkend="runtime-config"/> and on the + <xref linkend="sql-set"/> reference page. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Resets all settable run-time parameters to default values. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Set the <varname>timezone</varname> configuration variable to its default value: +<screen> +RESET timezone; +</screen></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>RESET</command> is a <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set"/></member> + <member><xref linkend="sql-show"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/revoke.sgml b/doc/src/sgml/ref/revoke.sgml new file mode 100644 index 0000000..62f1971 --- /dev/null +++ b/doc/src/sgml/ref/revoke.sgml @@ -0,0 +1,332 @@ +<!-- +doc/src/sgml/ref/revoke.sgml +PostgreSQL documentation +--> + +<refentry id="sql-revoke"> + <indexterm zone="sql-revoke"> + <primary>REVOKE</primary> + </indexterm> + + <refmeta> + <refentrytitle>REVOKE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>REVOKE</refname> + <refpurpose>remove access privileges</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +REVOKE [ GRANT OPTION FOR ] + { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER } + [, ...] | ALL [ PRIVILEGES ] } + ON { [ TABLE ] <replaceable class="parameter">table_name</replaceable> [, ...] + | ALL TABLES IN SCHEMA <replaceable>schema_name</replaceable> [, ...] } + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { SELECT | INSERT | UPDATE | REFERENCES } ( <replaceable class="parameter">column_name</replaceable> [, ...] ) + [, ...] | ALL [ PRIVILEGES ] ( <replaceable class="parameter">column_name</replaceable> [, ...] ) } + ON [ TABLE ] <replaceable class="parameter">table_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { USAGE | SELECT | UPDATE } + [, ...] | ALL [ PRIVILEGES ] } + ON { SEQUENCE <replaceable class="parameter">sequence_name</replaceable> [, ...] + | ALL SEQUENCES IN SCHEMA <replaceable>schema_name</replaceable> [, ...] } + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { CREATE | CONNECT | TEMPORARY | TEMP } [, ...] | ALL [ PRIVILEGES ] } + ON DATABASE <replaceable>database_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON DOMAIN <replaceable>domain_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON FOREIGN DATA WRAPPER <replaceable>fdw_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON FOREIGN SERVER <replaceable>server_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { EXECUTE | ALL [ PRIVILEGES ] } + ON { { FUNCTION | PROCEDURE | ROUTINE } <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...] + | ALL { FUNCTIONS | PROCEDURES | ROUTINES } IN SCHEMA <replaceable>schema_name</replaceable> [, ...] } + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON LANGUAGE <replaceable>lang_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } + ON LARGE OBJECT <replaceable class="parameter">loid</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { SET | ALTER SYSTEM } [, ...] | ALL [ PRIVILEGES ] } + ON PARAMETER <replaceable class="parameter">configuration_parameter</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { { CREATE | USAGE } [, ...] | ALL [ PRIVILEGES ] } + ON SCHEMA <replaceable>schema_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { CREATE | ALL [ PRIVILEGES ] } + ON TABLESPACE <replaceable>tablespace_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ GRANT OPTION FOR ] + { USAGE | ALL [ PRIVILEGES ] } + ON TYPE <replaceable>type_name</replaceable> [, ...] + FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +REVOKE [ ADMIN OPTION FOR ] + <replaceable class="parameter">role_name</replaceable> [, ...] FROM <replaceable class="parameter">role_specification</replaceable> [, ...] + [ GRANTED BY <replaceable class="parameter">role_specification</replaceable> ] + [ CASCADE | RESTRICT ] + +<phrase>where <replaceable class="parameter">role_specification</replaceable> can be:</phrase> + + [ GROUP ] <replaceable class="parameter">role_name</replaceable> + | PUBLIC + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER +</synopsis> + </refsynopsisdiv> + + <refsect1 id="sql-revoke-description"> + <title>Description</title> + + <para> + The <command>REVOKE</command> command revokes previously granted + privileges from one or more roles. The key word + <literal>PUBLIC</literal> refers to the implicitly defined group of + all roles. + </para> + + <para> + See the description of the <link linkend="sql-grant"><command>GRANT</command></link> command for + the meaning of the privilege types. + </para> + + <para> + Note that any particular role will have the sum + of privileges granted directly to it, privileges granted to any role it + is presently a member of, and privileges granted to + <literal>PUBLIC</literal>. Thus, for example, revoking <literal>SELECT</literal> privilege + from <literal>PUBLIC</literal> does not necessarily mean that all roles + have lost <literal>SELECT</literal> privilege on the object: those who have it granted + directly or via another role will still have it. Similarly, revoking + <literal>SELECT</literal> from a user might not prevent that user from using + <literal>SELECT</literal> if <literal>PUBLIC</literal> or another membership + role still has <literal>SELECT</literal> rights. + </para> + + <para> + If <literal>GRANT OPTION FOR</literal> is specified, only the grant + option for the privilege is revoked, not the privilege itself. + Otherwise, both the privilege and the grant option are revoked. + </para> + + <para> + If a user holds a privilege with grant option and has granted it to + other users then the privileges held by those other users are + called dependent privileges. If the privilege or the grant option + held by the first user is being revoked and dependent privileges + exist, those dependent privileges are also revoked if + <literal>CASCADE</literal> is specified; if it is not, the revoke action + will fail. This recursive revocation only affects privileges that + were granted through a chain of users that is traceable to the user + that is the subject of this <literal>REVOKE</literal> command. + Thus, the affected users might effectively keep the privilege if it + was also granted through other users. + </para> + + <para> + When revoking privileges on a table, the corresponding column privileges + (if any) are automatically revoked on each column of the table, as well. + On the other hand, if a role has been granted privileges on a table, then + revoking the same privileges from individual columns will have no effect. + </para> + + <para> + When revoking membership in a role, <literal>GRANT OPTION</literal> is instead + called <literal>ADMIN OPTION</literal>, but the behavior is similar. + This form of the command also allows a <literal>GRANTED BY</literal> + option, but that option is currently ignored (except for checking + the existence of the named role). + Note also that this form of the command does not + allow the noise word <literal>GROUP</literal> + in <replaceable class="parameter">role_specification</replaceable>. + </para> + </refsect1> + + <refsect1 id="sql-revoke-notes"> + <title>Notes</title> + + <para> + A user can only revoke privileges that were granted directly by + that user. If, for example, user A has granted a privilege with + grant option to user B, and user B has in turn granted it to user + C, then user A cannot revoke the privilege directly from C. + Instead, user A could revoke the grant option from user B and use + the <literal>CASCADE</literal> option so that the privilege is + in turn revoked from user C. For another example, if both A and B + have granted the same privilege to C, A can revoke their own grant + but not B's grant, so C will still effectively have the privilege. + </para> + + <para> + When a non-owner of an object attempts to <command>REVOKE</command> privileges + on the object, the command will fail outright if the user has no + privileges whatsoever on the object. As long as some privilege is + available, the command will proceed, but it will revoke only those + privileges for which the user has grant options. The <command>REVOKE ALL + PRIVILEGES</command> forms will issue a warning message if no grant options are + held, while the other forms will issue a warning if grant options for + any of the privileges specifically named in the command are not held. + (In principle these statements apply to the object owner as well, but + since the owner is always treated as holding all grant options, the + cases can never occur.) + </para> + + <para> + If a superuser chooses to issue a <command>GRANT</command> or <command>REVOKE</command> + command, the command is performed as though it were issued by the + owner of the affected object. Since all privileges ultimately come + from the object owner (possibly indirectly via chains of grant options), + it is possible for a superuser to revoke all privileges, but this might + require use of <literal>CASCADE</literal> as stated above. + </para> + + <para> + <command>REVOKE</command> can also be done by a role + that is not the owner of the affected object, but is a member of the role + that owns the object, or is a member of a role that holds privileges + <literal>WITH GRANT OPTION</literal> on the object. In this case the + command is performed as though it were issued by the containing role that + actually owns the object or holds the privileges + <literal>WITH GRANT OPTION</literal>. For example, if table + <literal>t1</literal> is owned by role <literal>g1</literal>, of which role + <literal>u1</literal> is a member, then <literal>u1</literal> can revoke privileges + on <literal>t1</literal> that are recorded as being granted by <literal>g1</literal>. + This would include grants made by <literal>u1</literal> as well as by other + members of role <literal>g1</literal>. + </para> + + <para> + If the role executing <command>REVOKE</command> holds privileges + indirectly via more than one role membership path, it is unspecified + which containing role will be used to perform the command. In such cases + it is best practice to use <command>SET ROLE</command> to become the specific + role you want to do the <command>REVOKE</command> as. Failure to do so might + lead to revoking privileges other than the ones you intended, or not + revoking anything at all. + </para> + + <para> + See <xref linkend="ddl-priv"/> for more information about specific + privilege types, as well as how to inspect objects' privileges. + </para> + </refsect1> + + <refsect1 id="sql-revoke-examples"> + <title>Examples</title> + + <para> + Revoke insert privilege for the public on table + <literal>films</literal>: + +<programlisting> +REVOKE INSERT ON films FROM PUBLIC; +</programlisting> + </para> + + <para> + Revoke all privileges from user <literal>manuel</literal> on view + <literal>kinds</literal>: + +<programlisting> +REVOKE ALL PRIVILEGES ON kinds FROM manuel; +</programlisting> + + Note that this actually means <quote>revoke all privileges that I + granted</quote>. + </para> + + <para> + Revoke membership in role <literal>admins</literal> from user <literal>joe</literal>: + +<programlisting> +REVOKE admins FROM joe; +</programlisting></para> + </refsect1> + + <refsect1 id="sql-revoke-compatibility"> + <title>Compatibility</title> + + <para> + The compatibility notes of the <link linkend="sql-grant"><command>GRANT</command></link> command + apply analogously to <command>REVOKE</command>. + The keyword <literal>RESTRICT</literal> or <literal>CASCADE</literal> + is required according to the standard, but <productname>PostgreSQL</productname> + assumes <literal>RESTRICT</literal> by default. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-grant"/></member> + <member><xref linkend="sql-alterdefaultprivileges"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/rollback.sgml b/doc/src/sgml/ref/rollback.sgml new file mode 100644 index 0000000..142f71e --- /dev/null +++ b/doc/src/sgml/ref/rollback.sgml @@ -0,0 +1,112 @@ +<!-- +doc/src/sgml/ref/rollback.sgml +PostgreSQL documentation +--> + +<refentry id="sql-rollback"> + <indexterm zone="sql-rollback"> + <primary>ROLLBACK</primary> + </indexterm> + + <refmeta> + <refentrytitle>ROLLBACK</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ROLLBACK</refname> + <refpurpose>abort the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ROLLBACK [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ROLLBACK</command> rolls back the current transaction and causes + all the updates made by the transaction to be discarded. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <indexterm zone="sql-rollback-chain"> + <primary>chained transactions</primary> + </indexterm> + + <variablelist> + <varlistentry> + <term><literal>WORK</literal></term> + <term><literal>TRANSACTION</literal></term> + <listitem> + <para> + Optional key words. They have no effect. + </para> + </listitem> + </varlistentry> + + <varlistentry id="sql-rollback-chain"> + <term><literal>AND CHAIN</literal></term> + <listitem> + <para> + If <literal>AND CHAIN</literal> is specified, a new transaction is + immediately started with the same transaction characteristics (see <xref + linkend="sql-set-transaction"/>) as the just finished one. Otherwise, + no new transaction is started. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-commit"><command>COMMIT</command></link> to + successfully terminate a transaction. + </para> + + <para> + Issuing <command>ROLLBACK</command> outside of a transaction + block emits a warning and otherwise has no effect. <command>ROLLBACK AND + CHAIN</command> outside of a transaction block is an error. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To abort all changes: +<programlisting> +ROLLBACK; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The command <command>ROLLBACK</command> conforms to the SQL standard. The + form <literal>ROLLBACK TRANSACTION</literal> is a PostgreSQL extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback-to"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/rollback_prepared.sgml b/doc/src/sgml/ref/rollback_prepared.sgml new file mode 100644 index 0000000..175a3e9 --- /dev/null +++ b/doc/src/sgml/ref/rollback_prepared.sgml @@ -0,0 +1,107 @@ +<!-- +doc/src/sgml/ref/rollback_prepared.sgml +PostgreSQL documentation +--> + +<refentry id="sql-rollback-prepared"> + <indexterm zone="sql-rollback-prepared"> + <primary>ROLLBACK PREPARED</primary> + </indexterm> + + <refmeta> + <refentrytitle>ROLLBACK PREPARED</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ROLLBACK PREPARED</refname> + <refpurpose>cancel a transaction that was earlier prepared for two-phase commit</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ROLLBACK PREPARED <replaceable class="parameter">transaction_id</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>ROLLBACK PREPARED</command> rolls back a transaction that is in + prepared state. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">transaction_id</replaceable></term> + <listitem> + <para> + The transaction identifier of the transaction that is to be + rolled back. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + To roll back a prepared transaction, you must be either the same user that + executed the transaction originally, or a superuser. But you do not + have to be in the same session that executed the transaction. + </para> + + <para> + This command cannot be executed inside a transaction block. The prepared + transaction is rolled back immediately. + </para> + + <para> + All currently available prepared transactions are listed in the + <link linkend="view-pg-prepared-xacts"><structname>pg_prepared_xacts</structname></link> + system view. + </para> + </refsect1> + + <refsect1 id="sql-rollback-prepared-examples"> + <title>Examples</title> + <para> + Roll back the transaction identified by the transaction + identifier <literal>foobar</literal>: + +<programlisting> +ROLLBACK PREPARED 'foobar'; +</programlisting></para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <command>ROLLBACK PREPARED</command> is a + <productname>PostgreSQL</productname> extension. It is intended for use by + external transaction management systems, some of which are covered by + standards (such as X/Open XA), but the SQL side of those systems is not + standardized. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-prepare-transaction"/></member> + <member><xref linkend="sql-commit-prepared"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/rollback_to.sgml b/doc/src/sgml/ref/rollback_to.sgml new file mode 100644 index 0000000..27fa95c --- /dev/null +++ b/doc/src/sgml/ref/rollback_to.sgml @@ -0,0 +1,158 @@ +<!-- +doc/src/sgml/ref/rollback_to.sgml +PostgreSQL documentation +--> + +<refentry id="sql-rollback-to"> + <indexterm zone="sql-rollback-to"> + <primary>ROLLBACK TO SAVEPOINT</primary> + </indexterm> + + <indexterm zone="sql-rollback-to"> + <primary>savepoints</primary> + <secondary>rolling back</secondary> + </indexterm> + + <refmeta> + <refentrytitle>ROLLBACK TO SAVEPOINT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>ROLLBACK TO SAVEPOINT</refname> + <refpurpose>roll back to a savepoint</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +ROLLBACK [ WORK | TRANSACTION ] TO [ SAVEPOINT ] <replaceable>savepoint_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + Roll back all commands that were executed after the savepoint was + established. The savepoint remains valid and can be rolled back to + again later, if needed. + </para> + + <para> + <command>ROLLBACK TO SAVEPOINT</command> implicitly destroys all savepoints that + were established after the named savepoint. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">savepoint_name</replaceable></term> + <listitem> + <para> + The savepoint to roll back to. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-release-savepoint"><command>RELEASE SAVEPOINT</command></link> to destroy a savepoint + without discarding the effects of commands executed after it was + established. + </para> + + <para> + Specifying a savepoint name that has not been established is an error. + </para> + + <para> + Cursors have somewhat non-transactional behavior with respect to + savepoints. Any cursor that is opened inside a savepoint will be closed + when the savepoint is rolled back. If a previously opened cursor is + affected by a <command>FETCH</command> or <command>MOVE</command> command inside a + savepoint that is later rolled back, the cursor remains at the + position that <command>FETCH</command> left it pointing to (that is, the cursor + motion caused by <command>FETCH</command> is not rolled back). + Closing a cursor is not undone by rolling back, either. + However, other side-effects caused by the cursor's query (such as + side-effects of volatile functions called by the query) <emphasis>are</emphasis> + rolled back if they occur during a savepoint that is later rolled back. + A cursor whose execution causes a transaction to abort is put in a + cannot-execute state, so while the transaction can be restored using + <command>ROLLBACK TO SAVEPOINT</command>, the cursor can no longer be used. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To undo the effects of the commands executed after <literal>my_savepoint</literal> + was established: +<programlisting> +ROLLBACK TO SAVEPOINT my_savepoint; +</programlisting> + </para> + + <para> + Cursor positions are not affected by savepoint rollback: +<programlisting> +BEGIN; + +DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2; + +SAVEPOINT foo; + +FETCH 1 FROM foo; + ?column? +---------- + 1 + +ROLLBACK TO SAVEPOINT foo; + +FETCH 1 FROM foo; + ?column? +---------- + 2 + +COMMIT; +</programlisting></para> + + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <acronym>SQL</acronym> standard specifies that the key word + <literal>SAVEPOINT</literal> is mandatory, but <productname>PostgreSQL</productname> + and <productname>Oracle</productname> allow it to be omitted. SQL allows + only <literal>WORK</literal>, not <literal>TRANSACTION</literal>, as a noise word + after <literal>ROLLBACK</literal>. Also, SQL has an optional clause + <literal>AND [ NO ] CHAIN</literal> which is not currently supported by + <productname>PostgreSQL</productname>. Otherwise, this command conforms to + the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-release-savepoint"/></member> + <member><xref linkend="sql-rollback"/></member> + <member><xref linkend="sql-savepoint"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/savepoint.sgml b/doc/src/sgml/ref/savepoint.sgml new file mode 100644 index 0000000..f84ac3d --- /dev/null +++ b/doc/src/sgml/ref/savepoint.sgml @@ -0,0 +1,165 @@ +<!-- +doc/src/sgml/ref/savepoint.sgml +PostgreSQL documentation +--> + +<refentry id="sql-savepoint"> + <indexterm zone="sql-savepoint"> + <primary>SAVEPOINT</primary> + </indexterm> + + <indexterm zone="sql-savepoint"> + <primary>savepoints</primary> + <secondary>defining</secondary> + </indexterm> + + <refmeta> + <refentrytitle>SAVEPOINT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SAVEPOINT</refname> + <refpurpose>define a new savepoint within the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SAVEPOINT <replaceable>savepoint_name</replaceable> +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SAVEPOINT</command> establishes a new savepoint within + the current transaction. + </para> + + <para> + A savepoint is a special mark inside a transaction that allows all commands + that are executed after it was established to be rolled back, restoring + the transaction state to what it was at the time of the savepoint. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable>savepoint_name</replaceable></term> + <listitem> + <para> + The name to give to the new savepoint. If savepoints with the + same name already exist, they will be inaccessible until newer + identically-named savepoints are released. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Use <link linkend="sql-rollback-to"><command>ROLLBACK TO</command></link> to + rollback to a savepoint. Use <link linkend="sql-release-savepoint"><command>RELEASE SAVEPOINT</command></link> + to destroy a savepoint, keeping + the effects of commands executed after it was established. + </para> + + <para> + Savepoints can only be established when inside a transaction block. + There can be multiple savepoints defined within a transaction. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To establish a savepoint and later undo the effects of all commands executed + after it was established: +<programlisting> +BEGIN; + INSERT INTO table1 VALUES (1); + SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (2); + ROLLBACK TO SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (3); +COMMIT; +</programlisting> + The above transaction will insert the values 1 and 3, but not 2. + </para> + + <para> + To establish and later destroy a savepoint: +<programlisting> +BEGIN; + INSERT INTO table1 VALUES (3); + SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (4); + RELEASE SAVEPOINT my_savepoint; +COMMIT; +</programlisting> + The above transaction will insert both 3 and 4. + </para> + + <para> + To use a single savepoint name: +<programlisting> +BEGIN; + INSERT INTO table1 VALUES (1); + SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (2); + SAVEPOINT my_savepoint; + INSERT INTO table1 VALUES (3); + + -- rollback to the second savepoint + ROLLBACK TO SAVEPOINT my_savepoint; + SELECT * FROM table1; -- shows rows 1 and 2 + + -- release the second savepoint + RELEASE SAVEPOINT my_savepoint; + + -- rollback to the first savepoint + ROLLBACK TO SAVEPOINT my_savepoint; + SELECT * FROM table1; -- shows only row 1 +COMMIT; +</programlisting> + The above transaction shows row 3 being rolled back first, then row 2. + </para> + + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + SQL requires a savepoint to be destroyed automatically when another + savepoint with the same name is established. In + <productname>PostgreSQL</productname>, the old savepoint is kept, though only the more + recent one will be used when rolling back or releasing. (Releasing the + newer savepoint with <command>RELEASE SAVEPOINT</command> will cause the older one + to again become accessible to <command>ROLLBACK TO SAVEPOINT</command> and + <command>RELEASE SAVEPOINT</command>.) Otherwise, <command>SAVEPOINT</command> is + fully SQL conforming. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-release-savepoint"/></member> + <member><xref linkend="sql-rollback"/></member> + <member><xref linkend="sql-rollback-to"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/security_label.sgml b/doc/src/sgml/ref/security_label.sgml new file mode 100644 index 0000000..5f96b7e --- /dev/null +++ b/doc/src/sgml/ref/security_label.sgml @@ -0,0 +1,233 @@ +<!-- +doc/src/sgml/ref/security_label.sgml +PostgreSQL documentation +--> + +<refentry id="sql-security-label"> + <indexterm zone="sql-security-label"> + <primary>SECURITY LABEL</primary> + </indexterm> + + <refmeta> + <refentrytitle>SECURITY LABEL</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SECURITY LABEL</refname> + <refpurpose>define or change a security label applied to an object</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SECURITY LABEL [ FOR <replaceable class="parameter">provider</replaceable> ] ON +{ + TABLE <replaceable class="parameter">object_name</replaceable> | + COLUMN <replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable> | + AGGREGATE <replaceable class="parameter">aggregate_name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) | + DATABASE <replaceable class="parameter">object_name</replaceable> | + DOMAIN <replaceable class="parameter">object_name</replaceable> | + EVENT TRIGGER <replaceable class="parameter">object_name</replaceable> | + FOREIGN TABLE <replaceable class="parameter">object_name</replaceable> + FUNCTION <replaceable class="parameter">function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + LARGE OBJECT <replaceable class="parameter">large_object_oid</replaceable> | + MATERIALIZED VIEW <replaceable class="parameter">object_name</replaceable> | + [ PROCEDURAL ] LANGUAGE <replaceable class="parameter">object_name</replaceable> | + PROCEDURE <replaceable class="parameter">procedure_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + PUBLICATION <replaceable class="parameter">object_name</replaceable> | + ROLE <replaceable class="parameter">object_name</replaceable> | + ROUTINE <replaceable class="parameter">routine_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) ] | + SCHEMA <replaceable class="parameter">object_name</replaceable> | + SEQUENCE <replaceable class="parameter">object_name</replaceable> | + SUBSCRIPTION <replaceable class="parameter">object_name</replaceable> | + TABLESPACE <replaceable class="parameter">object_name</replaceable> | + TYPE <replaceable class="parameter">object_name</replaceable> | + VIEW <replaceable class="parameter">object_name</replaceable> +} IS { <replaceable class="parameter">string_literal</replaceable> | NULL } + +<phrase>where <replaceable>aggregate_signature</replaceable> is:</phrase> + +* | +[ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] | +[ [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] ] ORDER BY [ <replaceable>argmode</replaceable> ] [ <replaceable>argname</replaceable> ] <replaceable>argtype</replaceable> [ , ... ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SECURITY LABEL</command> applies a security label to a database + object. An arbitrary number of security labels, one per label provider, can + be associated with a given database object. Label providers are loadable + modules which register themselves by using the function + <function>register_label_provider</function>. + </para> + + <note> + <para> + <function>register_label_provider</function> is not an SQL function; it can + only be called from C code loaded into the backend. + </para> + </note> + + <para> + The label provider determines whether a given label is valid and whether + it is permissible to assign that label to a given object. The meaning of a + given label is likewise at the discretion of the label provider. + <productname>PostgreSQL</productname> places no restrictions on whether or how a + label provider must interpret security labels; it merely provides a + mechanism for storing them. In practice, this facility is intended to allow + integration with label-based mandatory access control (MAC) systems such as + <productname>SELinux</productname>. Such systems make all access control decisions + based on object labels, rather than traditional discretionary access control + (DAC) concepts such as users and groups. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">object_name</replaceable></term> + <term><replaceable class="parameter">table_name.column_name</replaceable></term> + <term><replaceable class="parameter">aggregate_name</replaceable></term> + <term><replaceable class="parameter">function_name</replaceable></term> + <term><replaceable class="parameter">procedure_name</replaceable></term> + <term><replaceable class="parameter">routine_name</replaceable></term> + <listitem> + <para> + The name of the object to be labeled. Names of objects that reside in + schemas (tables, functions, etc.) can be schema-qualified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">provider</replaceable></term> + <listitem> + <para> + The name of the provider with which this label is to be associated. The + named provider must be loaded and must consent to the proposed labeling + operation. If exactly one provider is loaded, the provider name may be + omitted for brevity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argmode</replaceable></term> + + <listitem> + <para> + The mode of a function, procedure, or aggregate + argument: <literal>IN</literal>, <literal>OUT</literal>, + <literal>INOUT</literal>, or <literal>VARIADIC</literal>. + If omitted, the default is <literal>IN</literal>. + Note that <command>SECURITY LABEL</command> does not actually + pay any attention to <literal>OUT</literal> arguments, since only the input + arguments are needed to determine the function's identity. + So it is sufficient to list the <literal>IN</literal>, <literal>INOUT</literal>, + and <literal>VARIADIC</literal> arguments. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argname</replaceable></term> + + <listitem> + <para> + The name of a function, procedure, or aggregate argument. + Note that <command>SECURITY LABEL</command> does not actually + pay any attention to argument names, since only the argument data + types are needed to determine the function's identity. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">argtype</replaceable></term> + + <listitem> + <para> + The data type of a function, procedure, or aggregate argument. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">large_object_oid</replaceable></term> + <listitem> + <para> + The OID of the large object. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROCEDURAL</literal></term> + + <listitem> + <para> + This is a noise word. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">string_literal</replaceable></term> + <listitem> + <para> + The new setting of the security label, written as a string literal. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NULL</literal></term> + <listitem> + <para> + Write <literal>NULL</literal> to drop the security label. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + The following example shows how the security label of a table could + be set or changed: + +<programlisting> +SECURITY LABEL FOR selinux ON TABLE mytable IS 'system_u:object_r:sepgsql_table_t:s0'; +</programlisting> + + To remove the label: + +<programlisting> +SECURITY LABEL FOR selinux ON TABLE mytable IS NULL; +</programlisting> + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + <para> + There is no <command>SECURITY LABEL</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + <simplelist type="inline"> + <member><xref linkend="sepgsql"/></member> + <member><filename>src/test/modules/dummy_seclabel</filename></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml new file mode 100644 index 0000000..5df0d89 --- /dev/null +++ b/doc/src/sgml/ref/select.sgml @@ -0,0 +1,2200 @@ +<!-- +doc/src/sgml/ref/select.sgml +PostgreSQL documentation +--> + +<refentry id="sql-select"> + <indexterm zone="sql-select"> + <primary>SELECT</primary> + </indexterm> + + <indexterm zone="sql-select"> + <primary>TABLE command</primary> + </indexterm> + + <indexterm zone="sql-select"> + <primary>WITH</primary> + <secondary>in SELECT</secondary> + </indexterm> + + <refmeta> + <refentrytitle>SELECT</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SELECT</refname> + <refname>TABLE</refname> + <refname>WITH</refname> + <refpurpose>retrieve rows from a table or view</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ] +SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replaceable> [, ...] ) ] ] + [ * | <replaceable class="parameter">expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] ] + [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ] + [ WHERE <replaceable class="parameter">condition</replaceable> ] + [ GROUP BY [ ALL | DISTINCT ] <replaceable class="parameter">grouping_element</replaceable> [, ...] ] + [ HAVING <replaceable class="parameter">condition</replaceable> ] + [ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ] + [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ] + [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ] + [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ] + [ OFFSET <replaceable class="parameter">start</replaceable> [ ROW | ROWS ] ] + [ FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } { ONLY | WITH TIES } ] + [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT | SKIP LOCKED ] [...] ] + +<phrase>where <replaceable class="parameter">from_item</replaceable> can be one of:</phrase> + + [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ] + [ TABLESAMPLE <replaceable class="parameter">sampling_method</replaceable> ( <replaceable class="parameter">argument</replaceable> [, ...] ) [ REPEATABLE ( <replaceable class="parameter">seed</replaceable> ) ] ] + [ LATERAL ] ( <replaceable class="parameter">select</replaceable> ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] + <replaceable class="parameter">with_query_name</replaceable> [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ] + [ LATERAL ] <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) + [ WITH ORDINALITY ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ] + [ LATERAL ] <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) [ AS ] <replaceable class="parameter">alias</replaceable> ( <replaceable class="parameter">column_definition</replaceable> [, ...] ) + [ LATERAL ] <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) AS ( <replaceable class="parameter">column_definition</replaceable> [, ...] ) + [ LATERAL ] ROWS FROM( <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) [ AS ( <replaceable class="parameter">column_definition</replaceable> [, ...] ) ] [, ...] ) + [ WITH ORDINALITY ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ] + <replaceable class="parameter">from_item</replaceable> <replaceable class="parameter">join_type</replaceable> <replaceable class="parameter">from_item</replaceable> { ON <replaceable class="parameter">join_condition</replaceable> | USING ( <replaceable class="parameter">join_column</replaceable> [, ...] ) [ AS <replaceable class="parameter">join_using_alias</replaceable> ] } + <replaceable class="parameter">from_item</replaceable> NATURAL <replaceable class="parameter">join_type</replaceable> <replaceable class="parameter">from_item</replaceable> + <replaceable class="parameter">from_item</replaceable> CROSS JOIN <replaceable class="parameter">from_item</replaceable> + +<phrase>and <replaceable class="parameter">grouping_element</replaceable> can be one of:</phrase> + + ( ) + <replaceable class="parameter">expression</replaceable> + ( <replaceable class="parameter">expression</replaceable> [, ...] ) + ROLLUP ( { <replaceable class="parameter">expression</replaceable> | ( <replaceable class="parameter">expression</replaceable> [, ...] ) } [, ...] ) + CUBE ( { <replaceable class="parameter">expression</replaceable> | ( <replaceable class="parameter">expression</replaceable> [, ...] ) } [, ...] ) + GROUPING SETS ( <replaceable class="parameter">grouping_element</replaceable> [, ...] ) + +<phrase>and <replaceable class="parameter">with_query</replaceable> is:</phrase> + + <replaceable class="parameter">with_query_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] AS [ [ NOT ] MATERIALIZED ] ( <replaceable class="parameter">select</replaceable> | <replaceable class="parameter">values</replaceable> | <replaceable class="parameter">insert</replaceable> | <replaceable class="parameter">update</replaceable> | <replaceable class="parameter">delete</replaceable> ) + [ SEARCH { BREADTH | DEPTH } FIRST BY <replaceable>column_name</replaceable> [, ...] SET <replaceable>search_seq_col_name</replaceable> ] + [ CYCLE <replaceable>column_name</replaceable> [, ...] SET <replaceable>cycle_mark_col_name</replaceable> [ TO <replaceable>cycle_mark_value</replaceable> DEFAULT <replaceable>cycle_mark_default</replaceable> ] USING <replaceable>cycle_path_col_name</replaceable> ] + +TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] +</synopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SELECT</command> retrieves rows from zero or more tables. + The general processing of <command>SELECT</command> is as follows: + + <orderedlist> + <listitem> + <para> + All queries in the <literal>WITH</literal> list are computed. + These effectively serve as temporary tables that can be referenced + in the <literal>FROM</literal> list. A <literal>WITH</literal> query + that is referenced more than once in <literal>FROM</literal> is + computed only once, + unless specified otherwise with <literal>NOT MATERIALIZED</literal>. + (See <xref linkend="sql-with"/> below.) + </para> + </listitem> + + <listitem> + <para> + All elements in the <literal>FROM</literal> list are computed. + (Each element in the <literal>FROM</literal> list is a real or + virtual table.) If more than one element is specified in the + <literal>FROM</literal> list, they are cross-joined together. + (See <xref linkend="sql-from"/> below.) + </para> + </listitem> + + <listitem> + <para> + If the <literal>WHERE</literal> clause is specified, all rows + that do not satisfy the condition are eliminated from the + output. (See <xref linkend="sql-where"/> below.) + </para> + </listitem> + + <listitem> + <para> + If the <literal>GROUP BY</literal> clause is specified, + or if there are aggregate function calls, the + output is combined into groups of rows that match on one or more + values, and the results of aggregate functions are computed. + If the <literal>HAVING</literal> clause is present, it + eliminates groups that do not satisfy the given condition. (See + <xref linkend="sql-groupby"/> and + <xref linkend="sql-having"/> below.) + Although query output columns are nominally computed in the next + step, they can also be referenced (by name or ordinal number) + in the <literal>GROUP BY</literal> clause. + </para> + </listitem> + + <listitem> + <para> + The actual output rows are computed using the + <command>SELECT</command> output expressions for each selected + row or row group. (See <xref linkend="sql-select-list"/> below.) + </para> + </listitem> + + <listitem> + <para><literal>SELECT DISTINCT</literal> eliminates duplicate rows from the + result. <literal>SELECT DISTINCT ON</literal> eliminates rows that + match on all the specified expressions. <literal>SELECT ALL</literal> + (the default) will return all candidate rows, including + duplicates. (See <xref linkend="sql-distinct"/> below.) + </para> + </listitem> + + <listitem> + <para> + Using the operators <literal>UNION</literal>, + <literal>INTERSECT</literal>, and <literal>EXCEPT</literal>, the + output of more than one <command>SELECT</command> statement can + be combined to form a single result set. The + <literal>UNION</literal> operator returns all rows that are in + one or both of the result sets. The + <literal>INTERSECT</literal> operator returns all rows that are + strictly in both result sets. The <literal>EXCEPT</literal> + operator returns the rows that are in the first result set but + not in the second. In all three cases, duplicate rows are + eliminated unless <literal>ALL</literal> is specified. The noise + word <literal>DISTINCT</literal> can be added to explicitly specify + eliminating duplicate rows. Notice that <literal>DISTINCT</literal> is + the default behavior here, even though <literal>ALL</literal> is + the default for <command>SELECT</command> itself. (See + <xref linkend="sql-union"/>, <xref linkend="sql-intersect"/>, and + <xref linkend="sql-except"/> below.) + </para> + </listitem> + + <listitem> + <para> + If the <literal>ORDER BY</literal> clause is specified, the + returned rows are sorted in the specified order. If + <literal>ORDER BY</literal> is not given, the rows are returned + in whatever order the system finds fastest to produce. (See + <xref linkend="sql-orderby"/> below.) + </para> + </listitem> + + <listitem> + <para> + If the <literal>LIMIT</literal> (or <literal>FETCH FIRST</literal>) or <literal>OFFSET</literal> + clause is specified, the <command>SELECT</command> statement + only returns a subset of the result rows. (See <xref + linkend="sql-limit"/> below.) + </para> + </listitem> + + <listitem> + <para> + If <literal>FOR UPDATE</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> + or <literal>FOR KEY SHARE</literal> + is specified, the + <command>SELECT</command> statement locks the selected rows + against concurrent updates. (See <xref linkend="sql-for-update-share"/> + below.) + </para> + </listitem> + </orderedlist> + </para> + + <para> + You must have <literal>SELECT</literal> privilege on each column used + in a <command>SELECT</command> command. The use of <literal>FOR NO KEY UPDATE</literal>, + <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal> or <literal>FOR KEY SHARE</literal> requires + <literal>UPDATE</literal> privilege as well (for at least one column + of each table so selected). + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <refsect2 id="sql-with" xreflabel="WITH Clause"> + <title><literal>WITH</literal> Clause</title> + + <para> + The <literal>WITH</literal> clause allows you to specify one or more + subqueries that can be referenced by name in the primary query. + The subqueries effectively act as temporary tables or views + for the duration of the primary query. + Each subquery can be a <command>SELECT</command>, <command>TABLE</command>, <command>VALUES</command>, + <command>INSERT</command>, <command>UPDATE</command> or + <command>DELETE</command> statement. + When writing a data-modifying statement (<command>INSERT</command>, + <command>UPDATE</command> or <command>DELETE</command>) in + <literal>WITH</literal>, it is usual to include a <literal>RETURNING</literal> clause. + It is the output of <literal>RETURNING</literal>, <emphasis>not</emphasis> the underlying + table that the statement modifies, that forms the temporary table that is + read by the primary query. If <literal>RETURNING</literal> is omitted, the + statement is still executed, but it produces no output so it cannot be + referenced as a table by the primary query. + </para> + + <para> + A name (without schema qualification) must be specified for each + <literal>WITH</literal> query. Optionally, a list of column names + can be specified; if this is omitted, + the column names are inferred from the subquery. + </para> + + <para> + If <literal>RECURSIVE</literal> is specified, it allows a + <command>SELECT</command> subquery to reference itself by name. Such a + subquery must have the form +<synopsis> +<replaceable class="parameter">non_recursive_term</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">recursive_term</replaceable> +</synopsis> + where the recursive self-reference must appear on the right-hand + side of the <literal>UNION</literal>. Only one recursive self-reference + is permitted per query. Recursive data-modifying statements are not + supported, but you can use the results of a recursive + <command>SELECT</command> query in + a data-modifying statement. See <xref linkend="queries-with"/> for + an example. + </para> + + <para> + Another effect of <literal>RECURSIVE</literal> is that + <literal>WITH</literal> queries need not be ordered: a query + can reference another one that is later in the list. (However, + circular references, or mutual recursion, are not implemented.) + Without <literal>RECURSIVE</literal>, <literal>WITH</literal> queries + can only reference sibling <literal>WITH</literal> queries + that are earlier in the <literal>WITH</literal> list. + </para> + + <para> + When there are multiple queries in the <literal>WITH</literal> + clause, <literal>RECURSIVE</literal> should be written only once, + immediately after <literal>WITH</literal>. It applies to all queries + in the <literal>WITH</literal> clause, though it has no effect on + queries that do not use recursion or forward references. + </para> + + <para> + The optional <literal>SEARCH</literal> clause computes a <firstterm>search + sequence column</firstterm> that can be used for ordering the results of a + recursive query in either breadth-first or depth-first order. The + supplied column name list specifies the row key that is to be used for + keeping track of visited rows. A column named + <replaceable>search_seq_col_name</replaceable> will be added to the result + column list of the <literal>WITH</literal> query. This column can be + ordered by in the outer query to achieve the respective ordering. See + <xref linkend="queries-with-search"/> for examples. + </para> + + <para> + The optional <literal>CYCLE</literal> clause is used to detect cycles in + recursive queries. The supplied column name list specifies the row key + that is to be used for keeping track of visited rows. A column named + <replaceable>cycle_mark_col_name</replaceable> will be added to the result + column list of the <literal>WITH</literal> query. This column will be set + to <replaceable>cycle_mark_value</replaceable> when a cycle has been + detected, else to <replaceable>cycle_mark_default</replaceable>. + Furthermore, processing of the recursive union will stop when a cycle has + been detected. <replaceable>cycle_mark_value</replaceable> and + <replaceable>cycle_mark_default</replaceable> must be constants and they + must be coercible to a common data type, and the data type must have an + inequality operator. (The SQL standard requires that they be Boolean + constants or character strings, but PostgreSQL does not require that.) By + default, <literal>TRUE</literal> and <literal>FALSE</literal> (of type + <type>boolean</type>) are used. Furthermore, a column + named <replaceable>cycle_path_col_name</replaceable> will be added to the + result column list of the <literal>WITH</literal> query. This column is + used internally for tracking visited rows. See <xref + linkend="queries-with-cycle"/> for examples. + </para> + + <para> + Both the <literal>SEARCH</literal> and the <literal>CYCLE</literal> clause + are only valid for recursive <literal>WITH</literal> queries. The + <replaceable>with_query</replaceable> must be a <literal>UNION</literal> + (or <literal>UNION ALL</literal>) of two <literal>SELECT</literal> (or + equivalent) commands (no nested <literal>UNION</literal>s). If both + clauses are used, the column added by the <literal>SEARCH</literal> clause + appears before the columns added by the <literal>CYCLE</literal> clause. + </para> + + <para> + The primary query and the <literal>WITH</literal> queries are all + (notionally) executed at the same time. This implies that the effects of + a data-modifying statement in <literal>WITH</literal> cannot be seen from + other parts of the query, other than by reading its <literal>RETURNING</literal> + output. If two such data-modifying statements attempt to modify the same + row, the results are unspecified. + </para> + + <para> + A key property of <literal>WITH</literal> queries is that they + are normally evaluated only once per execution of the primary query, + even if the primary query refers to them more than once. + In particular, data-modifying statements are guaranteed to be + executed once and only once, regardless of whether the primary query + reads all or any of their output. + </para> + + <para> + However, a <literal>WITH</literal> query can be marked + <literal>NOT MATERIALIZED</literal> to remove this guarantee. In that + case, the <literal>WITH</literal> query can be folded into the primary + query much as though it were a simple sub-<literal>SELECT</literal> in + the primary query's <literal>FROM</literal> clause. This results in + duplicate computations if the primary query refers to + that <literal>WITH</literal> query more than once; but if each such use + requires only a few rows of the <literal>WITH</literal> query's total + output, <literal>NOT MATERIALIZED</literal> can provide a net savings by + allowing the queries to be optimized jointly. + <literal>NOT MATERIALIZED</literal> is ignored if it is attached to + a <literal>WITH</literal> query that is recursive or is not + side-effect-free (i.e., is not a plain <literal>SELECT</literal> + containing no volatile functions). + </para> + + <para> + By default, a side-effect-free <literal>WITH</literal> query is folded + into the primary query if it is used exactly once in the primary + query's <literal>FROM</literal> clause. This allows joint optimization + of the two query levels in situations where that should be semantically + invisible. However, such folding can be prevented by marking the + <literal>WITH</literal> query as <literal>MATERIALIZED</literal>. + That might be useful, for example, if the <literal>WITH</literal> query + is being used as an optimization fence to prevent the planner from + choosing a bad plan. + <productname>PostgreSQL</productname> versions before v12 never did + such folding, so queries written for older versions might rely on + <literal>WITH</literal> to act as an optimization fence. + </para> + + <para> + See <xref linkend="queries-with"/> for additional information. + </para> + </refsect2> + + <refsect2 id="sql-from" xreflabel="FROM Clause"> + <title><literal>FROM</literal> Clause</title> + + <para> + The <literal>FROM</literal> clause specifies one or more source + tables for the <command>SELECT</command>. If multiple sources are + specified, the result is the Cartesian product (cross join) of all + the sources. But usually qualification conditions are added (via + <literal>WHERE</literal>) to restrict the returned rows to a small subset of the + Cartesian product. + </para> + + <para> + The <literal>FROM</literal> clause can contain the following + elements: + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of an existing table or view. + If <literal>ONLY</literal> is specified before the table name, only that + table is scanned. If <literal>ONLY</literal> is not specified, the table + and all its descendant tables (if any) are scanned. Optionally, + <literal>*</literal> can be specified after the table name to explicitly + indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">alias</replaceable></term> + <listitem> + <para> + A substitute name for the <literal>FROM</literal> item containing the + alias. An alias is used for brevity or to eliminate ambiguity + for self-joins (where the same table is scanned multiple + times). When an alias is provided, it completely hides the + actual name of the table or function; for example given + <literal>FROM foo AS f</literal>, the remainder of the + <command>SELECT</command> must refer to this <literal>FROM</literal> + item as <literal>f</literal> not <literal>foo</literal>. If an alias is + written, a column alias list can also be written to provide + substitute names for one or more columns of the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TABLESAMPLE <replaceable class="parameter">sampling_method</replaceable> ( <replaceable class="parameter">argument</replaceable> [, ...] ) [ REPEATABLE ( <replaceable class="parameter">seed</replaceable> ) ]</literal></term> + <listitem> + <para> + A <literal>TABLESAMPLE</literal> clause after + a <replaceable class="parameter">table_name</replaceable> indicates that the + specified <replaceable class="parameter">sampling_method</replaceable> + should be used to retrieve a subset of the rows in that table. + This sampling precedes the application of any other filters such + as <literal>WHERE</literal> clauses. + The standard <productname>PostgreSQL</productname> distribution + includes two sampling methods, <literal>BERNOULLI</literal> + and <literal>SYSTEM</literal>, and other sampling methods can be + installed in the database via extensions. + </para> + + <para> + The <literal>BERNOULLI</literal> and <literal>SYSTEM</literal> sampling methods + each accept a single <replaceable class="parameter">argument</replaceable> + which is the fraction of the table to sample, expressed as a + percentage between 0 and 100. This argument can be + any <type>real</type>-valued expression. (Other sampling methods might + accept more or different arguments.) These two methods each return + a randomly-chosen sample of the table that will contain + approximately the specified percentage of the table's rows. + The <literal>BERNOULLI</literal> method scans the whole table and + selects or ignores individual rows independently with the specified + probability. + The <literal>SYSTEM</literal> method does block-level sampling with + each block having the specified chance of being selected; all rows + in each selected block are returned. + The <literal>SYSTEM</literal> method is significantly faster than + the <literal>BERNOULLI</literal> method when small sampling + percentages are specified, but it may return a less-random sample of + the table as a result of clustering effects. + </para> + + <para> + The optional <literal>REPEATABLE</literal> clause specifies + a <replaceable class="parameter">seed</replaceable> number or expression to use + for generating random numbers within the sampling method. The seed + value can be any non-null floating-point value. Two queries that + specify the same seed and <replaceable class="parameter">argument</replaceable> + values will select the same sample of the table, if the table has + not been changed meanwhile. But different seed values will usually + produce different samples. + If <literal>REPEATABLE</literal> is not given then a new random + sample is selected for each query, based upon a system-generated seed. + Note that some add-on sampling methods do not + accept <literal>REPEATABLE</literal>, and will always produce new + samples on each use. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">select</replaceable></term> + <listitem> + <para> + A sub-<command>SELECT</command> can appear in the + <literal>FROM</literal> clause. This acts as though its + output were created as a temporary table for the duration of + this single <command>SELECT</command> command. Note that the + sub-<command>SELECT</command> must be surrounded by + parentheses, and an alias <emphasis>must</emphasis> be + provided for it. A + <link linkend="sql-values"><command>VALUES</command></link> command + can also be used here. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">with_query_name</replaceable></term> + <listitem> + <para> + A <literal>WITH</literal> query is referenced by writing its name, + just as though the query's name were a table name. (In fact, + the <literal>WITH</literal> query hides any real table of the same name + for the purposes of the primary query. If necessary, you can + refer to a real table of the same name by schema-qualifying + the table's name.) + An alias can be provided in the same way as for a table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">function_name</replaceable></term> + <listitem> + <para> + Function calls can appear in the <literal>FROM</literal> + clause. (This is especially useful for functions that return + result sets, but any function can be used.) This acts as + though the function's output were created as a temporary table for the + duration of this single <command>SELECT</command> command. + If the function's result type is composite (including the case of a + function with multiple <literal>OUT</literal> parameters), each + attribute becomes a separate column in the implicit table. + </para> + + <para> + When the optional <command>WITH ORDINALITY</command> clause is added + to the function call, an additional column of type <type>bigint</type> + will be appended to the function's result column(s). This column + numbers the rows of the function's result set, starting from 1. + By default, this column is named <literal>ordinality</literal>. + </para> + + <para> + An alias can be provided in the same way as for a table. + If an alias is written, a column + alias list can also be written to provide substitute names for + one or more attributes of the function's composite return + type, including the ordinality column if present. + </para> + + <para> + Multiple function calls can be combined into a + single <literal>FROM</literal>-clause item by surrounding them + with <literal>ROWS FROM( ... )</literal>. The output of such an item is the + concatenation of the first row from each function, then the second + row from each function, etc. If some of the functions produce fewer + rows than others, null values are substituted for the missing data, so + that the total number of rows returned is always the same as for the + function that produced the most rows. + </para> + + <para> + If the function has been defined as returning the + <type>record</type> data type, then an alias or the key word + <literal>AS</literal> must be present, followed by a column + definition list in the form <literal>( <replaceable + class="parameter">column_name</replaceable> <replaceable + class="parameter">data_type</replaceable> <optional>, ... + </optional>)</literal>. The column definition list must match the + actual number and types of columns returned by the function. + </para> + + <para> + When using the <literal>ROWS FROM( ... )</literal> syntax, if one of the + functions requires a column definition list, it's preferred to put + the column definition list after the function call inside + <literal>ROWS FROM( ... )</literal>. A column definition list can be placed + after the <literal>ROWS FROM( ... )</literal> construct only if there's just + a single function and no <literal>WITH ORDINALITY</literal> clause. + </para> + + <para> + To use <literal>ORDINALITY</literal> together with a column definition + list, you must use the <literal>ROWS FROM( ... )</literal> syntax and put the + column definition list inside <literal>ROWS FROM( ... )</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">join_type</replaceable></term> + <listitem> + <para> + One of + <itemizedlist> + <listitem> + <para><literal>[ INNER ] JOIN</literal></para> + </listitem> + <listitem> + <para><literal>LEFT [ OUTER ] JOIN</literal></para> + </listitem> + <listitem> + <para><literal>RIGHT [ OUTER ] JOIN</literal></para> + </listitem> + <listitem> + <para><literal>FULL [ OUTER ] JOIN</literal></para> + </listitem> + </itemizedlist> + + For the <literal>INNER</literal> and <literal>OUTER</literal> join types, a + join condition must be specified, namely exactly one of + <literal>ON <replaceable + class="parameter">join_condition</replaceable></literal>, + <literal>USING (<replaceable + class="parameter">join_column</replaceable> [, ...])</literal>, + or <literal>NATURAL</literal>. See below for the meaning. + </para> + + <para> + A <literal>JOIN</literal> clause combines two <literal>FROM</literal> + items, which for convenience we will refer to as <quote>tables</quote>, + though in reality they can be any type of <literal>FROM</literal> item. + Use parentheses if necessary to determine the order of nesting. + In the absence of parentheses, <literal>JOIN</literal>s nest + left-to-right. In any case <literal>JOIN</literal> binds more + tightly than the commas separating <literal>FROM</literal>-list items. + All the <literal>JOIN</literal> options are just a notational + convenience, since they do nothing you couldn't do with plain + <literal>FROM</literal> and <literal>WHERE</literal>. + </para> + + <para><literal>LEFT OUTER JOIN</literal> returns all rows in the qualified + Cartesian product (i.e., all combined rows that pass its join + condition), plus one copy of each row in the left-hand table + for which there was no right-hand row that passed the join + condition. This left-hand row is extended to the full width + of the joined table by inserting null values for the + right-hand columns. Note that only the <literal>JOIN</literal> + clause's own condition is considered while deciding which rows + have matches. Outer conditions are applied afterwards. + </para> + + <para> + Conversely, <literal>RIGHT OUTER JOIN</literal> returns all the + joined rows, plus one row for each unmatched right-hand row + (extended with nulls on the left). This is just a notational + convenience, since you could convert it to a <literal>LEFT + OUTER JOIN</literal> by switching the left and right tables. + </para> + + <para><literal>FULL OUTER JOIN</literal> returns all the joined rows, plus + one row for each unmatched left-hand row (extended with nulls + on the right), plus one row for each unmatched right-hand row + (extended with nulls on the left). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ON <replaceable class="parameter">join_condition</replaceable></literal></term> + <listitem> + <para><replaceable class="parameter">join_condition</replaceable> is + an expression resulting in a value of type + <type>boolean</type> (similar to a <literal>WHERE</literal> + clause) that specifies which rows in a join are considered to + match. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>USING ( <replaceable class="parameter">join_column</replaceable> [, ...] ) [ AS <replaceable class="parameter">join_using_alias</replaceable> ]</literal></term> + <listitem> + <para> + A clause of the form <literal>USING ( a, b, ... )</literal> is + shorthand for <literal>ON left_table.a = right_table.a AND + left_table.b = right_table.b ...</literal>. Also, + <literal>USING</literal> implies that only one of each pair of + equivalent columns will be included in the join output, not + both. + </para> + + <para> + If a <replaceable class="parameter">join_using_alias</replaceable> + name is specified, it provides a table alias for the join columns. + Only the join columns listed in the <literal>USING</literal> clause + are addressable by this name. Unlike a regular <replaceable + class="parameter">alias</replaceable>, this does not hide the names of + the joined tables from the rest of the query. Also unlike a regular + <replaceable class="parameter">alias</replaceable>, you cannot write a + column alias list — the output names of the join columns are the + same as they appear in the <literal>USING</literal> list. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NATURAL</literal></term> + <listitem> + <para> + <literal>NATURAL</literal> is shorthand for a + <literal>USING</literal> list that mentions all columns in the two + tables that have matching names. If there are no common + column names, <literal>NATURAL</literal> is equivalent + to <literal>ON TRUE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CROSS JOIN</literal></term> + <listitem> + <para> + <literal>CROSS JOIN</literal> is equivalent to <literal>INNER JOIN ON + (TRUE)</literal>, that is, no rows are removed by qualification. + They produce a simple Cartesian product, the same result as you get from + listing the two tables at the top level of <literal>FROM</literal>, + but restricted by the join condition (if any). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LATERAL</literal></term> + <listitem> + <para> + The <literal>LATERAL</literal> key word can precede a + sub-<command>SELECT</command> <literal>FROM</literal> item. This allows the + sub-<command>SELECT</command> to refer to columns of <literal>FROM</literal> + items that appear before it in the <literal>FROM</literal> list. (Without + <literal>LATERAL</literal>, each sub-<command>SELECT</command> is + evaluated independently and so cannot cross-reference any other + <literal>FROM</literal> item.) + </para> + + <para><literal>LATERAL</literal> can also precede a function-call + <literal>FROM</literal> item, but in this case it is a noise word, because + the function expression can refer to earlier <literal>FROM</literal> items + in any case. + </para> + + <para> + A <literal>LATERAL</literal> item can appear at top level in the + <literal>FROM</literal> list, or within a <literal>JOIN</literal> tree. In the + latter case it can also refer to any items that are on the left-hand + side of a <literal>JOIN</literal> that it is on the right-hand side of. + </para> + + <para> + When a <literal>FROM</literal> item contains <literal>LATERAL</literal> + cross-references, evaluation proceeds as follows: for each row of the + <literal>FROM</literal> item providing the cross-referenced column(s), or + set of rows of multiple <literal>FROM</literal> items providing the + columns, the <literal>LATERAL</literal> item is evaluated using that + row or row set's values of the columns. The resulting row(s) are + joined as usual with the rows they were computed from. This is + repeated for each row or set of rows from the column source table(s). + </para> + + <para> + The column source table(s) must be <literal>INNER</literal> or + <literal>LEFT</literal> joined to the <literal>LATERAL</literal> item, else + there would not be a well-defined set of rows from which to compute + each set of rows for the <literal>LATERAL</literal> item. Thus, + although a construct such as <literal><replaceable>X</replaceable> RIGHT JOIN + LATERAL <replaceable>Y</replaceable></literal> is syntactically valid, it is + not actually allowed for <replaceable>Y</replaceable> to reference + <replaceable>X</replaceable>. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect2> + + <refsect2 id="sql-where" xreflabel="WHERE Clause"> + <title><literal>WHERE</literal> Clause</title> + + <para> + The optional <literal>WHERE</literal> clause has the general form +<synopsis> +WHERE <replaceable class="parameter">condition</replaceable> +</synopsis> + where <replaceable class="parameter">condition</replaceable> is + any expression that evaluates to a result of type + <type>boolean</type>. Any row that does not satisfy this + condition will be eliminated from the output. A row satisfies the + condition if it returns true when the actual row values are + substituted for any variable references. + </para> + </refsect2> + + <refsect2 id="sql-groupby" xreflabel="GROUP BY Clause"> + <title><literal>GROUP BY</literal> Clause</title> + + <para> + The optional <literal>GROUP BY</literal> clause has the general form +<synopsis> +GROUP BY [ ALL | DISTINCT ] <replaceable class="parameter">grouping_element</replaceable> [, ...] +</synopsis> + </para> + + <para> + <literal>GROUP BY</literal> will condense into a single row all + selected rows that share the same values for the grouped + expressions. An <replaceable + class="parameter">expression</replaceable> used inside a + <replaceable class="parameter">grouping_element</replaceable> + can be an input column name, or the name or ordinal number of an + output column (<command>SELECT</command> list item), or an arbitrary + expression formed from input-column values. In case of ambiguity, + a <literal>GROUP BY</literal> name will be interpreted as an + input-column name rather than an output column name. + </para> + + <para> + If any of <literal>GROUPING SETS</literal>, <literal>ROLLUP</literal> or + <literal>CUBE</literal> are present as grouping elements, then the + <literal>GROUP BY</literal> clause as a whole defines some number of + independent <replaceable>grouping sets</replaceable>. The effect of this is + equivalent to constructing a <literal>UNION ALL</literal> between + subqueries with the individual grouping sets as their + <literal>GROUP BY</literal> clauses. The optional <literal>DISTINCT</literal> + clause removes duplicate sets before processing; it does <emphasis>not</emphasis> + transform the <literal>UNION ALL</literal> into a <literal>UNION DISTINCT</literal>. + For further details on the handling + of grouping sets see <xref linkend="queries-grouping-sets"/>. + </para> + + <para> + Aggregate functions, if any are used, are computed across all rows + making up each group, producing a separate value for each group. + (If there are aggregate functions but no <literal>GROUP BY</literal> + clause, the query is treated as having a single group comprising all + the selected rows.) + The set of rows fed to each aggregate function can be further filtered by + attaching a <literal>FILTER</literal> clause to the aggregate function + call; see <xref linkend="syntax-aggregates"/> for more information. When + a <literal>FILTER</literal> clause is present, only those rows matching it + are included in the input to that aggregate function. + </para> + + <para> + When <literal>GROUP BY</literal> is present, + or any aggregate functions are present, it is not valid for + the <command>SELECT</command> list expressions to refer to + ungrouped columns except within aggregate functions or when the + ungrouped column is functionally dependent on the grouped columns, + since there would otherwise be more than one possible value to + return for an ungrouped column. A functional dependency exists if + the grouped columns (or a subset thereof) are the primary key of + the table containing the ungrouped column. + </para> + + <para> + Keep in mind that all aggregate functions are evaluated before + evaluating any <quote>scalar</quote> expressions in the <literal>HAVING</literal> + clause or <literal>SELECT</literal> list. This means that, for example, + a <literal>CASE</literal> expression cannot be used to skip evaluation of + an aggregate function; see <xref linkend="syntax-express-eval"/>. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be + specified with <literal>GROUP BY</literal>. + </para> + </refsect2> + + <refsect2 id="sql-having" xreflabel="HAVING Clause"> + <title><literal>HAVING</literal> Clause</title> + + <para> + The optional <literal>HAVING</literal> clause has the general form +<synopsis> +HAVING <replaceable class="parameter">condition</replaceable> +</synopsis> + where <replaceable class="parameter">condition</replaceable> is + the same as specified for the <literal>WHERE</literal> clause. + </para> + + <para> + <literal>HAVING</literal> eliminates group rows that do not + satisfy the condition. <literal>HAVING</literal> is different + from <literal>WHERE</literal>: <literal>WHERE</literal> filters + individual rows before the application of <literal>GROUP + BY</literal>, while <literal>HAVING</literal> filters group rows + created by <literal>GROUP BY</literal>. Each column referenced in + <replaceable class="parameter">condition</replaceable> must + unambiguously reference a grouping column, unless the reference + appears within an aggregate function or the ungrouped column is + functionally dependent on the grouping columns. + </para> + + <para> + The presence of <literal>HAVING</literal> turns a query into a grouped + query even if there is no <literal>GROUP BY</literal> clause. This is the + same as what happens when the query contains aggregate functions but + no <literal>GROUP BY</literal> clause. All the selected rows are considered to + form a single group, and the <command>SELECT</command> list and + <literal>HAVING</literal> clause can only reference table columns from + within aggregate functions. Such a query will emit a single row if the + <literal>HAVING</literal> condition is true, zero rows if it is not true. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be + specified with <literal>HAVING</literal>. + </para> + </refsect2> + + <refsect2 id="sql-window" xreflabel="WINDOW Clause"> + <title><literal>WINDOW</literal> Clause</title> + + <para> + The optional <literal>WINDOW</literal> clause has the general form +<synopsis> +WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] +</synopsis> + where <replaceable class="parameter">window_name</replaceable> is + a name that can be referenced from <literal>OVER</literal> clauses or + subsequent window definitions, and + <replaceable class="parameter">window_definition</replaceable> is +<synopsis> +[ <replaceable class="parameter">existing_window_name</replaceable> ] +[ PARTITION BY <replaceable class="parameter">expression</replaceable> [, ...] ] +[ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ] +[ <replaceable class="parameter">frame_clause</replaceable> ] +</synopsis> + </para> + + <para> + If an <replaceable class="parameter">existing_window_name</replaceable> + is specified it must refer to an earlier entry in the <literal>WINDOW</literal> + list; the new window copies its partitioning clause from that entry, + as well as its ordering clause if any. In this case the new window cannot + specify its own <literal>PARTITION BY</literal> clause, and it can specify + <literal>ORDER BY</literal> only if the copied window does not have one. + The new window always uses its own frame clause; the copied window + must not specify a frame clause. + </para> + + <para> + The elements of the <literal>PARTITION BY</literal> list are interpreted in + much the same fashion as elements of a <link + linkend="sql-groupby"><literal>GROUP BY</literal></link> clause, except that + they are always simple expressions and never the name or number of an + output column. + Another difference is that these expressions can contain aggregate + function calls, which are not allowed in a regular <literal>GROUP BY</literal> + clause. They are allowed here because windowing occurs after grouping + and aggregation. + </para> + + <para> + Similarly, the elements of the <literal>ORDER BY</literal> list are interpreted + in much the same fashion as elements of a statement-level <link + linkend="sql-orderby"><literal>ORDER BY</literal></link> clause, except that + the expressions are always taken as simple expressions and never the name + or number of an output column. + </para> + + <para> + The optional <replaceable class="parameter">frame_clause</replaceable> defines + the <firstterm>window frame</firstterm> for window functions that depend on the + frame (not all do). The window frame is a set of related rows for + each row of the query (called the <firstterm>current row</firstterm>). + The <replaceable class="parameter">frame_clause</replaceable> can be one of + +<synopsis> +{ RANGE | ROWS | GROUPS } <replaceable>frame_start</replaceable> [ <replaceable>frame_exclusion</replaceable> ] +{ RANGE | ROWS | GROUPS } BETWEEN <replaceable>frame_start</replaceable> AND <replaceable>frame_end</replaceable> [ <replaceable>frame_exclusion</replaceable> ] +</synopsis> + + where <replaceable>frame_start</replaceable> + and <replaceable>frame_end</replaceable> can be one of + +<synopsis> +UNBOUNDED PRECEDING +<replaceable>offset</replaceable> PRECEDING +CURRENT ROW +<replaceable>offset</replaceable> FOLLOWING +UNBOUNDED FOLLOWING +</synopsis> + + and <replaceable>frame_exclusion</replaceable> can be one of + +<synopsis> +EXCLUDE CURRENT ROW +EXCLUDE GROUP +EXCLUDE TIES +EXCLUDE NO OTHERS +</synopsis> + + If <replaceable>frame_end</replaceable> is omitted it defaults to <literal>CURRENT + ROW</literal>. Restrictions are that + <replaceable>frame_start</replaceable> cannot be <literal>UNBOUNDED FOLLOWING</literal>, + <replaceable>frame_end</replaceable> cannot be <literal>UNBOUNDED PRECEDING</literal>, + and the <replaceable>frame_end</replaceable> choice cannot appear earlier in the + above list of <replaceable>frame_start</replaceable> + and <replaceable>frame_end</replaceable> options than + the <replaceable>frame_start</replaceable> choice does — for example + <literal>RANGE BETWEEN CURRENT ROW AND <replaceable>offset</replaceable> + PRECEDING</literal> is not allowed. + </para> + + <para> + The default framing option is <literal>RANGE UNBOUNDED PRECEDING</literal>, + which is the same as <literal>RANGE BETWEEN UNBOUNDED PRECEDING AND + CURRENT ROW</literal>; it sets the frame to be all rows from the partition start + up through the current row's last <firstterm>peer</firstterm> (a row + that the window's <literal>ORDER BY</literal> clause considers + equivalent to the current row; all rows are peers if there + is no <literal>ORDER BY</literal>). + In general, <literal>UNBOUNDED PRECEDING</literal> means that the frame + starts with the first row of the partition, and similarly + <literal>UNBOUNDED FOLLOWING</literal> means that the frame ends with the last + row of the partition, regardless + of <literal>RANGE</literal>, <literal>ROWS</literal> + or <literal>GROUPS</literal> mode. + In <literal>ROWS</literal> mode, <literal>CURRENT ROW</literal> means + that the frame starts or ends with the current row; but + in <literal>RANGE</literal> or <literal>GROUPS</literal> mode it means + that the frame starts or ends with the current row's first or last peer + in the <literal>ORDER BY</literal> ordering. + The <replaceable>offset</replaceable> <literal>PRECEDING</literal> and + <replaceable>offset</replaceable> <literal>FOLLOWING</literal> options + vary in meaning depending on the frame mode. + In <literal>ROWS</literal> mode, the <replaceable>offset</replaceable> + is an integer indicating that the frame starts or ends that many rows + before or after the current row. + In <literal>GROUPS</literal> mode, the <replaceable>offset</replaceable> + is an integer indicating that the frame starts or ends that many peer + groups before or after the current row's peer group, where + a <firstterm>peer group</firstterm> is a group of rows that are + equivalent according to the window's <literal>ORDER BY</literal> clause. + In <literal>RANGE</literal> mode, use of + an <replaceable>offset</replaceable> option requires that there be + exactly one <literal>ORDER BY</literal> column in the window definition. + Then the frame contains those rows whose ordering column value is no + more than <replaceable>offset</replaceable> less than + (for <literal>PRECEDING</literal>) or more than + (for <literal>FOLLOWING</literal>) the current row's ordering column + value. In these cases the data type of + the <replaceable>offset</replaceable> expression depends on the data + type of the ordering column. For numeric ordering columns it is + typically of the same type as the ordering column, but for datetime + ordering columns it is an <type>interval</type>. + In all these cases, the value of the <replaceable>offset</replaceable> + must be non-null and non-negative. Also, while + the <replaceable>offset</replaceable> does not have to be a simple + constant, it cannot contain variables, aggregate functions, or window + functions. + </para> + + <para> + The <replaceable>frame_exclusion</replaceable> option allows rows around + the current row to be excluded from the frame, even if they would be + included according to the frame start and frame end options. + <literal>EXCLUDE CURRENT ROW</literal> excludes the current row from the + frame. + <literal>EXCLUDE GROUP</literal> excludes the current row and its + ordering peers from the frame. + <literal>EXCLUDE TIES</literal> excludes any peers of the current + row from the frame, but not the current row itself. + <literal>EXCLUDE NO OTHERS</literal> simply specifies explicitly the + default behavior of not excluding the current row or its peers. + </para> + + <para> + Beware that the <literal>ROWS</literal> mode can produce unpredictable + results if the <literal>ORDER BY</literal> ordering does not order the rows + uniquely. The <literal>RANGE</literal> and <literal>GROUPS</literal> + modes are designed to ensure that rows that are peers in + the <literal>ORDER BY</literal> ordering are treated alike: all rows of + a given peer group will be in the frame or excluded from it. + </para> + + <para> + The purpose of a <literal>WINDOW</literal> clause is to specify the + behavior of <firstterm>window functions</firstterm> appearing in the query's + <link linkend="sql-select-list"><command>SELECT</command> list</link> or + <link linkend="sql-orderby"><literal>ORDER BY</literal></link> clause. + These functions + can reference the <literal>WINDOW</literal> clause entries by name + in their <literal>OVER</literal> clauses. A <literal>WINDOW</literal> clause + entry does not have to be referenced anywhere, however; if it is not + used in the query it is simply ignored. It is possible to use window + functions without any <literal>WINDOW</literal> clause at all, since + a window function call can specify its window definition directly in + its <literal>OVER</literal> clause. However, the <literal>WINDOW</literal> + clause saves typing when the same window definition is needed for more + than one window function. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be + specified with <literal>WINDOW</literal>. + </para> + + <para> + Window functions are described in detail in + <xref linkend="tutorial-window"/>, + <xref linkend="syntax-window-functions"/>, and + <xref linkend="queries-window"/>. + </para> + </refsect2> + + <refsect2 id="sql-select-list" xreflabel="SELECT List"> + <title><command>SELECT</command> List</title> + + <para> + The <command>SELECT</command> list (between the key words + <literal>SELECT</literal> and <literal>FROM</literal>) specifies expressions + that form the output rows of the <command>SELECT</command> + statement. The expressions can (and usually do) refer to columns + computed in the <literal>FROM</literal> clause. + </para> + + <para> + Just as in a table, every output column of a <command>SELECT</command> + has a name. In a simple <command>SELECT</command> this name is just + used to label the column for display, but when the <command>SELECT</command> + is a sub-query of a larger query, the name is seen by the larger query + as the column name of the virtual table produced by the sub-query. + To specify the name to use for an output column, write + <literal>AS</literal> <replaceable class="parameter">output_name</replaceable> + after the column's expression. (You can omit <literal>AS</literal>, + but only if the desired output name does not match any + <productname>PostgreSQL</productname> keyword (see <xref + linkend="sql-keywords-appendix"/>). For protection against possible + future keyword additions, it is recommended that you always either + write <literal>AS</literal> or double-quote the output name.) + If you do not specify a column name, a name is chosen automatically + by <productname>PostgreSQL</productname>. If the column's expression + is a simple column reference then the chosen name is the same as that + column's name. In more complex cases a function or type name may be + used, or the system may fall back on a generated name such as + <literal>?column?</literal>. + </para> + + <para> + An output column's name can be used to refer to the column's value in + <literal>ORDER BY</literal> and <literal>GROUP BY</literal> clauses, but not in the + <literal>WHERE</literal> or <literal>HAVING</literal> clauses; there you must write + out the expression instead. + </para> + + <para> + Instead of an expression, <literal>*</literal> can be written in + the output list as a shorthand for all the columns of the selected + rows. Also, you can write <literal><replaceable + class="parameter">table_name</replaceable>.*</literal> as a + shorthand for the columns coming from just that table. In these + cases it is not possible to specify new names with <literal>AS</literal>; + the output column names will be the same as the table columns' names. + </para> + + <para> + According to the SQL standard, the expressions in the output list should + be computed before applying <literal>DISTINCT</literal>, <literal>ORDER + BY</literal>, or <literal>LIMIT</literal>. This is obviously necessary + when using <literal>DISTINCT</literal>, since otherwise it's not clear + what values are being made distinct. However, in many cases it is + convenient if output expressions are computed after <literal>ORDER + BY</literal> and <literal>LIMIT</literal>; particularly if the output list + contains any volatile or expensive functions. With that behavior, the + order of function evaluations is more intuitive and there will not be + evaluations corresponding to rows that never appear in the output. + <productname>PostgreSQL</productname> will effectively evaluate output expressions + after sorting and limiting, so long as those expressions are not + referenced in <literal>DISTINCT</literal>, <literal>ORDER BY</literal> + or <literal>GROUP BY</literal>. (As a counterexample, <literal>SELECT + f(x) FROM tab ORDER BY 1</literal> clearly must evaluate <function>f(x)</function> + before sorting.) Output expressions that contain set-returning functions + are effectively evaluated after sorting and before limiting, so + that <literal>LIMIT</literal> will act to cut off the output from a + set-returning function. + </para> + + <note> + <para> + <productname>PostgreSQL</productname> versions before 9.6 did not provide any + guarantees about the timing of evaluation of output expressions versus + sorting and limiting; it depended on the form of the chosen query plan. + </para> + </note> + </refsect2> + + <refsect2 id="sql-distinct" xreflabel="DISTINCT Clause"> + <title><literal>DISTINCT</literal> Clause</title> + + <para> + If <literal>SELECT DISTINCT</literal> is specified, all duplicate rows are + removed from the result set (one row is kept from each group of + duplicates). <literal>SELECT ALL</literal> specifies the opposite: all rows are + kept; that is the default. + </para> + + <para> + <literal>SELECT DISTINCT ON ( <replaceable + class="parameter">expression</replaceable> [, ...] )</literal> + keeps only the first row of each set of rows where the given + expressions evaluate to equal. The <literal>DISTINCT ON</literal> + expressions are interpreted using the same rules as for + <literal>ORDER BY</literal> (see above). Note that the <quote>first + row</quote> of each set is unpredictable unless <literal>ORDER + BY</literal> is used to ensure that the desired row appears first. For + example: +<programlisting> +SELECT DISTINCT ON (location) location, time, report + FROM weather_reports + ORDER BY location, time DESC; +</programlisting> + retrieves the most recent weather report for each location. But + if we had not used <literal>ORDER BY</literal> to force descending order + of time values for each location, we'd have gotten a report from + an unpredictable time for each location. + </para> + + <para> + The <literal>DISTINCT ON</literal> expression(s) must match the leftmost + <literal>ORDER BY</literal> expression(s). The <literal>ORDER BY</literal> clause + will normally contain additional expression(s) that determine the + desired precedence of rows within each <literal>DISTINCT ON</literal> group. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be + specified with <literal>DISTINCT</literal>. + </para> + </refsect2> + + <refsect2 id="sql-union" xreflabel="UNION Clause"> + <title><literal>UNION</literal> Clause</title> + + <para> + The <literal>UNION</literal> clause has this general form: +<synopsis> +<replaceable class="parameter">select_statement</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable> +</synopsis><replaceable class="parameter">select_statement</replaceable> is + any <command>SELECT</command> statement without an <literal>ORDER + BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause. + (<literal>ORDER BY</literal> and <literal>LIMIT</literal> can be attached to a + subexpression if it is enclosed in parentheses. Without + parentheses, these clauses will be taken to apply to the result of + the <literal>UNION</literal>, not to its right-hand input + expression.) + </para> + + <para> + The <literal>UNION</literal> operator computes the set union of + the rows returned by the involved <command>SELECT</command> + statements. A row is in the set union of two result sets if it + appears in at least one of the result sets. The two + <command>SELECT</command> statements that represent the direct + operands of the <literal>UNION</literal> must produce the same + number of columns, and corresponding columns must be of compatible + data types. + </para> + + <para> + The result of <literal>UNION</literal> does not contain any duplicate + rows unless the <literal>ALL</literal> option is specified. + <literal>ALL</literal> prevents elimination of duplicates. (Therefore, + <literal>UNION ALL</literal> is usually significantly quicker than + <literal>UNION</literal>; use <literal>ALL</literal> when you can.) + <literal>DISTINCT</literal> can be written to explicitly specify the + default behavior of eliminating duplicate rows. + </para> + + <para> + Multiple <literal>UNION</literal> operators in the same + <command>SELECT</command> statement are evaluated left to right, + unless otherwise indicated by parentheses. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and + <literal>FOR KEY SHARE</literal> cannot be + specified either for a <literal>UNION</literal> result or for any input of a + <literal>UNION</literal>. + </para> + </refsect2> + + <refsect2 id="sql-intersect" xreflabel="INTERSECT Clause"> + <title><literal>INTERSECT</literal> Clause</title> + + <para> + The <literal>INTERSECT</literal> clause has this general form: +<synopsis> +<replaceable class="parameter">select_statement</replaceable> INTERSECT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable> +</synopsis><replaceable class="parameter">select_statement</replaceable> is + any <command>SELECT</command> statement without an <literal>ORDER + BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause. + </para> + + <para> + The <literal>INTERSECT</literal> operator computes the set + intersection of the rows returned by the involved + <command>SELECT</command> statements. A row is in the + intersection of two result sets if it appears in both result sets. + </para> + + <para> + The result of <literal>INTERSECT</literal> does not contain any + duplicate rows unless the <literal>ALL</literal> option is specified. + With <literal>ALL</literal>, a row that has <replaceable>m</replaceable> duplicates in the + left table and <replaceable>n</replaceable> duplicates in the right table will appear + min(<replaceable>m</replaceable>,<replaceable>n</replaceable>) times in the result set. + <literal>DISTINCT</literal> can be written to explicitly specify the + default behavior of eliminating duplicate rows. + </para> + + <para> + Multiple <literal>INTERSECT</literal> operators in the same + <command>SELECT</command> statement are evaluated left to right, + unless parentheses dictate otherwise. + <literal>INTERSECT</literal> binds more tightly than + <literal>UNION</literal>. That is, <literal>A UNION B INTERSECT + C</literal> will be read as <literal>A UNION (B INTERSECT + C)</literal>. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and + <literal>FOR KEY SHARE</literal> cannot be + specified either for an <literal>INTERSECT</literal> result or for any input of + an <literal>INTERSECT</literal>. + </para> + </refsect2> + + <refsect2 id="sql-except" xreflabel="EXCEPT Clause"> + <title><literal>EXCEPT</literal> Clause</title> + + <para> + The <literal>EXCEPT</literal> clause has this general form: +<synopsis> +<replaceable class="parameter">select_statement</replaceable> EXCEPT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable> +</synopsis><replaceable class="parameter">select_statement</replaceable> is + any <command>SELECT</command> statement without an <literal>ORDER + BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, + <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause. + </para> + + <para> + The <literal>EXCEPT</literal> operator computes the set of rows + that are in the result of the left <command>SELECT</command> + statement but not in the result of the right one. + </para> + + <para> + The result of <literal>EXCEPT</literal> does not contain any + duplicate rows unless the <literal>ALL</literal> option is specified. + With <literal>ALL</literal>, a row that has <replaceable>m</replaceable> duplicates in the + left table and <replaceable>n</replaceable> duplicates in the right table will appear + max(<replaceable>m</replaceable>-<replaceable>n</replaceable>,0) times in the result set. + <literal>DISTINCT</literal> can be written to explicitly specify the + default behavior of eliminating duplicate rows. + </para> + + <para> + Multiple <literal>EXCEPT</literal> operators in the same + <command>SELECT</command> statement are evaluated left to right, + unless parentheses dictate otherwise. <literal>EXCEPT</literal> binds at + the same level as <literal>UNION</literal>. + </para> + + <para> + Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and + <literal>FOR KEY SHARE</literal> cannot be + specified either for an <literal>EXCEPT</literal> result or for any input of + an <literal>EXCEPT</literal>. + </para> + </refsect2> + + <refsect2 id="sql-orderby" xreflabel="ORDER BY Clause"> + <title><literal>ORDER BY</literal> Clause</title> + + <para> + The optional <literal>ORDER BY</literal> clause has this general form: +<synopsis> +ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] +</synopsis> + The <literal>ORDER BY</literal> clause causes the result rows to + be sorted according to the specified expression(s). If two rows are + equal according to the leftmost expression, they are compared + according to the next expression and so on. If they are equal + according to all specified expressions, they are returned in + an implementation-dependent order. + </para> + + <para> + Each <replaceable class="parameter">expression</replaceable> can be the + name or ordinal number of an output column + (<command>SELECT</command> list item), or it can be an arbitrary + expression formed from input-column values. + </para> + + <para> + The ordinal number refers to the ordinal (left-to-right) position + of the output column. This feature makes it possible to define an + ordering on the basis of a column that does not have a unique + name. This is never absolutely necessary because it is always + possible to assign a name to an output column using the + <literal>AS</literal> clause. + </para> + + <para> + It is also possible to use arbitrary expressions in the + <literal>ORDER BY</literal> clause, including columns that do not + appear in the <command>SELECT</command> output list. Thus the + following statement is valid: +<programlisting> +SELECT name FROM distributors ORDER BY code; +</programlisting> + A limitation of this feature is that an <literal>ORDER BY</literal> + clause applying to the result of a <literal>UNION</literal>, + <literal>INTERSECT</literal>, or <literal>EXCEPT</literal> clause can only + specify an output column name or number, not an expression. + </para> + + <para> + If an <literal>ORDER BY</literal> expression is a simple name that + matches both an output column name and an input column name, + <literal>ORDER BY</literal> will interpret it as the output column name. + This is the opposite of the choice that <literal>GROUP BY</literal> will + make in the same situation. This inconsistency is made to be + compatible with the SQL standard. + </para> + + <para> + Optionally one can add the key word <literal>ASC</literal> (ascending) or + <literal>DESC</literal> (descending) after any expression in the + <literal>ORDER BY</literal> clause. If not specified, <literal>ASC</literal> is + assumed by default. Alternatively, a specific ordering operator + name can be specified in the <literal>USING</literal> clause. + An ordering operator must be a less-than or greater-than + member of some B-tree operator family. + <literal>ASC</literal> is usually equivalent to <literal>USING <</literal> and + <literal>DESC</literal> is usually equivalent to <literal>USING ></literal>. + (But the creator of a user-defined data type can define exactly what the + default sort ordering is, and it might correspond to operators with other + names.) + </para> + + <para> + If <literal>NULLS LAST</literal> is specified, null values sort after all + non-null values; if <literal>NULLS FIRST</literal> is specified, null values + sort before all non-null values. If neither is specified, the default + behavior is <literal>NULLS LAST</literal> when <literal>ASC</literal> is specified + or implied, and <literal>NULLS FIRST</literal> when <literal>DESC</literal> is specified + (thus, the default is to act as though nulls are larger than non-nulls). + When <literal>USING</literal> is specified, the default nulls ordering depends + on whether the operator is a less-than or greater-than operator. + </para> + + <para> + Note that ordering options apply only to the expression they follow; + for example <literal>ORDER BY x, y DESC</literal> does not mean + the same thing as <literal>ORDER BY x DESC, y DESC</literal>. + </para> + + <para> + Character-string data is sorted according to the collation that applies + to the column being sorted. That can be overridden at need by including + a <literal>COLLATE</literal> clause in the + <replaceable class="parameter">expression</replaceable>, for example + <literal>ORDER BY mycolumn COLLATE "en_US"</literal>. + For more information see <xref linkend="sql-syntax-collate-exprs"/> and + <xref linkend="collation"/>. + </para> + </refsect2> + + <refsect2 id="sql-limit" xreflabel="LIMIT Clause"> + <title><literal>LIMIT</literal> Clause</title> + + <para> + The <literal>LIMIT</literal> clause consists of two independent + sub-clauses: +<synopsis> +LIMIT { <replaceable class="parameter">count</replaceable> | ALL } +OFFSET <replaceable class="parameter">start</replaceable> +</synopsis> + The parameter <replaceable class="parameter">count</replaceable> specifies the + maximum number of rows to return, while <replaceable + class="parameter">start</replaceable> specifies the number of rows + to skip before starting to return rows. When both are specified, + <replaceable class="parameter">start</replaceable> rows are skipped + before starting to count the <replaceable + class="parameter">count</replaceable> rows to be returned. + </para> + + <para> + If the <replaceable class="parameter">count</replaceable> expression + evaluates to NULL, it is treated as <literal>LIMIT ALL</literal>, i.e., no + limit. If <replaceable class="parameter">start</replaceable> evaluates + to NULL, it is treated the same as <literal>OFFSET 0</literal>. + </para> + + <para> + SQL:2008 introduced a different syntax to achieve the same result, + which <productname>PostgreSQL</productname> also supports. It is: +<synopsis> +OFFSET <replaceable class="parameter">start</replaceable> { ROW | ROWS } +FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } { ONLY | WITH TIES } +</synopsis> + In this syntax, the <replaceable class="parameter">start</replaceable> + or <replaceable class="parameter">count</replaceable> value is required by + the standard to be a literal constant, a parameter, or a variable name; + as a <productname>PostgreSQL</productname> extension, other expressions + are allowed, but will generally need to be enclosed in parentheses to avoid + ambiguity. + If <replaceable class="parameter">count</replaceable> is + omitted in a <literal>FETCH</literal> clause, it defaults to 1. + The <literal>WITH TIES</literal> option is used to return any additional + rows that tie for the last place in the result set according to + the <literal>ORDER BY</literal> clause; <literal>ORDER BY</literal> + is mandatory in this case, and <literal>SKIP LOCKED</literal> is + not allowed. + <literal>ROW</literal> and <literal>ROWS</literal> as well as + <literal>FIRST</literal> and <literal>NEXT</literal> are noise + words that don't influence the effects of these clauses. + According to the standard, the <literal>OFFSET</literal> clause must come + before the <literal>FETCH</literal> clause if both are present; but + <productname>PostgreSQL</productname> is laxer and allows either order. + </para> + + <para> + When using <literal>LIMIT</literal>, it is a good idea to use an + <literal>ORDER BY</literal> clause that constrains the result rows into a + unique order. Otherwise you will get an unpredictable subset of + the query's rows — you might be asking for the tenth through + twentieth rows, but tenth through twentieth in what ordering? You + don't know what ordering unless you specify <literal>ORDER BY</literal>. + </para> + + <para> + The query planner takes <literal>LIMIT</literal> into account when + generating a query plan, so you are very likely to get different + plans (yielding different row orders) depending on what you use + for <literal>LIMIT</literal> and <literal>OFFSET</literal>. Thus, using + different <literal>LIMIT</literal>/<literal>OFFSET</literal> values to select + different subsets of a query result <emphasis>will give + inconsistent results</emphasis> unless you enforce a predictable + result ordering with <literal>ORDER BY</literal>. This is not a bug; it + is an inherent consequence of the fact that SQL does not promise + to deliver the results of a query in any particular order unless + <literal>ORDER BY</literal> is used to constrain the order. + </para> + + <para> + It is even possible for repeated executions of the same <literal>LIMIT</literal> + query to return different subsets of the rows of a table, if there + is not an <literal>ORDER BY</literal> to enforce selection of a deterministic + subset. Again, this is not a bug; determinism of the results is + simply not guaranteed in such a case. + </para> + </refsect2> + + <refsect2 id="sql-for-update-share" xreflabel="The Locking Clause"> + <title>The Locking Clause</title> + + <para> + <literal>FOR UPDATE</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> + and <literal>FOR KEY SHARE</literal> + are <firstterm>locking clauses</firstterm>; they affect how <literal>SELECT</literal> + locks rows as they are obtained from the table. + </para> + + <para> + The locking clause has the general form + +<synopsis> +FOR <replaceable>lock_strength</replaceable> [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT | SKIP LOCKED ] +</synopsis> + + where <replaceable>lock_strength</replaceable> can be one of + +<synopsis> +UPDATE +NO KEY UPDATE +SHARE +KEY SHARE +</synopsis> + </para> + + <para> + For more information on each row-level lock mode, refer to + <xref linkend="locking-rows"/>. + </para> + + <para> + To prevent the operation from waiting for other transactions to commit, + use either the <literal>NOWAIT</literal> or <literal>SKIP LOCKED</literal> + option. With <literal>NOWAIT</literal>, the statement reports an error, rather + than waiting, if a selected row cannot be locked immediately. + With <literal>SKIP LOCKED</literal>, any selected rows that cannot be + immediately locked are skipped. Skipping locked rows provides an + inconsistent view of the data, so this is not suitable for general purpose + work, but can be used to avoid lock contention with multiple consumers + accessing a queue-like table. + Note that <literal>NOWAIT</literal> and <literal>SKIP LOCKED</literal> apply only + to the row-level lock(s) — the required <literal>ROW SHARE</literal> + table-level lock is still taken in the ordinary way (see + <xref linkend="mvcc"/>). You can use + <link linkend="sql-lock"><command>LOCK</command></link> + with the <literal>NOWAIT</literal> option first, + if you need to acquire the table-level lock without waiting. + </para> + + <para> + If specific tables are named in a locking clause, + then only rows coming from those tables are locked; any other + tables used in the <command>SELECT</command> are simply read as + usual. A locking + clause without a table list affects all tables used in the statement. + If a locking clause is + applied to a view or sub-query, it affects all tables used in + the view or sub-query. + However, these clauses + do not apply to <literal>WITH</literal> queries referenced by the primary query. + If you want row locking to occur within a <literal>WITH</literal> query, specify + a locking clause within the <literal>WITH</literal> query. + </para> + + <para> + Multiple locking + clauses can be written if it is necessary to specify different locking + behavior for different tables. If the same table is mentioned (or + implicitly affected) by more than one locking clause, + then it is processed as if it was only specified by the strongest one. + Similarly, a table is processed + as <literal>NOWAIT</literal> if that is specified in any of the clauses + affecting it. Otherwise, it is processed + as <literal>SKIP LOCKED</literal> if that is specified in any of the + clauses affecting it. + </para> + + <para> + The locking clauses cannot be + used in contexts where returned rows cannot be clearly identified with + individual table rows; for example they cannot be used with aggregation. + </para> + + <para> + When a locking clause + appears at the top level of a <command>SELECT</command> query, the rows that + are locked are exactly those that are returned by the query; in the + case of a join query, the rows locked are those that contribute to + returned join rows. In addition, rows that satisfied the query + conditions as of the query snapshot will be locked, although they + will not be returned if they were updated after the snapshot + and no longer satisfy the query conditions. If a + <literal>LIMIT</literal> is used, locking stops + once enough rows have been returned to satisfy the limit (but note that + rows skipped over by <literal>OFFSET</literal> will get locked). Similarly, + if a locking clause + is used in a cursor's query, only rows actually fetched or stepped past + by the cursor will be locked. + </para> + + <para> + When a locking clause + appears in a sub-<command>SELECT</command>, the rows locked are those + returned to the outer query by the sub-query. This might involve + fewer rows than inspection of the sub-query alone would suggest, + since conditions from the outer query might be used to optimize + execution of the sub-query. For example, +<programlisting> +SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5; +</programlisting> + will lock only rows having <literal>col1 = 5</literal>, even though that + condition is not textually within the sub-query. + </para> + + <para> + Previous releases failed to preserve a lock which is upgraded by a later + savepoint. For example, this code: +<programlisting> +BEGIN; +SELECT * FROM mytable WHERE key = 1 FOR UPDATE; +SAVEPOINT s; +UPDATE mytable SET ... WHERE key = 1; +ROLLBACK TO s; +</programlisting> + would fail to preserve the <literal>FOR UPDATE</literal> lock after the + <command>ROLLBACK TO</command>. This has been fixed in release 9.3. + </para> + + <caution> + <para> + It is possible for a <command>SELECT</command> command running at the <literal>READ + COMMITTED</literal> transaction isolation level and using <literal>ORDER + BY</literal> and a locking clause to return rows out of + order. This is because <literal>ORDER BY</literal> is applied first. + The command sorts the result, but might then block trying to obtain a lock + on one or more of the rows. Once the <literal>SELECT</literal> unblocks, some + of the ordering column values might have been modified, leading to those + rows appearing to be out of order (though they are in order in terms + of the original column values). This can be worked around at need by + placing the <literal>FOR UPDATE/SHARE</literal> clause in a sub-query, + for example +<programlisting> +SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1; +</programlisting> + Note that this will result in locking all rows of <structname>mytable</structname>, + whereas <literal>FOR UPDATE</literal> at the top level would lock only the + actually returned rows. This can make for a significant performance + difference, particularly if the <literal>ORDER BY</literal> is combined with + <literal>LIMIT</literal> or other restrictions. So this technique is recommended + only if concurrent updates of the ordering columns are expected and a + strictly sorted result is required. + </para> + + <para> + At the <literal>REPEATABLE READ</literal> or <literal>SERIALIZABLE</literal> + transaction isolation level this would cause a serialization failure (with + an <literal>SQLSTATE</literal> of <literal>'40001'</literal>), so there is + no possibility of receiving rows out of order under these isolation levels. + </para> + </caution> + </refsect2> + + <refsect2 id="sql-table"> + <title><literal>TABLE</literal> Command</title> + + <para> + The command +<programlisting> +TABLE <replaceable class="parameter">name</replaceable> +</programlisting> + is equivalent to +<programlisting> +SELECT * FROM <replaceable class="parameter">name</replaceable> +</programlisting> + It can be used as a top-level command or as a space-saving syntax + variant in parts of complex queries. Only the <literal>WITH</literal>, + <literal>UNION</literal>, <literal>INTERSECT</literal>, <literal>EXCEPT</literal>, + <literal>ORDER BY</literal>, <literal>LIMIT</literal>, <literal>OFFSET</literal>, + <literal>FETCH</literal> and <literal>FOR</literal> locking clauses can be used + with <command>TABLE</command>; the <literal>WHERE</literal> clause and any form of + aggregation cannot + be used. + </para> + </refsect2> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To join the table <literal>films</literal> with the table + <literal>distributors</literal>: + +<programlisting> +SELECT f.title, f.did, d.name, f.date_prod, f.kind + FROM distributors d JOIN films f USING (did); + + title | did | name | date_prod | kind +-------------------+-----+--------------+------------+---------- + The Third Man | 101 | British Lion | 1949-12-23 | Drama + The African Queen | 101 | British Lion | 1951-08-11 | Romantic + ... +</programlisting> + </para> + + <para> + To sum the column <literal>len</literal> of all films and group + the results by <literal>kind</literal>: + +<programlisting> +SELECT kind, sum(len) AS total FROM films GROUP BY kind; + + kind | total +----------+------- + Action | 07:34 + Comedy | 02:58 + Drama | 14:28 + Musical | 06:42 + Romantic | 04:38 +</programlisting> + </para> + + <para> + To sum the column <literal>len</literal> of all films, group + the results by <literal>kind</literal> and show those group totals + that are less than 5 hours: + +<programlisting> +SELECT kind, sum(len) AS total + FROM films + GROUP BY kind + HAVING sum(len) < interval '5 hours'; + + kind | total +----------+------- + Comedy | 02:58 + Romantic | 04:38 +</programlisting> + </para> + + <para> + The following two examples are identical ways of sorting the individual + results according to the contents of the second column + (<literal>name</literal>): + +<programlisting> +SELECT * FROM distributors ORDER BY name; +SELECT * FROM distributors ORDER BY 2; + + did | name +-----+------------------ + 109 | 20th Century Fox + 110 | Bavaria Atelier + 101 | British Lion + 107 | Columbia + 102 | Jean Luc Godard + 113 | Luso films + 104 | Mosfilm + 103 | Paramount + 106 | Toho + 105 | United Artists + 111 | Walt Disney + 112 | Warner Bros. + 108 | Westward +</programlisting> + </para> + + <para> + The next example shows how to obtain the union of the tables + <literal>distributors</literal> and + <literal>actors</literal>, restricting the results to those that begin + with the letter W in each table. Only distinct rows are wanted, so the + key word <literal>ALL</literal> is omitted. + +<programlisting> +distributors: actors: + did | name id | name +-----+-------------- ----+---------------- + 108 | Westward 1 | Woody Allen + 111 | Walt Disney 2 | Warren Beatty + 112 | Warner Bros. 3 | Walter Matthau + ... ... + +SELECT distributors.name + FROM distributors + WHERE distributors.name LIKE 'W%' +UNION +SELECT actors.name + FROM actors + WHERE actors.name LIKE 'W%'; + + name +---------------- + Walt Disney + Walter Matthau + Warner Bros. + Warren Beatty + Westward + Woody Allen +</programlisting> + </para> + + <para> + This example shows how to use a function in the <literal>FROM</literal> + clause, both with and without a column definition list: + +<programlisting> +CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$ + SELECT * FROM distributors WHERE did = $1; +$$ LANGUAGE SQL; + +SELECT * FROM distributors(111); + did | name +-----+------------- + 111 | Walt Disney + +CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$ + SELECT * FROM distributors WHERE did = $1; +$$ LANGUAGE SQL; + +SELECT * FROM distributors_2(111) AS (f1 int, f2 text); + f1 | f2 +-----+------------- + 111 | Walt Disney +</programlisting> + </para> + + <para> + Here is an example of a function with an ordinality column added: + +<programlisting> +SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY; + unnest | ordinality +--------+---------- + a | 1 + b | 2 + c | 3 + d | 4 + e | 5 + f | 6 +(6 rows) +</programlisting> + </para> + + <para> + This example shows how to use a simple <literal>WITH</literal> clause: + +<programlisting> +WITH t AS ( + SELECT random() as x FROM generate_series(1, 3) + ) +SELECT * FROM t +UNION ALL +SELECT * FROM t + + x +-------------------- + 0.534150459803641 + 0.520092216785997 + 0.0735620250925422 + 0.534150459803641 + 0.520092216785997 + 0.0735620250925422 +</programlisting> + + Notice that the <literal>WITH</literal> query was evaluated only once, + so that we got two sets of the same three random values. + </para> + + <para> + This example uses <literal>WITH RECURSIVE</literal> to find all + subordinates (direct or indirect) of the employee Mary, and their + level of indirectness, from a table that shows only direct + subordinates: + +<programlisting> +WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS ( + SELECT 1, employee_name, manager_name + FROM employee + WHERE manager_name = 'Mary' + UNION ALL + SELECT er.distance + 1, e.employee_name, e.manager_name + FROM employee_recursive er, employee e + WHERE er.employee_name = e.manager_name + ) +SELECT distance, employee_name FROM employee_recursive; +</programlisting> + + Notice the typical form of recursive queries: + an initial condition, followed by <literal>UNION</literal>, + followed by the recursive part of the query. Be sure that the + recursive part of the query will eventually return no tuples, or + else the query will loop indefinitely. (See <xref linkend="queries-with"/> + for more examples.) + </para> + + <para> + This example uses <literal>LATERAL</literal> to apply a set-returning function + <function>get_product_names()</function> for each row of the + <structname>manufacturers</structname> table: + +<programlisting> +SELECT m.name AS mname, pname +FROM manufacturers m, LATERAL get_product_names(m.id) pname; +</programlisting> + + Manufacturers not currently having any products would not appear in the + result, since it is an inner join. If we wished to include the names of + such manufacturers in the result, we could do: + +<programlisting> +SELECT m.name AS mname, pname +FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + Of course, the <command>SELECT</command> statement is compatible + with the SQL standard. But there are some extensions and some + missing features. + </para> + + <refsect2> + <title>Omitted <literal>FROM</literal> Clauses</title> + + <para> + <productname>PostgreSQL</productname> allows one to omit the + <literal>FROM</literal> clause. It has a straightforward use to + compute the results of simple expressions: +<programlisting> +SELECT 2+2; + + ?column? +---------- + 4 +</programlisting> + Some other <acronym>SQL</acronym> databases cannot do this except + by introducing a dummy one-row table from which to do the + <command>SELECT</command>. + </para> + </refsect2> + + <refsect2> + <title>Empty <literal>SELECT</literal> Lists</title> + + <para> + The list of output expressions after <literal>SELECT</literal> can be + empty, producing a zero-column result table. + This is not valid syntax according to the SQL standard. + <productname>PostgreSQL</productname> allows it to be consistent with + allowing zero-column tables. + However, an empty list is not allowed when <literal>DISTINCT</literal> is used. + </para> + </refsect2> + + <refsect2> + <title>Omitting the <literal>AS</literal> Key Word</title> + + <para> + In the SQL standard, the optional key word <literal>AS</literal> can be + omitted before an output column name whenever the new column name + is a valid column name (that is, not the same as any reserved + keyword). <productname>PostgreSQL</productname> is slightly more + restrictive: <literal>AS</literal> is required if the new column name + matches any keyword at all, reserved or not. Recommended practice is + to use <literal>AS</literal> or double-quote output column names, to prevent + any possible conflict against future keyword additions. + </para> + + <para> + In <literal>FROM</literal> items, both the standard and + <productname>PostgreSQL</productname> allow <literal>AS</literal> to + be omitted before an alias that is an unreserved keyword. But + this is impractical for output column names, because of syntactic + ambiguities. + </para> + </refsect2> + + <refsect2> + <title><literal>ONLY</literal> and Inheritance</title> + + <para> + The SQL standard requires parentheses around the table name when + writing <literal>ONLY</literal>, for example <literal>SELECT * FROM ONLY + (tab1), ONLY (tab2) WHERE ...</literal>. <productname>PostgreSQL</productname> + considers these parentheses to be optional. + </para> + + <para> + <productname>PostgreSQL</productname> allows a trailing <literal>*</literal> to be written to + explicitly specify the non-<literal>ONLY</literal> behavior of including + child tables. The standard does not allow this. + </para> + + <para> + (These points apply equally to all SQL commands supporting the + <literal>ONLY</literal> option.) + </para> + </refsect2> + + <refsect2> + <title><literal>TABLESAMPLE</literal> Clause Restrictions</title> + + <para> + The <literal>TABLESAMPLE</literal> clause is currently accepted only on + regular tables and materialized views. According to the SQL standard + it should be possible to apply it to any <literal>FROM</literal> item. + </para> + </refsect2> + + <refsect2> + <title>Function Calls in <literal>FROM</literal></title> + + <para> + <productname>PostgreSQL</productname> allows a function call to be + written directly as a member of the <literal>FROM</literal> list. In the SQL + standard it would be necessary to wrap such a function call in a + sub-<command>SELECT</command>; that is, the syntax + <literal>FROM <replaceable>func</replaceable>(...) <replaceable>alias</replaceable></literal> + is approximately equivalent to + <literal>FROM LATERAL (SELECT <replaceable>func</replaceable>(...)) <replaceable>alias</replaceable></literal>. + Note that <literal>LATERAL</literal> is considered to be implicit; this is + because the standard requires <literal>LATERAL</literal> semantics for an + <literal>UNNEST()</literal> item in <literal>FROM</literal>. + <productname>PostgreSQL</productname> treats <literal>UNNEST()</literal> the + same as other set-returning functions. + </para> + </refsect2> + + <refsect2> + <title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title> + + <para> + In the SQL-92 standard, an <literal>ORDER BY</literal> clause can + only use output column names or numbers, while a <literal>GROUP + BY</literal> clause can only use expressions based on input column + names. <productname>PostgreSQL</productname> extends each of + these clauses to allow the other choice as well (but it uses the + standard's interpretation if there is ambiguity). + <productname>PostgreSQL</productname> also allows both clauses to + specify arbitrary expressions. Note that names appearing in an + expression will always be taken as input-column names, not as + output-column names. + </para> + + <para> + SQL:1999 and later use a slightly different definition which is not + entirely upward compatible with SQL-92. + In most cases, however, <productname>PostgreSQL</productname> + will interpret an <literal>ORDER BY</literal> or <literal>GROUP + BY</literal> expression the same way SQL:1999 does. + </para> + </refsect2> + + <refsect2> + <title>Functional Dependencies</title> + + <para> + <productname>PostgreSQL</productname> recognizes functional dependency + (allowing columns to be omitted from <literal>GROUP BY</literal>) only when + a table's primary key is included in the <literal>GROUP BY</literal> list. + The SQL standard specifies additional conditions that should be + recognized. + </para> + </refsect2> + + <refsect2> + <title><literal>LIMIT</literal> and <literal>OFFSET</literal></title> + + <para> + The clauses <literal>LIMIT</literal> and <literal>OFFSET</literal> + are <productname>PostgreSQL</productname>-specific syntax, also + used by <productname>MySQL</productname>. The SQL:2008 standard + has introduced the clauses <literal>OFFSET ... FETCH {FIRST|NEXT} + ...</literal> for the same functionality, as shown above + in <xref linkend="sql-limit"/>. This + syntax is also used by <productname>IBM DB2</productname>. + (Applications written for <productname>Oracle</productname> + frequently use a workaround involving the automatically + generated <literal>rownum</literal> column, which is not available in + PostgreSQL, to implement the effects of these clauses.) + </para> + </refsect2> + + <refsect2> + <title><literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal>, <literal>FOR KEY SHARE</literal></title> + + <para> + Although <literal>FOR UPDATE</literal> appears in the SQL standard, the + standard allows it only as an option of <command>DECLARE CURSOR</command>. + <productname>PostgreSQL</productname> allows it in any <command>SELECT</command> + query as well as in sub-<command>SELECT</command>s, but this is an extension. + The <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> and + <literal>FOR KEY SHARE</literal> variants, as well as the <literal>NOWAIT</literal> + and <literal>SKIP LOCKED</literal> options, do not appear in the + standard. + </para> + </refsect2> + + <refsect2> + <title>Data-Modifying Statements in <literal>WITH</literal></title> + + <para> + <productname>PostgreSQL</productname> allows <command>INSERT</command>, + <command>UPDATE</command>, and <command>DELETE</command> to be used as <literal>WITH</literal> + queries. This is not found in the SQL standard. + </para> + </refsect2> + + <refsect2> + <title>Nonstandard Clauses</title> + + <para> + <literal>DISTINCT ON ( ... )</literal> is an extension of the + SQL standard. + </para> + + <para> + <literal>ROWS FROM( ... )</literal> is an extension of the SQL standard. + </para> + + <para> + The <literal>MATERIALIZED</literal> and <literal>NOT + MATERIALIZED</literal> options of <literal>WITH</literal> are extensions + of the SQL standard. + </para> + </refsect2> + + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/select_into.sgml b/doc/src/sgml/ref/select_into.sgml new file mode 100644 index 0000000..82a7778 --- /dev/null +++ b/doc/src/sgml/ref/select_into.sgml @@ -0,0 +1,156 @@ +<!-- +doc/src/sgml/ref/select_into.sgml +PostgreSQL documentation +--> + +<refentry id="sql-selectinto"> + <indexterm zone="sql-selectinto"> + <primary>SELECT INTO</primary> + </indexterm> + + <refmeta> + <refentrytitle>SELECT INTO</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SELECT INTO</refname> + <refpurpose>define a new table from the results of a query</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ] +SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replaceable> [, ...] ) ] ] + * | <replaceable class="parameter">expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] + INTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] <replaceable class="parameter">new_table</replaceable> + [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ] + [ WHERE <replaceable class="parameter">condition</replaceable> ] + [ GROUP BY <replaceable class="parameter">expression</replaceable> [, ...] ] + [ HAVING <replaceable class="parameter">condition</replaceable> ] + [ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ] + [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ] + [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ] + [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ] + [ OFFSET <replaceable class="parameter">start</replaceable> [ ROW | ROWS ] ] + [ FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } ONLY ] + [ FOR { UPDATE | SHARE } [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ] [...] ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SELECT INTO</command> creates a new table and fills it + with data computed by a query. The data is not returned to the + client, as it is with a normal <command>SELECT</command>. The new + table's columns have the names and data types associated with the + output columns of the <command>SELECT</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>TEMPORARY</literal> or <literal>TEMP</literal></term> + <listitem> + <para> + If specified, the table is created as a temporary table. Refer + to <xref linkend="sql-createtable"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>UNLOGGED</literal></term> + <listitem> + <para> + If specified, the table is created as an unlogged table. Refer + to <xref linkend="sql-createtable"/> for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">new_table</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to be created. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + All other parameters are described in detail under <xref + linkend="sql-select"/>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <link linkend="sql-createtableas"><command>CREATE TABLE AS</command></link> is functionally similar to + <command>SELECT INTO</command>. <command>CREATE TABLE AS</command> + is the recommended syntax, since this form of <command>SELECT + INTO</command> is not available in <application>ECPG</application> + or <application>PL/pgSQL</application>, because they interpret the + <literal>INTO</literal> clause differently. Furthermore, + <command>CREATE TABLE AS</command> offers a superset of the + functionality provided by <command>SELECT INTO</command>. + </para> + + <para> + In contrast to <command>CREATE TABLE AS</command>, <command>SELECT + INTO</command> does not allow specifying properties like a table's access + method with <xref linkend="sql-createtable-method" /> or the table's + tablespace with <xref linkend="sql-createtable-tablespace" />. Use + <command>CREATE TABLE AS</command> if necessary. Therefore, the default table + access method is chosen for the new table. See <xref + linkend="guc-default-table-access-method"/> for more information. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Create a new table <literal>films_recent</literal> consisting of only + recent entries from the table <literal>films</literal>: + +<programlisting> +SELECT * INTO films_recent FROM films WHERE date_prod >= '2002-01-01'; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard uses <command>SELECT INTO</command> to + represent selecting values into scalar variables of a host program, + rather than creating a new table. This indeed is the usage found + in <application>ECPG</application> (see <xref linkend="ecpg"/>) and + <application>PL/pgSQL</application> (see <xref linkend="plpgsql"/>). + The <productname>PostgreSQL</productname> usage of <command>SELECT + INTO</command> to represent table creation is historical. Some other SQL + implementations also use <command>SELECT INTO</command> in this way (but + most SQL implementations support <command>CREATE TABLE AS</command> + instead). Apart from such compatibility considerations, it is best to use + <command>CREATE TABLE AS</command> for this purpose in new code. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-createtableas"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/set.sgml b/doc/src/sgml/ref/set.sgml new file mode 100644 index 0000000..5459b29 --- /dev/null +++ b/doc/src/sgml/ref/set.sgml @@ -0,0 +1,332 @@ +<!-- +doc/src/sgml/ref/set.sgml +PostgreSQL documentation +--> + +<refentry id="sql-set"> + <indexterm zone="sql-set"> + <primary>SET</primary> + </indexterm> + + <refmeta> + <refentrytitle>SET</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SET</refname> + <refpurpose>change a run-time parameter</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SET [ SESSION | LOCAL ] <replaceable class="parameter">configuration_parameter</replaceable> { TO | = } { <replaceable class="parameter">value</replaceable> | '<replaceable class="parameter">value</replaceable>' | DEFAULT } +SET [ SESSION | LOCAL ] TIME ZONE { <replaceable class="parameter">value</replaceable> | '<replaceable class="parameter">value</replaceable>' | LOCAL | DEFAULT } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + The <command>SET</command> command changes run-time configuration + parameters. Many of the run-time parameters listed in + <xref linkend="runtime-config"/> can be changed on-the-fly with + <command>SET</command>. + (Some parameters can only be changed by superusers and users who + have been granted <literal>SET</literal> privilege on that parameter. + There are also parameters that cannot be changed after server or + session start.) + <command>SET</command> only affects the value used by the current + session. + </para> + + <para> + If <command>SET</command> (or equivalently <command>SET SESSION</command>) + is issued within a transaction that is later aborted, the effects of the + <command>SET</command> command disappear when the transaction is rolled + back. Once the surrounding transaction is committed, the effects + will persist until the end of the session, unless overridden by another + <command>SET</command>. + </para> + + <para> + The effects of <command>SET LOCAL</command> last only till the end of + the current transaction, whether committed or not. A special case is + <command>SET</command> followed by <command>SET LOCAL</command> within + a single transaction: the <command>SET LOCAL</command> value will be + seen until the end of the transaction, but afterwards (if the transaction + is committed) the <command>SET</command> value will take effect. + </para> + + <para> + The effects of <command>SET</command> or <command>SET LOCAL</command> are + also canceled by rolling back to a savepoint that is earlier than the + command. + </para> + + <para> + If <command>SET LOCAL</command> is used within a function that has a + <literal>SET</literal> option for the same variable (see + <xref linkend="sql-createfunction"/>), + the effects of the <command>SET LOCAL</command> command disappear at + function exit; that is, the value in effect when the function was called is + restored anyway. This allows <command>SET LOCAL</command> to be used for + dynamic or repeated changes of a parameter within a function, while still + having the convenience of using the <literal>SET</literal> option to save and + restore the caller's value. However, a regular <command>SET</command> command + overrides any surrounding function's <literal>SET</literal> option; its effects + will persist unless rolled back. + </para> + + <note> + <para> + In <productname>PostgreSQL</productname> versions 8.0 through 8.2, + the effects of a <command>SET LOCAL</command> would be canceled by + releasing an earlier savepoint, or by successful exit from a + <application>PL/pgSQL</application> exception block. This behavior + has been changed because it was deemed unintuitive. + </para> + </note> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>SESSION</literal></term> + <listitem> + <para> + Specifies that the command takes effect for the current session. + (This is the default if neither <literal>SESSION</literal> nor + <literal>LOCAL</literal> appears.) + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LOCAL</literal></term> + <listitem> + <para> + Specifies that the command takes effect for only the current + transaction. After <command>COMMIT</command> or <command>ROLLBACK</command>, + the session-level setting takes effect again. Issuing this + outside of a transaction block emits a warning and otherwise has + no effect. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">configuration_parameter</replaceable></term> + <listitem> + <para> + Name of a settable run-time parameter. Available parameters are + documented in <xref linkend="runtime-config"/> and below. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">value</replaceable></term> + <listitem> + <para> + New value of parameter. Values can be specified as string + constants, identifiers, numbers, or comma-separated lists of + these, as appropriate for the particular parameter. + <literal>DEFAULT</literal> can be written to specify + resetting the parameter to its default value (that is, whatever + value it would have had if no <command>SET</command> had been executed + in the current session). + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + Besides the configuration parameters documented in <xref + linkend="runtime-config"/>, there are a few that can only be + adjusted using the <command>SET</command> command or that have a + special syntax: + + <variablelist> + <varlistentry> + <term><literal>SCHEMA</literal></term> + <listitem> + <para><literal>SET SCHEMA '<replaceable>value</replaceable>'</literal> is an alias for + <literal>SET search_path TO <replaceable>value</replaceable></literal>. Only one + schema can be specified using this syntax. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>NAMES</literal></term> + <listitem> + <para><literal>SET NAMES <replaceable>value</replaceable></literal> is an alias for + <literal>SET client_encoding TO <replaceable>value</replaceable></literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SEED</literal></term> + <listitem> + <para> + Sets the internal seed for the random number generator (the + function <function>random</function>). Allowed values are + floating-point numbers between -1 and 1 inclusive. + </para> + + <para> + The seed can also be set by invoking the function + <function>setseed</function>: +<programlisting> +SELECT setseed(<replaceable>value</replaceable>); +</programlisting></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TIME ZONE</literal></term> + <listitem> + <para><literal>SET TIME ZONE '<replaceable>value</replaceable>'</literal> is an alias + for <literal>SET timezone TO '<replaceable>value</replaceable>'</literal>. The + syntax <literal>SET TIME ZONE</literal> allows special syntax + for the time zone specification. Here are examples of valid + values: + + <variablelist> + <varlistentry> + <term><literal>'PST8PDT'</literal></term> + <listitem> + <para> + The time zone for Berkeley, California. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>'Europe/Rome'</literal></term> + <listitem> + <para> + The time zone for Italy. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>-7</literal></term> + <listitem> + <para> + The time zone 7 hours west from UTC (equivalent + to PDT). Positive values are east from UTC. + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>INTERVAL '-08:00' HOUR TO MINUTE</literal></term> + <listitem> + <para> + The time zone 8 hours west from UTC (equivalent + to PST). + </para> + </listitem> + </varlistentry> + <varlistentry> + <term><literal>LOCAL</literal></term> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + Set the time zone to your local time zone (that is, the + server's default value of <varname>timezone</varname>). + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + Timezone settings given as numbers or intervals are internally + translated to POSIX timezone syntax. For example, after + <literal>SET TIME ZONE -7</literal>, <command>SHOW TIME ZONE</command> would + report <literal><-07>+07</literal>. + </para> + + <para> + Time zone abbreviations are not supported by <command>SET</command>; + see <xref linkend="datatype-timezones"/> for more information + about time zones. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The function <function>set_config</function> provides equivalent + functionality; see <xref linkend="functions-admin-set"/>. + Also, it is possible to UPDATE the + <link linkend="view-pg-settings"><structname>pg_settings</structname></link> + system view to perform the equivalent of <command>SET</command>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Set the schema search path: +<programlisting> +SET search_path TO my_schema, public; +</programlisting> + </para> + + <para> + Set the style of date to traditional + <productname>POSTGRES</productname> with <quote>day before month</quote> + input convention: +<screen> +SET datestyle TO postgres, dmy; +</screen> + </para> + + <para> + Set the time zone for Berkeley, California: +<screen> +SET TIME ZONE 'PST8PDT'; +</screen> + </para> + + <para> + Set the time zone for Italy: +<screen> +SET TIME ZONE 'Europe/Rome'; +</screen></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <literal>SET TIME ZONE</literal> extends syntax defined in the SQL + standard. The standard allows only numeric time zone offsets while + <productname>PostgreSQL</productname> allows more flexible + time-zone specifications. All other <literal>SET</literal> + features are <productname>PostgreSQL</productname> extensions. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-reset"/></member> + <member><xref linkend="sql-show"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/set_constraints.sgml b/doc/src/sgml/ref/set_constraints.sgml new file mode 100644 index 0000000..d91965a --- /dev/null +++ b/doc/src/sgml/ref/set_constraints.sgml @@ -0,0 +1,125 @@ +<!-- +doc/src/sgml/ref/set_constraints.sgml +PostgreSQL documentation +--> + +<refentry id="sql-set-constraints"> + <indexterm zone="sql-set-constraints"> + <primary>SET CONSTRAINTS</primary> + </indexterm> + + <refmeta> + <refentrytitle>SET CONSTRAINTS</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SET CONSTRAINTS</refname> + <refpurpose>set constraint check timing for the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SET CONSTRAINTS { ALL | <replaceable class="parameter">name</replaceable> [, ...] } { DEFERRED | IMMEDIATE } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SET CONSTRAINTS</command> sets the behavior of constraint + checking within the current transaction. <literal>IMMEDIATE</literal> + constraints are checked at the end of each + statement. <literal>DEFERRED</literal> constraints are not checked until + transaction commit. Each constraint has its own + <literal>IMMEDIATE</literal> or <literal>DEFERRED</literal> mode. + </para> + + <para> + Upon creation, a constraint is given one of three + characteristics: <literal>DEFERRABLE INITIALLY DEFERRED</literal>, + <literal>DEFERRABLE INITIALLY IMMEDIATE</literal>, or + <literal>NOT DEFERRABLE</literal>. The third + class is always <literal>IMMEDIATE</literal> and is not affected by the + <command>SET CONSTRAINTS</command> command. The first two classes start + every transaction in the indicated mode, but their behavior can be changed + within a transaction by <command>SET CONSTRAINTS</command>. + </para> + + <para> + <command>SET CONSTRAINTS</command> with a list of constraint names changes + the mode of just those constraints (which must all be deferrable). Each + constraint name can be schema-qualified. The + current schema search path is used to find the first matching name if + no schema name is specified. <command>SET CONSTRAINTS ALL</command> + changes the mode of all deferrable constraints. + </para> + + <para> + When <command>SET CONSTRAINTS</command> changes the mode of a constraint + from <literal>DEFERRED</literal> + to <literal>IMMEDIATE</literal>, the new mode takes effect + retroactively: any outstanding data modifications that would have + been checked at the end of the transaction are instead checked during the + execution of the <command>SET CONSTRAINTS</command> command. + If any such constraint is violated, the <command>SET CONSTRAINTS</command> + fails (and does not change the constraint mode). Thus, <command>SET + CONSTRAINTS</command> can be used to force checking of constraints to + occur at a specific point in a transaction. + </para> + + <para> + Currently, only <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, + <literal>REFERENCES</literal> (foreign key), and <literal>EXCLUDE</literal> + constraints are affected by this setting. + <literal>NOT NULL</literal> and <literal>CHECK</literal> constraints are + always checked immediately when a row is inserted or modified + (<emphasis>not</emphasis> at the end of the statement). + Uniqueness and exclusion constraints that have not been declared + <literal>DEFERRABLE</literal> are also checked immediately. + </para> + + <para> + The firing of triggers that are declared as <quote>constraint triggers</quote> + is also controlled by this setting — they fire at the same time + that the associated constraint should be checked. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Because <productname>PostgreSQL</productname> does not require constraint + names to be unique within a schema (but only per-table), it is possible + that there is more than one match for a specified constraint name. + In this case <command>SET CONSTRAINTS</command> will act on all matches. + For a non-schema-qualified name, once a match or matches have been found in + some schema in the search path, schemas appearing later in the path are not + searched. + </para> + + <para> + This command only alters the behavior of constraints within the + current transaction. Issuing this outside of a transaction block + emits a warning and otherwise has no effect. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command complies with the behavior defined in the SQL + standard, except for the limitation that, in + <productname>PostgreSQL</productname>, it does not apply to + <literal>NOT NULL</literal> and <literal>CHECK</literal> constraints. + Also, <productname>PostgreSQL</productname> checks non-deferrable + uniqueness constraints immediately, not at end of statement as the + standard would suggest. + </para> + + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/set_role.sgml b/doc/src/sgml/ref/set_role.sgml new file mode 100644 index 0000000..4e02322 --- /dev/null +++ b/doc/src/sgml/ref/set_role.sgml @@ -0,0 +1,155 @@ +<!-- +doc/src/sgml/ref/set_role.sgml +PostgreSQL documentation +--> + +<refentry id="sql-set-role"> + <indexterm zone="sql-set-role"> + <primary>SET ROLE</primary> + </indexterm> + + <refmeta> + <refentrytitle>SET ROLE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SET ROLE</refname> + <refpurpose>set the current user identifier of the current session</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SET [ SESSION | LOCAL ] ROLE <replaceable class="parameter">role_name</replaceable> +SET [ SESSION | LOCAL ] ROLE NONE +RESET ROLE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + This command sets the current user + identifier of the current SQL session to be <replaceable + class="parameter">role_name</replaceable>. The role name can be + written as either an identifier or a string literal. + After <command>SET ROLE</command>, permissions checking for SQL commands + is carried out as though the named role were the one that had logged + in originally. + </para> + + <para> + The specified <replaceable class="parameter">role_name</replaceable> + must be a role that the current session user is a member of. + (If the session user is a superuser, any role can be selected.) + </para> + + <para> + The <literal>SESSION</literal> and <literal>LOCAL</literal> modifiers act the same + as for the regular <link linkend="sql-set"><command>SET</command></link> + command. + </para> + + <para> + <literal>SET ROLE NONE</literal> sets the current user identifier to the + current session user identifier, as returned by + <function>session_user</function>. <literal>RESET ROLE</literal> sets the + current user identifier to the connection-time setting specified by the + <link linkend="libpq-connect-options">command-line options</link>, + <link linkend="sql-alterrole"><command>ALTER ROLE</command></link>, or + <link linkend="sql-alterdatabase"><command>ALTER DATABASE</command></link>, + if any such settings exist. Otherwise, <literal>RESET ROLE</literal> sets + the current user identifier to the current session user identifier. These + forms can be executed by any user. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + Using this command, it is possible to either add privileges or restrict + one's privileges. If the session user role has the <literal>INHERIT</literal> + attribute, then it automatically has all the privileges of every role that + it could <command>SET ROLE</command> to; in this case <command>SET ROLE</command> + effectively drops all the privileges assigned directly to the session user + and to the other roles it is a member of, leaving only the privileges + available to the named role. On the other hand, if the session user role + has the <literal>NOINHERIT</literal> attribute, <command>SET ROLE</command> drops the + privileges assigned directly to the session user and instead acquires the + privileges available to the named role. + </para> + + <para> + In particular, when a superuser chooses to <command>SET ROLE</command> to a + non-superuser role, they lose their superuser privileges. + </para> + + <para> + <command>SET ROLE</command> has effects comparable to + <link linkend="sql-set-session-authorization"><command>SET SESSION AUTHORIZATION</command></link>, but the privilege + checks involved are quite different. Also, + <command>SET SESSION AUTHORIZATION</command> determines which roles are + allowable for later <command>SET ROLE</command> commands, whereas changing + roles with <command>SET ROLE</command> does not change the set of roles + allowed to a later <command>SET ROLE</command>. + </para> + + <para> + <command>SET ROLE</command> does not process session variables as specified by + the role's <link linkend="sql-alterrole"><command>ALTER ROLE</command></link> settings; this only happens during + login. + </para> + + <para> + <command>SET ROLE</command> cannot be used within a + <literal>SECURITY DEFINER</literal> function. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + +<programlisting> +SELECT SESSION_USER, CURRENT_USER; + + session_user | current_user +--------------+-------------- + peter | peter + +SET ROLE 'paul'; + +SELECT SESSION_USER, CURRENT_USER; + + session_user | current_user +--------------+-------------- + peter | paul +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + <productname>PostgreSQL</productname> + allows identifier syntax (<literal>"<replaceable>rolename</replaceable>"</literal>), while + the SQL standard requires the role name to be written as a string + literal. SQL does not allow this command during a transaction; + <productname>PostgreSQL</productname> does not make this + restriction because there is no reason to. + The <literal>SESSION</literal> and <literal>LOCAL</literal> modifiers are a + <productname>PostgreSQL</productname> extension, as is the + <literal>RESET</literal> syntax. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set-session-authorization"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/set_session_auth.sgml b/doc/src/sgml/ref/set_session_auth.sgml new file mode 100644 index 0000000..f8fcafc --- /dev/null +++ b/doc/src/sgml/ref/set_session_auth.sgml @@ -0,0 +1,130 @@ +<!-- +doc/src/sgml/ref/set_session_auth.sgml +PostgreSQL documentation +--> + +<refentry id="sql-set-session-authorization"> + <indexterm zone="sql-set-session-authorization"> + <primary>SET SESSION AUTHORIZATION</primary> + </indexterm> + + <refmeta> + <refentrytitle>SET SESSION AUTHORIZATION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SET SESSION AUTHORIZATION</refname> + <refpurpose>set the session user identifier and the current user identifier of the current session</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SET [ SESSION | LOCAL ] SESSION AUTHORIZATION <replaceable class="parameter">user_name</replaceable> +SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT +RESET SESSION AUTHORIZATION +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + This command sets the session user identifier and the current user + identifier of the current SQL session to be <replaceable + class="parameter">user_name</replaceable>. The user name can be + written as either an identifier or a string literal. Using this + command, it is possible, for example, to temporarily become an + unprivileged user and later switch back to being a superuser. + </para> + + <para> + The session user identifier is initially set to be the (possibly + authenticated) user name provided by the client. The current user + identifier is normally equal to the session user identifier, but + might change temporarily in the context of <literal>SECURITY DEFINER</literal> + functions and similar mechanisms; it can also be changed by + <link linkend="sql-set-role"><command>SET ROLE</command></link>. + The current user identifier is relevant for permission checking. + </para> + + <para> + The session user identifier can be changed only if the initial session + user (the <firstterm>authenticated user</firstterm>) had the + superuser privilege. Otherwise, the command is accepted only if it + specifies the authenticated user name. + </para> + + <para> + The <literal>SESSION</literal> and <literal>LOCAL</literal> modifiers act the same + as for the regular <link linkend="sql-set"><command>SET</command></link> + command. + </para> + + <para> + The <literal>DEFAULT</literal> and <literal>RESET</literal> forms reset the session + and current user identifiers to be the originally authenticated user + name. These forms can be executed by any user. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>SET SESSION AUTHORIZATION</command> cannot be used within a + <literal>SECURITY DEFINER</literal> function. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + +<programlisting> +SELECT SESSION_USER, CURRENT_USER; + + session_user | current_user +--------------+-------------- + peter | peter + +SET SESSION AUTHORIZATION 'paul'; + +SELECT SESSION_USER, CURRENT_USER; + + session_user | current_user +--------------+-------------- + paul | paul +</programlisting> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL standard allows some other expressions to appear in place + of the literal <replaceable>user_name</replaceable>, but these options + are not important in practice. <productname>PostgreSQL</productname> + allows identifier syntax (<literal>"<replaceable>username</replaceable>"</literal>), which SQL + does not. SQL does not allow this command during a transaction; + <productname>PostgreSQL</productname> does not make this + restriction because there is no reason to. + The <literal>SESSION</literal> and <literal>LOCAL</literal> modifiers are a + <productname>PostgreSQL</productname> extension, as is the + <literal>RESET</literal> syntax. + </para> + + <para> + The privileges necessary to execute this command are left + implementation-defined by the standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set-role"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/set_transaction.sgml b/doc/src/sgml/ref/set_transaction.sgml new file mode 100644 index 0000000..727a927 --- /dev/null +++ b/doc/src/sgml/ref/set_transaction.sgml @@ -0,0 +1,290 @@ +<!-- +doc/src/sgml/ref/set_transaction.sgml +PostgreSQL documentation +--> + +<refentry id="sql-set-transaction"> + <indexterm zone="sql-set-transaction"> + <primary>SET TRANSACTION</primary> + </indexterm> + + <indexterm> + <primary>transaction isolation level</primary> + <secondary>setting</secondary> + </indexterm> + + <indexterm> + <primary>read-only transaction</primary> + <secondary>setting</secondary> + </indexterm> + + <indexterm> + <primary>deferrable transaction</primary> + <secondary>setting</secondary> + </indexterm> + + <refmeta> + <refentrytitle>SET TRANSACTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SET TRANSACTION</refname> + <refpurpose>set the characteristics of the current transaction</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SET TRANSACTION <replaceable class="parameter">transaction_mode</replaceable> [, ...] +SET TRANSACTION SNAPSHOT <replaceable class="parameter">snapshot_id</replaceable> +SET SESSION CHARACTERISTICS AS TRANSACTION <replaceable class="parameter">transaction_mode</replaceable> [, ...] + +<phrase>where <replaceable class="parameter">transaction_mode</replaceable> is one of:</phrase> + + ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED } + READ WRITE | READ ONLY + [ NOT ] DEFERRABLE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + The <command>SET TRANSACTION</command> command sets the + characteristics of the current transaction. It has no effect on any + subsequent transactions. <command>SET SESSION + CHARACTERISTICS</command> sets the default transaction + characteristics for subsequent transactions of a session. These + defaults can be overridden by <command>SET TRANSACTION</command> + for an individual transaction. + </para> + + <para> + The available transaction characteristics are the transaction + isolation level, the transaction access mode (read/write or + read-only), and the deferrable mode. + In addition, a snapshot can be selected, though only for the current + transaction, not as a session default. + </para> + + <para> + The isolation level of a transaction determines what data the + transaction can see when other transactions are running concurrently: + + <variablelist> + <varlistentry> + <term><literal>READ COMMITTED</literal></term> + <listitem> + <para> + A statement can only see rows committed before it began. This + is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>REPEATABLE READ</literal></term> + <listitem> + <para> + All statements of the current transaction can only see rows committed + before the first query or data-modification statement was executed in + this transaction. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SERIALIZABLE</literal></term> + <listitem> + <para> + All statements of the current transaction can only see rows committed + before the first query or data-modification statement was executed in + this transaction. If a pattern of reads and writes among concurrent + serializable transactions would create a situation which could not + have occurred for any serial (one-at-a-time) execution of those + transactions, one of them will be rolled back with a + <literal>serialization_failure</literal> error. + </para> + </listitem> + </varlistentry> + </variablelist> + + The SQL standard defines one additional level, <literal>READ + UNCOMMITTED</literal>. + In <productname>PostgreSQL</productname> <literal>READ + UNCOMMITTED</literal> is treated as <literal>READ COMMITTED</literal>. + </para> + + <para> + The transaction isolation level cannot be changed after the first query or + data-modification statement (<command>SELECT</command>, + <command>INSERT</command>, <command>DELETE</command>, + <command>UPDATE</command>, <command>MERGE</command>, + <command>FETCH</command>, or + <command>COPY</command>) of a transaction has been executed. See + <xref linkend="mvcc"/> for more information about transaction + isolation and concurrency control. + </para> + + <para> + The transaction access mode determines whether the transaction is + read/write or read-only. Read/write is the default. When a + transaction is read-only, the following SQL commands are + disallowed: <command>INSERT</command>, <command>UPDATE</command>, + <command>DELETE</command>, <command>MERGE</command>, and + <command>COPY FROM</command> if the + table they would write to is not a temporary table; all + <literal>CREATE</literal>, <literal>ALTER</literal>, and + <literal>DROP</literal> commands; <literal>COMMENT</literal>, + <literal>GRANT</literal>, <literal>REVOKE</literal>, + <literal>TRUNCATE</literal>; and <literal>EXPLAIN ANALYZE</literal> + and <literal>EXECUTE</literal> if the command they would execute is + among those listed. This is a high-level notion of read-only that + does not prevent all writes to disk. + </para> + + <para> + The <literal>DEFERRABLE</literal> transaction property has no effect + unless the transaction is also <literal>SERIALIZABLE</literal> and + <literal>READ ONLY</literal>. When all three of these properties are + selected for a + transaction, the transaction may block when first acquiring its snapshot, + after which it is able to run without the normal overhead of a + <literal>SERIALIZABLE</literal> transaction and without any risk of + contributing to or being canceled by a serialization failure. This mode + is well suited for long-running reports or backups. + </para> + + <para> + The <literal>SET TRANSACTION SNAPSHOT</literal> command allows a new + transaction to run with the same <firstterm>snapshot</firstterm> as an existing + transaction. The pre-existing transaction must have exported its snapshot + with the <literal>pg_export_snapshot</literal> function (see <xref + linkend="functions-snapshot-synchronization"/>). That function returns a + snapshot identifier, which must be given to <literal>SET TRANSACTION + SNAPSHOT</literal> to specify which snapshot is to be imported. The + identifier must be written as a string literal in this command, for example + <literal>'00000003-0000001B-1'</literal>. + <literal>SET TRANSACTION SNAPSHOT</literal> can only be executed at the + start of a transaction, before the first query or + data-modification statement (<command>SELECT</command>, + <command>INSERT</command>, <command>DELETE</command>, + <command>UPDATE</command>, <command>MERGE</command>, + <command>FETCH</command>, or + <command>COPY</command>) of the transaction. Furthermore, the transaction + must already be set to <literal>SERIALIZABLE</literal> or + <literal>REPEATABLE READ</literal> isolation level (otherwise, the snapshot + would be discarded immediately, since <literal>READ COMMITTED</literal> mode takes + a new snapshot for each command). If the importing transaction uses + <literal>SERIALIZABLE</literal> isolation level, then the transaction that + exported the snapshot must also use that isolation level. Also, a + non-read-only serializable transaction cannot import a snapshot from a + read-only transaction. + </para> + + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + If <command>SET TRANSACTION</command> is executed without a prior + <command>START TRANSACTION</command> or <command>BEGIN</command>, + it emits a warning and otherwise has no effect. + </para> + + <para> + It is possible to dispense with <command>SET TRANSACTION</command> + by instead specifying the desired <replaceable + class="parameter">transaction_modes</replaceable> in + <command>BEGIN</command> or <command>START TRANSACTION</command>. + But that option is not available for <command>SET TRANSACTION + SNAPSHOT</command>. + </para> + + <para> + The session default transaction modes can also be set or examined via the + configuration parameters <xref linkend="guc-default-transaction-isolation"/>, + <xref linkend="guc-default-transaction-read-only"/>, and + <xref linkend="guc-default-transaction-deferrable"/>. + (In fact <command>SET SESSION CHARACTERISTICS</command> is just a + verbose equivalent for setting these variables with <command>SET</command>.) + This means the defaults can be set in the configuration file, via + <command>ALTER DATABASE</command>, etc. Consult <xref linkend="runtime-config"/> + for more information. + </para> + + <para> + The current transaction's modes can similarly be set or examined via the + configuration parameters <xref linkend="guc-transaction-isolation"/>, + <xref linkend="guc-transaction-read-only"/>, and + <xref linkend="guc-transaction-deferrable"/>. Setting one of these + parameters acts the same as the corresponding <command>SET + TRANSACTION</command> option, with the same restrictions on when it can + be done. However, these parameters cannot be set in the configuration + file, or from any source other than live SQL. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To begin a new transaction with the same snapshot as an already + existing transaction, first export the snapshot from the existing + transaction. That will return the snapshot identifier, for example: + +<programlisting> +BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; +SELECT pg_export_snapshot(); + pg_export_snapshot +--------------------- + 00000003-0000001B-1 +(1 row) +</programlisting> + + Then give the snapshot identifier in a <command>SET TRANSACTION + SNAPSHOT</command> command at the beginning of the newly opened + transaction: + +<programlisting> +BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; +SET TRANSACTION SNAPSHOT '00000003-0000001B-1'; +</programlisting></para> + </refsect1> + + <refsect1 id="r1-sql-set-transaction-3"> + <title>Compatibility</title> + + <para> + These commands are defined in the <acronym>SQL</acronym> standard, + except for the <literal>DEFERRABLE</literal> transaction mode + and the <command>SET TRANSACTION SNAPSHOT</command> form, which are + <productname>PostgreSQL</productname> extensions. + </para> + + <para> + <literal>SERIALIZABLE</literal> is the default transaction + isolation level in the standard. In + <productname>PostgreSQL</productname> the default is ordinarily + <literal>READ COMMITTED</literal>, but you can change it as + mentioned above. + </para> + + <para> + In the SQL standard, there is one other transaction characteristic + that can be set with these commands: the size of the diagnostics + area. This concept is specific to embedded SQL, and therefore is + not implemented in the <productname>PostgreSQL</productname> server. + </para> + + <para> + The SQL standard requires commas between successive <replaceable + class="parameter">transaction_modes</replaceable>, but for historical + reasons <productname>PostgreSQL</productname> allows the commas to be + omitted. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/show.sgml b/doc/src/sgml/ref/show.sgml new file mode 100644 index 0000000..b3747b1 --- /dev/null +++ b/doc/src/sgml/ref/show.sgml @@ -0,0 +1,200 @@ +<!-- +doc/src/sgml/ref/show.sgml +PostgreSQL documentation +--> + +<refentry id="sql-show"> + <indexterm zone="sql-show"> + <primary>SHOW</primary> + </indexterm> + + <refmeta> + <refentrytitle>SHOW</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>SHOW</refname> + <refpurpose>show the value of a run-time parameter</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +SHOW <replaceable class="parameter">name</replaceable> +SHOW ALL +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>SHOW</command> will display the current setting of + run-time parameters. These variables can be set using the + <command>SET</command> statement, by editing the + <filename>postgresql.conf</filename> configuration file, through + the <envar>PGOPTIONS</envar> environmental variable (when using + <application>libpq</application> or a <application>libpq</application>-based + application), or through command-line flags when starting the + <command>postgres</command> server. See <xref + linkend="runtime-config"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name of a run-time parameter. Available parameters are + documented in <xref linkend="runtime-config"/> and on the <xref + linkend="sql-set"/> reference page. In + addition, there are a few parameters that can be shown but not + set: + + <variablelist> + <varlistentry> + <term><literal>SERVER_VERSION</literal></term> + <listitem> + <para> + Shows the server's version number. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SERVER_ENCODING</literal></term> + <listitem> + <para> + Shows the server-side character set encoding. At present, + this parameter can be shown but not set, because the + encoding is determined at database creation time. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LC_COLLATE</literal></term> + <listitem> + <para> + Shows the database's locale setting for collation (text + ordering). At present, this parameter can be shown but not + set, because the setting is determined at database creation + time. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>LC_CTYPE</literal></term> + <listitem> + <para> + Shows the database's locale setting for character + classification. At present, this parameter can be shown but + not set, because the setting is determined at database creation + time. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>IS_SUPERUSER</literal></term> + <listitem> + <para> + True if the current role has superuser privileges. + </para> + </listitem> + </varlistentry> + </variablelist></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ALL</literal></term> + <listitem> + <para> + Show the values of all configuration parameters, with descriptions. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + The function <function>current_setting</function> produces + equivalent output; see <xref linkend="functions-admin-set"/>. + Also, the + <link linkend="view-pg-settings"><structname>pg_settings</structname></link> + system view produces the same information. + + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Show the current setting of the parameter <varname>DateStyle</varname>: + +<programlisting> +SHOW DateStyle; + DateStyle +----------- + ISO, MDY +(1 row) +</programlisting> + </para> + + <para> + Show the current setting of the parameter <varname>geqo</varname>: +<programlisting> +SHOW geqo; + geqo +------ + on +(1 row) +</programlisting> + </para> + + <para> + Show all settings: +<programlisting> +SHOW ALL; + name | setting | description +-------------------------+---------+------------------------------------------------- + allow_system_table_mods | off | Allows modifications of the structure of ... + . + . + . + xmloption | content | Sets whether XML data in implicit parsing ... + zero_damaged_pages | off | Continues processing past damaged page headers. +(196 rows) +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The <command>SHOW</command> command is a + <productname>PostgreSQL</productname> extension. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-set"/></member> + <member><xref linkend="sql-reset"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/start_transaction.sgml b/doc/src/sgml/ref/start_transaction.sgml new file mode 100644 index 0000000..74ccd7e --- /dev/null +++ b/doc/src/sgml/ref/start_transaction.sgml @@ -0,0 +1,97 @@ +<!-- +doc/src/sgml/ref/start_transaction.sgml +PostgreSQL documentation +--> + +<refentry id="sql-start-transaction"> + <indexterm zone="sql-start-transaction"> + <primary>START TRANSACTION</primary> + </indexterm> + + <refmeta> + <refentrytitle>START TRANSACTION</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>START TRANSACTION</refname> + <refpurpose>start a transaction block</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +START TRANSACTION [ <replaceable class="parameter">transaction_mode</replaceable> [, ...] ] + +<phrase>where <replaceable class="parameter">transaction_mode</replaceable> is one of:</phrase> + + ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED } + READ WRITE | READ ONLY + [ NOT ] DEFERRABLE +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + This command begins a new transaction block. If the isolation level, + read/write mode, or deferrable mode is specified, the new transaction has those + characteristics, as if <link linkend="sql-set-transaction"><command>SET TRANSACTION</command></link> was executed. This is the same + as the <link linkend="sql-begin"><command>BEGIN</command></link> command. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <para> + Refer to <xref linkend="sql-set-transaction"/> for information on the meaning + of the parameters to this statement. + </para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + In the standard, it is not necessary to issue <command>START TRANSACTION</command> + to start a transaction block: any SQL command implicitly begins a block. + <productname>PostgreSQL</productname>'s behavior can be seen as implicitly + issuing a <command>COMMIT</command> after each command that does not + follow <command>START TRANSACTION</command> (or <command>BEGIN</command>), + and it is therefore often called <quote>autocommit</quote>. + Other relational database systems might offer an autocommit feature + as a convenience. + </para> + + <para> + The <literal>DEFERRABLE</literal> + <replaceable class="parameter">transaction_mode</replaceable> + is a <productname>PostgreSQL</productname> language extension. + </para> + + <para> + The SQL standard requires commas between successive <replaceable + class="parameter">transaction_modes</replaceable>, but for historical + reasons <productname>PostgreSQL</productname> allows the commas to be + omitted. + </para> + + <para> + See also the compatibility section of <xref linkend="sql-set-transaction"/>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-begin"/></member> + <member><xref linkend="sql-commit"/></member> + <member><xref linkend="sql-rollback"/></member> + <member><xref linkend="sql-savepoint"/></member> + <member><xref linkend="sql-set-transaction"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/truncate.sgml b/doc/src/sgml/ref/truncate.sgml new file mode 100644 index 0000000..9d846f8 --- /dev/null +++ b/doc/src/sgml/ref/truncate.sgml @@ -0,0 +1,233 @@ +<!-- +doc/src/sgml/ref/truncate.sgml +PostgreSQL documentation +--> + +<refentry id="sql-truncate"> + <indexterm zone="sql-truncate"> + <primary>TRUNCATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>TRUNCATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>TRUNCATE</refname> + <refpurpose>empty a table or set of tables</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +TRUNCATE [ TABLE ] [ ONLY ] <replaceable class="parameter">name</replaceable> [ * ] [, ... ] + [ RESTART IDENTITY | CONTINUE IDENTITY ] [ CASCADE | RESTRICT ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>TRUNCATE</command> quickly removes all rows from a set of + tables. It has the same effect as an unqualified + <command>DELETE</command> on each table, but since it does not actually + scan the tables it is faster. Furthermore, it reclaims disk space + immediately, rather than requiring a subsequent <command>VACUUM</command> + operation. This is most useful on large tables. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a table to truncate. + If <literal>ONLY</literal> is specified before the table name, only that table + is truncated. If <literal>ONLY</literal> is not specified, the table and all + its descendant tables (if any) are truncated. Optionally, <literal>*</literal> + can be specified after the table name to explicitly indicate that + descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTART IDENTITY</literal></term> + <listitem> + <para> + Automatically restart sequences owned by columns of + the truncated table(s). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CONTINUE IDENTITY</literal></term> + <listitem> + <para> + Do not change the values of sequences. This is the default. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>CASCADE</literal></term> + <listitem> + <para> + Automatically truncate all tables that have foreign-key references + to any of the named tables, or to any tables added to the group + due to <literal>CASCADE</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>RESTRICT</literal></term> + <listitem> + <para> + Refuse to truncate if any of the tables have foreign-key references + from tables that are not listed in the command. This is the default. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + You must have the <literal>TRUNCATE</literal> privilege on a table + to truncate it. + </para> + + <para> + <command>TRUNCATE</command> acquires an <literal>ACCESS EXCLUSIVE</literal> lock on each + table it operates on, which blocks all other concurrent operations + on the table. When <literal>RESTART IDENTITY</literal> is specified, any + sequences that are to be restarted are likewise locked exclusively. + If concurrent access to a table is required, then + the <command>DELETE</command> command should be used instead. + </para> + + <para> + <command>TRUNCATE</command> cannot be used on a table that has foreign-key + references from other tables, unless all such tables are also truncated + in the same command. Checking validity in such cases would require table + scans, and the whole point is not to do one. The <literal>CASCADE</literal> + option can be used to automatically include all dependent tables — + but be very careful when using this option, or else you might lose data you + did not intend to! + Note in particular that when the table to be truncated is a partition, + siblings partitions are left untouched, but cascading occurs to all + referencing tables and all their partitions with no distinction. + </para> + + <para> + <command>TRUNCATE</command> will not fire any <literal>ON DELETE</literal> + triggers that might exist for the tables. But it will fire + <literal>ON TRUNCATE</literal> triggers. + If <literal>ON TRUNCATE</literal> triggers are defined for any of + the tables, then all <literal>BEFORE TRUNCATE</literal> triggers are + fired before any truncation happens, and all <literal>AFTER + TRUNCATE</literal> triggers are fired after the last truncation is + performed and any sequences are reset. + The triggers will fire in the order that the tables are + to be processed (first those listed in the command, and then any + that were added due to cascading). + </para> + + <para> + <command>TRUNCATE</command> is not MVCC-safe. After truncation, the table will + appear empty to concurrent transactions, if they are using a snapshot + taken before the truncation occurred. + See <xref linkend="mvcc-caveats"/> for more details. + </para> + + <para> + <command>TRUNCATE</command> is transaction-safe with respect to the data + in the tables: the truncation will be safely rolled back if the surrounding + transaction does not commit. + </para> + + <para> + When <literal>RESTART IDENTITY</literal> is specified, the implied + <command>ALTER SEQUENCE RESTART</command> operations are also done + transactionally; that is, they will be rolled back if the surrounding + transaction does not commit. Be aware that if any additional + sequence operations are done on the restarted sequences before the + transaction rolls back, the effects of these operations on the sequences + will be rolled back, but not their effects on <function>currval()</function>; + that is, after the transaction <function>currval()</function> will continue to + reflect the last sequence value obtained inside the failed transaction, + even though the sequence itself may no longer be consistent with that. + This is similar to the usual behavior of <function>currval()</function> after + a failed transaction. + </para> + + <para> + <command>TRUNCATE</command> can be used for foreign tables if + supported by the foreign data wrapper, for instance, + see <xref linkend="postgres-fdw"/>. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Truncate the tables <literal>bigtable</literal> and + <literal>fattable</literal>: + +<programlisting> +TRUNCATE bigtable, fattable; +</programlisting> + </para> + + <para> + The same, and also reset any associated sequence generators: + +<programlisting> +TRUNCATE bigtable, fattable RESTART IDENTITY; +</programlisting> + </para> + + <para> + Truncate the table <literal>othertable</literal>, and cascade to any tables + that reference <literal>othertable</literal> via foreign-key + constraints: + +<programlisting> +TRUNCATE othertable CASCADE; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + The SQL:2008 standard includes a <command>TRUNCATE</command> command + with the syntax <literal>TRUNCATE TABLE + <replaceable>tablename</replaceable></literal>. The clauses + <literal>CONTINUE IDENTITY</literal>/<literal>RESTART IDENTITY</literal> + also appear in that standard, but have slightly different though related + meanings. Some of the concurrency behavior of this command is left + implementation-defined by the standard, so the above notes should be + considered and compared with other implementations if necessary. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-delete"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/unlisten.sgml b/doc/src/sgml/ref/unlisten.sgml new file mode 100644 index 0000000..687bf48 --- /dev/null +++ b/doc/src/sgml/ref/unlisten.sgml @@ -0,0 +1,133 @@ +<!-- +doc/src/sgml/ref/unlisten.sgml +PostgreSQL documentation +--> + +<refentry id="sql-unlisten"> + <indexterm zone="sql-unlisten"> + <primary>UNLISTEN</primary> + </indexterm> + + <refmeta> + <refentrytitle>UNLISTEN</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>UNLISTEN</refname> + <refpurpose>stop listening for a notification</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +UNLISTEN { <replaceable class="parameter">channel</replaceable> | * } +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>UNLISTEN</command> is used to remove an existing + registration for <command>NOTIFY</command> events. + <command>UNLISTEN</command> cancels any existing registration of + the current <productname>PostgreSQL</productname> session as a + listener on the notification channel named <replaceable + class="parameter">channel</replaceable>. The special wildcard + <literal>*</literal> cancels all listener registrations for the + current session. + </para> + + <para> + <xref linkend="sql-notify"/> + contains a more extensive + discussion of the use of <command>LISTEN</command> and + <command>NOTIFY</command>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">channel</replaceable></term> + <listitem> + <para> + Name of a notification channel (any identifier). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>*</literal></term> + <listitem> + <para> + All current listen registrations for this session are cleared. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + You can unlisten something you were not listening for; no warning or error + will appear. + </para> + + <para> + At the end of each session, <command>UNLISTEN *</command> is + automatically executed. + </para> + + <para> + A transaction that has executed <command>UNLISTEN</command> cannot be + prepared for two-phase commit. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To make a registration: + +<programlisting> +LISTEN virtual; +NOTIFY virtual; +Asynchronous notification "virtual" received from server process with PID 8448. +</programlisting> + </para> + + <para> + Once <command>UNLISTEN</command> has been executed, further <command>NOTIFY</command> + messages will be ignored: + +<programlisting> +UNLISTEN virtual; +NOTIFY virtual; +-- no NOTIFY event is received +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>UNLISTEN</command> command in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-listen"/></member> + <member><xref linkend="sql-notify"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/update.sgml b/doc/src/sgml/ref/update.sgml new file mode 100644 index 0000000..2ab24b0 --- /dev/null +++ b/doc/src/sgml/ref/update.sgml @@ -0,0 +1,475 @@ +<!-- +doc/src/sgml/ref/update.sgml +PostgreSQL documentation +--> + +<refentry id="sql-update"> + <indexterm zone="sql-update"> + <primary>UPDATE</primary> + </indexterm> + + <refmeta> + <refentrytitle>UPDATE</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>UPDATE</refname> + <refpurpose>update rows of a table</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +[ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ] +UPDATE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> ] + SET { <replaceable class="parameter">column_name</replaceable> = { <replaceable class="parameter">expression</replaceable> | DEFAULT } | + ( <replaceable class="parameter">column_name</replaceable> [, ...] ) = [ ROW ] ( { <replaceable class="parameter">expression</replaceable> | DEFAULT } [, ...] ) | + ( <replaceable class="parameter">column_name</replaceable> [, ...] ) = ( <replaceable class="parameter">sub-SELECT</replaceable> ) + } [, ...] + [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ] + [ WHERE <replaceable class="parameter">condition</replaceable> | WHERE CURRENT OF <replaceable class="parameter">cursor_name</replaceable> ] + [ RETURNING * | <replaceable class="parameter">output_expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>UPDATE</command> changes the values of the specified + columns in all rows that satisfy the condition. Only the columns to + be modified need be mentioned in the <literal>SET</literal> clause; + columns not explicitly modified retain their previous values. + </para> + + <para> + There are two ways to modify a table using information contained in + other tables in the database: using sub-selects, or specifying + additional tables in the <literal>FROM</literal> clause. Which + technique is more appropriate depends on the specific + circumstances. + </para> + + <para> + The optional <literal>RETURNING</literal> clause causes <command>UPDATE</command> + to compute and return value(s) based on each row actually updated. + Any expression using the table's columns, and/or columns of other + tables mentioned in <literal>FROM</literal>, can be computed. + The new (post-update) values of the table's columns are used. + The syntax of the <literal>RETURNING</literal> list is identical to that of the + output list of <command>SELECT</command>. + </para> + + <para> + You must have the <literal>UPDATE</literal> privilege on the table, + or at least on the column(s) that are listed to be updated. + You must also have the <literal>SELECT</literal> + privilege on any column whose values are read in the + <replaceable class="parameter">expressions</replaceable> or + <replaceable class="parameter">condition</replaceable>. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">with_query</replaceable></term> + <listitem> + <para> + The <literal>WITH</literal> clause allows you to specify one or more + subqueries that can be referenced by name in the <command>UPDATE</command> + query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> + for details. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of the table to update. + If <literal>ONLY</literal> is specified before the table name, matching rows + are updated in the named table only. If <literal>ONLY</literal> is not + specified, matching rows are also updated in any tables inheriting from + the named table. Optionally, <literal>*</literal> can be specified after the + table name to explicitly indicate that descendant tables are included. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">alias</replaceable></term> + <listitem> + <para> + A substitute name for the target table. When an alias is + provided, it completely hides the actual name of the table. For + example, given <literal>UPDATE foo AS f</literal>, the remainder of the + <command>UPDATE</command> statement must refer to this table as + <literal>f</literal> not <literal>foo</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a column in the table named by <replaceable + class="parameter">table_name</replaceable>. + The column name can be qualified with a subfield name or array + subscript, if needed. Do not include the table's name in the + specification of a target column — for example, + <literal>UPDATE table_name SET table_name.col = 1</literal> is invalid. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + An expression to assign to the column. The expression can use the + old values of this and other columns in the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DEFAULT</literal></term> + <listitem> + <para> + Set the column to its default value (which will be NULL if no specific + default expression has been assigned to it). An identity column will be + set to a new value generated by the associated sequence. For a + generated column, specifying this is permitted but merely specifies the + normal behavior of computing the column from its generation expression. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sub-SELECT</replaceable></term> + <listitem> + <para> + A <literal>SELECT</literal> sub-query that produces as many output columns + as are listed in the parenthesized column list preceding it. The + sub-query must yield no more than one row when executed. If it + yields one row, its column values are assigned to the target columns; + if it yields no rows, NULL values are assigned to the target columns. + The sub-query can refer to old values of the current row of the table + being updated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">from_item</replaceable></term> + <listitem> + <para> + A table expression allowing columns from other tables to appear in + the <literal>WHERE</literal> condition and update expressions. This + uses the same syntax as the <link + linkend="sql-from"><literal>FROM</literal></link> clause of + a <command>SELECT</command> statement; + for example, an alias for the table name can be specified. Do not + repeat the target table as a <replaceable>from_item</replaceable> + unless you intend a self-join (in which case it must appear with + an alias in the <replaceable>from_item</replaceable>). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">condition</replaceable></term> + <listitem> + <para> + An expression that returns a value of type <type>boolean</type>. + Only rows for which this expression returns <literal>true</literal> + will be updated. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">cursor_name</replaceable></term> + <listitem> + <para> + The name of the cursor to use in a <literal>WHERE CURRENT OF</literal> + condition. The row to be updated is the one most recently fetched + from this cursor. The cursor must be a non-grouping + query on the <command>UPDATE</command>'s target table. + Note that <literal>WHERE CURRENT OF</literal> cannot be + specified together with a Boolean condition. See + <xref linkend="sql-declare"/> + for more information about using cursors with + <literal>WHERE CURRENT OF</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_expression</replaceable></term> + <listitem> + <para> + An expression to be computed and returned by the <command>UPDATE</command> + command after each row is updated. The expression can use any + column names of the table named by <replaceable class="parameter">table_name</replaceable> + or table(s) listed in <literal>FROM</literal>. + Write <literal>*</literal> to return all columns. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">output_name</replaceable></term> + <listitem> + <para> + A name to use for a returned column. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + On successful completion, an <command>UPDATE</command> command returns a command + tag of the form +<screen> +UPDATE <replaceable class="parameter">count</replaceable> +</screen> + The <replaceable class="parameter">count</replaceable> is the number + of rows updated, including matched rows whose values did not change. + Note that the number may be less than the number of rows that matched + the <replaceable class="parameter">condition</replaceable> when + updates were suppressed by a <literal>BEFORE UPDATE</literal> trigger. If + <replaceable class="parameter">count</replaceable> is 0, no rows were + updated by the query (this is not considered an error). + </para> + + <para> + If the <command>UPDATE</command> command contains a <literal>RETURNING</literal> + clause, the result will be similar to that of a <command>SELECT</command> + statement containing the columns and values defined in the + <literal>RETURNING</literal> list, computed over the row(s) updated by the + command. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + When a <literal>FROM</literal> clause is present, what essentially happens + is that the target table is joined to the tables mentioned in the + <replaceable>from_item</replaceable> list, and each output row of the join + represents an update operation for the target table. When using + <literal>FROM</literal> you should ensure that the join + produces at most one output row for each row to be modified. In + other words, a target row shouldn't join to more than one row from + the other table(s). If it does, then only one of the join rows + will be used to update the target row, but which one will be used + is not readily predictable. + </para> + + <para> + Because of this indeterminacy, referencing other tables only within + sub-selects is safer, though often harder to read and slower than + using a join. + </para> + + <para> + In the case of a partitioned table, updating a row might cause it to no + longer satisfy the partition constraint of the containing partition. In that + case, if there is some other partition in the partition tree for which this + row satisfies its partition constraint, then the row is moved to that + partition. If there is no such partition, an error will occur. Behind the + scenes, the row movement is actually a <command>DELETE</command> and + <command>INSERT</command> operation. + </para> + + <para> + There is a possibility that a concurrent <command>UPDATE</command> or + <command>DELETE</command> on the row being moved will get a serialization + failure error. Suppose session 1 is performing an <command>UPDATE</command> + on a partition key, and meanwhile a concurrent session 2 for which this + row is visible performs an <command>UPDATE</command> or + <command>DELETE</command> operation on this row. In such case, + session 2's <command>UPDATE</command> or <command>DELETE</command> will + detect the row movement and raise a serialization failure error (which + always returns with an SQLSTATE code '40001'). Applications may wish to + retry the transaction if this occurs. In the usual case where the table + is not partitioned, or where there is no row movement, session 2 would + have identified the newly updated row and carried out the + <command>UPDATE</command>/<command>DELETE</command> on this new row + version. + </para> + + <para> + Note that while rows can be moved from local partitions to a foreign-table + partition (provided the foreign data wrapper supports tuple routing), they + cannot be moved from a foreign-table partition to another partition. + </para> + + <para> + An attempt of moving a row from one partition to another will fail if a + foreign key is found to directly reference an ancestor of the source + partition that is not the same as the ancestor that's mentioned in the + <command>UPDATE</command> query. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + Change the word <literal>Drama</literal> to <literal>Dramatic</literal> in the + column <structfield>kind</structfield> of the table <structname>films</structname>: + +<programlisting> +UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama'; +</programlisting> + </para> + + <para> + Adjust temperature entries and reset precipitation to its default + value in one row of the table <structname>weather</structname>: + +<programlisting> +UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT + WHERE city = 'San Francisco' AND date = '2003-07-03'; +</programlisting> + </para> + + <para> + Perform the same operation and return the updated entries: + +<programlisting> +UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT + WHERE city = 'San Francisco' AND date = '2003-07-03' + RETURNING temp_lo, temp_hi, prcp; +</programlisting> + </para> + + <para> + Use the alternative column-list syntax to do the same update: +<programlisting> +UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT) + WHERE city = 'San Francisco' AND date = '2003-07-03'; +</programlisting> + </para> + + <para> + Increment the sales count of the salesperson who manages the + account for Acme Corporation, using the <literal>FROM</literal> + clause syntax: +<programlisting> +UPDATE employees SET sales_count = sales_count + 1 FROM accounts + WHERE accounts.name = 'Acme Corporation' + AND employees.id = accounts.sales_person; +</programlisting> + </para> + + <para> + Perform the same operation, using a sub-select in the + <literal>WHERE</literal> clause: +<programlisting> +UPDATE employees SET sales_count = sales_count + 1 WHERE id = + (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation'); +</programlisting> + </para> + + <para> + Update contact names in an accounts table to match the currently assigned + salespeople: +<programlisting> +UPDATE accounts SET (contact_first_name, contact_last_name) = + (SELECT first_name, last_name FROM employees + WHERE employees.id = accounts.sales_person); +</programlisting> + A similar result could be accomplished with a join: +<programlisting> +UPDATE accounts SET contact_first_name = first_name, + contact_last_name = last_name + FROM employees WHERE employees.id = accounts.sales_person; +</programlisting> + However, the second query may give unexpected results + if <structname>employees</structname>.<structfield>id</structfield> is not a unique key, whereas + the first query is guaranteed to raise an error if there are multiple + <structfield>id</structfield> matches. Also, if there is no match for a particular + <structname>accounts</structname>.<structfield>sales_person</structfield> entry, the first query + will set the corresponding name fields to NULL, whereas the second query + will not update that row at all. + </para> + + <para> + Update statistics in a summary table to match the current data: +<programlisting> +UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) = + (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d + WHERE d.group_id = s.group_id); +</programlisting> + </para> + + <para> + Attempt to insert a new stock item along with the quantity of stock. If + the item already exists, instead update the stock count of the existing + item. To do this without failing the entire transaction, use savepoints: +<programlisting> +BEGIN; +-- other operations +SAVEPOINT sp1; +INSERT INTO wines VALUES('Chateau Lafite 2003', '24'); +-- Assume the above fails because of a unique key violation, +-- so now we issue these commands: +ROLLBACK TO sp1; +UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003'; +-- continue with other operations, and eventually +COMMIT; +</programlisting> + </para> + + <para> + Change the <structfield>kind</structfield> column of the table + <structname>films</structname> in the row on which the cursor + <literal>c_films</literal> is currently positioned: +<programlisting> +UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + This command conforms to the <acronym>SQL</acronym> standard, except + that the <literal>FROM</literal> and <literal>RETURNING</literal> clauses + are <productname>PostgreSQL</productname> extensions, as is the ability + to use <literal>WITH</literal> with <command>UPDATE</command>. + </para> + + <para> + Some other database systems offer a <literal>FROM</literal> option in which + the target table is supposed to be listed again within <literal>FROM</literal>. + That is not how <productname>PostgreSQL</productname> interprets + <literal>FROM</literal>. Be careful when porting applications that use this + extension. + </para> + + <para> + According to the standard, the source value for a parenthesized sub-list of + target column names can be any row-valued expression yielding the correct + number of columns. <productname>PostgreSQL</productname> only allows the + source value to be a <link linkend="sql-syntax-row-constructors">row + constructor</link> or a sub-<literal>SELECT</literal>. An individual column's + updated value can be specified as <literal>DEFAULT</literal> in the + row-constructor case, but not inside a sub-<literal>SELECT</literal>. + </para> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/vacuum.sgml b/doc/src/sgml/ref/vacuum.sgml new file mode 100644 index 0000000..c582021 --- /dev/null +++ b/doc/src/sgml/ref/vacuum.sgml @@ -0,0 +1,453 @@ +<!-- +doc/src/sgml/ref/vacuum.sgml +PostgreSQL documentation +--> + +<refentry id="sql-vacuum"> + <indexterm zone="sql-vacuum"> + <primary>VACUUM</primary> + </indexterm> + + <refmeta> + <refentrytitle>VACUUM</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>VACUUM</refname> + <refpurpose>garbage-collect and optionally analyze a database</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +VACUUM [ ( <replaceable class="parameter">option</replaceable> [, ...] ) ] [ <replaceable class="parameter">table_and_columns</replaceable> [, ...] ] +VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ <replaceable class="parameter">table_and_columns</replaceable> [, ...] ] + +<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase> + + FULL [ <replaceable class="parameter">boolean</replaceable> ] + FREEZE [ <replaceable class="parameter">boolean</replaceable> ] + VERBOSE [ <replaceable class="parameter">boolean</replaceable> ] + ANALYZE [ <replaceable class="parameter">boolean</replaceable> ] + DISABLE_PAGE_SKIPPING [ <replaceable class="parameter">boolean</replaceable> ] + SKIP_LOCKED [ <replaceable class="parameter">boolean</replaceable> ] + INDEX_CLEANUP { AUTO | ON | OFF } + PROCESS_TOAST [ <replaceable class="parameter">boolean</replaceable> ] + TRUNCATE [ <replaceable class="parameter">boolean</replaceable> ] + PARALLEL <replaceable class="parameter">integer</replaceable> + +<phrase>and <replaceable class="parameter">table_and_columns</replaceable> is:</phrase> + + <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>VACUUM</command> reclaims storage occupied by dead tuples. + In normal <productname>PostgreSQL</productname> operation, tuples that + are deleted or obsoleted by an update are not physically removed from + their table; they remain present until a <command>VACUUM</command> is + done. Therefore it's necessary to do <command>VACUUM</command> + periodically, especially on frequently-updated tables. + </para> + + <para> + Without a <replaceable class="parameter">table_and_columns</replaceable> + list, <command>VACUUM</command> processes every table and materialized view + in the current database that the current user has permission to vacuum. + With a list, <command>VACUUM</command> processes only those table(s). + </para> + + <para> + <command>VACUUM ANALYZE</command> performs a <command>VACUUM</command> + and then an <command>ANALYZE</command> for each selected table. This + is a handy combination form for routine maintenance scripts. See + <xref linkend="sql-analyze"/> + for more details about its processing. + </para> + + <para> + Plain <command>VACUUM</command> (without <literal>FULL</literal>) simply reclaims + space and makes it + available for re-use. This form of the command can operate in parallel + with normal reading and writing of the table, as an exclusive lock + is not obtained. However, extra space is not returned to the operating + system (in most cases); it's just kept available for re-use within the + same table. It also allows us to leverage multiple CPUs in order to process + indexes. This feature is known as <firstterm>parallel vacuum</firstterm>. + To disable this feature, one can use <literal>PARALLEL</literal> option and + specify parallel workers as zero. <command>VACUUM FULL</command> rewrites + the entire contents of the table into a new disk file with no extra space, + allowing unused space to be returned to the operating system. This form is + much slower and requires an <literal>ACCESS EXCLUSIVE</literal> lock on + each table while it is being processed. + </para> + + <para> + When the option list is surrounded by parentheses, the options can be + written in any order. Without parentheses, options must be specified + in exactly the order shown above. + The parenthesized syntax was added in + <productname>PostgreSQL</productname> 9.0; the unparenthesized + syntax is deprecated. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><literal>FULL</literal></term> + <listitem> + <para> + Selects <quote>full</quote> vacuum, which can reclaim more + space, but takes much longer and exclusively locks the table. + This method also requires extra disk space, since it writes a + new copy of the table and doesn't release the old copy until + the operation is complete. Usually this should only be used when a + significant amount of space needs to be reclaimed from within the table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>FREEZE</literal></term> + <listitem> + <para> + Selects aggressive <quote>freezing</quote> of tuples. + Specifying <literal>FREEZE</literal> is equivalent to performing + <command>VACUUM</command> with the + <xref linkend="guc-vacuum-freeze-min-age"/> and + <xref linkend="guc-vacuum-freeze-table-age"/> parameters + set to zero. Aggressive freezing is always performed when the + table is rewritten, so this option is redundant when <literal>FULL</literal> + is specified. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>VERBOSE</literal></term> + <listitem> + <para> + Prints a detailed vacuum activity report for each table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ANALYZE</literal></term> + <listitem> + <para> + Updates statistics used by the planner to determine the most + efficient way to execute a query. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>DISABLE_PAGE_SKIPPING</literal></term> + <listitem> + <para> + Normally, <command>VACUUM</command> will skip pages based on the <link + linkend="vacuum-for-visibility-map">visibility map</link>. Pages where + all tuples are known to be frozen can always be skipped, and those + where all tuples are known to be visible to all transactions may be + skipped except when performing an aggressive vacuum. Furthermore, + except when performing an aggressive vacuum, some pages may be skipped + in order to avoid waiting for other sessions to finish using them. + This option disables all page-skipping behavior, and is intended to + be used only when the contents of the visibility map are + suspect, which should happen only if there is a hardware or software + issue causing database corruption. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>SKIP_LOCKED</literal></term> + <listitem> + <para> + Specifies that <command>VACUUM</command> should not wait for any + conflicting locks to be released when beginning work on a relation: + if a relation cannot be locked immediately without waiting, the relation + is skipped. Note that even with this option, + <command>VACUUM</command> may still block when opening the relation's + indexes. Additionally, <command>VACUUM ANALYZE</command> may still + block when acquiring sample rows from partitions, table inheritance + children, and some types of foreign tables. Also, while + <command>VACUUM</command> ordinarily processes all partitions of + specified partitioned tables, this option will cause + <command>VACUUM</command> to skip all partitions if there is a + conflicting lock on the partitioned table. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>INDEX_CLEANUP</literal></term> + <listitem> + <para> + Normally, <command>VACUUM</command> will skip index vacuuming + when there are very few dead tuples in the table. The cost of + processing all of the table's indexes is expected to greatly + exceed the benefit of removing dead index tuples when this + happens. This option can be used to force + <command>VACUUM</command> to process indexes when there are more + than zero dead tuples. The default is <literal>AUTO</literal>, + which allows <command>VACUUM</command> to skip index vacuuming + when appropriate. If <literal>INDEX_CLEANUP</literal> is set to + <literal>ON</literal>, <command>VACUUM</command> will + conservatively remove all dead tuples from indexes. This may be + useful for backwards compatibility with earlier releases of + <productname>PostgreSQL</productname> where this was the + standard behavior. + </para> + <para> + <literal>INDEX_CLEANUP</literal> can also be set to + <literal>OFF</literal> to force <command>VACUUM</command> to + <emphasis>always</emphasis> skip index vacuuming, even when + there are many dead tuples in the table. This may be useful + when it is necessary to make <command>VACUUM</command> run as + quickly as possible to avoid imminent transaction ID wraparound + (see <xref linkend="vacuum-for-wraparound"/>). However, the + wraparound failsafe mechanism controlled by <xref + linkend="guc-vacuum-failsafe-age"/> will generally trigger + automatically to avoid transaction ID wraparound failure, and + should be preferred. If index cleanup is not performed + regularly, performance may suffer, because as the table is + modified indexes will accumulate dead tuples and the table + itself will accumulate dead line pointers that cannot be removed + until index cleanup is completed. + </para> + <para> + This option has no effect for tables that have no index and is + ignored if the <literal>FULL</literal> option is used. It also + has no effect on the transaction ID wraparound failsafe + mechanism. When triggered it will skip index vacuuming, even + when <literal>INDEX_CLEANUP</literal> is set to + <literal>ON</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PROCESS_TOAST</literal></term> + <listitem> + <para> + Specifies that <command>VACUUM</command> should attempt to process the + corresponding <literal>TOAST</literal> table for each relation, if one + exists. This is usually the desired behavior and is the default. + Setting this option to false may be useful when it is only necessary to + vacuum the main relation. This option is required when the + <literal>FULL</literal> option is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>TRUNCATE</literal></term> + <listitem> + <para> + Specifies that <command>VACUUM</command> should attempt to + truncate off any empty pages at the end of the table and allow + the disk space for the truncated pages to be returned to + the operating system. This is normally the desired behavior + and is the default unless the <literal>vacuum_truncate</literal> + option has been set to false for the table to be vacuumed. + Setting this option to false may be useful to avoid + <literal>ACCESS EXCLUSIVE</literal> lock on the table that + the truncation requires. This option is ignored if the + <literal>FULL</literal> option is used. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>PARALLEL</literal></term> + <listitem> + <para> + Perform index vacuum and index cleanup phases of <command>VACUUM</command> + in parallel using <replaceable class="parameter">integer</replaceable> + background workers (for the details of each vacuum phase, please + refer to <xref linkend="vacuum-phases"/>). The number of workers used + to perform the operation is equal to the number of indexes on the + relation that support parallel vacuum which is limited by the number of + workers specified with <literal>PARALLEL</literal> option if any which is + further limited by <xref linkend="guc-max-parallel-maintenance-workers"/>. + An index can participate in parallel vacuum if and only if the size of the + index is more than <xref linkend="guc-min-parallel-index-scan-size"/>. + Please note that it is not guaranteed that the number of parallel workers + specified in <replaceable class="parameter">integer</replaceable> will be + used during execution. It is possible for a vacuum to run with fewer + workers than specified, or even with no workers at all. Only one worker + can be used per index. So parallel workers are launched only when there + are at least <literal>2</literal> indexes in the table. Workers for + vacuum are launched before the start of each phase and exit at the end of + the phase. These behaviors might change in a future release. This + option can't be used with the <literal>FULL</literal> option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">boolean</replaceable></term> + <listitem> + <para> + Specifies whether the selected option should be turned on or off. + You can write <literal>TRUE</literal>, <literal>ON</literal>, or + <literal>1</literal> to enable the option, and <literal>FALSE</literal>, + <literal>OFF</literal>, or <literal>0</literal> to disable it. The + <replaceable class="parameter">boolean</replaceable> value can also + be omitted, in which case <literal>TRUE</literal> is assumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">integer</replaceable></term> + <listitem> + <para> + Specifies a non-negative integer value passed to the selected option. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">table_name</replaceable></term> + <listitem> + <para> + The name (optionally schema-qualified) of a specific table or + materialized view to vacuum. If the specified table is a partitioned + table, all of its leaf partitions are vacuumed. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">column_name</replaceable></term> + <listitem> + <para> + The name of a specific column to analyze. Defaults to all columns. + If a column list is specified, <literal>ANALYZE</literal> must also be + specified. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Outputs</title> + + <para> + When <literal>VERBOSE</literal> is specified, <command>VACUUM</command> emits + progress messages to indicate which table is currently being + processed. Various statistics about the tables are printed as well. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + To vacuum a table, one must ordinarily be the table's owner or a + superuser. However, database owners are allowed to + vacuum all tables in their databases, except shared catalogs. + (The restriction for shared catalogs means that a true database-wide + <command>VACUUM</command> can only be performed by a superuser.) + <command>VACUUM</command> will skip over any tables that the calling user + does not have permission to vacuum. + </para> + + <para> + <command>VACUUM</command> cannot be executed inside a transaction block. + </para> + + <para> + For tables with <acronym>GIN</acronym> indexes, <command>VACUUM</command> (in + any form) also completes any pending index insertions, by moving pending + index entries to the appropriate places in the main <acronym>GIN</acronym> index + structure. See <xref linkend="gin-fast-update"/> for details. + </para> + + <para> + We recommend that all databases be vacuumed regularly in + order to remove dead rows. <productname>PostgreSQL</productname> includes + an <quote>autovacuum</quote> facility which can automate routine vacuum + maintenance. For more information about automatic and manual vacuuming, + see <xref linkend="routine-vacuuming"/>. + </para> + + <para> + The <option>FULL</option> option is not recommended for routine use, + but might be useful in special cases. An example is when you have deleted + or updated most of the rows in a table and would like the table to + physically shrink to occupy less disk space and allow faster table + scans. <command>VACUUM FULL</command> will usually shrink the table + more than a plain <command>VACUUM</command> would. + </para> + + <para> + The <option>PARALLEL</option> option is used only for vacuum purposes. + If this option is specified with the <option>ANALYZE</option> option, + it does not affect <option>ANALYZE</option>. + </para> + + <para> + <command>VACUUM</command> causes a substantial increase in I/O traffic, + which might cause poor performance for other active sessions. Therefore, + it is sometimes advisable to use the cost-based vacuum delay feature. For + parallel vacuum, each worker sleeps in proportion to the work done by that + worker. See <xref linkend="runtime-config-resource-vacuum-cost"/> for + details. + </para> + + <para> + Each backend running <command>VACUUM</command> without the + <literal>FULL</literal> option will report its progress in the + <structname>pg_stat_progress_vacuum</structname> view. Backends running + <command>VACUUM FULL</command> will instead report their progress in the + <structname>pg_stat_progress_cluster</structname> view. See + <xref linkend="vacuum-progress-reporting"/> and + <xref linkend="cluster-progress-reporting"/> for details. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To clean a single table <literal>onek</literal>, analyze it for + the optimizer and print a detailed vacuum activity report: + +<programlisting> +VACUUM (VERBOSE, ANALYZE) onek; +</programlisting></para> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para> + There is no <command>VACUUM</command> statement in the SQL standard. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="app-vacuumdb"/></member> + <member><xref linkend="runtime-config-resource-vacuum-cost"/></member> + <member><xref linkend="autovacuum"/></member> + <member><xref linkend="vacuum-progress-reporting"/></member> + <member><xref linkend="cluster-progress-reporting"/></member> + </simplelist> + </refsect1> +</refentry> diff --git a/doc/src/sgml/ref/vacuumdb.sgml b/doc/src/sgml/ref/vacuumdb.sgml new file mode 100644 index 0000000..956c0f0 --- /dev/null +++ b/doc/src/sgml/ref/vacuumdb.sgml @@ -0,0 +1,632 @@ +<!-- +doc/src/sgml/ref/vacuumdb.sgml +PostgreSQL documentation +--> + +<refentry id="app-vacuumdb"> + <indexterm zone="app-vacuumdb"> + <primary>vacuumdb</primary> + </indexterm> + + <refmeta> + <refentrytitle><application>vacuumdb</application></refentrytitle> + <manvolnum>1</manvolnum> + <refmiscinfo>Application</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>vacuumdb</refname> + <refpurpose>garbage-collect and analyze a <productname>PostgreSQL</productname> database</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <cmdsynopsis> + <command>vacuumdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + + <arg choice="plain" rep="repeat"> + <arg choice="opt"> + <group choice="plain"> + <arg choice="plain"><option>-t</option></arg> + <arg choice="plain"><option>--table</option></arg> + </group> + <replaceable>table</replaceable> + <arg choice="opt">( <replaceable class="parameter">column</replaceable> [,...] )</arg> + </arg> + </arg> + + <arg choice="opt"><replaceable>dbname</replaceable></arg> + </cmdsynopsis> + + <cmdsynopsis> + <command>vacuumdb</command> + <arg rep="repeat"><replaceable>connection-option</replaceable></arg> + <arg rep="repeat"><replaceable>option</replaceable></arg> + <group choice="plain"> + <arg choice="plain"><option>-a</option></arg> + <arg choice="plain"><option>--all</option></arg> + </group> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <application>vacuumdb</application> is a utility for cleaning a + <productname>PostgreSQL</productname> database. + <application>vacuumdb</application> will also generate internal statistics + used by the <productname>PostgreSQL</productname> query optimizer. + </para> + + <para> + <application>vacuumdb</application> is a wrapper around the SQL + command <link linkend="sql-vacuum"><command>VACUUM</command></link>. + There is no effective difference between vacuuming and analyzing + databases via this utility and via other methods for accessing the + server. + </para> + + </refsect1> + + + <refsect1> + <title>Options</title> + + <para> + <application>vacuumdb</application> accepts the following command-line arguments: + <variablelist> + <varlistentry> + <term><option>-a</option></term> + <term><option>--all</option></term> + <listitem> + <para> + Vacuum all databases. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option><optional>-d</optional> <replaceable class="parameter">dbname</replaceable></option></term> + <term><option><optional>--dbname=</optional><replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to be cleaned or analyzed, + when <option>-a</option>/<option>--all</option> is not used. + If this is not specified, the database name is read + from the environment variable <envar>PGDATABASE</envar>. If + that is not set, the user name specified for the connection is + used. The <replaceable>dbname</replaceable> can be a <link + linkend="libpq-connstring">connection string</link>. If so, + connection string parameters will override any conflicting command + line options. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--disable-page-skipping</option></term> + <listitem> + <para> + Disable skipping pages based on the contents of the visibility map. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 9.6 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e</option></term> + <term><option>--echo</option></term> + <listitem> + <para> + Echo the commands that <application>vacuumdb</application> generates + and sends to the server. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f</option></term> + <term><option>--full</option></term> + <listitem> + <para> + Perform <quote>full</quote> vacuuming. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-F</option></term> + <term><option>--freeze</option></term> + <listitem> + <para> + Aggressively <quote>freeze</quote> tuples. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--force-index-cleanup</option></term> + <listitem> + <para> + Always remove index entries pointing to dead tuples. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 12 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-j <replaceable class="parameter">njobs</replaceable></option></term> + <term><option>--jobs=<replaceable class="parameter">njobs</replaceable></option></term> + <listitem> + <para> + Execute the vacuum or analyze commands in parallel by running + <replaceable class="parameter">njobs</replaceable> + commands simultaneously. This option may reduce the processing time + but it also increases the load on the database server. + </para> + <para> + <application>vacuumdb</application> will open + <replaceable class="parameter">njobs</replaceable> connections to the + database, so make sure your <xref linkend="guc-max-connections"/> + setting is high enough to accommodate all connections. + </para> + <para> + Note that using this mode together with the <option>-f</option> + (<literal>FULL</literal>) option might cause deadlock failures if + certain system catalogs are processed in parallel. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--min-mxid-age <replaceable class="parameter">mxid_age</replaceable></option></term> + <listitem> + <para> + Only execute the vacuum or analyze commands on tables with a multixact + ID age of at least <replaceable class="parameter">mxid_age</replaceable>. + This setting is useful for prioritizing tables to process to prevent + multixact ID wraparound (see + <xref linkend="vacuum-for-multixact-wraparound"/>). + </para> + <para> + For the purposes of this option, the multixact ID age of a relation is + the greatest of the ages of the main relation and its associated + <acronym>TOAST</acronym> table, if one exists. Since the commands + issued by <application>vacuumdb</application> will also process the + <acronym>TOAST</acronym> table for the relation if necessary, it does + not need to be considered separately. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 9.6 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--min-xid-age <replaceable class="parameter">xid_age</replaceable></option></term> + <listitem> + <para> + Only execute the vacuum or analyze commands on tables with a + transaction ID age of at least + <replaceable class="parameter">xid_age</replaceable>. This setting + is useful for prioritizing tables to process to prevent transaction + ID wraparound (see <xref linkend="vacuum-for-wraparound"/>). + </para> + <para> + For the purposes of this option, the transaction ID age of a relation + is the greatest of the ages of the main relation and its associated + <acronym>TOAST</acronym> table, if one exists. Since the commands + issued by <application>vacuumdb</application> will also process the + <acronym>TOAST</acronym> table for the relation if necessary, it does + not need to be considered separately. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 9.6 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-index-cleanup</option></term> + <listitem> + <para> + Do not remove index entries pointing to dead tuples. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 12 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-process-toast</option></term> + <listitem> + <para> + Skip the TOAST table associated with the table to vacuum, if any. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 14 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--no-truncate</option></term> + <listitem> + <para> + Do not truncate empty pages at the end of the table. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 12 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-P <replaceable class="parameter">parallel_workers</replaceable></option></term> + <term><option>--parallel=<replaceable class="parameter">parallel_workers</replaceable></option></term> + <listitem> + <para> + Specify the number of parallel workers for <firstterm>parallel vacuum</firstterm>. + This allows the vacuum to leverage multiple CPUs to process indexes. + See <xref linkend="sql-vacuum"/>. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 13 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-q</option></term> + <term><option>--quiet</option></term> + <listitem> + <para> + Do not display progress messages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--skip-locked</option></term> + <listitem> + <para> + Skip relations that cannot be immediately locked for processing. + </para> + <note> + <para> + This option is only available for servers running + <productname>PostgreSQL</productname> 12 and later. + </para> + </note> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t <replaceable class="parameter">table</replaceable> [ (<replaceable class="parameter">column</replaceable> [,...]) ]</option></term> + <term><option>--table=<replaceable class="parameter">table</replaceable> [ (<replaceable class="parameter">column</replaceable> [,...]) ]</option></term> + <listitem> + <para> + Clean or analyze <replaceable class="parameter">table</replaceable> only. + Column names can be specified only in conjunction with + the <option>--analyze</option> or <option>--analyze-only</option> options. + Multiple tables can be vacuumed by writing multiple + <option>-t</option> switches. + </para> + <tip> + <para> + If you specify columns, you probably have to escape the parentheses + from the shell. (See examples below.) + </para> + </tip> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v</option></term> + <term><option>--verbose</option></term> + <listitem> + <para> + Print detailed information during processing. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-V</option></term> + <term><option>--version</option></term> + <listitem> + <para> + Print the <application>vacuumdb</application> version and exit. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-z</option></term> + <term><option>--analyze</option></term> + <listitem> + <para> + Also calculate statistics for use by the optimizer. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Z</option></term> + <term><option>--analyze-only</option></term> + <listitem> + <para> + Only calculate statistics for use by the optimizer (no vacuum). + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--analyze-in-stages</option></term> + <listitem> + <para> + Only calculate statistics for use by the optimizer (no vacuum), + like <option>--analyze-only</option>. Run three + stages of analyze; the first stage uses the lowest possible statistics + target (see <xref linkend="guc-default-statistics-target"/>) + to produce usable statistics faster, and subsequent stages build the + full statistics. + </para> + + <para> + This option is only useful to analyze a database that currently has + no statistics or has wholly incorrect ones, such as if it is newly + populated from a restored dump or by <command>pg_upgrade</command>. + Be aware that running with this option in a database with existing + statistics may cause the query optimizer choices to become + transiently worse due to the low statistics targets of the early + stages. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <term><option>--help</option></term> + <listitem> + <para> + Show help about <application>vacuumdb</application> command line + arguments, and exit. + </para> + </listitem> + </varlistentry> + + </variablelist> + </para> + + <para> + <application>vacuumdb</application> also accepts + the following command-line arguments for connection parameters: + <variablelist> + <varlistentry> + <term><option>-h <replaceable class="parameter">host</replaceable></option></term> + <term><option>--host=<replaceable class="parameter">host</replaceable></option></term> + <listitem> + <para> + Specifies the host name of the machine on which the server + is running. If the value begins with a slash, it is used + as the directory for the Unix domain socket. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p <replaceable class="parameter">port</replaceable></option></term> + <term><option>--port=<replaceable class="parameter">port</replaceable></option></term> + <listitem> + <para> + Specifies the TCP port or local Unix domain socket file + extension on which the server + is listening for connections. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-U <replaceable class="parameter">username</replaceable></option></term> + <term><option>--username=<replaceable class="parameter">username</replaceable></option></term> + <listitem> + <para> + User name to connect as. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option></term> + <term><option>--no-password</option></term> + <listitem> + <para> + Never issue a password prompt. If the server requires + password authentication and a password is not available by + other means such as a <filename>.pgpass</filename> file, the + connection attempt will fail. This option can be useful in + batch jobs and scripts where no user is present to enter a + password. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-W</option></term> + <term><option>--password</option></term> + <listitem> + <para> + Force <application>vacuumdb</application> to prompt for a + password before connecting to a database. + </para> + + <para> + This option is never essential, since + <application>vacuumdb</application> will automatically prompt + for a password if the server demands password authentication. + However, <application>vacuumdb</application> will waste a + connection attempt finding out that the server wants a password. + In some cases it is worth typing <option>-W</option> to avoid the extra + connection attempt. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>--maintenance-db=<replaceable class="parameter">dbname</replaceable></option></term> + <listitem> + <para> + Specifies the name of the database to connect to to discover which + databases should be vacuumed, + when <option>-a</option>/<option>--all</option> is used. + If not specified, the <literal>postgres</literal> database will be used, + or if that does not exist, <literal>template1</literal> will be used. + This can be a <link linkend="libpq-connstring">connection + string</link>. If so, connection string parameters will override any + conflicting command line options. Also, connection string parameters + other than the database name itself will be re-used when connecting + to other databases. + </para> + </listitem> + </varlistentry> + </variablelist> + </para> + </refsect1> + + + <refsect1> + <title>Environment</title> + + <variablelist> + <varlistentry> + <term><envar>PGDATABASE</envar></term> + <term><envar>PGHOST</envar></term> + <term><envar>PGPORT</envar></term> + <term><envar>PGUSER</envar></term> + + <listitem> + <para> + Default connection parameters + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><envar>PG_COLOR</envar></term> + <listitem> + <para> + Specifies whether to use color in diagnostic messages. Possible values + are <literal>always</literal>, <literal>auto</literal> and + <literal>never</literal>. + </para> + </listitem> + </varlistentry> + </variablelist> + + <para> + This utility, like most other <productname>PostgreSQL</productname> utilities, + also uses the environment variables supported by <application>libpq</application> + (see <xref linkend="libpq-envars"/>). + </para> + + </refsect1> + + + <refsect1> + <title>Diagnostics</title> + + <para> + In case of difficulty, see <xref linkend="sql-vacuum"/> + and <xref linkend="app-psql"/> for + discussions of potential problems and error messages. + The database server must be running at the + targeted host. Also, any default connection settings and environment + variables used by the <application>libpq</application> front-end + library will apply. + </para> + + </refsect1> + + + <refsect1> + <title>Notes</title> + + <para> + <application>vacuumdb</application> might need to connect several + times to the <productname>PostgreSQL</productname> server, asking + for a password each time. It is convenient to have a + <filename>~/.pgpass</filename> file in such cases. See <xref + linkend="libpq-pgpass"/> for more information. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + To clean the database <literal>test</literal>: +<screen> +<prompt>$ </prompt><userinput>vacuumdb test</userinput> +</screen> + </para> + + <para> + To clean and analyze for the optimizer a database named + <literal>bigdb</literal>: +<screen> +<prompt>$ </prompt><userinput>vacuumdb --analyze bigdb</userinput> +</screen> + </para> + + <para> + To clean a single table + <literal>foo</literal> in a database named + <literal>xyzzy</literal>, and analyze a single column + <literal>bar</literal> of the table for the optimizer: +<screen> +<prompt>$ </prompt><userinput>vacuumdb --analyze --verbose --table='foo(bar)' xyzzy</userinput> +</screen></para> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-vacuum"/></member> + </simplelist> + </refsect1> + +</refentry> diff --git a/doc/src/sgml/ref/values.sgml b/doc/src/sgml/ref/values.sgml new file mode 100644 index 0000000..4bf7bfd --- /dev/null +++ b/doc/src/sgml/ref/values.sgml @@ -0,0 +1,251 @@ +<!-- +doc/src/sgml/ref/values.sgml +PostgreSQL documentation +--> + +<refentry id="sql-values"> + <indexterm zone="sql-values"> + <primary>VALUES</primary> + </indexterm> + + <refmeta> + <refentrytitle>VALUES</refentrytitle> + <manvolnum>7</manvolnum> + <refmiscinfo>SQL - Language Statements</refmiscinfo> + </refmeta> + + <refnamediv> + <refname>VALUES</refname> + <refpurpose>compute a set of rows</refpurpose> + </refnamediv> + + <refsynopsisdiv> +<synopsis> +VALUES ( <replaceable class="parameter">expression</replaceable> [, ...] ) [, ...] + [ ORDER BY <replaceable class="parameter">sort_expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [, ...] ] + [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ] + [ OFFSET <replaceable class="parameter">start</replaceable> [ ROW | ROWS ] ] + [ FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } ONLY ] +</synopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <command>VALUES</command> computes a row value or set of row values + specified by value expressions. It is most commonly used to generate + a <quote>constant table</quote> within a larger command, but it can be + used on its own. + </para> + + <para> + When more than one row is specified, all the rows must have the same + number of elements. The data types of the resulting table's columns are + determined by combining the explicit or inferred types of the expressions + appearing in that column, using the same rules as for <literal>UNION</literal> + (see <xref linkend="typeconv-union-case"/>). + </para> + + <para> + Within larger commands, <command>VALUES</command> is syntactically allowed + anywhere that <command>SELECT</command> is. Because it is treated like a + <command>SELECT</command> by the grammar, it is possible to use + the <literal>ORDER BY</literal>, <literal>LIMIT</literal> (or + equivalently <literal>FETCH FIRST</literal>), + and <literal>OFFSET</literal> clauses with a + <command>VALUES</command> command. + </para> + </refsect1> + + <refsect1> + <title>Parameters</title> + + <variablelist> + <varlistentry> + <term><replaceable class="parameter">expression</replaceable></term> + <listitem> + <para> + A constant or expression to compute and insert at the indicated place + in the resulting table (set of rows). In a <command>VALUES</command> list + appearing at the top level of an <command>INSERT</command>, an + <replaceable class="parameter">expression</replaceable> can be replaced + by <literal>DEFAULT</literal> to indicate that the destination column's + default value should be inserted. <literal>DEFAULT</literal> cannot + be used when <command>VALUES</command> appears in other contexts. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">sort_expression</replaceable></term> + <listitem> + <para> + An expression or integer constant indicating how to sort the result + rows. This expression can refer to the columns of the + <command>VALUES</command> result as <literal>column1</literal>, <literal>column2</literal>, + etc. For more details see + <xref linkend="sql-orderby"/> + in the <xref linkend="sql-select"/> documentation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">operator</replaceable></term> + <listitem> + <para> + A sorting operator. For details see + <xref linkend="sql-orderby"/> + in the <xref linkend="sql-select"/> documentation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">count</replaceable></term> + <listitem> + <para> + The maximum number of rows to return. For details see + <xref linkend="sql-limit"/> + in the <xref linkend="sql-select"/> documentation. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><replaceable class="parameter">start</replaceable></term> + <listitem> + <para> + The number of rows to skip before starting to return rows. + For details see <xref linkend="sql-limit"/> + in the <xref linkend="sql-select"/> documentation. + </para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para> + <command>VALUES</command> lists with very large numbers of rows should be avoided, + as you might encounter out-of-memory failures or poor performance. + <command>VALUES</command> appearing within <command>INSERT</command> is a special case + (because the desired column types are known from the <command>INSERT</command>'s + target table, and need not be inferred by scanning the <command>VALUES</command> + list), so it can handle larger lists than are practical in other contexts. + </para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para> + A bare <command>VALUES</command> command: + +<programlisting> +VALUES (1, 'one'), (2, 'two'), (3, 'three'); +</programlisting> + + This will return a table of two columns and three rows. It's effectively + equivalent to: + +<programlisting> +SELECT 1 AS column1, 'one' AS column2 +UNION ALL +SELECT 2, 'two' +UNION ALL +SELECT 3, 'three'; +</programlisting> + + </para> + + <para> + More usually, <command>VALUES</command> is used within a larger SQL command. + The most common use is in <command>INSERT</command>: + +<programlisting> +INSERT INTO films (code, title, did, date_prod, kind) + VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama'); +</programlisting> + </para> + + <para> + In the context of <command>INSERT</command>, entries of a <command>VALUES</command> list + can be <literal>DEFAULT</literal> to indicate that the column default + should be used here instead of specifying a value: + +<programlisting> +INSERT INTO films VALUES + ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes'), + ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama', DEFAULT); +</programlisting> + </para> + + <para> + <command>VALUES</command> can also be used where a sub-<command>SELECT</command> might + be written, for example in a <literal>FROM</literal> clause: + +<programlisting> +SELECT f.* + FROM films f, (VALUES('MGM', 'Horror'), ('UA', 'Sci-Fi')) AS t (studio, kind) + WHERE f.studio = t.studio AND f.kind = t.kind; + +UPDATE employees SET salary = salary * v.increase + FROM (VALUES(1, 200000, 1.2), (2, 400000, 1.4)) AS v (depno, target, increase) + WHERE employees.depno = v.depno AND employees.sales >= v.target; +</programlisting> + + Note that an <literal>AS</literal> clause is required when <command>VALUES</command> + is used in a <literal>FROM</literal> clause, just as is true for + <command>SELECT</command>. It is not required that the <literal>AS</literal> clause + specify names for all the columns, but it's good practice to do so. + (The default column names for <command>VALUES</command> are <literal>column1</literal>, + <literal>column2</literal>, etc. in <productname>PostgreSQL</productname>, but + these names might be different in other database systems.) + </para> + + <para> + When <command>VALUES</command> is used in <command>INSERT</command>, the values are all + automatically coerced to the data type of the corresponding destination + column. When it's used in other contexts, it might be necessary to specify + the correct data type. If the entries are all quoted literal constants, + coercing the first is sufficient to determine the assumed type for all: + +<programlisting> +SELECT * FROM machines +WHERE ip_address IN (VALUES('192.168.0.1'::inet), ('192.168.0.10'), ('192.168.1.43')); +</programlisting></para> + + <tip> + <para> + For simple <literal>IN</literal> tests, it's better to rely on the + <link linkend="functions-comparisons-in-scalar">list-of-scalars</link> + form of <literal>IN</literal> than to write a <command>VALUES</command> + query as shown above. The list of scalars method requires less writing + and is often more efficient. + </para> + </tip> + </refsect1> + + <refsect1> + <title>Compatibility</title> + + <para><command>VALUES</command> conforms to the SQL standard. + <literal>LIMIT</literal> and <literal>OFFSET</literal> are + <productname>PostgreSQL</productname> extensions; see also + under <xref linkend="sql-select"/>. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <simplelist type="inline"> + <member><xref linkend="sql-insert"/></member> + <member><xref linkend="sql-select"/></member> + </simplelist> + </refsect1> +</refentry> |