SQL procedures
I've been working on SQL procedures. (Some might call them "stored
procedures", but I'm not aware of any procedures that are not stored, so
that's not a term that I'm using here.)
Everything that follows is intended to align with the SQL standard, at
least in spirit.
This first patch does a bunch of preparation work. It adds the
CREATE/ALTER/DROP PROCEDURE commands and the CALL statement to call a
procedure. It also adds ROUTINE syntax which can refer to a function or
procedure. I have extended that to include aggregates. And then there
is a bunch of leg work, such as psql and pg_dump support. The
documentation is a lot of copy-and-paste right now; that can be
revisited sometime. The provided procedural languages (an ever more
confusing term) each needed a small touch-up to handle pg_proc entries
with prorettype == 0.
Right now, there is no support for returning values from procedures via
OUT parameters. That will need some definitional pondering; and see
also below for a possible alternative.
With this, you can write procedures that are somewhat compatible with
DB2, MySQL, and to a lesser extent Oracle.
Separately, I will send patches that implement (the beginnings of) two
separate features on top of this:
- Transaction control in procedure bodies
- Returning multiple result sets
(In various previous discussions on "real stored procedures" or
something like that, most people seemed to have one of these two
features in mind. I think that depends on what other SQL systems one
has worked with previously.)
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Attachments:
v1-0001-SQL-procedures.patchtext/plain; charset=UTF-8; name=v1-0001-SQL-procedures.patch; x-mac-creator=0; x-mac-type=0Download
From 6ea86532a25c90c8aafd5375fb9ea3da53d2dd39 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 31 Oct 2017 12:48:39 -0400
Subject: [PATCH v1] SQL procedures
CREATE/ALTER/DROP PROCEDURE, ALTER/DROP ROUTINE, CALL statement, utility
statement support, support in the built-in PLs, support in pg_dump and
psql
---
doc/src/sgml/catalogs.sgml | 2 +-
doc/src/sgml/ecpg.sgml | 4 +-
doc/src/sgml/information_schema.sgml | 18 +-
doc/src/sgml/plpgsql.sgml | 2 +-
doc/src/sgml/ref/allfiles.sgml | 6 +
doc/src/sgml/ref/alter_extension.sgml | 12 +-
doc/src/sgml/ref/alter_procedure.sgml | 302 ++++++++++++++++++++
doc/src/sgml/ref/alter_routine.sgml | 98 +++++++
doc/src/sgml/ref/call.sgml | 97 +++++++
doc/src/sgml/ref/comment.sgml | 13 +-
doc/src/sgml/ref/create_function.sgml | 4 +-
doc/src/sgml/ref/create_procedure.sgml | 374 +++++++++++++++++++++++++
doc/src/sgml/ref/drop_procedure.sgml | 161 +++++++++++
doc/src/sgml/ref/drop_routine.sgml | 90 ++++++
doc/src/sgml/ref/grant.sgml | 4 +-
doc/src/sgml/ref/revoke.sgml | 4 +-
doc/src/sgml/ref/security_label.sgml | 12 +-
doc/src/sgml/reference.sgml | 6 +
src/backend/catalog/aclchk.c | 60 +++-
src/backend/catalog/information_schema.sql | 25 +-
src/backend/catalog/objectaddress.c | 19 +-
src/backend/catalog/pg_proc.c | 3 +-
src/backend/commands/aggregatecmds.c | 2 +-
src/backend/commands/alter.c | 6 +
src/backend/commands/dropcmds.c | 38 ++-
src/backend/commands/event_trigger.c | 14 +
src/backend/commands/functioncmds.c | 131 ++++++++-
src/backend/commands/opclasscmds.c | 4 +-
src/backend/executor/functions.c | 13 +-
src/backend/nodes/copyfuncs.c | 15 +
src/backend/nodes/equalfuncs.c | 13 +
src/backend/optimizer/util/clauses.c | 1 +
src/backend/parser/gram.y | 254 ++++++++++++++++-
src/backend/parser/parse_agg.c | 11 +
src/backend/parser/parse_expr.c | 8 +
src/backend/parser/parse_func.c | 201 ++++++++-----
src/backend/tcop/utility.c | 44 ++-
src/backend/utils/adt/ruleutils.c | 6 +
src/backend/utils/cache/lsyscache.c | 19 ++
src/bin/pg_dump/dumputils.c | 5 +-
src/bin/pg_dump/pg_backup_archiver.c | 7 +-
src/bin/pg_dump/pg_dump.c | 32 ++-
src/bin/pg_dump/t/002_pg_dump.pl | 38 +++
src/bin/psql/describe.c | 8 +-
src/bin/psql/tab-complete.c | 77 ++++-
src/include/commands/defrem.h | 3 +-
src/include/nodes/nodes.h | 1 +
src/include/nodes/parsenodes.h | 17 ++
src/include/parser/kwlist.h | 4 +
src/include/parser/parse_func.h | 8 +-
src/include/parser/parse_node.h | 3 +-
src/include/utils/lsyscache.h | 1 +
src/interfaces/ecpg/preproc/ecpg.tokens | 2 +-
src/interfaces/ecpg/preproc/ecpg.trailer | 5 +-
src/interfaces/ecpg/preproc/ecpg_keywords.c | 1 -
src/pl/plperl/GNUmakefile | 2 +-
src/pl/plperl/expected/plperl_call.out | 29 ++
src/pl/plperl/plperl.c | 8 +-
src/pl/plperl/sql/plperl_call.sql | 36 +++
src/pl/plpgsql/src/pl_comp.c | 88 +++---
src/pl/plpgsql/src/pl_exec.c | 8 +-
src/pl/plpython/Makefile | 1 +
src/pl/plpython/expected/plpython_call.out | 35 +++
src/pl/plpython/plpy_exec.c | 14 +-
src/pl/plpython/plpy_procedure.c | 5 +-
src/pl/plpython/plpy_procedure.h | 3 +-
src/pl/plpython/sql/plpython_call.sql | 41 +++
src/pl/tcl/Makefile | 2 +-
src/pl/tcl/expected/pltcl_call.out | 29 ++
src/pl/tcl/pltcl.c | 13 +-
src/pl/tcl/sql/pltcl_call.sql | 36 +++
src/test/regress/expected/create_procedure.out | 86 ++++++
src/test/regress/expected/object_address.out | 15 +-
src/test/regress/expected/plpgsql.out | 41 +++
src/test/regress/expected/polymorphism.out | 16 +-
src/test/regress/parallel_schedule | 2 +-
src/test/regress/serial_schedule | 1 +
src/test/regress/sql/create_procedure.sql | 79 ++++++
src/test/regress/sql/object_address.sql | 4 +-
src/test/regress/sql/plpgsql.sql | 49 ++++
80 files changed, 2679 insertions(+), 272 deletions(-)
create mode 100644 doc/src/sgml/ref/alter_procedure.sgml
create mode 100644 doc/src/sgml/ref/alter_routine.sgml
create mode 100644 doc/src/sgml/ref/call.sgml
create mode 100644 doc/src/sgml/ref/create_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_routine.sgml
create mode 100644 src/pl/plperl/expected/plperl_call.out
create mode 100644 src/pl/plperl/sql/plperl_call.sql
create mode 100644 src/pl/plpython/expected/plpython_call.out
create mode 100644 src/pl/plpython/sql/plpython_call.sql
create mode 100644 src/pl/tcl/expected/pltcl_call.out
create mode 100644 src/pl/tcl/sql/pltcl_call.sql
create mode 100644 src/test/regress/expected/create_procedure.out
create mode 100644 src/test/regress/sql/create_procedure.sql
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index ef60a58631..f36930c721 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -5241,7 +5241,7 @@ <title><structname>pg_proc</structname> Columns</title>
<entry><structfield>prorettype</structfield></entry>
<entry><type>oid</type></entry>
<entry><literal><link linkend="catalog-pg-type"><structname>pg_type</structname></link>.oid</literal></entry>
- <entry>Data type of the return value</entry>
+ <entry>Data type of the return value, or null for a procedure</entry>
</row>
<row>
diff --git a/doc/src/sgml/ecpg.sgml b/doc/src/sgml/ecpg.sgml
index bc3d080774..f503f2d35f 100644
--- a/doc/src/sgml/ecpg.sgml
+++ b/doc/src/sgml/ecpg.sgml
@@ -4778,7 +4778,9 @@ <title>Setting Callbacks</title>
<term><literal>DO <replaceable>name</replaceable> (<replaceable>args</replaceable>)</literal></term>
<listitem>
<para>
- Call the specified C functions with the specified arguments.
+ Call the specified C functions with the specified arguments. (This
+ use is different from the meaning of <literal>CALL</literal>
+ and <literal>DO</literal> in the normal PostgreSQL grammar.)
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/information_schema.sgml b/doc/src/sgml/information_schema.sgml
index 58c54254d7..ab28acc854 100644
--- a/doc/src/sgml/information_schema.sgml
+++ b/doc/src/sgml/information_schema.sgml
@@ -3972,8 +3972,8 @@ <title><literal>routine_privileges</literal> Columns</title>
<title><literal>routines</literal></title>
<para>
- The view <literal>routines</literal> contains all functions in the
- current database. Only those functions are shown that the current
+ The view <literal>routines</literal> contains all functions and procedures in the
+ current database. Only those functions and procedures are shown that the current
user has access to (by way of being the owner or having some
privilege).
</para>
@@ -4037,8 +4037,8 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>routine_type</literal></entry>
<entry><type>character_data</type></entry>
<entry>
- Always <literal>FUNCTION</literal> (In the future there might
- be other types of routines.)
+ <literal>FUNCTION</literal> for a
+ function, <literal>PROCEDURE</literal> for a procedure
</entry>
</row>
@@ -4087,7 +4087,7 @@ <title><literal>routines</literal> Columns</title>
the view <literal>element_types</literal>), else
<literal>USER-DEFINED</literal> (in that case, the type is
identified in <literal>type_udt_name</literal> and associated
- columns).
+ columns). Null for a procedure.
</entry>
</row>
@@ -4180,7 +4180,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the database that the return data type of the function
- is defined in (always the current database)
+ is defined in (always the current database). Null for a procedure.
</entry>
</row>
@@ -4189,7 +4189,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the schema that the return data type of the function is
- defined in
+ defined in. Null for a procedure.
</entry>
</row>
@@ -4197,7 +4197,7 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>type_udt_name</literal></entry>
<entry><type>sql_identifier</type></entry>
<entry>
- Name of the return data type of the function
+ Name of the return data type of the function. Null for a procedure.
</entry>
</row>
@@ -4314,7 +4314,7 @@ <title><literal>routines</literal> Columns</title>
<entry>
If the function automatically returns null if any of its
arguments are null, then <literal>YES</literal>, else
- <literal>NO</literal>.
+ <literal>NO</literal>. Null for a procedure.
</entry>
</row>
diff --git a/doc/src/sgml/plpgsql.sgml b/doc/src/sgml/plpgsql.sgml
index 7323c2f67d..b3d72b6f95 100644
--- a/doc/src/sgml/plpgsql.sgml
+++ b/doc/src/sgml/plpgsql.sgml
@@ -5244,7 +5244,7 @@ <title>Porting a Function that Creates Another Function from <application>PL/SQL
<para>
Here is how this function would end up in <productname>PostgreSQL</productname>:
<programlisting>
-CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
+CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$
DECLARE
referrer_keys CURSOR IS
SELECT * FROM cs_referrer_keys
diff --git a/doc/src/sgml/ref/allfiles.sgml b/doc/src/sgml/ref/allfiles.sgml
index 01acc2ef9d..22e6893211 100644
--- a/doc/src/sgml/ref/allfiles.sgml
+++ b/doc/src/sgml/ref/allfiles.sgml
@@ -26,8 +26,10 @@
<!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">
@@ -48,6 +50,7 @@
<!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">
@@ -75,6 +78,7 @@
<!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">
@@ -122,8 +126,10 @@
<!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">
diff --git a/doc/src/sgml/ref/alter_extension.sgml b/doc/src/sgml/ref/alter_extension.sgml
index c2b0669c38..d83b0f1dbb 100644
--- a/doc/src/sgml/ref/alter_extension.sgml
+++ b/doc/src/sgml/ref/alter_extension.sgml
@@ -45,6 +45,8 @@
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> |
@@ -170,12 +172,14 @@ <title>Parameters</title>
<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, sequences, text search objects,
+ operator classes, operator families, procedures, routines, sequences, text search objects,
types, and views can be schema-qualified.
</para>
</listitem>
@@ -204,7 +208,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -222,7 +226,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -235,7 +239,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/alter_procedure.sgml b/doc/src/sgml/ref/alter_procedure.sgml
new file mode 100644
index 0000000000..2863eefb07
--- /dev/null
+++ b/doc/src/sgml/ref/alter_procedure.sgml
@@ -0,0 +1,302 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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 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> 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 needed 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.
+ </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>
+ The name of the extension that the procedure is to depend on.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>IMMUTABLE</literal></term>
+ <term><literal>STABLE</literal></term>
+ <term><literal>VOLATILE</literal></term>
+ <term><literal>PARALLEL</literal></term>
+ <term><literal>LEAKPROOF</literal></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
+
+ <listitem>
+ <para>
+ These attributes are accepted for compatibility
+ with <xref linkend="sql-alterfunction"> but are currently not used for
+ procedures.
+ </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>sqrt</literal> for type
+ <type>integer</type> to <literal>square_root</literal>:
+<programlisting>
+ALTER PROCEDURE sqrt(integer) RENAME TO square_root;
+</programlisting>
+ </para>
+
+ <para>
+ To change the owner of the procedure <literal>sqrt</literal> for type
+ <type>integer</type> to <literal>joe</literal>:
+<programlisting>
+ALTER PROCEDURE sqrt(integer) OWNER TO joe;
+</programlisting>
+ </para>
+
+ <para>
+ To change the schema of the procedure <literal>sqrt</literal> for type
+ <type>integer</type> to <literal>maths</literal>:
+<programlisting>
+ALTER PROCEDURE sqrt(integer) SET SCHEMA maths;
+</programlisting>
+ </para>
+
+ <para>
+ To mark the procedure <literal>sqrt</literal> for type
+ <type>integer</type> as being dependent on the extension
+ <literal>mathlib</literal>:
+<programlisting>
+ALTER PROCEDURE sqrt(integer) DEPENDS ON EXTENSION mathlib;
+</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>
+ </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 0000000000..821fab0ddb
--- /dev/null
+++ b/doc/src/sgml/ref/alter_routine.sgml
@@ -0,0 +1,98 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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>
+ </refsect1>
+</refentry>
diff --git a/doc/src/sgml/ref/call.sgml b/doc/src/sgml/ref/call.sgml
new file mode 100644
index 0000000000..a0f7e6d888
--- /dev/null
+++ b/doc/src/sgml/ref/call.sgml
@@ -0,0 +1,97 @@
+<!--
+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>
+ </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 for the procedure call.
+ See <xref linkend="sql-syntax-calling-funcs"> for the full details on
+ function and procedure call syntax, including use of named parameters.
+ </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>
+ </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.
+ </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/comment.sgml b/doc/src/sgml/ref/comment.sgml
index d705792a45..1c2aa2a2b5 100644
--- a/doc/src/sgml/ref/comment.sgml
+++ b/doc/src/sgml/ref/comment.sgml
@@ -46,8 +46,10 @@
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> |
@@ -121,13 +123,15 @@ <title>Parameters</title>
<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 tables,
aggregates, collations, conversions, domains, foreign tables, functions,
- indexes, operators, operator classes, operator families, sequences,
+ indexes, operators, operator classes, operator families, procedures, routines, sequences,
statistics, text search objects, types, and views can be
schema-qualified. When commenting on a column,
<replaceable class="parameter">relation_name</replaceable> must refer
@@ -170,7 +174,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argmode</replaceable></term>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -187,7 +191,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argname</replaceable></term>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -199,7 +203,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argtype</replaceable></term>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
@@ -325,6 +329,7 @@ <title>Examples</title>
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 ROLE my_role IS 'Administration group for finance tables';
COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records';
COMMENT ON SCHEMA my_schema IS 'Departmental data';
diff --git a/doc/src/sgml/ref/create_function.sgml b/doc/src/sgml/ref/create_function.sgml
index 970dc13359..55fa65851f 100644
--- a/doc/src/sgml/ref/create_function.sgml
+++ b/doc/src/sgml/ref/create_function.sgml
@@ -450,7 +450,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
<listitem>
<para>
@@ -466,7 +466,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">result_rows</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
<listitem>
<para>
diff --git a/doc/src/sgml/ref/create_procedure.sgml b/doc/src/sgml/ref/create_procedure.sgml
new file mode 100644
index 0000000000..f1377f19ad
--- /dev/null
+++ b/doc/src/sgml/ref/create_procedure.sgml
@@ -0,0 +1,374 @@
+<!--
+doc/src/sgml/ref/create_procedure.sgml
+-->
+
+<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> } [, ... ]
+ | 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> | = <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>'
+ } ...
+</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
+ with the same input argument types in the same schema. However,
+ 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 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>
+ </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> 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>. 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>IMMUTABLE</literal></term>
+ <term><literal>STABLE</literal></term>
+ <term><literal>VOLATILE</literal></term>
+ <term><literal>LEAKPROOF</literal></term>
+ <term><literal>PARALLEL</literal></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
+
+ <listitem>
+ <para>
+ These attributes are accepted for compatibility
+ with <xref linkend="sql-createfunction"> but are currently not used for
+ procedures.
+ </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>
+ </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>
+ 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 <xref linkend="SQL-LOAD"> 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>
+ </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>
+
+<programlisting>
+CREATE PROCEDURE insert_data(a integer, b integer)
+LANGUAGE SQL
+AS $$
+INSERT INTO tbl VALUES (a);
+INSERT INTO tbl VALUES (b);
+$$;
+</programlisting>
+ </refsect1>
+
+ <refsect1 id="sql-createprocedure-compat">
+ <title>Compatibility</title>
+
+ <para>
+ A <command>CREATE PROCEDURE</command> command is defined in SQL:1999 and later.
+ The <productname>PostgreSQL</productname> version is similar but
+ not fully compatible. The attributes are not portable, neither are the
+ different available languages.
+ </para>
+
+ <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>
+
+ <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>
+ </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/drop_procedure.sgml b/doc/src/sgml/ref/drop_procedure.sgml
new file mode 100644
index 0000000000..0f2484f119
--- /dev/null
+++ b/doc/src/sgml/ref/drop_procedure.sgml
@@ -0,0 +1,161 @@
+<!--
+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 an existing
+ procedure. To execute this command the user must be the
+ owner of the procedure. The argument types to the
+ procedure 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. 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> 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 PROCEDURE</command> does not actually pay
+ any attention to argument names, since only the argument data
+ types are needed 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.
+ </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-examples">
+ <title>Examples</title>
+
+<programlisting>
+DROP PROCEDURE do_db_maintenance();
+</programlisting>
+ </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</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-createprocedure"></member>
+ <member><xref linkend="sql-alterprocedure"></member>
+ <member><xref linkend="sql-dropfunction"></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 0000000000..803b7367a2
--- /dev/null
+++ b/doc/src/sgml/ref/drop_routine.sgml
@@ -0,0 +1,90 @@
+<!--
+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 an existing
+ routine, which can be an aggregate function, a normal function, or a
+ procedure. 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-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</para>
+ </listitem>
+ <listitem>
+ <para>The ability to specify argument modes and names</para>
+ </listitem>
+ <listitem>
+ <para>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>
+ </refsect1>
+
+</refentry>
diff --git a/doc/src/sgml/ref/grant.sgml b/doc/src/sgml/ref/grant.sgml
index 475c85b835..ad416644d9 100644
--- a/doc/src/sgml/ref/grant.sgml
+++ b/doc/src/sgml/ref/grant.sgml
@@ -55,8 +55,8 @@
TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] }
+ 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 class="parameter">schema_name</replaceable> [, ...] }
TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
diff --git a/doc/src/sgml/ref/revoke.sgml b/doc/src/sgml/ref/revoke.sgml
index e3e3f2ffc3..41e359548b 100644
--- a/doc/src/sgml/ref/revoke.sgml
+++ b/doc/src/sgml/ref/revoke.sgml
@@ -70,8 +70,8 @@
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable>schema_name</replaceable> [, ...] }
+ 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 { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
diff --git a/doc/src/sgml/ref/security_label.sgml b/doc/src/sgml/ref/security_label.sgml
index ce5a1c1975..6ff9e7a6b0 100644
--- a/doc/src/sgml/ref/security_label.sgml
+++ b/doc/src/sgml/ref/security_label.sgml
@@ -34,8 +34,10 @@
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> |
@@ -93,10 +95,12 @@ <title>Parameters</title>
<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 tables,
- aggregates, domains, foreign tables, functions, sequences, types, and
+ aggregates, domains, foreign tables, functions, procedures, routines, sequences, types, and
views can be schema-qualified.
</para>
</listitem>
@@ -119,7 +123,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -137,7 +141,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -150,7 +154,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/reference.sgml b/doc/src/sgml/reference.sgml
index 9000b3aaaa..52760ca62a 100644
--- a/doc/src/sgml/reference.sgml
+++ b/doc/src/sgml/reference.sgml
@@ -54,8 +54,10 @@ <title>SQL Commands</title>
&alterOperatorClass;
&alterOperatorFamily;
&alterPolicy;
+ &alterProcedure;
&alterPublication;
&alterRole;
+ &alterRoutine;
&alterRule;
&alterSchema;
&alterSequence;
@@ -76,6 +78,7 @@ <title>SQL Commands</title>
&alterView;
&analyze;
&begin;
+ &call;
&checkpoint;
&close;
&cluster;
@@ -103,6 +106,7 @@ <title>SQL Commands</title>
&createOperatorClass;
&createOperatorFamily;
&createPolicy;
+ &createProcedure;
&createPublication;
&createRole;
&createRule;
@@ -150,8 +154,10 @@ <title>SQL Commands</title>
&dropOperatorFamily;
&dropOwned;
&dropPolicy;
+ &dropProcedure;
&dropPublication;
&dropRole;
+ &dropRoutine;
&dropRule;
&dropSchema;
&dropSequence;
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index ccde66a7dd..0b9d324918 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -482,6 +482,14 @@ ExecuteGrantStmt(GrantStmt *stmt)
all_privileges = ACL_ALL_RIGHTS_NAMESPACE;
errormsg = gettext_noop("invalid privilege type %s for schema");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TABLESPACE:
all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
errormsg = gettext_noop("invalid privilege type %s for tablespace");
@@ -584,6 +592,8 @@ ExecGrantStmt_oids(InternalGrant *istmt)
ExecGrant_ForeignServer(istmt);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
ExecGrant_Function(istmt);
break;
case ACL_OBJECT_LANGUAGE:
@@ -671,7 +681,7 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
Oid funcid;
- funcid = LookupFuncWithArgs(func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, func, false);
objects = lappend_oid(objects, funcid);
}
break;
@@ -709,6 +719,26 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
objects = lappend_oid(objects, oid);
}
break;
+ case ACL_OBJECT_PROCEDURE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid procid;
+
+ procid = LookupFuncWithArgs(OBJECT_PROCEDURE, func, false);
+ objects = lappend_oid(objects, procid);
+ }
+ break;
+ case ACL_OBJECT_ROUTINE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid routid;
+
+ routid = LookupFuncWithArgs(OBJECT_ROUTINE, func, false);
+ objects = lappend_oid(objects, routid);
+ }
+ break;
case ACL_OBJECT_TABLESPACE:
foreach(cell, objnames)
{
@@ -785,8 +815,10 @@ objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
objects = list_concat(objects, objs);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
{
- ScanKeyData key[1];
+ ScanKeyData key[2];
Relation rel;
HeapScanDesc scan;
HeapTuple tuple;
@@ -795,9 +827,21 @@ objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
Anum_pg_proc_pronamespace,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(namespaceId));
+ if (objtype == ACL_OBJECT_FUNCTION)
+ ScanKeyInit(&key[1],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDNE,
+ InvalidOid);
+ else if (objtype == ACL_OBJECT_PROCEDURE)
+ ScanKeyInit(&key[1],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDEQ,
+ InvalidOid);
rel = heap_open(ProcedureRelationId, AccessShareLock);
- scan = heap_beginscan_catalog(rel, 1, key);
+ scan = heap_beginscan_catalog(rel,
+ objtype == ACL_OBJECT_ROUTINE ? 1 : 2,
+ key);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
@@ -955,6 +999,14 @@ ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *s
all_privileges = ACL_ALL_RIGHTS_FUNCTION;
errormsg = gettext_noop("invalid privilege type %s for function");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TYPE:
all_privileges = ACL_ALL_RIGHTS_TYPE;
errormsg = gettext_noop("invalid privilege type %s for type");
@@ -1423,7 +1475,7 @@ RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
istmt.objtype = ACL_OBJECT_TYPE;
break;
case ProcedureRelationId:
- istmt.objtype = ACL_OBJECT_FUNCTION;
+ istmt.objtype = ACL_OBJECT_ROUTINE;
break;
case LanguageRelationId:
istmt.objtype = ACL_OBJECT_LANGUAGE;
diff --git a/src/backend/catalog/information_schema.sql b/src/backend/catalog/information_schema.sql
index 236f6be37e..360725d59a 100644
--- a/src/backend/catalog/information_schema.sql
+++ b/src/backend/catalog/information_schema.sql
@@ -1413,7 +1413,8 @@ CREATE VIEW routines AS
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(n.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
- CAST('FUNCTION' AS character_data) AS routine_type,
+ CAST(CASE WHEN p.prorettype <> 0 THEN 'FUNCTION' ELSE 'PROCEDURE' END
+ AS character_data) AS routine_type,
CAST(null AS sql_identifier) AS module_catalog,
CAST(null AS sql_identifier) AS module_schema,
CAST(null AS sql_identifier) AS module_name,
@@ -1422,7 +1423,8 @@ CREATE VIEW routines AS
CAST(null AS sql_identifier) AS udt_name,
CAST(
- CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
+ CASE WHEN p.prorettype = 0 THEN NULL
+ WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(t.oid, null)
ELSE 'USER-DEFINED' END AS character_data)
AS data_type,
@@ -1440,7 +1442,7 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
- CAST(current_database() AS sql_identifier) AS type_udt_catalog,
+ CAST(CASE WHEN p.prorettype <> 0 THEN current_database() END AS sql_identifier) AS type_udt_catalog,
CAST(nt.nspname AS sql_identifier) AS type_udt_schema,
CAST(t.typname AS sql_identifier) AS type_udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
@@ -1462,7 +1464,8 @@ CREATE VIEW routines AS
CAST('GENERAL' AS character_data) AS parameter_style,
CAST(CASE WHEN p.provolatile = 'i' THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_deterministic,
CAST('MODIFIES' AS character_data) AS sql_data_access,
- CAST(CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_null_call,
+ CAST(CASE WHEN p.prorettype <> 0 THEN
+ CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END END AS yes_or_no) AS is_null_call,
CAST(null AS character_data) AS sql_path,
CAST('YES' AS yes_or_no) AS schema_level_routine,
CAST(0 AS cardinal_number) AS max_dynamic_result_sets,
@@ -1503,13 +1506,15 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS result_cast_maximum_cardinality,
CAST(null AS sql_identifier) AS result_cast_dtd_identifier
- FROM pg_namespace n, pg_proc p, pg_language l,
- pg_type t, pg_namespace nt
+ FROM (pg_namespace n
+ JOIN pg_proc p ON n.oid = p.pronamespace
+ JOIN pg_language l ON p.prolang = l.oid)
+ LEFT JOIN
+ (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid)
+ ON p.prorettype = t.oid
- WHERE n.oid = p.pronamespace AND p.prolang = l.oid
- AND p.prorettype = t.oid AND t.typnamespace = nt.oid
- AND (pg_has_role(p.proowner, 'USAGE')
- OR has_function_privilege(p.oid, 'EXECUTE'));
+ WHERE (pg_has_role(p.proowner, 'USAGE')
+ OR has_function_privilege(p.oid, 'EXECUTE'));
GRANT SELECT ON routines TO PUBLIC;
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c2ad7c675e..55e23c86be 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -566,6 +566,9 @@ static const struct object_type_map
{
"function", OBJECT_FUNCTION
},
+ {
+ "procedure", OBJECT_PROCEDURE
+ },
/* OCLASS_TYPE */
{
"type", OBJECT_TYPE
@@ -884,13 +887,11 @@ get_object_address(ObjectType objtype, Node *object,
address = get_object_address_type(objtype, castNode(TypeName, object), missing_ok);
break;
case OBJECT_AGGREGATE:
- address.classId = ProcedureRelationId;
- address.objectId = LookupAggWithArgs(castNode(ObjectWithArgs, object), missing_ok);
- address.objectSubId = 0;
- break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
address.classId = ProcedureRelationId;
- address.objectId = LookupFuncWithArgs(castNode(ObjectWithArgs, object), missing_ok);
+ address.objectId = LookupFuncWithArgs(objtype, castNode(ObjectWithArgs, object), missing_ok);
address.objectSubId = 0;
break;
case OBJECT_OPERATOR:
@@ -2025,6 +2026,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
*/
if (type == OBJECT_AGGREGATE ||
type == OBJECT_FUNCTION ||
+ type == OBJECT_PROCEDURE ||
+ type == OBJECT_ROUTINE ||
type == OBJECT_OPERATOR ||
type == OBJECT_CAST ||
type == OBJECT_AMOP ||
@@ -2168,6 +2171,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
objnode = (Node *) list_make2(name, args);
break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_AGGREGATE:
case OBJECT_OPERATOR:
{
@@ -2253,6 +2258,8 @@ check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address,
break;
case OBJECT_AGGREGATE:
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
if (!pg_proc_ownercheck(address.objectId, roleid))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString((castNode(ObjectWithArgs, object))->objname));
@@ -4026,6 +4033,8 @@ getProcedureTypeDescription(StringInfo buffer, Oid procid)
if (procForm->proisagg)
appendStringInfoString(buffer, "aggregate");
+ else if (procForm->prorettype == InvalidOid)
+ appendStringInfoString(buffer, "procedure");
else
appendStringInfoString(buffer, "function");
diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c
index 47916cfb54..7d05e4bdb2 100644
--- a/src/backend/catalog/pg_proc.c
+++ b/src/backend/catalog/pg_proc.c
@@ -857,7 +857,8 @@ fmgr_sql_validator(PG_FUNCTION_ARGS)
/* Disallow pseudotype result */
/* except for RECORD, VOID, or polymorphic */
- if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
+ if (proc->prorettype &&
+ get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
proc->prorettype != RECORDOID &&
proc->prorettype != VOIDOID &&
!IsPolymorphicType(proc->prorettype))
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index adc9877e79..2e2ee883e2 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -307,7 +307,7 @@ DefineAggregate(ParseState *pstate, List *name, List *args, bool oldstyle, List
interpret_function_parameter_list(pstate,
args,
InvalidOid,
- true, /* is an aggregate */
+ OBJECT_AGGREGATE,
¶meterTypes,
&allParameterTypes,
¶meterModes,
diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
index 4f8147907c..21e3f1efe1 100644
--- a/src/backend/commands/alter.c
+++ b/src/backend/commands/alter.c
@@ -378,6 +378,8 @@ ExecRenameStmt(RenameStmt *stmt)
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
case OBJECT_LANGUAGE:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -495,6 +497,8 @@ ExecAlterObjectSchemaStmt(AlterObjectSchemaStmt *stmt,
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -842,6 +846,8 @@ ExecAlterOwnerStmt(AlterOwnerStmt *stmt)
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TABLESPACE:
case OBJECT_TSDICTIONARY:
diff --git a/src/backend/commands/dropcmds.c b/src/backend/commands/dropcmds.c
index 2b30677d6f..7e6baa1928 100644
--- a/src/backend/commands/dropcmds.c
+++ b/src/backend/commands/dropcmds.c
@@ -26,6 +26,7 @@
#include "nodes/makefuncs.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
+#include "utils/lsyscache.h"
#include "utils/syscache.h"
@@ -91,21 +92,12 @@ RemoveObjects(DropStmt *stmt)
*/
if (stmt->removeType == OBJECT_FUNCTION)
{
- Oid funcOid = address.objectId;
- HeapTuple tup;
-
- tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
- if (!HeapTupleIsValid(tup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", funcOid);
-
- if (((Form_pg_proc) GETSTRUCT(tup))->proisagg)
+ if (get_func_isagg(address.objectId))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function",
NameListToString(castNode(ObjectWithArgs, object)->objname)),
errhint("Use DROP AGGREGATE to drop aggregate functions.")));
-
- ReleaseSysCache(tup);
}
/* Check permissions. */
@@ -338,6 +330,32 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
}
break;
}
+ case OBJECT_PROCEDURE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("procedure %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
+ case OBJECT_ROUTINE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("routine %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
case OBJECT_AGGREGATE:
{
ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index 938133bbe4..988a04ceae 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -106,8 +106,10 @@ static event_trigger_support_data event_trigger_support[] = {
{"OPERATOR CLASS", true},
{"OPERATOR FAMILY", true},
{"POLICY", true},
+ {"PROCEDURE", true},
{"PUBLICATION", true},
{"ROLE", false},
+ {"ROUTINE", true},
{"RULE", true},
{"SCHEMA", true},
{"SEQUENCE", true},
@@ -1103,8 +1105,10 @@ EventTriggerSupportsObjectType(ObjectType obtype)
case OBJECT_OPERATOR:
case OBJECT_OPFAMILY:
case OBJECT_POLICY:
+ case OBJECT_PROCEDURE:
case OBJECT_PUBLICATION:
case OBJECT_PUBLICATION_REL:
+ case OBJECT_ROUTINE:
case OBJECT_RULE:
case OBJECT_SCHEMA:
case OBJECT_SEQUENCE:
@@ -1215,6 +1219,8 @@ EventTriggerSupportsGrantObjectType(GrantObjectType objtype)
case ACL_OBJECT_LANGUAGE:
case ACL_OBJECT_LARGEOBJECT:
case ACL_OBJECT_NAMESPACE:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
case ACL_OBJECT_TYPE:
return true;
@@ -2243,6 +2249,10 @@ stringify_grantobjtype(GrantObjectType objtype)
return "LARGE OBJECT";
case ACL_OBJECT_NAMESPACE:
return "SCHEMA";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURE";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINE";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACE";
case ACL_OBJECT_TYPE:
@@ -2285,6 +2295,10 @@ stringify_adefprivs_objtype(GrantObjectType objtype)
return "LARGE OBJECTS";
case ACL_OBJECT_NAMESPACE:
return "SCHEMAS";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURES";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINES";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACES";
case ACL_OBJECT_TYPE:
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 7de844b2ca..1f3156d870 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -51,6 +51,8 @@
#include "commands/alter.h"
#include "commands/defrem.h"
#include "commands/proclang.h"
+#include "executor/execdesc.h"
+#include "executor/executor.h"
#include "miscadmin.h"
#include "optimizer/var.h"
#include "parser/parse_coerce.h"
@@ -179,7 +181,7 @@ void
interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
@@ -233,7 +235,7 @@ interpret_function_parameter_list(ParseState *pstate,
errmsg("SQL function cannot accept shell type %s",
TypeNameToString(t))));
/* We don't allow creating aggregates on shell types either */
- else if (is_aggregate)
+ else if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregate cannot accept shell type %s",
@@ -262,16 +264,28 @@ interpret_function_parameter_list(ParseState *pstate,
if (t->setof)
{
- if (is_aggregate)
+ if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregates cannot accept set arguments")));
+ else if (objtype == OBJECT_PROCEDURE)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedures cannot accept set arguments")));
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("functions cannot accept set arguments")));
}
+ if (objtype == OBJECT_PROCEDURE)
+ {
+ if (fp->mode == FUNC_PARAM_OUT || fp->mode == FUNC_PARAM_INOUT)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ (errmsg("procedures cannot have OUT parameters"))));
+ }
+
/* handle input parameters */
if (fp->mode != FUNC_PARAM_OUT && fp->mode != FUNC_PARAM_TABLE)
{
@@ -990,7 +1004,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
interpret_function_parameter_list(pstate,
stmt->parameters,
languageOid,
- false, /* not an aggregate */
+ stmt->is_procedure ? OBJECT_PROCEDURE : OBJECT_FUNCTION,
¶meterTypes,
&allParameterTypes,
¶meterModes,
@@ -999,7 +1013,24 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
&variadicArgType,
&requiredResultType);
- if (stmt->returnType)
+ if (stmt->is_procedure)
+ {
+ Assert(!stmt->returnType);
+
+ prorettype = InvalidOid;
+ returnsSet = false;
+
+ if (isStrict)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure cannot be declared as strict")));
+
+ if (isWindowFunc)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure cannot have WINDOW attribute")));
+ }
+ else if (stmt->returnType)
{
/* explicit RETURNS clause */
compute_return_type(stmt->returnType, languageOid,
@@ -1182,7 +1213,7 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
rel = heap_open(ProcedureRelationId, RowExclusiveLock);
- funcOid = LookupFuncWithArgs(stmt->func, false);
+ funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
if (!HeapTupleIsValid(tup)) /* should not happen */
@@ -1219,6 +1250,11 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
elog(ERROR, "option \"%s\" not recognized", defel->defname);
}
+ if (procForm->prorettype == InvalidOid && strict_item)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure strictness cannot be changed")));
+
if (volatility_item)
procForm->provolatile = interpret_func_volatility(volatility_item);
if (strict_item)
@@ -1472,7 +1508,7 @@ CreateCast(CreateCastStmt *stmt)
{
Form_pg_proc procstruct;
- funcid = LookupFuncWithArgs(stmt->func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
if (!HeapTupleIsValid(tuple))
@@ -1853,7 +1889,7 @@ CreateTransform(CreateTransformStmt *stmt)
*/
if (stmt->fromsql)
{
- fromsqlfuncid = LookupFuncWithArgs(stmt->fromsql, false);
+ fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->fromsql->objname));
@@ -1879,7 +1915,7 @@ CreateTransform(CreateTransformStmt *stmt)
if (stmt->tosql)
{
- tosqlfuncid = LookupFuncWithArgs(stmt->tosql, false);
+ tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->tosql->objname));
@@ -2168,3 +2204,80 @@ ExecuteDoStmt(DoStmt *stmt)
/* execute the inline handler */
OidFunctionCall1(laninline, PointerGetDatum(codeblock));
}
+
+/*
+ * Execute CALL statement
+ */
+void
+ExecuteCallStmt(ParseState *pstate, CallStmt *stmt)
+{
+ List *targs;
+ ListCell *lc;
+ Node *node;
+ FuncExpr *fexpr;
+ int nargs;
+ int i;
+ AclResult aclresult;
+ FmgrInfo flinfo;
+ FunctionCallInfoData fcinfo;
+
+ targs = NIL;
+ foreach(lc, stmt->funccall->args)
+ {
+ targs = lappend(targs, transformExpr(pstate,
+ (Node *) lfirst(lc),
+ EXPR_KIND_CALL));
+ }
+
+ node = ParseFuncOrColumn(pstate,
+ stmt->funccall->funcname,
+ targs,
+ pstate->p_last_srf,
+ stmt->funccall,
+ true,
+ stmt->funccall->location);
+
+ fexpr = castNode(FuncExpr, node);
+
+ aclresult = pg_proc_aclcheck(fexpr->funcid, GetUserId(), ACL_EXECUTE);
+ if (aclresult != ACLCHECK_OK)
+ aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(fexpr->funcid));
+ InvokeFunctionExecuteHook(fexpr->funcid);
+
+ nargs = list_length(fexpr->args);
+
+ /* safety check; see ExecInitFunc() */
+ if (nargs > FUNC_MAX_ARGS)
+ ereport(ERROR,
+ (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
+ errmsg_plural("cannot pass more than %d argument to a procedure",
+ "cannot pass more than %d arguments to a procedure",
+ FUNC_MAX_ARGS,
+ FUNC_MAX_ARGS)));
+
+ fmgr_info(fexpr->funcid, &flinfo);
+ InitFunctionCallInfoData(fcinfo, &flinfo, nargs, fexpr->inputcollid, NULL, NULL);
+
+ i = 0;
+ foreach (lc, fexpr->args)
+ {
+ EState *estate;
+ ExprState *exprstate;
+ ExprContext *econtext;
+ Datum val;
+ bool isnull;
+
+ estate = CreateExecutorState();
+ exprstate = ExecPrepareExpr(lfirst(lc), estate);
+ econtext = CreateStandaloneExprContext();
+ val = ExecEvalExprSwitchContext(exprstate, econtext, &isnull);
+ FreeExecutorState(estate);
+
+ fcinfo.arg[i] = val;
+ fcinfo.argnull[i] = isnull;
+
+ i++;
+ }
+
+ FunctionCallInvoke(&fcinfo);
+}
diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c
index d23e6d6f25..76d500462f 100644
--- a/src/backend/commands/opclasscmds.c
+++ b/src/backend/commands/opclasscmds.c
@@ -520,7 +520,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
@@ -894,7 +894,7 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 98eb777421..564ccb004f 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -390,6 +390,7 @@ sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
list_make1(param),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
@@ -658,7 +659,8 @@ init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
fcache->rettype = rettype;
/* Fetch the typlen and byval info for the result type */
- get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
+ if (rettype)
+ get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
/* Remember whether we're returning setof something */
fcache->returnsSet = procedureStruct->proretset;
@@ -1322,7 +1324,7 @@ fmgr_sql(PG_FUNCTION_ARGS)
else
{
/* Should only get here for VOID functions */
- Assert(fcache->rettype == VOIDOID);
+ Assert(fcache->rettype == InvalidOid || fcache->rettype == VOIDOID);
fcinfo->isnull = true;
result = (Datum) 0;
}
@@ -1546,7 +1548,10 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
if (modifyTargetList)
*modifyTargetList = false; /* initialize for no change */
if (junkFilter)
- *junkFilter = NULL; /* initialize in case of VOID result */
+ *junkFilter = NULL; /* initialize in case of procedure/VOID result */
+
+ if (!rettype)
+ return false;
/*
* Find the last canSetTag query in the list. This isn't necessarily the
@@ -1591,7 +1596,7 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
else
{
/* Empty function body, or last statement is a utility command */
- if (rettype != VOIDOID)
+ if (rettype && rettype != VOIDOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("return type mismatch in function declared to return %s",
diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
index c1a83ca909..7acee32256 100644
--- a/src/backend/nodes/copyfuncs.c
+++ b/src/backend/nodes/copyfuncs.c
@@ -3208,6 +3208,16 @@ _copyClosePortalStmt(const ClosePortalStmt *from)
return newnode;
}
+static CallStmt *
+_copyCallStmt(const CallStmt *from)
+{
+ CallStmt *newnode = makeNode(CallStmt);
+
+ COPY_NODE_FIELD(funccall);
+
+ return newnode;
+}
+
static ClusterStmt *
_copyClusterStmt(const ClusterStmt *from)
{
@@ -3409,6 +3419,7 @@ _copyCreateFunctionStmt(const CreateFunctionStmt *from)
COPY_NODE_FIELD(funcname);
COPY_NODE_FIELD(parameters);
COPY_NODE_FIELD(returnType);
+ COPY_SCALAR_FIELD(is_procedure);
COPY_NODE_FIELD(options);
COPY_NODE_FIELD(withClause);
@@ -3433,6 +3444,7 @@ _copyAlterFunctionStmt(const AlterFunctionStmt *from)
{
AlterFunctionStmt *newnode = makeNode(AlterFunctionStmt);
+ COPY_SCALAR_FIELD(objtype);
COPY_NODE_FIELD(func);
COPY_NODE_FIELD(actions);
@@ -5100,6 +5112,9 @@ copyObjectImpl(const void *from)
case T_ClosePortalStmt:
retval = _copyClosePortalStmt(from);
break;
+ case T_CallStmt:
+ retval = _copyCallStmt(from);
+ break;
case T_ClusterStmt:
retval = _copyClusterStmt(from);
break;
diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c
index 7a700018e7..134a974373 100644
--- a/src/backend/nodes/equalfuncs.c
+++ b/src/backend/nodes/equalfuncs.c
@@ -1201,6 +1201,14 @@ _equalClosePortalStmt(const ClosePortalStmt *a, const ClosePortalStmt *b)
return true;
}
+static bool
+_equalCallStmt(const CallStmt *a, const CallStmt *b)
+{
+ COMPARE_NODE_FIELD(funccall);
+
+ return true;
+}
+
static bool
_equalClusterStmt(const ClusterStmt *a, const ClusterStmt *b)
{
@@ -1364,6 +1372,7 @@ _equalCreateFunctionStmt(const CreateFunctionStmt *a, const CreateFunctionStmt *
COMPARE_NODE_FIELD(funcname);
COMPARE_NODE_FIELD(parameters);
COMPARE_NODE_FIELD(returnType);
+ COMPARE_SCALAR_FIELD(is_procedure);
COMPARE_NODE_FIELD(options);
COMPARE_NODE_FIELD(withClause);
@@ -1384,6 +1393,7 @@ _equalFunctionParameter(const FunctionParameter *a, const FunctionParameter *b)
static bool
_equalAlterFunctionStmt(const AlterFunctionStmt *a, const AlterFunctionStmt *b)
{
+ COMPARE_SCALAR_FIELD(objtype);
COMPARE_NODE_FIELD(func);
COMPARE_NODE_FIELD(actions);
@@ -3244,6 +3254,9 @@ equal(const void *a, const void *b)
case T_ClosePortalStmt:
retval = _equalClosePortalStmt(a, b);
break;
+ case T_CallStmt:
+ retval = _equalCallStmt(a, b);
+ break;
case T_ClusterStmt:
retval = _equalClusterStmt(a, b);
break;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 652843a146..d0855e6287 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -4379,6 +4379,7 @@ inline_function(Oid funcid, Oid result_type, Oid result_collid,
if (funcform->prolang != SQLlanguageId ||
funcform->prosecdef ||
funcform->proretset ||
+ funcform->prorettype == InvalidOid ||
funcform->prorettype == RECORDOID ||
!heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
funcform->pronargs != list_length(args))
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 4c83a63f7d..bf460ef83b 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -253,7 +253,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
AlterCompositeTypeStmt AlterUserMappingStmt
AlterRoleStmt AlterRoleSetStmt AlterPolicyStmt
AlterDefaultPrivilegesStmt DefACLAction
- AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
+ AnalyzeStmt CallStmt ClosePortalStmt ClusterStmt CommentStmt
ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
CreateDomainStmt CreateExtensionStmt CreateGroupStmt CreateOpClassStmt
CreateOpFamilyStmt AlterOpFamilyStmt CreatePLangStmt
@@ -610,7 +610,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
BOOLEAN_P BOTH BY
- CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
+ CACHE CALL CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
CLUSTER COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
@@ -659,14 +659,14 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
PARALLEL PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
- PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROGRAM PUBLICATION
+ PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
QUOTE
RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
- ROW ROWS RULE
+ ROUTINE ROUTINES ROW ROWS RULE
SAVEPOINT SCHEMA SCHEMAS SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
@@ -844,6 +844,7 @@ stmt :
| AlterTSDictionaryStmt
| AlterUserMappingStmt
| AnalyzeStmt
+ | CallStmt
| CheckPointStmt
| ClosePortalStmt
| ClusterStmt
@@ -939,6 +940,20 @@ stmt :
{ $$ = NULL; }
;
+/*****************************************************************************
+ *
+ * CALL statement
+ *
+ *****************************************************************************/
+
+CallStmt: CALL func_application
+ {
+ CallStmt *n = makeNode(CallStmt);
+ n->funccall = castNode(FuncCall, $2);
+ $$ = (Node *)n;
+ }
+ ;
+
/*****************************************************************************
*
* Create a new Postgres DBMS role
@@ -4482,6 +4497,24 @@ AlterExtensionContentsStmt:
n->object = (Node *) lcons(makeString($9), $7);
$$ = (Node *)n;
}
+ | ALTER EXTENSION name add_drop PROCEDURE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
+ | ALTER EXTENSION name add_drop ROUTINE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
| ALTER EXTENSION name add_drop SCHEMA name
{
AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
@@ -6364,6 +6397,22 @@ CommentStmt:
n->comment = $8;
$$ = (Node *) n;
}
+ | COMMENT ON PROCEDURE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
+ | COMMENT ON ROUTINE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
| COMMENT ON RULE name ON any_name IS comment_text
{
CommentStmt *n = makeNode(CommentStmt);
@@ -6542,6 +6591,26 @@ SecLabelStmt:
n->label = $9;
$$ = (Node *) n;
}
+ | SECURITY LABEL opt_provider ON PROCEDURE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
+ | SECURITY LABEL opt_provider ON ROUTINE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
;
opt_provider: FOR NonReservedWord_or_Sconst { $$ = $2; }
@@ -6905,6 +6974,22 @@ privilege_target:
n->objs = $2;
$$ = n;
}
+ | PROCEDURE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $2;
+ $$ = n;
+ }
+ | ROUTINE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $2;
+ $$ = n;
+ }
| DATABASE name_list
{
PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
@@ -6985,6 +7070,22 @@ privilege_target:
n->objs = $5;
$$ = n;
}
+ | ALL PROCEDURES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $5;
+ $$ = n;
+ }
+ | ALL ROUTINES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $5;
+ $$ = n;
+ }
;
@@ -7341,6 +7442,18 @@ CreateFunctionStmt:
n->withClause = $7;
$$ = (Node *)n;
}
+ | CREATE opt_or_replace PROCEDURE func_name func_args_with_defaults
+ createfunc_opt_list
+ {
+ CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
+ n->replace = $2;
+ n->funcname = $4;
+ n->parameters = $5;
+ n->returnType = NULL;
+ n->is_procedure = true;
+ n->options = $6;
+ $$ = (Node *)n;
+ }
;
opt_or_replace:
@@ -7758,7 +7871,7 @@ table_func_column_list:
;
/*****************************************************************************
- * ALTER FUNCTION
+ * ALTER FUNCTION / ALTER PROCEDURE / ALTER ROUTINE
*
* RENAME and OWNER subcommands are already provided by the generic
* ALTER infrastructure, here we just specify alterations that can
@@ -7769,6 +7882,23 @@ AlterFunctionStmt:
ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
{
AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_FUNCTION;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER PROCEDURE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER ROUTINE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_ROUTINE;
n->func = $3;
n->actions = $4;
$$ = (Node *) n;
@@ -7793,6 +7923,8 @@ opt_restrict:
* QUERY:
*
* DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP PROCEDURE procname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP ROUTINE routname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
* DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
* DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
*
@@ -7819,6 +7951,46 @@ RemoveFuncStmt:
n->concurrent = false;
$$ = (Node *)n;
}
+ | DROP PROCEDURE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP PROCEDURE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
;
RemoveAggrStmt:
@@ -8276,6 +8448,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = true;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER PUBLICATION name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8285,6 +8466,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER ROUTINE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8664,6 +8854,22 @@ AlterObjectDependsStmt:
n->extname = makeString($7);
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
| ALTER TRIGGER name ON qualified_name DEPENDS ON EXTENSION name
{
AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
@@ -8779,6 +8985,24 @@ AlterObjectSchemaStmt:
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER TABLE relation_expr SET SCHEMA name
{
AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
@@ -9054,6 +9278,22 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec
n->newowner = $9;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name OWNER TO RoleSpec
{
AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
@@ -14617,6 +14857,7 @@ unreserved_keyword:
| BEGIN_P
| BY
| CACHE
+ | CALL
| CALLED
| CASCADE
| CASCADED
@@ -14776,6 +15017,7 @@ unreserved_keyword:
| PRIVILEGES
| PROCEDURAL
| PROCEDURE
+ | PROCEDURES
| PROGRAM
| PUBLICATION
| QUOTE
@@ -14802,6 +15044,8 @@ unreserved_keyword:
| ROLE
| ROLLBACK
| ROLLUP
+ | ROUTINE
+ | ROUTINES
| ROWS
| RULE
| SAVEPOINT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 64111f315e..4c4f4cdc3d 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -508,6 +508,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
break;
+ case EXPR_KIND_CALL:
+ if (isAgg)
+ err = _("aggregate functions are not allowed in CALL arguments");
+ else
+ err = _("grouping operations are not allowed in CALL arguments");
+
+ break;
+
/*
* There is intentionally no default: case here, so that the
* compiler will warn if we add a new ParseExprKind without
@@ -883,6 +891,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("window functions are not allowed in partition key expression");
break;
+ case EXPR_KIND_CALL:
+ err = _("window functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 1aaa5244e6..951582a24f 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -480,6 +480,7 @@ transformIndirection(ParseState *pstate, A_Indirection *ind)
list_make1(result),
last_srf,
NULL,
+ false,
location);
if (newresult == NULL)
unknown_attribute(pstate, result, strVal(n), location);
@@ -629,6 +630,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -676,6 +678,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -736,6 +739,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -1477,6 +1481,7 @@ transformFuncCall(ParseState *pstate, FuncCall *fn)
targs,
last_srf,
fn,
+ false,
fn->location);
}
@@ -1812,6 +1817,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_RETURNING:
case EXPR_KIND_VALUES:
case EXPR_KIND_VALUES_SINGLE:
+ case EXPR_KIND_CALL:
/* okay */
break;
case EXPR_KIND_CHECK_CONSTRAINT:
@@ -3462,6 +3468,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "WHEN";
case EXPR_KIND_PARTITION_EXPRESSION:
return "PARTITION BY";
+ case EXPR_KIND_CALL:
+ return "CALL";
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index fc0d6bc2f2..500769b23c 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -71,7 +71,7 @@ static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
*/
Node *
ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location)
+ Node *last_srf, FuncCall *fn, bool proc_call, int location)
{
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
@@ -263,7 +263,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
actual_arg_types[0], rettype, -1,
COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
}
- else if (fdresult == FUNCDETAIL_NORMAL)
+ else if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
/*
* Normal function found; was there anything indicating it must be an
@@ -306,6 +306,26 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("OVER specified, but %s is not a window function nor an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_NORMAL && proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is not a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a function, use SELECT."),
+ parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a procedure, use CALL."),
+ parser_errposition(pstate, location)));
}
else if (fdresult == FUNCDETAIL_AGGREGATE)
{
@@ -635,7 +655,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
check_srf_call_placement(pstate, last_srf, location);
/* build the appropriate output structure */
- if (fdresult == FUNCDETAIL_NORMAL)
+ if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
FuncExpr *funcexpr = makeNode(FuncExpr);
@@ -1589,6 +1609,8 @@ func_get_detail(List *funcname,
result = FUNCDETAIL_AGGREGATE;
else if (pform->proiswindow)
result = FUNCDETAIL_WINDOWFUNC;
+ else if (pform->prorettype == InvalidOid)
+ result = FUNCDETAIL_PROCEDURE;
else
result = FUNCDETAIL_NORMAL;
ReleaseSysCache(ftup);
@@ -1984,16 +2006,28 @@ LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
/*
* LookupFuncWithArgs
- * Like LookupFuncName, but the argument types are specified by a
- * ObjectWithArgs node.
+ *
+ * Like LookupFuncName, but the argument types are specified by a
+ * ObjectWithArgs node. Also, this function can check whether the result is a
+ * function, procedure, or aggregate, based on the objtype argument. Pass
+ * OBJECT_ROUTINE to accept any of them.
+ *
+ * For historical reasons, we also accept aggregates when looking for a
+ * function.
*/
Oid
-LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
+LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
{
Oid argoids[FUNC_MAX_ARGS];
int argcount;
int i;
ListCell *args_item;
+ Oid oid;
+
+ Assert(objtype == OBJECT_AGGREGATE ||
+ objtype == OBJECT_FUNCTION ||
+ objtype == OBJECT_PROCEDURE ||
+ objtype == OBJECT_ROUTINE);
argcount = list_length(func->objargs);
if (argcount > FUNC_MAX_ARGS)
@@ -2013,90 +2047,100 @@ LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
args_item = lnext(args_item);
}
- return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
-}
-
-/*
- * LookupAggWithArgs
- * Find an aggregate function from a given ObjectWithArgs node.
- *
- * This is almost like LookupFuncWithArgs, but the error messages refer
- * to aggregates rather than plain functions, and we verify that the found
- * function really is an aggregate.
- */
-Oid
-LookupAggWithArgs(ObjectWithArgs *agg, bool noError)
-{
- Oid argoids[FUNC_MAX_ARGS];
- int argcount;
- int i;
- ListCell *lc;
- Oid oid;
- HeapTuple ftup;
- Form_pg_proc pform;
-
- argcount = list_length(agg->objargs);
- if (argcount > FUNC_MAX_ARGS)
- ereport(ERROR,
- (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
- errmsg_plural("functions cannot have more than %d argument",
- "functions cannot have more than %d arguments",
- FUNC_MAX_ARGS,
- FUNC_MAX_ARGS)));
+ /*
+ * When looking for a function or routine, we pass noError through to
+ * LookupFuncName and let it make any error messages. Otherwise, we make
+ * our own errors for the aggregate and procedure cases.
+ */
+ oid = LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids,
+ (objtype == OBJECT_FUNCTION || objtype == OBJECT_ROUTINE) ? noError : true);
- i = 0;
- foreach(lc, agg->objargs)
+ if (objtype == OBJECT_FUNCTION)
{
- TypeName *t = (TypeName *) lfirst(lc);
-
- argoids[i] = LookupTypeNameOid(NULL, t, noError);
- i++;
+ /* Make sure it's a function, not a procedure */
+ if (oid && get_func_rettype(oid) == InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a function",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
}
-
- oid = LookupFuncName(agg->objname, argcount, argoids, true);
-
- if (!OidIsValid(oid))
+ else if (objtype == OBJECT_PROCEDURE)
{
- if (noError)
- return InvalidOid;
- if (argcount == 0)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s(*) does not exist",
- NameListToString(agg->objname))));
- else
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a procedure named \"%s\"",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("procedure %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+
+ /* Make sure it's a procedure */
+ if (get_func_rettype(oid) != InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s does not exist",
- func_signature_string(agg->objname, argcount,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a procedure",
+ func_signature_string(func->objname, argcount,
NIL, argoids))));
+ }
}
-
- /* Make sure it's an aggregate */
- ftup = SearchSysCache1(PROCOID, ObjectIdGetDatum(oid));
- if (!HeapTupleIsValid(ftup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", oid);
- pform = (Form_pg_proc) GETSTRUCT(ftup);
-
- if (!pform->proisagg)
+ else if (objtype == OBJECT_AGGREGATE)
{
- ReleaseSysCache(ftup);
- if (noError)
- return InvalidOid;
- /* we do not use the (*) notation for functions... */
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function %s is not an aggregate",
- func_signature_string(agg->objname, argcount,
- NIL, argoids))));
- }
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a aggregate named \"%s\"",
+ NameListToString(func->objname))));
+ else if (argcount == 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s(*) does not exist",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
- ReleaseSysCache(ftup);
+ /* Make sure it's an aggregate */
+ if (!get_func_isagg(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ /* we do not use the (*) notation for functions... */
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("function %s is not an aggregate",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+ }
return oid;
}
-
/*
* check_srf_call_placement
* Verify that a set-returning function is called in a valid place,
@@ -2236,6 +2280,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("set-returning functions are not allowed in partition key expressions");
break;
+ case EXPR_KIND_CALL:
+ err = _("set-returning functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 82a707af7b..4da1f8f643 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -657,6 +657,10 @@ standard_ProcessUtility(PlannedStmt *pstmt,
}
break;
+ case T_CallStmt:
+ ExecuteCallStmt(pstate, castNode(CallStmt, parsetree));
+ break;
+
case T_ClusterStmt:
/* we choose to allow this during "read only" transactions */
PreventCommandDuringRecovery("CLUSTER");
@@ -1957,9 +1961,15 @@ AlterObjectTypeCommandTag(ObjectType objtype)
case OBJECT_POLICY:
tag = "ALTER POLICY";
break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
case OBJECT_ROLE:
tag = "ALTER ROLE";
break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
case OBJECT_RULE:
tag = "ALTER RULE";
break;
@@ -2261,6 +2271,12 @@ CreateCommandTag(Node *parsetree)
case OBJECT_FUNCTION:
tag = "DROP FUNCTION";
break;
+ case OBJECT_PROCEDURE:
+ tag = "DROP PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "DROP ROUTINE";
+ break;
case OBJECT_AGGREGATE:
tag = "DROP AGGREGATE";
break;
@@ -2359,7 +2375,20 @@ CreateCommandTag(Node *parsetree)
break;
case T_AlterFunctionStmt:
- tag = "ALTER FUNCTION";
+ switch (((AlterFunctionStmt *) parsetree)->objtype)
+ {
+ case OBJECT_FUNCTION:
+ tag = "ALTER FUNCTION";
+ break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
+ default:
+ tag = "???";
+ }
break;
case T_GrantStmt:
@@ -2438,7 +2467,10 @@ CreateCommandTag(Node *parsetree)
break;
case T_CreateFunctionStmt:
- tag = "CREATE FUNCTION";
+ if (((CreateFunctionStmt *) parsetree)->is_procedure)
+ tag = "CREATE PROCEDURE";
+ else
+ tag = "CREATE FUNCTION";
break;
case T_IndexStmt:
@@ -2493,6 +2525,10 @@ CreateCommandTag(Node *parsetree)
tag = "LOAD";
break;
+ case T_CallStmt:
+ tag = "CALL";
+ break;
+
case T_ClusterStmt:
tag = "CLUSTER";
break;
@@ -3116,6 +3152,10 @@ GetCommandLogLevel(Node *parsetree)
lev = LOGSTMT_ALL;
break;
+ case T_CallStmt:
+ lev = LOGSTMT_ALL;
+ break;
+
case T_ClusterStmt:
lev = LOGSTMT_DDL;
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index b1e70a0d19..ca5d117c02 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -2674,6 +2674,12 @@ pg_get_function_result(PG_FUNCTION_ARGS)
if (!HeapTupleIsValid(proctup))
PG_RETURN_NULL();
+ if (((Form_pg_proc) GETSTRUCT(proctup))->prorettype == InvalidOid)
+ {
+ ReleaseSysCache(proctup);
+ PG_RETURN_NULL();
+ }
+
initStringInfo(&buf);
print_function_rettype(&buf, proctup);
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index 48961e31aa..c4e2d33c8d 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -1614,6 +1614,25 @@ func_parallel(Oid funcid)
return result;
}
+/*
+ * get_func_isagg
+ * Given procedure id, return the function's proisagg field.
+ */
+bool
+get_func_isagg(Oid funcid)
+{
+ HeapTuple tp;
+ bool result;
+
+ tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
+ if (!HeapTupleIsValid(tp))
+ elog(ERROR, "cache lookup failed for function %u", funcid);
+
+ result = ((Form_pg_proc) GETSTRUCT(tp))->proisagg;
+ ReleaseSysCache(tp);
+ return result;
+}
+
/*
* get_func_leakproof
* Given procedure id, return the function's leakproof field.
diff --git a/src/bin/pg_dump/dumputils.c b/src/bin/pg_dump/dumputils.c
index e4c95feb63..c0ae4c4e1a 100644
--- a/src/bin/pg_dump/dumputils.c
+++ b/src/bin/pg_dump/dumputils.c
@@ -33,7 +33,7 @@ static void AddAcl(PQExpBuffer aclbuf, const char *keyword,
* name: the object name, in the form to use in the commands (already quoted)
* subname: the sub-object name, if any (already quoted); NULL if none
* type: the object type (as seen in GRANT command: must be one of
- * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
+ * TABLE, SEQUENCE, FUNCTION, PROCEDURE, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
* FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT)
* acls: the ACL string fetched from the database
* racls: the ACL string of any initial-but-now-revoked privileges
@@ -524,6 +524,9 @@ do { \
else if (strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "FUNCTIONS") == 0)
CONVERT_PRIV('X', "EXECUTE");
+ else if (strcmp(type, "PROCEDURE") == 0 ||
+ strcmp(type, "PROCEDURES") == 0)
+ CONVERT_PRIV('X', "EXECUTE");
else if (strcmp(type, "LANGUAGE") == 0)
CONVERT_PRIV('U', "USAGE");
else if (strcmp(type, "SCHEMA") == 0 ||
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index ec2fa8b9b9..41741aefbc 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -2889,7 +2889,8 @@ _tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt)
if (ropt->indexNames.head != NULL && (!(simple_string_list_member(&ropt->indexNames, te->tag))))
return 0;
}
- else if (strcmp(te->desc, "FUNCTION") == 0)
+ else if (strcmp(te->desc, "FUNCTION") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0)
{
if (!ropt->selFunction)
return 0;
@@ -3388,7 +3389,8 @@ _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "OPERATOR") == 0 ||
strcmp(type, "OPERATOR CLASS") == 0 ||
- strcmp(type, "OPERATOR FAMILY") == 0)
+ strcmp(type, "OPERATOR FAMILY") == 0 ||
+ strcmp(type, "PROCEDURE") == 0)
{
/* Chop "DROP " off the front and make a modifiable copy */
char *first = pg_strdup(te->dropStmt + 5);
@@ -3560,6 +3562,7 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData)
strcmp(te->desc, "OPERATOR") == 0 ||
strcmp(te->desc, "OPERATOR CLASS") == 0 ||
strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0 ||
strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
strcmp(te->desc, "SCHEMA") == 0 ||
strcmp(te->desc, "EVENT TRIGGER") == 0 ||
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 8733426e8a..cbf3f1656d 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -11341,6 +11341,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char *funcargs;
char *funciargs;
char *funcresult;
+ bool is_procedure;
char *proallargtypes;
char *proargmodes;
char *proargnames;
@@ -11362,6 +11363,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char **argnames = NULL;
char **configitems = NULL;
int nconfigitems = 0;
+ const char *keyword;
int i;
/* Skip if not to be dumped */
@@ -11505,7 +11507,11 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
{
funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
- funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
+ is_procedure = PQgetisnull(res, 0, PQfnumber(res, "funcresult"));
+ if (is_procedure)
+ funcresult = NULL;
+ else
+ funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
proallargtypes = proargmodes = proargnames = NULL;
}
else
@@ -11514,6 +11520,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
funcargs = funciargs = funcresult = NULL;
+ is_procedure = false;
}
if (PQfnumber(res, "protrftypes") != -1)
protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
@@ -11645,22 +11652,29 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
funcsig_tag = format_function_signature(fout, finfo, false);
+ keyword = is_procedure ? "PROCEDURE" : "FUNCTION";
+
/*
* DROP must be fully qualified in case same name appears in pg_catalog
*/
- appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
+ appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
+ keyword,
fmtId(finfo->dobj.namespace->dobj.name),
funcsig);
- appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
+ appendPQExpBuffer(q, "CREATE %s %s",
+ keyword,
+ funcfullsig ? funcfullsig :
funcsig);
- if (funcresult)
- appendPQExpBuffer(q, "RETURNS %s", funcresult);
+ if (is_procedure)
+ ;
+ else if (funcresult)
+ appendPQExpBuffer(q, " RETURNS %s", funcresult);
else
{
rettypename = getFormattedTypeName(fout, finfo->prorettype,
zeroAsOpaque);
- appendPQExpBuffer(q, "RETURNS %s%s",
+ appendPQExpBuffer(q, " RETURNS %s%s",
(proretset[0] == 't') ? "SETOF " : "",
rettypename);
free(rettypename);
@@ -11767,7 +11781,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
appendPQExpBuffer(q, "\n %s;\n", asPart->data);
- appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
+ appendPQExpBuffer(labelq, "%s %s", keyword, funcsig);
if (dopt->binary_upgrade)
binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
@@ -11778,7 +11792,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.namespace->dobj.name,
NULL,
finfo->rolname, false,
- "FUNCTION", SECTION_PRE_DATA,
+ keyword, SECTION_PRE_DATA,
q->data, delqry->data, NULL,
NULL, 0,
NULL, NULL);
@@ -11795,7 +11809,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.catId, 0, finfo->dobj.dumpId);
if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
- dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
+ dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
funcsig, NULL, funcsig_tag,
finfo->dobj.namespace->dobj.name,
finfo->rolname, finfo->proacl, finfo->rproacl,
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index fa3b56a426..7cf9bdadb2 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -3654,6 +3654,44 @@
section_data => 1,
section_post_data => 1, }, },
+ 'CREATE PROCEDURE dump_test.ptest1' => {
+ all_runs => 1,
+ create_order => 41,
+ create_sql => 'CREATE PROCEDURE dump_test.ptest1(a int)
+ LANGUAGE SQL AS $$ INSERT INTO dump_test.test_table (col1) VALUES (a) $$;',
+ regexp => qr/^
+ \QCREATE PROCEDURE ptest1(a integer)\E
+ \n\s+\QLANGUAGE sql\E
+ \n\s+AS\ \$\$\Q INSERT INTO dump_test.test_table (col1) VALUES (a) \E\$\$;
+ /xm,
+ like => {
+ binary_upgrade => 1,
+ clean => 1,
+ clean_if_exists => 1,
+ createdb => 1,
+ defaults => 1,
+ exclude_test_table => 1,
+ exclude_test_table_data => 1,
+ no_blobs => 1,
+ no_privs => 1,
+ no_owner => 1,
+ only_dump_test_schema => 1,
+ pg_dumpall_dbprivs => 1,
+ schema_only => 1,
+ section_pre_data => 1,
+ test_schema_plus_blobs => 1,
+ with_oids => 1, },
+ unlike => {
+ column_inserts => 1,
+ data_only => 1,
+ exclude_dump_test_schema => 1,
+ only_dump_test_table => 1,
+ pg_dumpall_globals => 1,
+ pg_dumpall_globals_clean => 1,
+ role => 1,
+ section_data => 1,
+ section_post_data => 1, }, },
+
'CREATE TYPE dump_test.int42 populated' => {
all_runs => 1,
create_order => 42,
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 638275ca2f..7116d67694 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -353,6 +353,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
" CASE\n"
" WHEN p.proisagg THEN '%s'\n"
" WHEN p.proiswindow THEN '%s'\n"
+ " WHEN p.prorettype = 0 THEN '%s'\n"
" WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
" ELSE '%s'\n"
" END as \"%s\"",
@@ -361,8 +362,9 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("window"),
+ gettext_noop("proc"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else if (pset.sversion >= 80100)
appendPQExpBuffer(&buf,
@@ -407,7 +409,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else
appendPQExpBuffer(&buf,
@@ -424,7 +426,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
if (verbose)
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index a09c49d6cf..b4f74d0a08 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -397,7 +397,7 @@ static const SchemaQuery Query_for_list_of_functions = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
- NULL,
+ "p.prorettype <> 0",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
@@ -423,6 +423,36 @@ static const SchemaQuery Query_for_list_of_indexes = {
NULL
};
+static const SchemaQuery Query_for_list_of_procedures = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ "p.prorettype = 0",
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_routines = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
static const SchemaQuery Query_for_list_of_sequences = {
/* catname */
"pg_catalog.pg_class c",
@@ -1032,8 +1062,10 @@ static const pgsql_thing_t words_after_create[] = {
{"OWNED", NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
{"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
{"POLICY", NULL, NULL},
+ {"PROCEDURE", NULL, &Query_for_list_of_procedures},
{"PUBLICATION", Query_for_list_of_publications},
{"ROLE", Query_for_list_of_roles},
+ {"ROUTINE", NULL, &Query_for_list_of_routines, THING_NO_CREATE},
{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
{"SCHEMA", Query_for_list_of_schemas},
{"SEQUENCE", NULL, &Query_for_list_of_sequences},
@@ -1407,7 +1439,7 @@ psql_completion(const char *text, int start, int end)
/* Known command-starting keywords. */
static const char *const sql_commands[] = {
- "ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER",
+ "ABORT", "ALTER", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
"COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
"DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
"FETCH", "GRANT", "IMPORT", "INSERT", "LISTEN", "LOAD", "LOCK",
@@ -1520,11 +1552,11 @@ psql_completion(const char *text, int start, int end)
/* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
else if (TailMatches7("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
COMPLETE_WITH_CONST("SET TABLESPACE");
- /* ALTER AGGREGATE,FUNCTION <name> */
- else if (Matches3("ALTER", "AGGREGATE|FUNCTION", MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> */
+ else if (Matches3("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- /* ALTER AGGREGATE,FUNCTION <name> (...) */
- else if (Matches4("ALTER", "AGGREGATE|FUNCTION", MatchAny, MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> (...) */
+ else if (Matches4("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny))
{
if (ends_with(prev_wd, ')'))
COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
@@ -2145,6 +2177,11 @@ psql_completion(const char *text, int start, int end)
/* ROLLBACK */
else if (Matches1("ROLLBACK"))
COMPLETE_WITH_LIST4("WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
+/* CALL */
+ else if (Matches1("CALL"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (Matches2("CALL", MatchAny))
+ COMPLETE_WITH_CONST("(");
/* CLUSTER */
else if (Matches1("CLUSTER"))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, "UNION SELECT 'VERBOSE'");
@@ -2176,6 +2213,7 @@ psql_completion(const char *text, int start, int end)
"SERVER", "INDEX", "LANGUAGE", "POLICY", "PUBLICATION", "RULE",
"SCHEMA", "SEQUENCE", "STATISTICS", "SUBSCRIPTION",
"TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
+ "PROCEDURE", "ROUTINE",
"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
"TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
@@ -2685,7 +2723,7 @@ psql_completion(const char *text, int start, int end)
"COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
MatchAny) ||
Matches4("DROP", "ACCESS", "METHOD", MatchAny) ||
- (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, MatchAny) &&
+ (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
ends_with(prev_wd, ')')) ||
Matches4("DROP", "EVENT", "TRIGGER", MatchAny) ||
Matches5("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
@@ -2694,9 +2732,9 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
/* help completing some of the variants */
- else if (Matches3("DROP", "AGGREGATE|FUNCTION", MatchAny))
+ else if (Matches3("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- else if (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, "("))
+ else if (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
else if (Matches2("DROP", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
@@ -2893,10 +2931,12 @@ psql_completion(const char *text, int start, int end)
* objects supported.
*/
if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES"))
- COMPLETE_WITH_LIST5("TABLES", "SEQUENCES", "FUNCTIONS", "TYPES", "SCHEMAS");
+ COMPLETE_WITH_LIST7("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS");
else
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf,
" UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
+ " UNION SELECT 'ALL PROCEDURES IN SCHEMA'"
+ " UNION SELECT 'ALL ROUTINES IN SCHEMA'"
" UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
" UNION SELECT 'ALL TABLES IN SCHEMA'"
" UNION SELECT 'DATABASE'"
@@ -2906,6 +2946,8 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'FUNCTION'"
" UNION SELECT 'LANGUAGE'"
" UNION SELECT 'LARGE OBJECT'"
+ " UNION SELECT 'PROCEDURE'"
+ " UNION SELECT 'ROUTINE'"
" UNION SELECT 'SCHEMA'"
" UNION SELECT 'SEQUENCE'"
" UNION SELECT 'TABLE'"
@@ -2913,7 +2955,10 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'TYPE'");
}
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "ALL"))
- COMPLETE_WITH_LIST3("FUNCTIONS IN SCHEMA", "SEQUENCES IN SCHEMA",
+ COMPLETE_WITH_LIST5("FUNCTIONS IN SCHEMA",
+ "PROCEDURES IN SCHEMA",
+ "ROUTINES IN SCHEMA",
+ "SEQUENCES IN SCHEMA",
"TABLES IN SCHEMA");
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "SERVER");
@@ -2934,6 +2979,10 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (TailMatches1("LANGUAGE"))
COMPLETE_WITH_QUERY(Query_for_list_of_languages);
+ else if (TailMatches1("PROCEDURE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (TailMatches1("ROUTINE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
else if (TailMatches1("SCHEMA"))
COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
else if (TailMatches1("SEQUENCE"))
@@ -3163,7 +3212,7 @@ psql_completion(const char *text, int start, int end)
static const char *const list_SECURITY_LABEL[] =
{"TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
"EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION", "LARGE OBJECT",
- "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "ROLE", "SCHEMA",
+ "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
"SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW", NULL};
COMPLETE_WITH_LIST(list_SECURITY_LABEL);
@@ -3233,8 +3282,8 @@ psql_completion(const char *text, int start, int end)
/* Complete SET <var> with "TO" */
else if (Matches2("SET", MatchAny))
COMPLETE_WITH_CONST("TO");
- /* Complete ALTER DATABASE|FUNCTION|ROLE|USER ... SET <name> */
- else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|ROLE|USER") &&
+ /* Complete ALTER DATABASE|FUNCTION||PROCEDURE|ROLE|ROUTINE|USER ... SET <name> */
+ else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER") &&
TailMatches2("SET", MatchAny))
COMPLETE_WITH_LIST2("FROM CURRENT", "TO");
/* Suggest possible variable values */
diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
index f7bb4a54f7..13d5925b18 100644
--- a/src/include/commands/defrem.h
+++ b/src/include/commands/defrem.h
@@ -59,12 +59,13 @@ extern void DropTransformById(Oid transformOid);
extern void IsThereFunctionInNamespace(const char *proname, int pronargs,
oidvector *proargtypes, Oid nspOid);
extern void ExecuteDoStmt(DoStmt *stmt);
+extern void ExecuteCallStmt(ParseState *pstate, CallStmt *stmt);
extern Oid get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok);
extern Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok);
extern void interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h
index ffeeb4919b..43ee88bd39 100644
--- a/src/include/nodes/nodes.h
+++ b/src/include/nodes/nodes.h
@@ -413,6 +413,7 @@ typedef enum NodeTag
T_DropSubscriptionStmt,
T_CreateStatsStmt,
T_AlterCollationStmt,
+ T_CallStmt,
/*
* TAGS FOR PARSE TREE NODES (parsenodes.h)
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 732e5d6788..b721240577 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -355,6 +355,7 @@ typedef struct FuncCall
bool agg_distinct; /* arguments were labeled DISTINCT */
bool func_variadic; /* last argument was labeled VARIADIC */
struct WindowDef *over; /* OVER clause, if any */
+ bool proc_call; /* CALL statement */
int location; /* token location, or -1 if unknown */
} FuncCall;
@@ -1636,9 +1637,11 @@ typedef enum ObjectType
OBJECT_OPERATOR,
OBJECT_OPFAMILY,
OBJECT_POLICY,
+ OBJECT_PROCEDURE,
OBJECT_PUBLICATION,
OBJECT_PUBLICATION_REL,
OBJECT_ROLE,
+ OBJECT_ROUTINE,
OBJECT_RULE,
OBJECT_SCHEMA,
OBJECT_SEQUENCE,
@@ -1849,6 +1852,8 @@ typedef enum GrantObjectType
ACL_OBJECT_LANGUAGE, /* procedural language */
ACL_OBJECT_LARGEOBJECT, /* largeobject */
ACL_OBJECT_NAMESPACE, /* namespace */
+ ACL_OBJECT_PROCEDURE, /* procedure */
+ ACL_OBJECT_ROUTINE, /* routine */
ACL_OBJECT_TABLESPACE, /* tablespace */
ACL_OBJECT_TYPE /* type */
} GrantObjectType;
@@ -2742,6 +2747,7 @@ typedef struct CreateFunctionStmt
List *funcname; /* qualified name of function to create */
List *parameters; /* a list of FunctionParameter */
TypeName *returnType; /* the return type */
+ bool is_procedure;
List *options; /* a list of DefElem */
List *withClause; /* a list of DefElem */
} CreateFunctionStmt;
@@ -2768,6 +2774,7 @@ typedef struct FunctionParameter
typedef struct AlterFunctionStmt
{
NodeTag type;
+ ObjectType objtype;
ObjectWithArgs *func; /* name and args of function */
List *actions; /* list of DefElem */
} AlterFunctionStmt;
@@ -2792,6 +2799,16 @@ typedef struct InlineCodeBlock
bool langIsTrusted; /* trusted property of the language */
} InlineCodeBlock;
+/* ----------------------
+ * CALL statement
+ * ----------------------
+ */
+typedef struct CallStmt
+{
+ NodeTag type;
+ FuncCall *funccall;
+} CallStmt;
+
/* ----------------------
* Alter Object Rename Statement
* ----------------------
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index f50e45e886..a932400058 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -63,6 +63,7 @@ PG_KEYWORD("boolean", BOOLEAN_P, COL_NAME_KEYWORD)
PG_KEYWORD("both", BOTH, RESERVED_KEYWORD)
PG_KEYWORD("by", BY, UNRESERVED_KEYWORD)
PG_KEYWORD("cache", CACHE, UNRESERVED_KEYWORD)
+PG_KEYWORD("call", CALL, UNRESERVED_KEYWORD)
PG_KEYWORD("called", CALLED, UNRESERVED_KEYWORD)
PG_KEYWORD("cascade", CASCADE, UNRESERVED_KEYWORD)
PG_KEYWORD("cascaded", CASCADED, UNRESERVED_KEYWORD)
@@ -310,6 +311,7 @@ PG_KEYWORD("prior", PRIOR, UNRESERVED_KEYWORD)
PG_KEYWORD("privileges", PRIVILEGES, UNRESERVED_KEYWORD)
PG_KEYWORD("procedural", PROCEDURAL, UNRESERVED_KEYWORD)
PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD)
+PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD)
@@ -340,6 +342,8 @@ PG_KEYWORD("right", RIGHT, TYPE_FUNC_NAME_KEYWORD)
PG_KEYWORD("role", ROLE, UNRESERVED_KEYWORD)
PG_KEYWORD("rollback", ROLLBACK, UNRESERVED_KEYWORD)
PG_KEYWORD("rollup", ROLLUP, UNRESERVED_KEYWORD)
+PG_KEYWORD("routine", ROUTINE, UNRESERVED_KEYWORD)
+PG_KEYWORD("routines", ROUTINES, UNRESERVED_KEYWORD)
PG_KEYWORD("row", ROW, COL_NAME_KEYWORD)
PG_KEYWORD("rows", ROWS, UNRESERVED_KEYWORD)
PG_KEYWORD("rule", RULE, UNRESERVED_KEYWORD)
diff --git a/src/include/parser/parse_func.h b/src/include/parser/parse_func.h
index b4b6084b1b..fccccd21ed 100644
--- a/src/include/parser/parse_func.h
+++ b/src/include/parser/parse_func.h
@@ -24,6 +24,7 @@ typedef enum
FUNCDETAIL_NOTFOUND, /* no matching function */
FUNCDETAIL_MULTIPLE, /* too many matching functions */
FUNCDETAIL_NORMAL, /* found a matching regular function */
+ FUNCDETAIL_PROCEDURE, /* found a matching procedure */
FUNCDETAIL_AGGREGATE, /* found a matching aggregate function */
FUNCDETAIL_WINDOWFUNC, /* found a matching window function */
FUNCDETAIL_COERCION /* it's a type coercion request */
@@ -31,7 +32,8 @@ typedef enum
extern Node *ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location);
+ Node *last_srf, FuncCall *fn, bool proc_call,
+ int location);
extern FuncDetailCode func_get_detail(List *funcname,
List *fargs, List *fargnames,
@@ -62,10 +64,8 @@ extern const char *func_signature_string(List *funcname, int nargs,
extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes,
bool noError);
-extern Oid LookupFuncWithArgs(ObjectWithArgs *func,
+extern Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func,
bool noError);
-extern Oid LookupAggWithArgs(ObjectWithArgs *agg,
- bool noError);
extern void check_srf_call_placement(ParseState *pstate, Node *last_srf,
int location);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index 68930c1f4a..0fc69761a6 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -67,7 +67,8 @@ typedef enum ParseExprKind
EXPR_KIND_EXECUTE_PARAMETER, /* parameter value in EXECUTE */
EXPR_KIND_TRIGGER_WHEN, /* WHEN condition in CREATE TRIGGER */
EXPR_KIND_POLICY, /* USING or WITH CHECK expr in policy */
- EXPR_KIND_PARTITION_EXPRESSION /* PARTITION BY expression */
+ EXPR_KIND_PARTITION_EXPRESSION, /* PARTITION BY expression */
+ EXPR_KIND_CALL /* CALL argument */
} ParseExprKind;
diff --git a/src/include/utils/lsyscache.h b/src/include/utils/lsyscache.h
index 07208b56ce..b316cc594c 100644
--- a/src/include/utils/lsyscache.h
+++ b/src/include/utils/lsyscache.h
@@ -118,6 +118,7 @@ extern bool get_func_retset(Oid funcid);
extern bool func_strict(Oid funcid);
extern char func_volatile(Oid funcid);
extern char func_parallel(Oid funcid);
+extern bool get_func_isagg(Oid funcid);
extern bool get_func_leakproof(Oid funcid);
extern float4 get_func_cost(Oid funcid);
extern float4 get_func_rows(Oid funcid);
diff --git a/src/interfaces/ecpg/preproc/ecpg.tokens b/src/interfaces/ecpg/preproc/ecpg.tokens
index 68ba925efe..1d613af02f 100644
--- a/src/interfaces/ecpg/preproc/ecpg.tokens
+++ b/src/interfaces/ecpg/preproc/ecpg.tokens
@@ -2,7 +2,7 @@
/* special embedded SQL tokens */
%token SQL_ALLOCATE SQL_AUTOCOMMIT SQL_BOOL SQL_BREAK
- SQL_CALL SQL_CARDINALITY SQL_CONNECT
+ SQL_CARDINALITY SQL_CONNECT
SQL_COUNT
SQL_DATETIME_INTERVAL_CODE
SQL_DATETIME_INTERVAL_PRECISION SQL_DESCRIBE
diff --git a/src/interfaces/ecpg/preproc/ecpg.trailer b/src/interfaces/ecpg/preproc/ecpg.trailer
index f60a62099d..19dc781885 100644
--- a/src/interfaces/ecpg/preproc/ecpg.trailer
+++ b/src/interfaces/ecpg/preproc/ecpg.trailer
@@ -1460,13 +1460,13 @@ action : CONTINUE_P
$<action>$.command = NULL;
$<action>$.str = mm_strdup("continue");
}
- | SQL_CALL name '(' c_args ')'
+ | CALL name '(' c_args ')'
{
$<action>$.code = W_DO;
$<action>$.command = cat_str(4, $2, mm_strdup("("), $4, mm_strdup(")"));
$<action>$.str = cat2_str(mm_strdup("call"), mm_strdup($<action>$.command));
}
- | SQL_CALL name
+ | CALL name
{
$<action>$.code = W_DO;
$<action>$.command = cat2_str($2, mm_strdup("()"));
@@ -1482,7 +1482,6 @@ ECPGKeywords: ECPGKeywords_vanames { $$ = $1; }
;
ECPGKeywords_vanames: SQL_BREAK { $$ = mm_strdup("break"); }
- | SQL_CALL { $$ = mm_strdup("call"); }
| SQL_CARDINALITY { $$ = mm_strdup("cardinality"); }
| SQL_COUNT { $$ = mm_strdup("count"); }
| SQL_DATETIME_INTERVAL_CODE { $$ = mm_strdup("datetime_interval_code"); }
diff --git a/src/interfaces/ecpg/preproc/ecpg_keywords.c b/src/interfaces/ecpg/preproc/ecpg_keywords.c
index 3b52b8f3a2..848b2d4849 100644
--- a/src/interfaces/ecpg/preproc/ecpg_keywords.c
+++ b/src/interfaces/ecpg/preproc/ecpg_keywords.c
@@ -33,7 +33,6 @@ static const ScanKeyword ECPGScanKeywords[] = {
{"autocommit", SQL_AUTOCOMMIT, 0},
{"bool", SQL_BOOL, 0},
{"break", SQL_BREAK, 0},
- {"call", SQL_CALL, 0},
{"cardinality", SQL_CARDINALITY, 0},
{"connect", SQL_CONNECT, 0},
{"count", SQL_COUNT, 0},
diff --git a/src/pl/plperl/GNUmakefile b/src/pl/plperl/GNUmakefile
index 91d1296b21..b829027d05 100644
--- a/src/pl/plperl/GNUmakefile
+++ b/src/pl/plperl/GNUmakefile
@@ -55,7 +55,7 @@ endif # win32
SHLIB_LINK = $(perl_embed_ldflags)
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=plperl --load-extension=plperlu
-REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array
+REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array plperl_call
# if Perl can support two interpreters in one backend,
# test plperl-and-plperlu cases
ifneq ($(PERL),)
diff --git a/src/pl/plperl/expected/plperl_call.out b/src/pl/plperl/expected/plperl_call.out
new file mode 100644
index 0000000000..4bccfcb7c8
--- /dev/null
+++ b/src/pl/plperl/expected/plperl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index ca0d1bccf8..edd99f8013 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -1915,7 +1915,7 @@ plperl_inline_handler(PG_FUNCTION_ARGS)
desc.fn_retistuple = false;
desc.fn_retisset = false;
desc.fn_retisarray = false;
- desc.result_oid = VOIDOID;
+ desc.result_oid = InvalidOid;
desc.nargs = 0;
desc.reference = NULL;
@@ -2481,7 +2481,7 @@ plperl_func_handler(PG_FUNCTION_ARGS)
}
retval = (Datum) 0;
}
- else
+ else if (prodesc->result_oid)
{
retval = plperl_sv_to_datum(perlret,
prodesc->result_oid,
@@ -2826,7 +2826,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -3343,7 +3343,7 @@ plperl_return_next_internal(SV *sv)
tuplestore_puttuple(current_call_data->tuple_store, tuple);
}
- else
+ else if (prodesc->result_oid)
{
Datum ret[1];
bool isNull[1];
diff --git a/src/pl/plperl/sql/plperl_call.sql b/src/pl/plperl/sql/plperl_call.sql
new file mode 100644
index 0000000000..bd2b63b418
--- /dev/null
+++ b/src/pl/plperl/sql/plperl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/plpgsql/src/pl_comp.c b/src/pl/plpgsql/src/pl_comp.c
index 9931ee038f..00b89ea056 100644
--- a/src/pl/plpgsql/src/pl_comp.c
+++ b/src/pl/plpgsql/src/pl_comp.c
@@ -275,7 +275,6 @@ do_compile(FunctionCallInfo fcinfo,
bool isnull;
char *proc_source;
HeapTuple typeTup;
- Form_pg_type typeStruct;
PLpgSQL_variable *var;
PLpgSQL_rec *rec;
int i;
@@ -531,53 +530,58 @@ do_compile(FunctionCallInfo fcinfo,
/*
* Lookup the function's return type
*/
- typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
- if (!HeapTupleIsValid(typeTup))
- elog(ERROR, "cache lookup failed for type %u", rettypeid);
- typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
-
- /* Disallow pseudotype result, except VOID or RECORD */
- /* (note we already replaced polymorphic types) */
- if (typeStruct->typtype == TYPTYPE_PSEUDO)
+ if (rettypeid)
{
- if (rettypeid == VOIDOID ||
- rettypeid == RECORDOID)
- /* okay */ ;
- else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("trigger functions can only be called as triggers")));
- else
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("PL/pgSQL functions cannot return type %s",
- format_type_be(rettypeid))));
- }
+ Form_pg_type typeStruct;
- if (typeStruct->typrelid != InvalidOid ||
- rettypeid == RECORDOID)
- function->fn_retistuple = true;
- else
- {
- function->fn_retbyval = typeStruct->typbyval;
- function->fn_rettyplen = typeStruct->typlen;
+ typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
+ if (!HeapTupleIsValid(typeTup))
+ elog(ERROR, "cache lookup failed for type %u", rettypeid);
+ typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
- /*
- * install $0 reference, but only for polymorphic return
- * types, and not when the return is specified through an
- * output parameter.
- */
- if (IsPolymorphicType(procStruct->prorettype) &&
- num_out_args == 0)
+ /* Disallow pseudotype result, except VOID or RECORD */
+ /* (note we already replaced polymorphic types) */
+ if (typeStruct->typtype == TYPTYPE_PSEUDO)
{
- (void) plpgsql_build_variable("$0", 0,
- build_datatype(typeTup,
- -1,
- function->fn_input_collation),
- true);
+ if (rettypeid == VOIDOID ||
+ rettypeid == RECORDOID)
+ /* okay */ ;
+ else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("trigger functions can only be called as triggers")));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("PL/pgSQL functions cannot return type %s",
+ format_type_be(rettypeid))));
+ }
+
+ if (typeStruct->typrelid != InvalidOid ||
+ rettypeid == RECORDOID)
+ function->fn_retistuple = true;
+ else
+ {
+ function->fn_retbyval = typeStruct->typbyval;
+ function->fn_rettyplen = typeStruct->typlen;
+
+ /*
+ * install $0 reference, but only for polymorphic return
+ * types, and not when the return is specified through an
+ * output parameter.
+ */
+ if (IsPolymorphicType(procStruct->prorettype) &&
+ num_out_args == 0)
+ {
+ (void) plpgsql_build_variable("$0", 0,
+ build_datatype(typeTup,
+ -1,
+ function->fn_input_collation),
+ true);
+ }
}
+ ReleaseSysCache(typeTup);
}
- ReleaseSysCache(typeTup);
break;
case PLPGSQL_DML_TRIGGER:
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index e605ec829e..1069fdd6ad 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -462,7 +462,7 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
estate.err_text = NULL;
estate.err_stmt = (PLpgSQL_stmt *) (func->action);
rc = exec_stmt_block(&estate, func->action);
- if (rc != PLPGSQL_RC_RETURN)
+ if (rc != PLPGSQL_RC_RETURN && func->fn_rettype)
{
estate.err_stmt = NULL;
estate.err_text = NULL;
@@ -509,6 +509,12 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
}
else if (!estate.retisnull)
{
+ if (!func->fn_rettype)
+ {
+ ereport(ERROR,
+ (errmsg("cannot return a value from a procedure")));
+ }
+
if (estate.retistuple)
{
/*
diff --git a/src/pl/plpython/Makefile b/src/pl/plpython/Makefile
index 7680d49cb6..cc91afebde 100644
--- a/src/pl/plpython/Makefile
+++ b/src/pl/plpython/Makefile
@@ -78,6 +78,7 @@ REGRESS = \
plpython_spi \
plpython_newline \
plpython_void \
+ plpython_call \
plpython_params \
plpython_setof \
plpython_record \
diff --git a/src/pl/plpython/expected/plpython_call.out b/src/pl/plpython/expected/plpython_call.out
new file mode 100644
index 0000000000..58c184e2ea
--- /dev/null
+++ b/src/pl/plpython/expected/plpython_call.out
@@ -0,0 +1,35 @@
+--
+-- Tests for procedures / CALL syntax
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+CALL test_proc1();
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+CALL test_proc2();
+ERROR: PL/Python procedure did not return None
+CONTEXT: PL/Python function "test_proc2"
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plpython/plpy_exec.c b/src/pl/plpython/plpy_exec.c
index 26f61dd0f3..1b7a9470d4 100644
--- a/src/pl/plpython/plpy_exec.c
+++ b/src/pl/plpython/plpy_exec.c
@@ -197,12 +197,19 @@ PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
error_context_stack = &plerrcontext;
/*
- * If the function is declared to return void, the Python return value
+ * For a procedure or function declared to return void, the Python return value
* must be None. For void-returning functions, we also treat a None
* return value as a special "void datum" rather than NULL (as is the
* case for non-void-returning functions).
*/
- if (proc->result.out.d.typoid == VOIDOID)
+ if (proc->is_procedure)
+ {
+ if (plrv != Py_None)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("PL/Python procedure did not return None")));
+ }
+ else if (proc->result.out.d.typoid == VOIDOID)
{
if (plrv != Py_None)
ereport(ERROR,
@@ -715,7 +722,8 @@ plpython_return_error_callback(void *arg)
{
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
- if (exec_ctx->curr_proc)
+ if (exec_ctx->curr_proc &&
+ !exec_ctx->curr_proc->is_procedure)
errcontext("while creating return value");
}
diff --git a/src/pl/plpython/plpy_procedure.c b/src/pl/plpython/plpy_procedure.c
index 26acc88b27..7b04a60e90 100644
--- a/src/pl/plpython/plpy_procedure.c
+++ b/src/pl/plpython/plpy_procedure.c
@@ -188,6 +188,7 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
proc->fn_tid = procTup->t_self;
proc->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
proc->is_setof = procStruct->proretset;
+ proc->is_procedure = (procStruct->prorettype == InvalidOid);
PLy_typeinfo_init(&proc->result, proc->mcxt);
proc->src = NULL;
proc->argnames = NULL;
@@ -207,9 +208,9 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
/*
* get information required for output conversion of the return value,
- * but only if this isn't a trigger.
+ * but only if this isn't a trigger or procedure.
*/
- if (!is_trigger)
+ if (!is_trigger && procStruct->prorettype)
{
HeapTuple rvTypeTup;
Form_pg_type rvTypeStruct;
diff --git a/src/pl/plpython/plpy_procedure.h b/src/pl/plpython/plpy_procedure.h
index d05944fc39..0bb1b652b0 100644
--- a/src/pl/plpython/plpy_procedure.h
+++ b/src/pl/plpython/plpy_procedure.h
@@ -30,7 +30,8 @@ typedef struct PLyProcedure
TransactionId fn_xmin;
ItemPointerData fn_tid;
bool fn_readonly;
- bool is_setof; /* true, if procedure returns result set */
+ bool is_setof; /* true, if function returns result set */
+ bool is_procedure;
PLyTypeInfo result; /* also used to store info for trigger tuple
* type */
char *src; /* textual procedure code, after mangling */
diff --git a/src/pl/plpython/sql/plpython_call.sql b/src/pl/plpython/sql/plpython_call.sql
new file mode 100644
index 0000000000..3fb74de5f0
--- /dev/null
+++ b/src/pl/plpython/sql/plpython_call.sql
@@ -0,0 +1,41 @@
+--
+-- Tests for procedures / CALL syntax
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/tcl/Makefile b/src/pl/tcl/Makefile
index b8971d3cc8..6a92a9b6aa 100644
--- a/src/pl/tcl/Makefile
+++ b/src/pl/tcl/Makefile
@@ -28,7 +28,7 @@ DATA = pltcl.control pltcl--1.0.sql pltcl--unpackaged--1.0.sql \
pltclu.control pltclu--1.0.sql pltclu--unpackaged--1.0.sql
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=pltcl
-REGRESS = pltcl_setup pltcl_queries pltcl_start_proc pltcl_subxact pltcl_unicode
+REGRESS = pltcl_setup pltcl_queries pltcl_call pltcl_start_proc pltcl_subxact pltcl_unicode
# Tcl on win32 ships with import libraries only for Microsoft Visual C++,
# which are not compatible with mingw gcc. Therefore we need to build a
diff --git a/src/pl/tcl/expected/pltcl_call.out b/src/pl/tcl/expected/pltcl_call.out
new file mode 100644
index 0000000000..7221a37ad0
--- /dev/null
+++ b/src/pl/tcl/expected/pltcl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 6d97ddc99b..e0792d93e1 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -146,6 +146,7 @@ typedef struct pltcl_proc_desc
Oid result_typid; /* OID of fn's result type */
FmgrInfo result_in_func; /* input function for fn's result type */
Oid result_typioparam; /* param to pass to same */
+ bool fn_is_procedure;/* true if this is a procedure */
bool fn_retisset; /* true if function returns a set */
bool fn_retistuple; /* true if function returns composite */
bool fn_retisdomain; /* true if function returns domain */
@@ -968,7 +969,7 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
retval = (Datum) 0;
fcinfo->isnull = true;
}
- else if (fcinfo->isnull)
+ else if (fcinfo->isnull && !prodesc->fn_is_procedure)
{
retval = InputFunctionCall(&prodesc->result_in_func,
NULL,
@@ -1026,11 +1027,13 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
call_state);
retval = HeapTupleGetDatum(tup);
}
- else
+ else if (!prodesc->fn_is_procedure)
retval = InputFunctionCall(&prodesc->result_in_func,
utf_u2e(Tcl_GetStringResult(interp)),
prodesc->result_typioparam,
-1);
+ else
+ retval = 0;
return retval;
}
@@ -1506,7 +1509,9 @@ compile_pltcl_function(Oid fn_oid, Oid tgreloid,
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ prodesc->fn_is_procedure = (procStruct->prorettype == InvalidOid);
+
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -2199,7 +2204,7 @@ pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
tuplestore_puttuple(call_state->tuple_store, tuple);
}
}
- else
+ else if (!prodesc->fn_is_procedure)
{
Datum retval;
bool isNull = false;
diff --git a/src/pl/tcl/sql/pltcl_call.sql b/src/pl/tcl/sql/pltcl_call.sql
new file mode 100644
index 0000000000..ef1f540f50
--- /dev/null
+++ b/src/pl/tcl/sql/pltcl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/test/regress/expected/create_procedure.out b/src/test/regress/expected/create_procedure.out
new file mode 100644
index 0000000000..eeb129d71f
--- /dev/null
+++ b/src/test/regress/expected/create_procedure.out
@@ -0,0 +1,86 @@
+CALL nonexistent(); -- error
+ERROR: function nonexistent() does not exist
+LINE 1: CALL nonexistent();
+ ^
+HINT: No function matches the given name and argument types. You might need to add explicit type casts.
+CALL random(); -- error
+ERROR: random() is not a procedure
+LINE 1: CALL random();
+ ^
+HINT: To call a function, use SELECT.
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+CREATE TABLE cp_test (a int, b text);
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+SELECT ptest1('x'); -- error
+ERROR: ptest1(unknown) is a procedure
+LINE 1: SELECT ptest1('x');
+ ^
+HINT: To call a procedure, use CALL.
+CALL ptest1('a'); -- ok
+\df ptest1
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+--------+------------------+---------------------+------
+ public | ptest1 | | x text | proc
+(1 row)
+
+SELECT * FROM cp_test ORDER BY a;
+ a | b
+---+---
+ 1 | a
+(1 row)
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+CALL ptest2();
+-- various error cases
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedure cannot have WINDOW attribute
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedure cannot be declared as strict
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedures cannot have OUT parameters
+ALTER PROCEDURE ptest1(text) STRICT;
+ERROR: procedure strictness cannot be changed
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ERROR: ptest1(text) is not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+ERROR: procedure nonexistent() does not exist
+DROP FUNCTION ptest1(text); -- error: not a function
+ERROR: ptest1(text) is not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+DROP PROCEDURE nonexistent();
+ERROR: procedure nonexistent() does not exist
+-- privileges
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+ERROR: permission denied for function ptest1
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+-- ROUTINE syntax
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+DROP ROUTINE testfunc1(int);
+-- cleanup
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+DROP TABLE cp_test;
+DROP USER regress_user1;
diff --git a/src/test/regress/expected/object_address.out b/src/test/regress/expected/object_address.out
index 1fdadbc9ef..bfd9d54c11 100644
--- a/src/test/regress/expected/object_address.out
+++ b/src/test/regress/expected/object_address.out
@@ -29,6 +29,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -88,7 +89,7 @@ BEGIN
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -171,6 +172,12 @@ WARNING: error for function,{addr_nsp,zwei},{}: function addr_nsp.zwei() does n
WARNING: error for function,{addr_nsp,zwei},{integer}: function addr_nsp.zwei(integer) does not exist
WARNING: error for function,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for function,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins},{}: procedure eins() does not exist
+WARNING: error for procedure,{eins},{integer}: procedure eins(integer) does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{}: procedure addr_nsp.zwei() does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{integer}: procedure addr_nsp.zwei(integer) does not exist
+WARNING: error for procedure,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for type,{eins},{}: type "eins" does not exist
WARNING: error for type,{eins},{integer}: type "eins" does not exist
WARNING: error for type,{addr_nsp,zwei},{}: name list length must be exactly 1
@@ -371,6 +378,7 @@ WITH objects (type, name, args) AS (VALUES
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
@@ -431,6 +439,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
type | addr_nsp | gendomain | addr_nsp.gendomain | t
function | pg_catalog | | pg_catalog.pg_identify_object(pg_catalog.oid,pg_catalog.oid,integer) | t
aggregate | addr_nsp | | addr_nsp.genaggr(integer) | t
+ procedure | addr_nsp | | addr_nsp.proc(integer) | t
sequence | addr_nsp | gentable_a_seq | addr_nsp.gentable_a_seq | t
table | addr_nsp | gentable | addr_nsp.gentable | t
table column | addr_nsp | gentable | addr_nsp.gentable.b | t
@@ -469,7 +478,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
subscription | | addr_sub | addr_sub | t
publication | | addr_pub | addr_pub | t
publication relation | | | gentable in publication addr_pub | t
-(46 rows)
+(47 rows)
---
--- Cleanup resources
@@ -480,6 +489,6 @@ NOTICE: drop cascades to 4 other objects
DROP PUBLICATION addr_pub;
DROP SUBSCRIPTION addr_sub;
DROP SCHEMA addr_nsp CASCADE;
-NOTICE: drop cascades to 12 other objects
+NOTICE: drop cascades to 13 other objects
DROP OWNED BY regress_addr_user;
DROP USER regress_addr_user;
diff --git a/src/test/regress/expected/plpgsql.out b/src/test/regress/expected/plpgsql.out
index bb3532676b..d6e5bc3353 100644
--- a/src/test/regress/expected/plpgsql.out
+++ b/src/test/regress/expected/plpgsql.out
@@ -6040,3 +6040,44 @@ END; $$ LANGUAGE plpgsql;
ERROR: "x" is not a scalar variable
LINE 3: GET DIAGNOSTICS x = ROW_COUNT;
^
+--
+-- Procedures
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+CALL test_proc1();
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+CALL test_proc2();
+ERROR: cannot return a value from a procedure
+CONTEXT: PL/pgSQL function test_proc2() while casting return value to function's return type
+CREATE TABLE proc_test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+CALL test_proc3(55);
+SELECT * FROM proc_test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE proc_test1;
diff --git a/src/test/regress/expected/polymorphism.out b/src/test/regress/expected/polymorphism.out
index 91cfb743b6..66e35a6a5c 100644
--- a/src/test/regress/expected/polymorphism.out
+++ b/src/test/regress/expected/polymorphism.out
@@ -915,10 +915,10 @@ select dfunc();
-- verify it lists properly
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-----------------------------------------------------------+--------
- public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-----------------------------------------------------------+------
+ public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | func
(1 row)
drop function dfunc(int, int);
@@ -1083,10 +1083,10 @@ $$ select array_upper($1, 1) $$ language sql;
ERROR: cannot remove parameter defaults from existing function
HINT: Use DROP FUNCTION dfunc(integer[]) first.
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-------------------------------------------------+--------
- public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-------------------------------------------------+------
+ public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | func
(1 row)
drop function dfunc(a variadic int[]);
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index aa5e6af621..9343aa02c7 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -53,7 +53,7 @@ test: copy copyselect copydml
# ----------
# More groups of parallel tests
# ----------
-test: create_misc create_operator
+test: create_misc create_operator create_procedure
# These depend on the above two
test: create_index create_view
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index 3866314a92..8dd4b7ba0c 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -63,6 +63,7 @@ test: copyselect
test: copydml
test: create_misc
test: create_operator
+test: create_procedure
test: create_index
test: create_view
test: create_aggregate
diff --git a/src/test/regress/sql/create_procedure.sql b/src/test/regress/sql/create_procedure.sql
new file mode 100644
index 0000000000..f09ba2ad30
--- /dev/null
+++ b/src/test/regress/sql/create_procedure.sql
@@ -0,0 +1,79 @@
+CALL nonexistent(); -- error
+CALL random(); -- error
+
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+
+CREATE TABLE cp_test (a int, b text);
+
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+
+SELECT ptest1('x'); -- error
+CALL ptest1('a'); -- ok
+
+\df ptest1
+
+SELECT * FROM cp_test ORDER BY a;
+
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+
+CALL ptest2();
+
+
+-- various error cases
+
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+
+ALTER PROCEDURE ptest1(text) STRICT;
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+
+DROP FUNCTION ptest1(text); -- error: not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+DROP PROCEDURE nonexistent();
+
+
+-- privileges
+
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+
+
+-- ROUTINE syntax
+
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+
+DROP ROUTINE testfunc1(int);
+
+
+-- cleanup
+
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+
+DROP TABLE cp_test;
+
+DROP USER regress_user1;
diff --git a/src/test/regress/sql/object_address.sql b/src/test/regress/sql/object_address.sql
index 63821b8008..55faa71edf 100644
--- a/src/test/regress/sql/object_address.sql
+++ b/src/test/regress/sql/object_address.sql
@@ -32,6 +32,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -81,7 +82,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -147,6 +148,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
diff --git a/src/test/regress/sql/plpgsql.sql b/src/test/regress/sql/plpgsql.sql
index 6620ea6172..1c355132b7 100644
--- a/src/test/regress/sql/plpgsql.sql
+++ b/src/test/regress/sql/plpgsql.sql
@@ -4820,3 +4820,52 @@ CREATE FUNCTION fx(x WSlot) RETURNS void AS $$
GET DIAGNOSTICS x = ROW_COUNT;
RETURN;
END; $$ LANGUAGE plpgsql;
+
+
+--
+-- Procedures
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE proc_test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM proc_test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE proc_test1;
base-commit: ee4673ac071f8352c41cc673299b7ec695f079ff
--
2.14.3
On 31 October 2017 at 18:23, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
I've been working on SQL procedures. (Some might call them "stored
procedures", but I'm not aware of any procedures that are not stored, so
that's not a term that I'm using here.)
I guess that the DO command might have a variant to allow you to
execute a procedure that isn't stored?
Not suggesting you implement that, just thinking about why/when the
"stored" word would be appropriate.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
I've been working on SQL procedures.
No comment yet on the big picture here, but ...
The provided procedural languages (an ever more
confusing term) each needed a small touch-up to handle pg_proc entries
with prorettype == 0.
Putting 0 in prorettype seems like a pretty bad idea. Why not use VOIDOID
for the prorettype value? Or if there is some reason why "void" isn't the
right pseudotype, maybe you should invent a new one, analogous to the
"trigger" and "event_trigger" pseudotypes.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
2017-10-31 18:23 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:
I've been working on SQL procedures. (Some might call them "stored
procedures", but I'm not aware of any procedures that are not stored, so
that's not a term that I'm using here.)Everything that follows is intended to align with the SQL standard, at
least in spirit.This first patch does a bunch of preparation work. It adds the
CREATE/ALTER/DROP PROCEDURE commands and the CALL statement to call a
procedure. It also adds ROUTINE syntax which can refer to a function or
procedure. I have extended that to include aggregates. And then there
is a bunch of leg work, such as psql and pg_dump support. The
documentation is a lot of copy-and-paste right now; that can be
revisited sometime. The provided procedural languages (an ever more
confusing term) each needed a small touch-up to handle pg_proc entries
with prorettype == 0.Right now, there is no support for returning values from procedures via
OUT parameters. That will need some definitional pondering; and see
also below for a possible alternative.With this, you can write procedures that are somewhat compatible with
DB2, MySQL, and to a lesser extent Oracle.Separately, I will send patches that implement (the beginnings of) two
separate features on top of this:- Transaction control in procedure bodies
- Returning multiple result sets
(In various previous discussions on "real stored procedures" or
something like that, most people seemed to have one of these two
features in mind. I think that depends on what other SQL systems one
has worked with previously.)
great. I hope so I can help with testing
Regards
Pavel
Show quoted text
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
2017-10-31 18:23 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:
I've been working on SQL procedures. (Some might call them "stored
procedures", but I'm not aware of any procedures that are not stored, so
that's not a term that I'm using here.)Everything that follows is intended to align with the SQL standard, at
least in spirit.This first patch does a bunch of preparation work. It adds the
CREATE/ALTER/DROP PROCEDURE commands and the CALL statement to call a
procedure. It also adds ROUTINE syntax which can refer to a function or
procedure. I have extended that to include aggregates. And then there
is a bunch of leg work, such as psql and pg_dump support. The
documentation is a lot of copy-and-paste right now; that can be
revisited sometime. The provided procedural languages (an ever more
confusing term) each needed a small touch-up to handle pg_proc entries
with prorettype == 0.Right now, there is no support for returning values from procedures via
OUT parameters. That will need some definitional pondering; and see
also below for a possible alternative.With this, you can write procedures that are somewhat compatible with
DB2, MySQL, and to a lesser extent Oracle.Separately, I will send patches that implement (the beginnings of) two
separate features on top of this:- Transaction control in procedure bodies
- Returning multiple result sets
(In various previous discussions on "real stored procedures" or
something like that, most people seemed to have one of these two
features in mind. I think that depends on what other SQL systems one
has worked with previously.)
Not sure if disabling RETURN is good idea. I can imagine so optional
returning something like int status can be good idea. Cheaper than raising
a exception.
Regards
Pavel
Show quoted text
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 31 October 2017 at 17:23, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
I've been working on SQL procedures. (Some might call them "stored
procedures", but I'm not aware of any procedures that are not stored, so
that's not a term that I'm using here.)
Looks good
Everything that follows is intended to align with the SQL standard, at
least in spirit.
+1
This first patch does a bunch of preparation work. It adds the
CREATE/ALTER/DROP PROCEDURE commands and the CALL statement to call a
procedure.
I guess it would be really useful to have a cut-down language to use
as an example, but its probably easier to just wait for PLpgSQL.
You mention PARALLEL SAFE is not used for procedures. Isn't it an
architectural restriction that procedures would not be able to execute
in parallel? (At least this year)
It also adds ROUTINE syntax which can refer to a function or
procedure.
I think we need an explanatory section of the docs, but there doesn't
seem to be one for Functions, so there is no place to add some text
that says the above.
I found it confusing that ALTER and DROP ROUTINE exists but not CREATE
ROUTINE. At very least we should say somewhere "there is no CREATE
ROUTINE", so its absence is clearly intentional. I did wonder whether
we should have it as well, but its just one less thing to review, so
good.
Was surprised that pg_dump didn't use DROP ROUTINE, when appropriate.
I have extended that to include aggregates. And then there
is a bunch of leg work, such as psql and pg_dump support. The
documentation is a lot of copy-and-paste right now; that can be
revisited sometime. The provided procedural languages (an ever more
confusing term) each needed a small touch-up to handle pg_proc entries
with prorettype == 0.Right now, there is no support for returning values from procedures via
OUT parameters. That will need some definitional pondering; and see
also below for a possible alternative.With this, you can write procedures that are somewhat compatible with
DB2, MySQL, and to a lesser extent Oracle.Separately, I will send patches that implement (the beginnings of) two
separate features on top of this:- Transaction control in procedure bodies
- Returning multiple result sets
Both of those would be good, though my suggested priority would be
transaction control first and then multiple result sets, if we cannot
have both this release.
(In various previous discussions on "real stored procedures" or
something like that, most people seemed to have one of these two
features in mind. I think that depends on what other SQL systems one
has worked with previously.)
Almost all of the meat happens in later patches, so no other review comments.
That seems seems strange in a patch of this size, but its true.
Procedures are just a new type of object with very little interaction
with replication, persistence or optimization.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 10/31/17 14:23, Tom Lane wrote:
Putting 0 in prorettype seems like a pretty bad idea.
It seemed like the natural thing to do, since we use a zero OID to
indicate "nothing" in many other places.
Why not use VOIDOID for the prorettype value?
We need a way to distinguish functions that are callable by SELECT and
procedures that are callable by CALL.
Or if there is some reason why "void" isn't the
right pseudotype, maybe you should invent a new one, analogous to the
"trigger" and "event_trigger" pseudotypes.
I guess that would be doable, but I think it would make things more
complicated without any gain that I can see. In the case of the
pseudotypes you mention, those are the actual types mentioned in the
CREATE FUNCTION command. If we invented a new pseudotype, that would
run the risk of existing code creating nonsensical reverse compilations
like CREATE FUNCTION RETURNS PROCEDURE. Catalog queries using
prorettype == 0 would behave sensibly by default. For example, an inner
or outer join against pg_type would automatically make sense.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 10/31/17 16:50, Pavel Stehule wrote:
Not sure if disabling RETURN is good idea. I can imagine so optional
returning something like int status can be good idea. Cheaper than
raising a exception.
We could allow a RETURN without argument in PL/pgSQL, if you just want
to exit early. That syntax is currently not available, but it should
not be hard to add.
I don't understand the point about wanting to return an int. How would
you pass that around, since there is no declared return type?
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On Tue, Oct 31, 2017 at 12:23 PM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
- Transaction control in procedure bodies
This feature is really key, since it enables via SQL lots of things
that are not possible without external coding, including:
*) very long running processes in a single routine
*) transaction isolation control inside the procedure (currently
client app has to declare this)
*) certain error handling cases that require client side support
*) simple in-database threading
*) simple construction of daemon scripts (yeah, you can use bgworker
for this, but pure sql daemon with a cron heartbeat hook is hard to
beat for simplicity)
I do wonder how transaction control could be added later.
The last time I (lightly) looked at this, I was starting to think that
working transaction control into the SPI interface was the wrong
approach; pl/pgsql would have to adopt a very different set of
behaviors if it was called in a function or a proc. If you restricted
language choice to purely SQL, you could work around this problem; SPI
languages would be totally abstracted from those sets of
considerations and you could always call an arbitrary language
function if you needed to. SQL has no flow control but I'm not too
concerned about that.
merlin
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
2017-11-08 15:23 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:
On 10/31/17 16:50, Pavel Stehule wrote:
Not sure if disabling RETURN is good idea. I can imagine so optional
returning something like int status can be good idea. Cheaper than
raising a exception.We could allow a RETURN without argument in PL/pgSQL, if you just want
to exit early. That syntax is currently not available, but it should
not be hard to add.I don't understand the point about wanting to return an int. How would
you pass that around, since there is no declared return type?
We can create auto session variable STATUS. This variable can be 0 if
procedure was returned without explicit RETURN value. Or it can hold
different value specified by RETURN expr.
This value can be read by GET DIAGNOSTICS xxx = STATUS
or some similar.
Show quoted text
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
2017-11-08 15:31 GMT+01:00 Pavel Stehule <pavel.stehule@gmail.com>:
2017-11-08 15:23 GMT+01:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.
com>:On 10/31/17 16:50, Pavel Stehule wrote:
Not sure if disabling RETURN is good idea. I can imagine so optional
returning something like int status can be good idea. Cheaper than
raising a exception.We could allow a RETURN without argument in PL/pgSQL, if you just want
to exit early. That syntax is currently not available, but it should
not be hard to add.I don't understand the point about wanting to return an int. How would
you pass that around, since there is no declared return type?We can create auto session variable STATUS. This variable can be 0 if
procedure was returned without explicit RETURN value. Or it can hold
different value specified by RETURN expr.This value can be read by GET DIAGNOSTICS xxx = STATUS
or some similar.
The motivation is allow some mechanism cheaper than our exceptions.
Regards
Pavel
Show quoted text
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 08.11.2017 17:23, Merlin Moncure wrote:
On Tue, Oct 31, 2017 at 12:23 PM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:- Transaction control in procedure bodies
This feature is really key, since it enables via SQL lots of things
that are not possible without external coding, including:
*) very long running processes in a single routine
*) transaction isolation control inside the procedure (currently
client app has to declare this)
*) certain error handling cases that require client side support
*) simple in-database threading
*) simple construction of daemon scripts (yeah, you can use bgworker
for this, but pure sql daemon with a cron heartbeat hook is hard to
beat for simplicity)I do wonder how transaction control could be added later.
The last time I (lightly) looked at this, I was starting to think that
working transaction control into the SPI interface was the wrong
approach; pl/pgsql would have to adopt a very different set of
behaviors if it was called in a function or a proc. If you restricted
language choice to purely SQL, you could work around this problem; SPI
languages would be totally abstracted from those sets of
considerations and you could always call an arbitrary language
function if you needed to. SQL has no flow control but I'm not too
concerned about that.merlin
I am also very interested in answer on this question: how you are going
to implement transaction control inside procedure?
Right now in PostgresPRO EE supports autonomous transactions. Them are
supported both for SQL and plpgsql/plpython APIs.
Them are implemented by saving/restoring transaction context, so unlike
most of other ATX implementations, in pgpro autonomous
transaction is executed by the same backend. But it is not so easy to
do: in Postgres almost any module have its own static variables which
keeps transaction specific data.
So we have to provide a dozen of suspend/resume functions:
SuspendSnapshot(), SuspendPredicate(), SuspendStorage(),
SuspendInvalidationInfo(), SuspendPgXact(), PgStatSuspend(),
TriggerSuspend(), SuspendSPI()... and properly handle local cache
invalidation. Patch consists of more than 5 thousand lines.
So my question is whether you are going to implement something similar
or use completely different approach?
In first case it will be good to somehow unite our efforts... For
example we can publish our ATX patch for Postgres 10.
We have not done it yet, because there seems to be no chances to push
this patch to community.
--
Konstantin Knizhnik
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 10/31/17 14:23, Tom Lane wrote:
Why not use VOIDOID for the prorettype value?
We need a way to distinguish functions that are callable by SELECT and
procedures that are callable by CALL.
Do procedures of this ilk belong in pg_proc at all? It seems like a large
fraction of the attributes tracked in pg_proc are senseless for this
purpose. A new catalog might be a better approach.
In any case, I buy none of your arguments that 0 is a better choice than a
new pseudotype.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 11/6/17 16:27, Simon Riggs wrote:
You mention PARALLEL SAFE is not used for procedures. Isn't it an
architectural restriction that procedures would not be able to execute
in parallel? (At least this year)
I'm not sure what you are referring to here. I don't think the
functionality I'm proposing does anything in parallel or has any
interaction with it.
I think we need an explanatory section of the docs, but there doesn't
seem to be one for Functions, so there is no place to add some text
that says the above.I found it confusing that ALTER and DROP ROUTINE exists but not CREATE
ROUTINE. At very least we should say somewhere "there is no CREATE
ROUTINE", so its absence is clearly intentional. I did wonder whether
we should have it as well, but its just one less thing to review, so
good.
I'll look for a place to add some documentation around this.
Was surprised that pg_dump didn't use DROP ROUTINE, when appropriate.
It's not clear to me why that would be preferred.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 11/8/17 09:33, Pavel Stehule wrote:
We can create auto session variable STATUS. This variable can be 0
if procedure was returned without explicit RETURN value. Or it can
hold different value specified by RETURN expr.This value can be read by GET DIAGNOSTICS xxx = STATUS
or some similar.
The motivation is allow some mechanism cheaper than our exceptions.
I suppose this could be a separately discussed feature. We'd also want
to consider various things that PL/pgSQL pretends to be compatible with.
One of the main motivations for procedures is to do more complex and
expensive things including transaction control. So saving exception
overhead is not really on the priority list there.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 11/8/17 09:23, Merlin Moncure wrote:
I do wonder how transaction control could be added later.
The last time I (lightly) looked at this, I was starting to think that
working transaction control into the SPI interface was the wrong
approach; pl/pgsql would have to adopt a very different set of
behaviors if it was called in a function or a proc. If you restricted
language choice to purely SQL, you could work around this problem; SPI
languages would be totally abstracted from those sets of
considerations and you could always call an arbitrary language
function if you needed to. SQL has no flow control but I'm not too
concerned about that.
I have already submitted a separate patch that addresses these questions.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On Wed, Nov 8, 2017 at 9:13 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
I have already submitted a separate patch that addresses these questions.
Maybe I'm obtuse, but I'm not seeing it? In very interested in the
general approach to transaction management; if you've described it in
the patch I'll read it there. Thanks for doing this.
merlin
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 11/8/17 11:11, Merlin Moncure wrote:
On Wed, Nov 8, 2017 at 9:13 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:I have already submitted a separate patch that addresses these questions.
Maybe I'm obtuse, but I'm not seeing it? In very interested in the
general approach to transaction management; if you've described it in
the patch I'll read it there. Thanks for doing this.
/messages/by-id/178d3380-0fae-2982-00d6-c43100bc8748@2ndquadrant.com
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On Wed, Nov 8, 2017 at 11:03 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
On 11/8/17 11:11, Merlin Moncure wrote:
On Wed, Nov 8, 2017 at 9:13 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:I have already submitted a separate patch that addresses these questions.
Maybe I'm obtuse, but I'm not seeing it? In very interested in the
general approach to transaction management; if you've described it in
the patch I'll read it there. Thanks for doing this./messages/by-id/178d3380-0fae-2982-00d6-c43100bc8748@2ndquadrant.com
All right, thanks. So,
*) Are you sure you want to go the SPI route? 'sql' language
(non-spi) procedures might be simpler from implementation standpoint
and do not need any language adjustments?
*) Is it possible to jump into SPI without having a snapshot already
set up. For example? If I wanted to set isolation level in a
procedure, would I get impacted by this error?
ERROR: SET TRANSACTION ISOLATION LEVEL must be called before any query
merlin
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
On 11/8/17 12:15, Merlin Moncure wrote:
On Wed, Nov 8, 2017 at 11:03 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:On 11/8/17 11:11, Merlin Moncure wrote:
On Wed, Nov 8, 2017 at 9:13 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:I have already submitted a separate patch that addresses these questions.
Maybe I'm obtuse, but I'm not seeing it? In very interested in the
general approach to transaction management; if you've described it in
the patch I'll read it there. Thanks for doing this./messages/by-id/178d3380-0fae-2982-00d6-c43100bc8748@2ndquadrant.com
All right, thanks. So,
Could we have this discussion in that other thread? This thread is just
about procedures at mostly a syntax level.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Here is an updated patch. It's updated for the recent documentation
format changes. I added some more documentation as suggested by reviewers.
I also added more tests about how the various privilege commands (GRANT,
GRANT on ALL, default privileges) would work with the new object type.
I had not looked at that in much detail with the previous version of the
patch, but it seems to work the way I would have wanted without any code
changes, so it's all documentation additions and new tests.
As part of this I have also developed additional tests for how the same
privilege commands apply to aggregates, which didn't appear to be
covered yet, and I was worried that I might have broken it, which it
seems I did not. This is included in the big patch, but I have also
included it here as a separate patch, as it could be committed
independently as additional tests for existing functionality.
It this point, this patch has no more open TODOs or
need-to-think-about-this-later's that I'm aware of.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Attachments:
v2-0001-SQL-procedures.patchtext/plain; charset=UTF-8; name=v2-0001-SQL-procedures.patch; x-mac-creator=0; x-mac-type=0Download
From b150165e3b177bd9833385036b7ffbaf060ad8e2 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 14 Nov 2017 10:42:47 -0500
Subject: [PATCH v2] SQL procedures
CREATE/ALTER/DROP PROCEDURE, ALTER/DROP ROUTINE, CALL statement, utility
statement support, support in the built-in PLs, support in pg_dump and
psql
---
doc/src/sgml/catalogs.sgml | 2 +-
doc/src/sgml/ddl.sgml | 2 +-
doc/src/sgml/ecpg.sgml | 4 +-
doc/src/sgml/information_schema.sgml | 18 +-
doc/src/sgml/plpgsql.sgml | 2 +-
doc/src/sgml/ref/allfiles.sgml | 6 +
doc/src/sgml/ref/alter_default_privileges.sgml | 8 +-
doc/src/sgml/ref/alter_extension.sgml | 12 +-
doc/src/sgml/ref/alter_function.sgml | 2 +
doc/src/sgml/ref/alter_procedure.sgml | 303 +++++++++++++++++++++
doc/src/sgml/ref/alter_routine.sgml | 102 +++++++
doc/src/sgml/ref/call.sgml | 97 +++++++
doc/src/sgml/ref/comment.sgml | 13 +-
doc/src/sgml/ref/create_function.sgml | 8 +-
doc/src/sgml/ref/create_procedure.sgml | 363 +++++++++++++++++++++++++
doc/src/sgml/ref/drop_function.sgml | 2 +
doc/src/sgml/ref/drop_procedure.sgml | 162 +++++++++++
doc/src/sgml/ref/drop_routine.sgml | 94 +++++++
doc/src/sgml/ref/grant.sgml | 25 +-
doc/src/sgml/ref/revoke.sgml | 4 +-
doc/src/sgml/ref/security_label.sgml | 12 +-
doc/src/sgml/reference.sgml | 6 +
doc/src/sgml/xfunc.sgml | 33 +++
src/backend/catalog/aclchk.c | 60 +++-
src/backend/catalog/information_schema.sql | 25 +-
src/backend/catalog/objectaddress.c | 19 +-
src/backend/catalog/pg_proc.c | 3 +-
src/backend/commands/aggregatecmds.c | 2 +-
src/backend/commands/alter.c | 6 +
src/backend/commands/dropcmds.c | 38 ++-
src/backend/commands/event_trigger.c | 14 +
src/backend/commands/functioncmds.c | 131 ++++++++-
src/backend/commands/opclasscmds.c | 4 +-
src/backend/executor/functions.c | 13 +-
src/backend/nodes/copyfuncs.c | 15 +
src/backend/nodes/equalfuncs.c | 13 +
src/backend/optimizer/util/clauses.c | 1 +
src/backend/parser/gram.y | 255 ++++++++++++++++-
src/backend/parser/parse_agg.c | 11 +
src/backend/parser/parse_expr.c | 8 +
src/backend/parser/parse_func.c | 201 ++++++++------
src/backend/tcop/utility.c | 44 ++-
src/backend/utils/adt/ruleutils.c | 6 +
src/backend/utils/cache/lsyscache.c | 19 ++
src/bin/pg_dump/dumputils.c | 5 +-
src/bin/pg_dump/pg_backup_archiver.c | 7 +-
src/bin/pg_dump/pg_dump.c | 32 ++-
src/bin/pg_dump/t/002_pg_dump.pl | 38 +++
src/bin/psql/describe.c | 8 +-
src/bin/psql/tab-complete.c | 77 +++++-
src/include/commands/defrem.h | 3 +-
src/include/nodes/nodes.h | 1 +
src/include/nodes/parsenodes.h | 17 ++
src/include/parser/kwlist.h | 4 +
src/include/parser/parse_func.h | 8 +-
src/include/parser/parse_node.h | 3 +-
src/include/utils/lsyscache.h | 1 +
src/interfaces/ecpg/preproc/ecpg.tokens | 2 +-
src/interfaces/ecpg/preproc/ecpg.trailer | 5 +-
src/interfaces/ecpg/preproc/ecpg_keywords.c | 1 -
src/pl/plperl/GNUmakefile | 2 +-
src/pl/plperl/expected/plperl_call.out | 29 ++
src/pl/plperl/plperl.c | 8 +-
src/pl/plperl/sql/plperl_call.sql | 36 +++
src/pl/plpgsql/src/pl_comp.c | 88 +++---
src/pl/plpgsql/src/pl_exec.c | 8 +-
src/pl/plpython/Makefile | 1 +
src/pl/plpython/expected/plpython_call.out | 35 +++
src/pl/plpython/plpy_exec.c | 14 +-
src/pl/plpython/plpy_procedure.c | 5 +-
src/pl/plpython/plpy_procedure.h | 3 +-
src/pl/plpython/sql/plpython_call.sql | 41 +++
src/pl/tcl/Makefile | 2 +-
src/pl/tcl/expected/pltcl_call.out | 29 ++
src/pl/tcl/pltcl.c | 13 +-
src/pl/tcl/sql/pltcl_call.sql | 36 +++
src/test/regress/expected/create_procedure.out | 86 ++++++
src/test/regress/expected/object_address.out | 15 +-
src/test/regress/expected/plpgsql.out | 41 +++
src/test/regress/expected/polymorphism.out | 16 +-
src/test/regress/expected/privileges.out | 128 ++++++++-
src/test/regress/parallel_schedule | 2 +-
src/test/regress/serial_schedule | 1 +
src/test/regress/sql/create_procedure.sql | 79 ++++++
src/test/regress/sql/object_address.sql | 4 +-
src/test/regress/sql/plpgsql.sql | 49 ++++
src/test/regress/sql/privileges.sql | 55 +++-
87 files changed, 2912 insertions(+), 294 deletions(-)
create mode 100644 doc/src/sgml/ref/alter_procedure.sgml
create mode 100644 doc/src/sgml/ref/alter_routine.sgml
create mode 100644 doc/src/sgml/ref/call.sgml
create mode 100644 doc/src/sgml/ref/create_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_routine.sgml
create mode 100644 src/pl/plperl/expected/plperl_call.out
create mode 100644 src/pl/plperl/sql/plperl_call.sql
create mode 100644 src/pl/plpython/expected/plpython_call.out
create mode 100644 src/pl/plpython/sql/plpython_call.sql
create mode 100644 src/pl/tcl/expected/pltcl_call.out
create mode 100644 src/pl/tcl/sql/pltcl_call.sql
create mode 100644 src/test/regress/expected/create_procedure.out
create mode 100644 src/test/regress/sql/create_procedure.sql
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index ef60a58631..f36930c721 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -5241,7 +5241,7 @@ <title><structname>pg_proc</structname> Columns</title>
<entry><structfield>prorettype</structfield></entry>
<entry><type>oid</type></entry>
<entry><literal><link linkend="catalog-pg-type"><structname>pg_type</structname></link>.oid</literal></entry>
- <entry>Data type of the return value</entry>
+ <entry>Data type of the return value, or null for a procedure</entry>
</row>
<row>
diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml
index daba66c187..efc11b2a38 100644
--- a/doc/src/sgml/ddl.sgml
+++ b/doc/src/sgml/ddl.sgml
@@ -3947,7 +3947,7 @@ <title>Other Database Objects</title>
<listitem>
<para>
- Functions and operators
+ Functions, procedures, and operators
</para>
</listitem>
diff --git a/doc/src/sgml/ecpg.sgml b/doc/src/sgml/ecpg.sgml
index bc3d080774..f503f2d35f 100644
--- a/doc/src/sgml/ecpg.sgml
+++ b/doc/src/sgml/ecpg.sgml
@@ -4778,7 +4778,9 @@ <title>Setting Callbacks</title>
<term><literal>DO <replaceable>name</replaceable> (<replaceable>args</replaceable>)</literal></term>
<listitem>
<para>
- Call the specified C functions with the specified arguments.
+ Call the specified C functions with the specified arguments. (This
+ use is different from the meaning of <literal>CALL</literal>
+ and <literal>DO</literal> in the normal PostgreSQL grammar.)
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/information_schema.sgml b/doc/src/sgml/information_schema.sgml
index 58c54254d7..ab28acc854 100644
--- a/doc/src/sgml/information_schema.sgml
+++ b/doc/src/sgml/information_schema.sgml
@@ -3972,8 +3972,8 @@ <title><literal>routine_privileges</literal> Columns</title>
<title><literal>routines</literal></title>
<para>
- The view <literal>routines</literal> contains all functions in the
- current database. Only those functions are shown that the current
+ The view <literal>routines</literal> contains all functions and procedures in the
+ current database. Only those functions and procedures are shown that the current
user has access to (by way of being the owner or having some
privilege).
</para>
@@ -4037,8 +4037,8 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>routine_type</literal></entry>
<entry><type>character_data</type></entry>
<entry>
- Always <literal>FUNCTION</literal> (In the future there might
- be other types of routines.)
+ <literal>FUNCTION</literal> for a
+ function, <literal>PROCEDURE</literal> for a procedure
</entry>
</row>
@@ -4087,7 +4087,7 @@ <title><literal>routines</literal> Columns</title>
the view <literal>element_types</literal>), else
<literal>USER-DEFINED</literal> (in that case, the type is
identified in <literal>type_udt_name</literal> and associated
- columns).
+ columns). Null for a procedure.
</entry>
</row>
@@ -4180,7 +4180,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the database that the return data type of the function
- is defined in (always the current database)
+ is defined in (always the current database). Null for a procedure.
</entry>
</row>
@@ -4189,7 +4189,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the schema that the return data type of the function is
- defined in
+ defined in. Null for a procedure.
</entry>
</row>
@@ -4197,7 +4197,7 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>type_udt_name</literal></entry>
<entry><type>sql_identifier</type></entry>
<entry>
- Name of the return data type of the function
+ Name of the return data type of the function. Null for a procedure.
</entry>
</row>
@@ -4314,7 +4314,7 @@ <title><literal>routines</literal> Columns</title>
<entry>
If the function automatically returns null if any of its
arguments are null, then <literal>YES</literal>, else
- <literal>NO</literal>.
+ <literal>NO</literal>. Null for a procedure.
</entry>
</row>
diff --git a/doc/src/sgml/plpgsql.sgml b/doc/src/sgml/plpgsql.sgml
index 7323c2f67d..b3d72b6f95 100644
--- a/doc/src/sgml/plpgsql.sgml
+++ b/doc/src/sgml/plpgsql.sgml
@@ -5244,7 +5244,7 @@ <title>Porting a Function that Creates Another Function from <application>PL/SQL
<para>
Here is how this function would end up in <productname>PostgreSQL</productname>:
<programlisting>
-CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
+CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$
DECLARE
referrer_keys CURSOR IS
SELECT * FROM cs_referrer_keys
diff --git a/doc/src/sgml/ref/allfiles.sgml b/doc/src/sgml/ref/allfiles.sgml
index 01acc2ef9d..22e6893211 100644
--- a/doc/src/sgml/ref/allfiles.sgml
+++ b/doc/src/sgml/ref/allfiles.sgml
@@ -26,8 +26,10 @@
<!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">
@@ -48,6 +50,7 @@
<!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">
@@ -75,6 +78,7 @@
<!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">
@@ -122,8 +126,10 @@
<!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">
diff --git a/doc/src/sgml/ref/alter_default_privileges.sgml b/doc/src/sgml/ref/alter_default_privileges.sgml
index bc7401f845..42ec60a680 100644
--- a/doc/src/sgml/ref/alter_default_privileges.sgml
+++ b/doc/src/sgml/ref/alter_default_privileges.sgml
@@ -39,7 +39,7 @@
TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
- ON FUNCTIONS
+ ON { FUNCTIONS | ROUTINES }
TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
@@ -66,7 +66,7 @@
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
- ON FUNCTIONS
+ ON { FUNCTIONS | ROUTINES }
FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
@@ -93,7 +93,9 @@ <title>Description</title>
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.
+ altered. For this command, functions include aggregates and procedures.
+ The words <literal>FUNCTIONS</literal> and <literal>ROUTINES</literal> are
+ equivalent in this command.
</para>
<para>
diff --git a/doc/src/sgml/ref/alter_extension.sgml b/doc/src/sgml/ref/alter_extension.sgml
index c2b0669c38..d83b0f1dbb 100644
--- a/doc/src/sgml/ref/alter_extension.sgml
+++ b/doc/src/sgml/ref/alter_extension.sgml
@@ -45,6 +45,8 @@
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> |
@@ -170,12 +172,14 @@ <title>Parameters</title>
<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, sequences, text search objects,
+ operator classes, operator families, procedures, routines, sequences, text search objects,
types, and views can be schema-qualified.
</para>
</listitem>
@@ -204,7 +208,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -222,7 +226,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -235,7 +239,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/alter_function.sgml b/doc/src/sgml/ref/alter_function.sgml
index fd35e98a88..847e300bd4 100644
--- a/doc/src/sgml/ref/alter_function.sgml
+++ b/doc/src/sgml/ref/alter_function.sgml
@@ -359,6 +359,8 @@ <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_procedure.sgml b/doc/src/sgml/ref/alter_procedure.sgml
new file mode 100644
index 0000000000..c8fa9451c5
--- /dev/null
+++ b/doc/src/sgml/ref/alter_procedure.sgml
@@ -0,0 +1,303 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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 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> 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 needed 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.
+ </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>
+ The name of the extension that the procedure is to depend on.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>IMMUTABLE</literal></term>
+ <term><literal>STABLE</literal></term>
+ <term><literal>VOLATILE</literal></term>
+ <term><literal>PARALLEL</literal></term>
+ <term><literal>LEAKPROOF</literal></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
+
+ <listitem>
+ <para>
+ These attributes are accepted for compatibility
+ with <xref linkend="sql-alterfunction"> but are currently not used for
+ procedures.
+ </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_routine.sgml b/doc/src/sgml/ref/alter_routine.sgml
new file mode 100644
index 0000000000..d02b5618dc
--- /dev/null
+++ b/doc/src/sgml/ref/alter_routine.sgml
@@ -0,0 +1,102 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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/call.sgml b/doc/src/sgml/ref/call.sgml
new file mode 100644
index 0000000000..a0f7e6d888
--- /dev/null
+++ b/doc/src/sgml/ref/call.sgml
@@ -0,0 +1,97 @@
+<!--
+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>
+ </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 for the procedure call.
+ See <xref linkend="sql-syntax-calling-funcs"> for the full details on
+ function and procedure call syntax, including use of named parameters.
+ </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>
+ </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.
+ </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/comment.sgml b/doc/src/sgml/ref/comment.sgml
index d705792a45..1c2aa2a2b5 100644
--- a/doc/src/sgml/ref/comment.sgml
+++ b/doc/src/sgml/ref/comment.sgml
@@ -46,8 +46,10 @@
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> |
@@ -121,13 +123,15 @@ <title>Parameters</title>
<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 tables,
aggregates, collations, conversions, domains, foreign tables, functions,
- indexes, operators, operator classes, operator families, sequences,
+ indexes, operators, operator classes, operator families, procedures, routines, sequences,
statistics, text search objects, types, and views can be
schema-qualified. When commenting on a column,
<replaceable class="parameter">relation_name</replaceable> must refer
@@ -170,7 +174,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argmode</replaceable></term>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -187,7 +191,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argname</replaceable></term>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -199,7 +203,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argtype</replaceable></term>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
@@ -325,6 +329,7 @@ <title>Examples</title>
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 ROLE my_role IS 'Administration group for finance tables';
COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records';
COMMENT ON SCHEMA my_schema IS 'Departmental data';
diff --git a/doc/src/sgml/ref/create_function.sgml b/doc/src/sgml/ref/create_function.sgml
index 970dc13359..5c8d1b7e1b 100644
--- a/doc/src/sgml/ref/create_function.sgml
+++ b/doc/src/sgml/ref/create_function.sgml
@@ -55,7 +55,7 @@ <title>Description</title>
<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
+ 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 of different argument types can share a name (this is
called <firstterm>overloading</firstterm>).
@@ -450,7 +450,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
<listitem>
<para>
@@ -466,7 +466,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">result_rows</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
<listitem>
<para>
@@ -818,7 +818,7 @@ <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>
<title>Compatibility</title>
<para>
- A <command>CREATE FUNCTION</command> command is defined in SQL:1999 and later.
+ A <command>CREATE FUNCTION</command> command is defined in the SQL standard.
The <productname>PostgreSQL</productname> version is similar but
not fully compatible. The attributes are not portable, neither are the
different available languages.
diff --git a/doc/src/sgml/ref/create_procedure.sgml b/doc/src/sgml/ref/create_procedure.sgml
new file mode 100644
index 0000000000..b2948750a8
--- /dev/null
+++ b/doc/src/sgml/ref/create_procedure.sgml
@@ -0,0 +1,363 @@
+<!--
+doc/src/sgml/ref/create_procedure.sgml
+-->
+
+<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> } [, ... ]
+ | 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> | = <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>'
+ } ...
+</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 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>
+ </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> 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>. 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>IMMUTABLE</literal></term>
+ <term><literal>STABLE</literal></term>
+ <term><literal>VOLATILE</literal></term>
+ <term><literal>LEAKPROOF</literal></term>
+ <term><literal>PARALLEL</literal></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
+
+ <listitem>
+ <para>
+ These attributes are accepted for compatibility
+ with <xref linkend="sql-createfunction"> but are currently not used for
+ procedures.
+ </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>
+ </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>
+ 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 <xref linkend="SQL-LOAD"> 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>
+ </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>
+
+<programlisting>
+CREATE PROCEDURE insert_data(a integer, b integer)
+LANGUAGE SQL
+AS $$
+INSERT INTO tbl VALUES (a);
+INSERT INTO tbl VALUES (b);
+$$;
+
+CALL insert_data(1, 2);
+</programlisting>
+ </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> version is similar but
+ not fully compatible. 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/drop_function.sgml b/doc/src/sgml/ref/drop_function.sgml
index 05b405dda1..b926ca4839 100644
--- a/doc/src/sgml/ref/drop_function.sgml
+++ b/doc/src/sgml/ref/drop_function.sgml
@@ -185,6 +185,8 @@ <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>
diff --git a/doc/src/sgml/ref/drop_procedure.sgml b/doc/src/sgml/ref/drop_procedure.sgml
new file mode 100644
index 0000000000..c091822705
--- /dev/null
+++ b/doc/src/sgml/ref/drop_procedure.sgml
@@ -0,0 +1,162 @@
+<!--
+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 an existing
+ procedure. To execute this command the user must be the
+ owner of the procedure. The argument types to the
+ procedure 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. 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> 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 PROCEDURE</command> does not actually pay
+ any attention to argument names, since only the argument data
+ types are needed 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.
+ </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-examples">
+ <title>Examples</title>
+
+<programlisting>
+DROP PROCEDURE do_db_maintenance();
+</programlisting>
+ </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</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-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_routine.sgml b/doc/src/sgml/ref/drop_routine.sgml
new file mode 100644
index 0000000000..feb4bb3187
--- /dev/null
+++ b/doc/src/sgml/ref/drop_routine.sgml
@@ -0,0 +1,94 @@
+<!--
+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 an existing
+ routine, which can be an aggregate function, a normal function, or a
+ procedure. 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-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</para>
+ </listitem>
+ <listitem>
+ <para>The ability to specify argument modes and names</para>
+ </listitem>
+ <listitem>
+ <para>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/grant.sgml b/doc/src/sgml/ref/grant.sgml
index 475c85b835..39738c28ae 100644
--- a/doc/src/sgml/ref/grant.sgml
+++ b/doc/src/sgml/ref/grant.sgml
@@ -55,8 +55,8 @@
TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] }
+ 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 ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
@@ -96,7 +96,7 @@ <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,
+ table, sequence, database, foreign-data wrapper, foreign server, function, procedure,
procedural language, schema, or tablespace), and one that grants
membership in a role. These variants are similar in many ways, but
they are different enough to be described separately.
@@ -115,8 +115,11 @@ <title>GRANT on Database Objects</title>
<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, and functions (but note that <literal>ALL
- TABLES</literal> is considered to include views and foreign tables).
+ 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 functions, but not procedures,
+ again just like the specific-object <command>GRANT</command> command.
</para>
<para>
@@ -169,7 +172,7 @@ <title>GRANT on Database Objects</title>
granted to <literal>PUBLIC</literal> are as follows:
<literal>CONNECT</literal> and <literal>TEMPORARY</literal> (create
temporary tables) privileges for databases;
- <literal>EXECUTE</literal> privilege for functions; and
+ <literal>EXECUTE</literal> privilege for functions and procedures; and
<literal>USAGE</literal> privilege for languages and data types
(including domains).
The object owner can, of course, <command>REVOKE</command>
@@ -329,10 +332,12 @@ <title>GRANT on Database Objects</title>
<term><literal>EXECUTE</literal></term>
<listitem>
<para>
- Allows the use of the specified function and the use of any
- operators that are implemented on top of the function. This is
- the only type of privilege that is applicable to functions.
- (This syntax works for aggregate functions, as well.)
+ Allows the use of the specified function or procedure and the use of
+ any operators that are implemented on top of the function. This is the
+ only type of privilege that is applicable to functions and procedures.
+ The <literal>FUNCTION</literal> syntax also works for aggregate
+ functions. Or use <literal>ROUTINE</literal> to refer to a function,
+ aggregate function, or procedure regardless of what it is.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/revoke.sgml b/doc/src/sgml/ref/revoke.sgml
index e3e3f2ffc3..41e359548b 100644
--- a/doc/src/sgml/ref/revoke.sgml
+++ b/doc/src/sgml/ref/revoke.sgml
@@ -70,8 +70,8 @@
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable>schema_name</replaceable> [, ...] }
+ 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 { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
diff --git a/doc/src/sgml/ref/security_label.sgml b/doc/src/sgml/ref/security_label.sgml
index ce5a1c1975..6ff9e7a6b0 100644
--- a/doc/src/sgml/ref/security_label.sgml
+++ b/doc/src/sgml/ref/security_label.sgml
@@ -34,8 +34,10 @@
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> |
@@ -93,10 +95,12 @@ <title>Parameters</title>
<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 tables,
- aggregates, domains, foreign tables, functions, sequences, types, and
+ aggregates, domains, foreign tables, functions, procedures, routines, sequences, types, and
views can be schema-qualified.
</para>
</listitem>
@@ -119,7 +123,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -137,7 +141,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -150,7 +154,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/reference.sgml b/doc/src/sgml/reference.sgml
index 9000b3aaaa..52760ca62a 100644
--- a/doc/src/sgml/reference.sgml
+++ b/doc/src/sgml/reference.sgml
@@ -54,8 +54,10 @@ <title>SQL Commands</title>
&alterOperatorClass;
&alterOperatorFamily;
&alterPolicy;
+ &alterProcedure;
&alterPublication;
&alterRole;
+ &alterRoutine;
&alterRule;
&alterSchema;
&alterSequence;
@@ -76,6 +78,7 @@ <title>SQL Commands</title>
&alterView;
&analyze;
&begin;
+ &call;
&checkpoint;
&close;
&cluster;
@@ -103,6 +106,7 @@ <title>SQL Commands</title>
&createOperatorClass;
&createOperatorFamily;
&createPolicy;
+ &createProcedure;
&createPublication;
&createRole;
&createRule;
@@ -150,8 +154,10 @@ <title>SQL Commands</title>
&dropOperatorFamily;
&dropOwned;
&dropPolicy;
+ &dropProcedure;
&dropPublication;
&dropRole;
+ &dropRoutine;
&dropRule;
&dropSchema;
&dropSequence;
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 9bdb72cd98..f30767168d 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -72,6 +72,39 @@ <title>User-defined Functions</title>
</para>
</sect1>
+ <sect1 id="xproc">
+ <title>User-defined Procedures</title>
+
+ <indexterm zone="xproc">
+ <primary>procedure</primary>
+ <secondary>user-defined</secondary>
+ </indexterm>
+
+ <para>
+ A procedure is a database object similar to a function. The difference is
+ that a procedure does not return a value, so there is no return type
+ declaration. While a function is called as part of a query or DML
+ command, a procedure is called explicitly using
+ the <xref linkend="sql-call"> statement.
+ </para>
+
+ <para>
+ The explanations on how to define user-defined functions in the rest of
+ this chapter apply to procedures as well, except that
+ the <xref linkend="sql-createprocedure"> command is used instead, there is
+ no return type, and some other features such as strictness don't apply.
+ </para>
+
+ <para>
+ Collectively, functions and procedures are also known
+ as <firstterm>routines</firstterm><indexterm><primary>routine</primary></indexterm>.
+ There are commands such as <xref linkend="sql-alterroutine">
+ and <xref linkend="sql-droproutine"> that can operate on functions and
+ procedures without having to know which kind it is. Note, however, that
+ there is no <literal>CREATE ROUTINE</literal> command.
+ </para>
+ </sect1>
+
<sect1 id="xfunc-sql">
<title>Query Language (<acronym>SQL</acronym>) Functions</title>
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index ccde66a7dd..0b9d324918 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -482,6 +482,14 @@ ExecuteGrantStmt(GrantStmt *stmt)
all_privileges = ACL_ALL_RIGHTS_NAMESPACE;
errormsg = gettext_noop("invalid privilege type %s for schema");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TABLESPACE:
all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
errormsg = gettext_noop("invalid privilege type %s for tablespace");
@@ -584,6 +592,8 @@ ExecGrantStmt_oids(InternalGrant *istmt)
ExecGrant_ForeignServer(istmt);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
ExecGrant_Function(istmt);
break;
case ACL_OBJECT_LANGUAGE:
@@ -671,7 +681,7 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
Oid funcid;
- funcid = LookupFuncWithArgs(func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, func, false);
objects = lappend_oid(objects, funcid);
}
break;
@@ -709,6 +719,26 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
objects = lappend_oid(objects, oid);
}
break;
+ case ACL_OBJECT_PROCEDURE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid procid;
+
+ procid = LookupFuncWithArgs(OBJECT_PROCEDURE, func, false);
+ objects = lappend_oid(objects, procid);
+ }
+ break;
+ case ACL_OBJECT_ROUTINE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid routid;
+
+ routid = LookupFuncWithArgs(OBJECT_ROUTINE, func, false);
+ objects = lappend_oid(objects, routid);
+ }
+ break;
case ACL_OBJECT_TABLESPACE:
foreach(cell, objnames)
{
@@ -785,8 +815,10 @@ objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
objects = list_concat(objects, objs);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
{
- ScanKeyData key[1];
+ ScanKeyData key[2];
Relation rel;
HeapScanDesc scan;
HeapTuple tuple;
@@ -795,9 +827,21 @@ objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
Anum_pg_proc_pronamespace,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(namespaceId));
+ if (objtype == ACL_OBJECT_FUNCTION)
+ ScanKeyInit(&key[1],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDNE,
+ InvalidOid);
+ else if (objtype == ACL_OBJECT_PROCEDURE)
+ ScanKeyInit(&key[1],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDEQ,
+ InvalidOid);
rel = heap_open(ProcedureRelationId, AccessShareLock);
- scan = heap_beginscan_catalog(rel, 1, key);
+ scan = heap_beginscan_catalog(rel,
+ objtype == ACL_OBJECT_ROUTINE ? 1 : 2,
+ key);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
@@ -955,6 +999,14 @@ ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *s
all_privileges = ACL_ALL_RIGHTS_FUNCTION;
errormsg = gettext_noop("invalid privilege type %s for function");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TYPE:
all_privileges = ACL_ALL_RIGHTS_TYPE;
errormsg = gettext_noop("invalid privilege type %s for type");
@@ -1423,7 +1475,7 @@ RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
istmt.objtype = ACL_OBJECT_TYPE;
break;
case ProcedureRelationId:
- istmt.objtype = ACL_OBJECT_FUNCTION;
+ istmt.objtype = ACL_OBJECT_ROUTINE;
break;
case LanguageRelationId:
istmt.objtype = ACL_OBJECT_LANGUAGE;
diff --git a/src/backend/catalog/information_schema.sql b/src/backend/catalog/information_schema.sql
index 236f6be37e..360725d59a 100644
--- a/src/backend/catalog/information_schema.sql
+++ b/src/backend/catalog/information_schema.sql
@@ -1413,7 +1413,8 @@ CREATE VIEW routines AS
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(n.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
- CAST('FUNCTION' AS character_data) AS routine_type,
+ CAST(CASE WHEN p.prorettype <> 0 THEN 'FUNCTION' ELSE 'PROCEDURE' END
+ AS character_data) AS routine_type,
CAST(null AS sql_identifier) AS module_catalog,
CAST(null AS sql_identifier) AS module_schema,
CAST(null AS sql_identifier) AS module_name,
@@ -1422,7 +1423,8 @@ CREATE VIEW routines AS
CAST(null AS sql_identifier) AS udt_name,
CAST(
- CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
+ CASE WHEN p.prorettype = 0 THEN NULL
+ WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(t.oid, null)
ELSE 'USER-DEFINED' END AS character_data)
AS data_type,
@@ -1440,7 +1442,7 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
- CAST(current_database() AS sql_identifier) AS type_udt_catalog,
+ CAST(CASE WHEN p.prorettype <> 0 THEN current_database() END AS sql_identifier) AS type_udt_catalog,
CAST(nt.nspname AS sql_identifier) AS type_udt_schema,
CAST(t.typname AS sql_identifier) AS type_udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
@@ -1462,7 +1464,8 @@ CREATE VIEW routines AS
CAST('GENERAL' AS character_data) AS parameter_style,
CAST(CASE WHEN p.provolatile = 'i' THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_deterministic,
CAST('MODIFIES' AS character_data) AS sql_data_access,
- CAST(CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_null_call,
+ CAST(CASE WHEN p.prorettype <> 0 THEN
+ CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END END AS yes_or_no) AS is_null_call,
CAST(null AS character_data) AS sql_path,
CAST('YES' AS yes_or_no) AS schema_level_routine,
CAST(0 AS cardinal_number) AS max_dynamic_result_sets,
@@ -1503,13 +1506,15 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS result_cast_maximum_cardinality,
CAST(null AS sql_identifier) AS result_cast_dtd_identifier
- FROM pg_namespace n, pg_proc p, pg_language l,
- pg_type t, pg_namespace nt
+ FROM (pg_namespace n
+ JOIN pg_proc p ON n.oid = p.pronamespace
+ JOIN pg_language l ON p.prolang = l.oid)
+ LEFT JOIN
+ (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid)
+ ON p.prorettype = t.oid
- WHERE n.oid = p.pronamespace AND p.prolang = l.oid
- AND p.prorettype = t.oid AND t.typnamespace = nt.oid
- AND (pg_has_role(p.proowner, 'USAGE')
- OR has_function_privilege(p.oid, 'EXECUTE'));
+ WHERE (pg_has_role(p.proowner, 'USAGE')
+ OR has_function_privilege(p.oid, 'EXECUTE'));
GRANT SELECT ON routines TO PUBLIC;
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index 8d55c76fc4..9553675975 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -566,6 +566,9 @@ static const struct object_type_map
{
"function", OBJECT_FUNCTION
},
+ {
+ "procedure", OBJECT_PROCEDURE
+ },
/* OCLASS_TYPE */
{
"type", OBJECT_TYPE
@@ -884,13 +887,11 @@ get_object_address(ObjectType objtype, Node *object,
address = get_object_address_type(objtype, castNode(TypeName, object), missing_ok);
break;
case OBJECT_AGGREGATE:
- address.classId = ProcedureRelationId;
- address.objectId = LookupAggWithArgs(castNode(ObjectWithArgs, object), missing_ok);
- address.objectSubId = 0;
- break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
address.classId = ProcedureRelationId;
- address.objectId = LookupFuncWithArgs(castNode(ObjectWithArgs, object), missing_ok);
+ address.objectId = LookupFuncWithArgs(objtype, castNode(ObjectWithArgs, object), missing_ok);
address.objectSubId = 0;
break;
case OBJECT_OPERATOR:
@@ -2025,6 +2026,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
*/
if (type == OBJECT_AGGREGATE ||
type == OBJECT_FUNCTION ||
+ type == OBJECT_PROCEDURE ||
+ type == OBJECT_ROUTINE ||
type == OBJECT_OPERATOR ||
type == OBJECT_CAST ||
type == OBJECT_AMOP ||
@@ -2168,6 +2171,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
objnode = (Node *) list_make2(name, args);
break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_AGGREGATE:
case OBJECT_OPERATOR:
{
@@ -2253,6 +2258,8 @@ check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address,
break;
case OBJECT_AGGREGATE:
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
if (!pg_proc_ownercheck(address.objectId, roleid))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString((castNode(ObjectWithArgs, object))->objname));
@@ -4026,6 +4033,8 @@ getProcedureTypeDescription(StringInfo buffer, Oid procid)
if (procForm->proisagg)
appendStringInfoString(buffer, "aggregate");
+ else if (procForm->prorettype == InvalidOid)
+ appendStringInfoString(buffer, "procedure");
else
appendStringInfoString(buffer, "function");
diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c
index 47916cfb54..7d05e4bdb2 100644
--- a/src/backend/catalog/pg_proc.c
+++ b/src/backend/catalog/pg_proc.c
@@ -857,7 +857,8 @@ fmgr_sql_validator(PG_FUNCTION_ARGS)
/* Disallow pseudotype result */
/* except for RECORD, VOID, or polymorphic */
- if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
+ if (proc->prorettype &&
+ get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
proc->prorettype != RECORDOID &&
proc->prorettype != VOIDOID &&
!IsPolymorphicType(proc->prorettype))
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index adc9877e79..2e2ee883e2 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -307,7 +307,7 @@ DefineAggregate(ParseState *pstate, List *name, List *args, bool oldstyle, List
interpret_function_parameter_list(pstate,
args,
InvalidOid,
- true, /* is an aggregate */
+ OBJECT_AGGREGATE,
¶meterTypes,
&allParameterTypes,
¶meterModes,
diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
index 4f8147907c..21e3f1efe1 100644
--- a/src/backend/commands/alter.c
+++ b/src/backend/commands/alter.c
@@ -378,6 +378,8 @@ ExecRenameStmt(RenameStmt *stmt)
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
case OBJECT_LANGUAGE:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -495,6 +497,8 @@ ExecAlterObjectSchemaStmt(AlterObjectSchemaStmt *stmt,
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -842,6 +846,8 @@ ExecAlterOwnerStmt(AlterOwnerStmt *stmt)
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TABLESPACE:
case OBJECT_TSDICTIONARY:
diff --git a/src/backend/commands/dropcmds.c b/src/backend/commands/dropcmds.c
index 2b30677d6f..7e6baa1928 100644
--- a/src/backend/commands/dropcmds.c
+++ b/src/backend/commands/dropcmds.c
@@ -26,6 +26,7 @@
#include "nodes/makefuncs.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
+#include "utils/lsyscache.h"
#include "utils/syscache.h"
@@ -91,21 +92,12 @@ RemoveObjects(DropStmt *stmt)
*/
if (stmt->removeType == OBJECT_FUNCTION)
{
- Oid funcOid = address.objectId;
- HeapTuple tup;
-
- tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
- if (!HeapTupleIsValid(tup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", funcOid);
-
- if (((Form_pg_proc) GETSTRUCT(tup))->proisagg)
+ if (get_func_isagg(address.objectId))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function",
NameListToString(castNode(ObjectWithArgs, object)->objname)),
errhint("Use DROP AGGREGATE to drop aggregate functions.")));
-
- ReleaseSysCache(tup);
}
/* Check permissions. */
@@ -338,6 +330,32 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
}
break;
}
+ case OBJECT_PROCEDURE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("procedure %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
+ case OBJECT_ROUTINE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("routine %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
case OBJECT_AGGREGATE:
{
ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index fa7d0d015a..a602c20b41 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -106,8 +106,10 @@ static event_trigger_support_data event_trigger_support[] = {
{"OPERATOR CLASS", true},
{"OPERATOR FAMILY", true},
{"POLICY", true},
+ {"PROCEDURE", true},
{"PUBLICATION", true},
{"ROLE", false},
+ {"ROUTINE", true},
{"RULE", true},
{"SCHEMA", true},
{"SEQUENCE", true},
@@ -1103,8 +1105,10 @@ EventTriggerSupportsObjectType(ObjectType obtype)
case OBJECT_OPERATOR:
case OBJECT_OPFAMILY:
case OBJECT_POLICY:
+ case OBJECT_PROCEDURE:
case OBJECT_PUBLICATION:
case OBJECT_PUBLICATION_REL:
+ case OBJECT_ROUTINE:
case OBJECT_RULE:
case OBJECT_SCHEMA:
case OBJECT_SEQUENCE:
@@ -1215,6 +1219,8 @@ EventTriggerSupportsGrantObjectType(GrantObjectType objtype)
case ACL_OBJECT_LANGUAGE:
case ACL_OBJECT_LARGEOBJECT:
case ACL_OBJECT_NAMESPACE:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
case ACL_OBJECT_TYPE:
return true;
@@ -2243,6 +2249,10 @@ stringify_grantobjtype(GrantObjectType objtype)
return "LARGE OBJECT";
case ACL_OBJECT_NAMESPACE:
return "SCHEMA";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURE";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINE";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACE";
case ACL_OBJECT_TYPE:
@@ -2285,6 +2295,10 @@ stringify_adefprivs_objtype(GrantObjectType objtype)
return "LARGE OBJECTS";
case ACL_OBJECT_NAMESPACE:
return "SCHEMAS";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURES";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINES";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACES";
case ACL_OBJECT_TYPE:
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 7de844b2ca..1f3156d870 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -51,6 +51,8 @@
#include "commands/alter.h"
#include "commands/defrem.h"
#include "commands/proclang.h"
+#include "executor/execdesc.h"
+#include "executor/executor.h"
#include "miscadmin.h"
#include "optimizer/var.h"
#include "parser/parse_coerce.h"
@@ -179,7 +181,7 @@ void
interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
@@ -233,7 +235,7 @@ interpret_function_parameter_list(ParseState *pstate,
errmsg("SQL function cannot accept shell type %s",
TypeNameToString(t))));
/* We don't allow creating aggregates on shell types either */
- else if (is_aggregate)
+ else if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregate cannot accept shell type %s",
@@ -262,16 +264,28 @@ interpret_function_parameter_list(ParseState *pstate,
if (t->setof)
{
- if (is_aggregate)
+ if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregates cannot accept set arguments")));
+ else if (objtype == OBJECT_PROCEDURE)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedures cannot accept set arguments")));
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("functions cannot accept set arguments")));
}
+ if (objtype == OBJECT_PROCEDURE)
+ {
+ if (fp->mode == FUNC_PARAM_OUT || fp->mode == FUNC_PARAM_INOUT)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ (errmsg("procedures cannot have OUT parameters"))));
+ }
+
/* handle input parameters */
if (fp->mode != FUNC_PARAM_OUT && fp->mode != FUNC_PARAM_TABLE)
{
@@ -990,7 +1004,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
interpret_function_parameter_list(pstate,
stmt->parameters,
languageOid,
- false, /* not an aggregate */
+ stmt->is_procedure ? OBJECT_PROCEDURE : OBJECT_FUNCTION,
¶meterTypes,
&allParameterTypes,
¶meterModes,
@@ -999,7 +1013,24 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
&variadicArgType,
&requiredResultType);
- if (stmt->returnType)
+ if (stmt->is_procedure)
+ {
+ Assert(!stmt->returnType);
+
+ prorettype = InvalidOid;
+ returnsSet = false;
+
+ if (isStrict)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure cannot be declared as strict")));
+
+ if (isWindowFunc)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure cannot have WINDOW attribute")));
+ }
+ else if (stmt->returnType)
{
/* explicit RETURNS clause */
compute_return_type(stmt->returnType, languageOid,
@@ -1182,7 +1213,7 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
rel = heap_open(ProcedureRelationId, RowExclusiveLock);
- funcOid = LookupFuncWithArgs(stmt->func, false);
+ funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
if (!HeapTupleIsValid(tup)) /* should not happen */
@@ -1219,6 +1250,11 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
elog(ERROR, "option \"%s\" not recognized", defel->defname);
}
+ if (procForm->prorettype == InvalidOid && strict_item)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedure strictness cannot be changed")));
+
if (volatility_item)
procForm->provolatile = interpret_func_volatility(volatility_item);
if (strict_item)
@@ -1472,7 +1508,7 @@ CreateCast(CreateCastStmt *stmt)
{
Form_pg_proc procstruct;
- funcid = LookupFuncWithArgs(stmt->func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
if (!HeapTupleIsValid(tuple))
@@ -1853,7 +1889,7 @@ CreateTransform(CreateTransformStmt *stmt)
*/
if (stmt->fromsql)
{
- fromsqlfuncid = LookupFuncWithArgs(stmt->fromsql, false);
+ fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->fromsql->objname));
@@ -1879,7 +1915,7 @@ CreateTransform(CreateTransformStmt *stmt)
if (stmt->tosql)
{
- tosqlfuncid = LookupFuncWithArgs(stmt->tosql, false);
+ tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->tosql->objname));
@@ -2168,3 +2204,80 @@ ExecuteDoStmt(DoStmt *stmt)
/* execute the inline handler */
OidFunctionCall1(laninline, PointerGetDatum(codeblock));
}
+
+/*
+ * Execute CALL statement
+ */
+void
+ExecuteCallStmt(ParseState *pstate, CallStmt *stmt)
+{
+ List *targs;
+ ListCell *lc;
+ Node *node;
+ FuncExpr *fexpr;
+ int nargs;
+ int i;
+ AclResult aclresult;
+ FmgrInfo flinfo;
+ FunctionCallInfoData fcinfo;
+
+ targs = NIL;
+ foreach(lc, stmt->funccall->args)
+ {
+ targs = lappend(targs, transformExpr(pstate,
+ (Node *) lfirst(lc),
+ EXPR_KIND_CALL));
+ }
+
+ node = ParseFuncOrColumn(pstate,
+ stmt->funccall->funcname,
+ targs,
+ pstate->p_last_srf,
+ stmt->funccall,
+ true,
+ stmt->funccall->location);
+
+ fexpr = castNode(FuncExpr, node);
+
+ aclresult = pg_proc_aclcheck(fexpr->funcid, GetUserId(), ACL_EXECUTE);
+ if (aclresult != ACLCHECK_OK)
+ aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(fexpr->funcid));
+ InvokeFunctionExecuteHook(fexpr->funcid);
+
+ nargs = list_length(fexpr->args);
+
+ /* safety check; see ExecInitFunc() */
+ if (nargs > FUNC_MAX_ARGS)
+ ereport(ERROR,
+ (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
+ errmsg_plural("cannot pass more than %d argument to a procedure",
+ "cannot pass more than %d arguments to a procedure",
+ FUNC_MAX_ARGS,
+ FUNC_MAX_ARGS)));
+
+ fmgr_info(fexpr->funcid, &flinfo);
+ InitFunctionCallInfoData(fcinfo, &flinfo, nargs, fexpr->inputcollid, NULL, NULL);
+
+ i = 0;
+ foreach (lc, fexpr->args)
+ {
+ EState *estate;
+ ExprState *exprstate;
+ ExprContext *econtext;
+ Datum val;
+ bool isnull;
+
+ estate = CreateExecutorState();
+ exprstate = ExecPrepareExpr(lfirst(lc), estate);
+ econtext = CreateStandaloneExprContext();
+ val = ExecEvalExprSwitchContext(exprstate, econtext, &isnull);
+ FreeExecutorState(estate);
+
+ fcinfo.arg[i] = val;
+ fcinfo.argnull[i] = isnull;
+
+ i++;
+ }
+
+ FunctionCallInvoke(&fcinfo);
+}
diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c
index 1641e68abe..35c7c67bf5 100644
--- a/src/backend/commands/opclasscmds.c
+++ b/src/backend/commands/opclasscmds.c
@@ -520,7 +520,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
@@ -894,7 +894,7 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 98eb777421..564ccb004f 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -390,6 +390,7 @@ sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
list_make1(param),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
@@ -658,7 +659,8 @@ init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
fcache->rettype = rettype;
/* Fetch the typlen and byval info for the result type */
- get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
+ if (rettype)
+ get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
/* Remember whether we're returning setof something */
fcache->returnsSet = procedureStruct->proretset;
@@ -1322,7 +1324,7 @@ fmgr_sql(PG_FUNCTION_ARGS)
else
{
/* Should only get here for VOID functions */
- Assert(fcache->rettype == VOIDOID);
+ Assert(fcache->rettype == InvalidOid || fcache->rettype == VOIDOID);
fcinfo->isnull = true;
result = (Datum) 0;
}
@@ -1546,7 +1548,10 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
if (modifyTargetList)
*modifyTargetList = false; /* initialize for no change */
if (junkFilter)
- *junkFilter = NULL; /* initialize in case of VOID result */
+ *junkFilter = NULL; /* initialize in case of procedure/VOID result */
+
+ if (!rettype)
+ return false;
/*
* Find the last canSetTag query in the list. This isn't necessarily the
@@ -1591,7 +1596,7 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
else
{
/* Empty function body, or last statement is a utility command */
- if (rettype != VOIDOID)
+ if (rettype && rettype != VOIDOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("return type mismatch in function declared to return %s",
diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
index 76e75459b4..751f7e7eb2 100644
--- a/src/backend/nodes/copyfuncs.c
+++ b/src/backend/nodes/copyfuncs.c
@@ -3208,6 +3208,16 @@ _copyClosePortalStmt(const ClosePortalStmt *from)
return newnode;
}
+static CallStmt *
+_copyCallStmt(const CallStmt *from)
+{
+ CallStmt *newnode = makeNode(CallStmt);
+
+ COPY_NODE_FIELD(funccall);
+
+ return newnode;
+}
+
static ClusterStmt *
_copyClusterStmt(const ClusterStmt *from)
{
@@ -3409,6 +3419,7 @@ _copyCreateFunctionStmt(const CreateFunctionStmt *from)
COPY_NODE_FIELD(funcname);
COPY_NODE_FIELD(parameters);
COPY_NODE_FIELD(returnType);
+ COPY_SCALAR_FIELD(is_procedure);
COPY_NODE_FIELD(options);
COPY_NODE_FIELD(withClause);
@@ -3433,6 +3444,7 @@ _copyAlterFunctionStmt(const AlterFunctionStmt *from)
{
AlterFunctionStmt *newnode = makeNode(AlterFunctionStmt);
+ COPY_SCALAR_FIELD(objtype);
COPY_NODE_FIELD(func);
COPY_NODE_FIELD(actions);
@@ -5102,6 +5114,9 @@ copyObjectImpl(const void *from)
case T_ClosePortalStmt:
retval = _copyClosePortalStmt(from);
break;
+ case T_CallStmt:
+ retval = _copyCallStmt(from);
+ break;
case T_ClusterStmt:
retval = _copyClusterStmt(from);
break;
diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c
index 2866fd7b4a..2e869a9d5d 100644
--- a/src/backend/nodes/equalfuncs.c
+++ b/src/backend/nodes/equalfuncs.c
@@ -1201,6 +1201,14 @@ _equalClosePortalStmt(const ClosePortalStmt *a, const ClosePortalStmt *b)
return true;
}
+static bool
+_equalCallStmt(const CallStmt *a, const CallStmt *b)
+{
+ COMPARE_NODE_FIELD(funccall);
+
+ return true;
+}
+
static bool
_equalClusterStmt(const ClusterStmt *a, const ClusterStmt *b)
{
@@ -1364,6 +1372,7 @@ _equalCreateFunctionStmt(const CreateFunctionStmt *a, const CreateFunctionStmt *
COMPARE_NODE_FIELD(funcname);
COMPARE_NODE_FIELD(parameters);
COMPARE_NODE_FIELD(returnType);
+ COMPARE_SCALAR_FIELD(is_procedure);
COMPARE_NODE_FIELD(options);
COMPARE_NODE_FIELD(withClause);
@@ -1384,6 +1393,7 @@ _equalFunctionParameter(const FunctionParameter *a, const FunctionParameter *b)
static bool
_equalAlterFunctionStmt(const AlterFunctionStmt *a, const AlterFunctionStmt *b)
{
+ COMPARE_SCALAR_FIELD(objtype);
COMPARE_NODE_FIELD(func);
COMPARE_NODE_FIELD(actions);
@@ -3246,6 +3256,9 @@ equal(const void *a, const void *b)
case T_ClosePortalStmt:
retval = _equalClosePortalStmt(a, b);
break;
+ case T_CallStmt:
+ retval = _equalCallStmt(a, b);
+ break;
case T_ClusterStmt:
retval = _equalClusterStmt(a, b);
break;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 66e098f488..52140dabc1 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -4379,6 +4379,7 @@ inline_function(Oid funcid, Oid result_type, Oid result_collid,
if (funcform->prolang != SQLlanguageId ||
funcform->prosecdef ||
funcform->proretset ||
+ funcform->prorettype == InvalidOid ||
funcform->prorettype == RECORDOID ||
!heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
funcform->pronargs != list_length(args))
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index c301ca465d..ebfc94f896 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -253,7 +253,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
AlterCompositeTypeStmt AlterUserMappingStmt
AlterRoleStmt AlterRoleSetStmt AlterPolicyStmt
AlterDefaultPrivilegesStmt DefACLAction
- AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
+ AnalyzeStmt CallStmt ClosePortalStmt ClusterStmt CommentStmt
ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
CreateDomainStmt CreateExtensionStmt CreateGroupStmt CreateOpClassStmt
CreateOpFamilyStmt AlterOpFamilyStmt CreatePLangStmt
@@ -611,7 +611,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
BOOLEAN_P BOTH BY
- CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
+ CACHE CALL CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
CLUSTER COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
@@ -660,14 +660,14 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
PARALLEL PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
- PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROGRAM PUBLICATION
+ PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
QUOTE
RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
- ROW ROWS RULE
+ ROUTINE ROUTINES ROW ROWS RULE
SAVEPOINT SCHEMA SCHEMAS SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
@@ -845,6 +845,7 @@ stmt :
| AlterTSDictionaryStmt
| AlterUserMappingStmt
| AnalyzeStmt
+ | CallStmt
| CheckPointStmt
| ClosePortalStmt
| ClusterStmt
@@ -940,6 +941,20 @@ stmt :
{ $$ = NULL; }
;
+/*****************************************************************************
+ *
+ * CALL statement
+ *
+ *****************************************************************************/
+
+CallStmt: CALL func_application
+ {
+ CallStmt *n = makeNode(CallStmt);
+ n->funccall = castNode(FuncCall, $2);
+ $$ = (Node *)n;
+ }
+ ;
+
/*****************************************************************************
*
* Create a new Postgres DBMS role
@@ -4554,6 +4569,24 @@ AlterExtensionContentsStmt:
n->object = (Node *) lcons(makeString($9), $7);
$$ = (Node *)n;
}
+ | ALTER EXTENSION name add_drop PROCEDURE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
+ | ALTER EXTENSION name add_drop ROUTINE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
| ALTER EXTENSION name add_drop SCHEMA name
{
AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
@@ -6436,6 +6469,22 @@ CommentStmt:
n->comment = $8;
$$ = (Node *) n;
}
+ | COMMENT ON PROCEDURE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
+ | COMMENT ON ROUTINE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
| COMMENT ON RULE name ON any_name IS comment_text
{
CommentStmt *n = makeNode(CommentStmt);
@@ -6614,6 +6663,26 @@ SecLabelStmt:
n->label = $9;
$$ = (Node *) n;
}
+ | SECURITY LABEL opt_provider ON PROCEDURE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
+ | SECURITY LABEL opt_provider ON ROUTINE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
;
opt_provider: FOR NonReservedWord_or_Sconst { $$ = $2; }
@@ -6977,6 +7046,22 @@ privilege_target:
n->objs = $2;
$$ = n;
}
+ | PROCEDURE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $2;
+ $$ = n;
+ }
+ | ROUTINE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $2;
+ $$ = n;
+ }
| DATABASE name_list
{
PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
@@ -7057,6 +7142,22 @@ privilege_target:
n->objs = $5;
$$ = n;
}
+ | ALL PROCEDURES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $5;
+ $$ = n;
+ }
+ | ALL ROUTINES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $5;
+ $$ = n;
+ }
;
@@ -7213,6 +7314,7 @@ DefACLAction:
defacl_privilege_target:
TABLES { $$ = ACL_OBJECT_RELATION; }
| FUNCTIONS { $$ = ACL_OBJECT_FUNCTION; }
+ | ROUTINES { $$ = ACL_OBJECT_FUNCTION; }
| SEQUENCES { $$ = ACL_OBJECT_SEQUENCE; }
| TYPES_P { $$ = ACL_OBJECT_TYPE; }
| SCHEMAS { $$ = ACL_OBJECT_NAMESPACE; }
@@ -7413,6 +7515,18 @@ CreateFunctionStmt:
n->withClause = $7;
$$ = (Node *)n;
}
+ | CREATE opt_or_replace PROCEDURE func_name func_args_with_defaults
+ createfunc_opt_list
+ {
+ CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
+ n->replace = $2;
+ n->funcname = $4;
+ n->parameters = $5;
+ n->returnType = NULL;
+ n->is_procedure = true;
+ n->options = $6;
+ $$ = (Node *)n;
+ }
;
opt_or_replace:
@@ -7830,7 +7944,7 @@ table_func_column_list:
;
/*****************************************************************************
- * ALTER FUNCTION
+ * ALTER FUNCTION / ALTER PROCEDURE / ALTER ROUTINE
*
* RENAME and OWNER subcommands are already provided by the generic
* ALTER infrastructure, here we just specify alterations that can
@@ -7841,6 +7955,23 @@ AlterFunctionStmt:
ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
{
AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_FUNCTION;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER PROCEDURE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER ROUTINE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_ROUTINE;
n->func = $3;
n->actions = $4;
$$ = (Node *) n;
@@ -7865,6 +7996,8 @@ opt_restrict:
* QUERY:
*
* DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP PROCEDURE procname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP ROUTINE routname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
* DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
* DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
*
@@ -7891,6 +8024,46 @@ RemoveFuncStmt:
n->concurrent = false;
$$ = (Node *)n;
}
+ | DROP PROCEDURE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP PROCEDURE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
;
RemoveAggrStmt:
@@ -8348,6 +8521,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = true;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER PUBLICATION name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8357,6 +8539,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER ROUTINE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8736,6 +8927,22 @@ AlterObjectDependsStmt:
n->extname = makeString($7);
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
| ALTER TRIGGER name ON qualified_name DEPENDS ON EXTENSION name
{
AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
@@ -8851,6 +9058,24 @@ AlterObjectSchemaStmt:
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER TABLE relation_expr SET SCHEMA name
{
AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
@@ -9126,6 +9351,22 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec
n->newowner = $9;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name OWNER TO RoleSpec
{
AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
@@ -14689,6 +14930,7 @@ unreserved_keyword:
| BEGIN_P
| BY
| CACHE
+ | CALL
| CALLED
| CASCADE
| CASCADED
@@ -14848,6 +15090,7 @@ unreserved_keyword:
| PRIVILEGES
| PROCEDURAL
| PROCEDURE
+ | PROCEDURES
| PROGRAM
| PUBLICATION
| QUOTE
@@ -14874,6 +15117,8 @@ unreserved_keyword:
| ROLE
| ROLLBACK
| ROLLUP
+ | ROUTINE
+ | ROUTINES
| ROWS
| RULE
| SAVEPOINT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 64111f315e..4c4f4cdc3d 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -508,6 +508,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
break;
+ case EXPR_KIND_CALL:
+ if (isAgg)
+ err = _("aggregate functions are not allowed in CALL arguments");
+ else
+ err = _("grouping operations are not allowed in CALL arguments");
+
+ break;
+
/*
* There is intentionally no default: case here, so that the
* compiler will warn if we add a new ParseExprKind without
@@ -883,6 +891,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("window functions are not allowed in partition key expression");
break;
+ case EXPR_KIND_CALL:
+ err = _("window functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 86d1da0677..29f9da796f 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -480,6 +480,7 @@ transformIndirection(ParseState *pstate, A_Indirection *ind)
list_make1(result),
last_srf,
NULL,
+ false,
location);
if (newresult == NULL)
unknown_attribute(pstate, result, strVal(n), location);
@@ -629,6 +630,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -676,6 +678,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -736,6 +739,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -1477,6 +1481,7 @@ transformFuncCall(ParseState *pstate, FuncCall *fn)
targs,
last_srf,
fn,
+ false,
fn->location);
}
@@ -1812,6 +1817,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_RETURNING:
case EXPR_KIND_VALUES:
case EXPR_KIND_VALUES_SINGLE:
+ case EXPR_KIND_CALL:
/* okay */
break;
case EXPR_KIND_CHECK_CONSTRAINT:
@@ -3462,6 +3468,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "WHEN";
case EXPR_KIND_PARTITION_EXPRESSION:
return "PARTITION BY";
+ case EXPR_KIND_CALL:
+ return "CALL";
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index a11843332b..2f20516e76 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -71,7 +71,7 @@ static Node *ParseComplexProjection(ParseState *pstate, const char *funcname,
*/
Node *
ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location)
+ Node *last_srf, FuncCall *fn, bool proc_call, int location)
{
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
@@ -263,7 +263,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
actual_arg_types[0], rettype, -1,
COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
}
- else if (fdresult == FUNCDETAIL_NORMAL)
+ else if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
/*
* Normal function found; was there anything indicating it must be an
@@ -306,6 +306,26 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("OVER specified, but %s is not a window function nor an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_NORMAL && proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is not a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a function, use SELECT."),
+ parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a procedure, use CALL."),
+ parser_errposition(pstate, location)));
}
else if (fdresult == FUNCDETAIL_AGGREGATE)
{
@@ -635,7 +655,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
check_srf_call_placement(pstate, last_srf, location);
/* build the appropriate output structure */
- if (fdresult == FUNCDETAIL_NORMAL)
+ if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
FuncExpr *funcexpr = makeNode(FuncExpr);
@@ -1589,6 +1609,8 @@ func_get_detail(List *funcname,
result = FUNCDETAIL_AGGREGATE;
else if (pform->proiswindow)
result = FUNCDETAIL_WINDOWFUNC;
+ else if (pform->prorettype == InvalidOid)
+ result = FUNCDETAIL_PROCEDURE;
else
result = FUNCDETAIL_NORMAL;
ReleaseSysCache(ftup);
@@ -1984,16 +2006,28 @@ LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
/*
* LookupFuncWithArgs
- * Like LookupFuncName, but the argument types are specified by a
- * ObjectWithArgs node.
+ *
+ * Like LookupFuncName, but the argument types are specified by a
+ * ObjectWithArgs node. Also, this function can check whether the result is a
+ * function, procedure, or aggregate, based on the objtype argument. Pass
+ * OBJECT_ROUTINE to accept any of them.
+ *
+ * For historical reasons, we also accept aggregates when looking for a
+ * function.
*/
Oid
-LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
+LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
{
Oid argoids[FUNC_MAX_ARGS];
int argcount;
int i;
ListCell *args_item;
+ Oid oid;
+
+ Assert(objtype == OBJECT_AGGREGATE ||
+ objtype == OBJECT_FUNCTION ||
+ objtype == OBJECT_PROCEDURE ||
+ objtype == OBJECT_ROUTINE);
argcount = list_length(func->objargs);
if (argcount > FUNC_MAX_ARGS)
@@ -2013,90 +2047,100 @@ LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
args_item = lnext(args_item);
}
- return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
-}
-
-/*
- * LookupAggWithArgs
- * Find an aggregate function from a given ObjectWithArgs node.
- *
- * This is almost like LookupFuncWithArgs, but the error messages refer
- * to aggregates rather than plain functions, and we verify that the found
- * function really is an aggregate.
- */
-Oid
-LookupAggWithArgs(ObjectWithArgs *agg, bool noError)
-{
- Oid argoids[FUNC_MAX_ARGS];
- int argcount;
- int i;
- ListCell *lc;
- Oid oid;
- HeapTuple ftup;
- Form_pg_proc pform;
-
- argcount = list_length(agg->objargs);
- if (argcount > FUNC_MAX_ARGS)
- ereport(ERROR,
- (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
- errmsg_plural("functions cannot have more than %d argument",
- "functions cannot have more than %d arguments",
- FUNC_MAX_ARGS,
- FUNC_MAX_ARGS)));
+ /*
+ * When looking for a function or routine, we pass noError through to
+ * LookupFuncName and let it make any error messages. Otherwise, we make
+ * our own errors for the aggregate and procedure cases.
+ */
+ oid = LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids,
+ (objtype == OBJECT_FUNCTION || objtype == OBJECT_ROUTINE) ? noError : true);
- i = 0;
- foreach(lc, agg->objargs)
+ if (objtype == OBJECT_FUNCTION)
{
- TypeName *t = (TypeName *) lfirst(lc);
-
- argoids[i] = LookupTypeNameOid(NULL, t, noError);
- i++;
+ /* Make sure it's a function, not a procedure */
+ if (oid && get_func_rettype(oid) == InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a function",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
}
-
- oid = LookupFuncName(agg->objname, argcount, argoids, true);
-
- if (!OidIsValid(oid))
+ else if (objtype == OBJECT_PROCEDURE)
{
- if (noError)
- return InvalidOid;
- if (argcount == 0)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s(*) does not exist",
- NameListToString(agg->objname))));
- else
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a procedure named \"%s\"",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("procedure %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+
+ /* Make sure it's a procedure */
+ if (get_func_rettype(oid) != InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s does not exist",
- func_signature_string(agg->objname, argcount,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a procedure",
+ func_signature_string(func->objname, argcount,
NIL, argoids))));
+ }
}
-
- /* Make sure it's an aggregate */
- ftup = SearchSysCache1(PROCOID, ObjectIdGetDatum(oid));
- if (!HeapTupleIsValid(ftup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", oid);
- pform = (Form_pg_proc) GETSTRUCT(ftup);
-
- if (!pform->proisagg)
+ else if (objtype == OBJECT_AGGREGATE)
{
- ReleaseSysCache(ftup);
- if (noError)
- return InvalidOid;
- /* we do not use the (*) notation for functions... */
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function %s is not an aggregate",
- func_signature_string(agg->objname, argcount,
- NIL, argoids))));
- }
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a aggregate named \"%s\"",
+ NameListToString(func->objname))));
+ else if (argcount == 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s(*) does not exist",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
- ReleaseSysCache(ftup);
+ /* Make sure it's an aggregate */
+ if (!get_func_isagg(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ /* we do not use the (*) notation for functions... */
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("function %s is not an aggregate",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+ }
return oid;
}
-
/*
* check_srf_call_placement
* Verify that a set-returning function is called in a valid place,
@@ -2236,6 +2280,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("set-returning functions are not allowed in partition key expressions");
break;
+ case EXPR_KIND_CALL:
+ err = _("set-returning functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 82a707af7b..4da1f8f643 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -657,6 +657,10 @@ standard_ProcessUtility(PlannedStmt *pstmt,
}
break;
+ case T_CallStmt:
+ ExecuteCallStmt(pstate, castNode(CallStmt, parsetree));
+ break;
+
case T_ClusterStmt:
/* we choose to allow this during "read only" transactions */
PreventCommandDuringRecovery("CLUSTER");
@@ -1957,9 +1961,15 @@ AlterObjectTypeCommandTag(ObjectType objtype)
case OBJECT_POLICY:
tag = "ALTER POLICY";
break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
case OBJECT_ROLE:
tag = "ALTER ROLE";
break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
case OBJECT_RULE:
tag = "ALTER RULE";
break;
@@ -2261,6 +2271,12 @@ CreateCommandTag(Node *parsetree)
case OBJECT_FUNCTION:
tag = "DROP FUNCTION";
break;
+ case OBJECT_PROCEDURE:
+ tag = "DROP PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "DROP ROUTINE";
+ break;
case OBJECT_AGGREGATE:
tag = "DROP AGGREGATE";
break;
@@ -2359,7 +2375,20 @@ CreateCommandTag(Node *parsetree)
break;
case T_AlterFunctionStmt:
- tag = "ALTER FUNCTION";
+ switch (((AlterFunctionStmt *) parsetree)->objtype)
+ {
+ case OBJECT_FUNCTION:
+ tag = "ALTER FUNCTION";
+ break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
+ default:
+ tag = "???";
+ }
break;
case T_GrantStmt:
@@ -2438,7 +2467,10 @@ CreateCommandTag(Node *parsetree)
break;
case T_CreateFunctionStmt:
- tag = "CREATE FUNCTION";
+ if (((CreateFunctionStmt *) parsetree)->is_procedure)
+ tag = "CREATE PROCEDURE";
+ else
+ tag = "CREATE FUNCTION";
break;
case T_IndexStmt:
@@ -2493,6 +2525,10 @@ CreateCommandTag(Node *parsetree)
tag = "LOAD";
break;
+ case T_CallStmt:
+ tag = "CALL";
+ break;
+
case T_ClusterStmt:
tag = "CLUSTER";
break;
@@ -3116,6 +3152,10 @@ GetCommandLogLevel(Node *parsetree)
lev = LOGSTMT_ALL;
break;
+ case T_CallStmt:
+ lev = LOGSTMT_ALL;
+ break;
+
case T_ClusterStmt:
lev = LOGSTMT_DDL;
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 06cf32f5d7..8514c21c40 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -2691,6 +2691,12 @@ pg_get_function_result(PG_FUNCTION_ARGS)
if (!HeapTupleIsValid(proctup))
PG_RETURN_NULL();
+ if (((Form_pg_proc) GETSTRUCT(proctup))->prorettype == InvalidOid)
+ {
+ ReleaseSysCache(proctup);
+ PG_RETURN_NULL();
+ }
+
initStringInfo(&buf);
print_function_rettype(&buf, proctup);
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index 0ea2f2bc54..5211360777 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -1614,6 +1614,25 @@ func_parallel(Oid funcid)
return result;
}
+/*
+ * get_func_isagg
+ * Given procedure id, return the function's proisagg field.
+ */
+bool
+get_func_isagg(Oid funcid)
+{
+ HeapTuple tp;
+ bool result;
+
+ tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
+ if (!HeapTupleIsValid(tp))
+ elog(ERROR, "cache lookup failed for function %u", funcid);
+
+ result = ((Form_pg_proc) GETSTRUCT(tp))->proisagg;
+ ReleaseSysCache(tp);
+ return result;
+}
+
/*
* get_func_leakproof
* Given procedure id, return the function's leakproof field.
diff --git a/src/bin/pg_dump/dumputils.c b/src/bin/pg_dump/dumputils.c
index 70d8f24d17..12290a1aae 100644
--- a/src/bin/pg_dump/dumputils.c
+++ b/src/bin/pg_dump/dumputils.c
@@ -33,7 +33,7 @@ static void AddAcl(PQExpBuffer aclbuf, const char *keyword,
* name: the object name, in the form to use in the commands (already quoted)
* subname: the sub-object name, if any (already quoted); NULL if none
* type: the object type (as seen in GRANT command: must be one of
- * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
+ * TABLE, SEQUENCE, FUNCTION, PROCEDURE, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
* FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT)
* acls: the ACL string fetched from the database
* racls: the ACL string of any initial-but-now-revoked privileges
@@ -524,6 +524,9 @@ do { \
else if (strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "FUNCTIONS") == 0)
CONVERT_PRIV('X', "EXECUTE");
+ else if (strcmp(type, "PROCEDURE") == 0 ||
+ strcmp(type, "PROCEDURES") == 0)
+ CONVERT_PRIV('X', "EXECUTE");
else if (strcmp(type, "LANGUAGE") == 0)
CONVERT_PRIV('U', "USAGE");
else if (strcmp(type, "SCHEMA") == 0 ||
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index ec2fa8b9b9..41741aefbc 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -2889,7 +2889,8 @@ _tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt)
if (ropt->indexNames.head != NULL && (!(simple_string_list_member(&ropt->indexNames, te->tag))))
return 0;
}
- else if (strcmp(te->desc, "FUNCTION") == 0)
+ else if (strcmp(te->desc, "FUNCTION") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0)
{
if (!ropt->selFunction)
return 0;
@@ -3388,7 +3389,8 @@ _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "OPERATOR") == 0 ||
strcmp(type, "OPERATOR CLASS") == 0 ||
- strcmp(type, "OPERATOR FAMILY") == 0)
+ strcmp(type, "OPERATOR FAMILY") == 0 ||
+ strcmp(type, "PROCEDURE") == 0)
{
/* Chop "DROP " off the front and make a modifiable copy */
char *first = pg_strdup(te->dropStmt + 5);
@@ -3560,6 +3562,7 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData)
strcmp(te->desc, "OPERATOR") == 0 ||
strcmp(te->desc, "OPERATOR CLASS") == 0 ||
strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0 ||
strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
strcmp(te->desc, "SCHEMA") == 0 ||
strcmp(te->desc, "EVENT TRIGGER") == 0 ||
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index d8fb356130..e6701aaa78 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -11349,6 +11349,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char *funcargs;
char *funciargs;
char *funcresult;
+ bool is_procedure;
char *proallargtypes;
char *proargmodes;
char *proargnames;
@@ -11370,6 +11371,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char **argnames = NULL;
char **configitems = NULL;
int nconfigitems = 0;
+ const char *keyword;
int i;
/* Skip if not to be dumped */
@@ -11513,7 +11515,11 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
{
funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
- funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
+ is_procedure = PQgetisnull(res, 0, PQfnumber(res, "funcresult"));
+ if (is_procedure)
+ funcresult = NULL;
+ else
+ funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
proallargtypes = proargmodes = proargnames = NULL;
}
else
@@ -11522,6 +11528,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
funcargs = funciargs = funcresult = NULL;
+ is_procedure = false;
}
if (PQfnumber(res, "protrftypes") != -1)
protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
@@ -11653,22 +11660,29 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
funcsig_tag = format_function_signature(fout, finfo, false);
+ keyword = is_procedure ? "PROCEDURE" : "FUNCTION";
+
/*
* DROP must be fully qualified in case same name appears in pg_catalog
*/
- appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
+ appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
+ keyword,
fmtId(finfo->dobj.namespace->dobj.name),
funcsig);
- appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
+ appendPQExpBuffer(q, "CREATE %s %s",
+ keyword,
+ funcfullsig ? funcfullsig :
funcsig);
- if (funcresult)
- appendPQExpBuffer(q, "RETURNS %s", funcresult);
+ if (is_procedure)
+ ;
+ else if (funcresult)
+ appendPQExpBuffer(q, " RETURNS %s", funcresult);
else
{
rettypename = getFormattedTypeName(fout, finfo->prorettype,
zeroAsOpaque);
- appendPQExpBuffer(q, "RETURNS %s%s",
+ appendPQExpBuffer(q, " RETURNS %s%s",
(proretset[0] == 't') ? "SETOF " : "",
rettypename);
free(rettypename);
@@ -11775,7 +11789,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
appendPQExpBuffer(q, "\n %s;\n", asPart->data);
- appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
+ appendPQExpBuffer(labelq, "%s %s", keyword, funcsig);
if (dopt->binary_upgrade)
binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
@@ -11786,7 +11800,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.namespace->dobj.name,
NULL,
finfo->rolname, false,
- "FUNCTION", SECTION_PRE_DATA,
+ keyword, SECTION_PRE_DATA,
q->data, delqry->data, NULL,
NULL, 0,
NULL, NULL);
@@ -11803,7 +11817,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.catId, 0, finfo->dobj.dumpId);
if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
- dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
+ dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
funcsig, NULL, funcsig_tag,
finfo->dobj.namespace->dobj.name,
finfo->rolname, finfo->proacl, finfo->rproacl,
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index fa3b56a426..7cf9bdadb2 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -3654,6 +3654,44 @@
section_data => 1,
section_post_data => 1, }, },
+ 'CREATE PROCEDURE dump_test.ptest1' => {
+ all_runs => 1,
+ create_order => 41,
+ create_sql => 'CREATE PROCEDURE dump_test.ptest1(a int)
+ LANGUAGE SQL AS $$ INSERT INTO dump_test.test_table (col1) VALUES (a) $$;',
+ regexp => qr/^
+ \QCREATE PROCEDURE ptest1(a integer)\E
+ \n\s+\QLANGUAGE sql\E
+ \n\s+AS\ \$\$\Q INSERT INTO dump_test.test_table (col1) VALUES (a) \E\$\$;
+ /xm,
+ like => {
+ binary_upgrade => 1,
+ clean => 1,
+ clean_if_exists => 1,
+ createdb => 1,
+ defaults => 1,
+ exclude_test_table => 1,
+ exclude_test_table_data => 1,
+ no_blobs => 1,
+ no_privs => 1,
+ no_owner => 1,
+ only_dump_test_schema => 1,
+ pg_dumpall_dbprivs => 1,
+ schema_only => 1,
+ section_pre_data => 1,
+ test_schema_plus_blobs => 1,
+ with_oids => 1, },
+ unlike => {
+ column_inserts => 1,
+ data_only => 1,
+ exclude_dump_test_schema => 1,
+ only_dump_test_table => 1,
+ pg_dumpall_globals => 1,
+ pg_dumpall_globals_clean => 1,
+ role => 1,
+ section_data => 1,
+ section_post_data => 1, }, },
+
'CREATE TYPE dump_test.int42 populated' => {
all_runs => 1,
create_order => 42,
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index b7b978a361..0b0644a653 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -353,6 +353,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
" CASE\n"
" WHEN p.proisagg THEN '%s'\n"
" WHEN p.proiswindow THEN '%s'\n"
+ " WHEN p.prorettype = 0 THEN '%s'\n"
" WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
" ELSE '%s'\n"
" END as \"%s\"",
@@ -361,8 +362,9 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("window"),
+ gettext_noop("proc"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else if (pset.sversion >= 80100)
appendPQExpBuffer(&buf,
@@ -407,7 +409,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else
appendPQExpBuffer(&buf,
@@ -424,7 +426,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
if (verbose)
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index b3e3799c13..468e50aa31 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -397,7 +397,7 @@ static const SchemaQuery Query_for_list_of_functions = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
- NULL,
+ "p.prorettype <> 0",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
@@ -423,6 +423,36 @@ static const SchemaQuery Query_for_list_of_indexes = {
NULL
};
+static const SchemaQuery Query_for_list_of_procedures = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ "p.prorettype = 0",
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_routines = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
static const SchemaQuery Query_for_list_of_sequences = {
/* catname */
"pg_catalog.pg_class c",
@@ -1032,8 +1062,10 @@ static const pgsql_thing_t words_after_create[] = {
{"OWNED", NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
{"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
{"POLICY", NULL, NULL},
+ {"PROCEDURE", NULL, &Query_for_list_of_procedures},
{"PUBLICATION", Query_for_list_of_publications},
{"ROLE", Query_for_list_of_roles},
+ {"ROUTINE", NULL, &Query_for_list_of_routines, THING_NO_CREATE},
{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
{"SCHEMA", Query_for_list_of_schemas},
{"SEQUENCE", NULL, &Query_for_list_of_sequences},
@@ -1407,7 +1439,7 @@ psql_completion(const char *text, int start, int end)
/* Known command-starting keywords. */
static const char *const sql_commands[] = {
- "ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER",
+ "ABORT", "ALTER", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
"COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
"DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
"FETCH", "GRANT", "IMPORT", "INSERT", "LISTEN", "LOAD", "LOCK",
@@ -1520,11 +1552,11 @@ psql_completion(const char *text, int start, int end)
/* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
else if (TailMatches7("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
COMPLETE_WITH_CONST("SET TABLESPACE");
- /* ALTER AGGREGATE,FUNCTION <name> */
- else if (Matches3("ALTER", "AGGREGATE|FUNCTION", MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> */
+ else if (Matches3("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- /* ALTER AGGREGATE,FUNCTION <name> (...) */
- else if (Matches4("ALTER", "AGGREGATE|FUNCTION", MatchAny, MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> (...) */
+ else if (Matches4("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny))
{
if (ends_with(prev_wd, ')'))
COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
@@ -2145,6 +2177,11 @@ psql_completion(const char *text, int start, int end)
/* ROLLBACK */
else if (Matches1("ROLLBACK"))
COMPLETE_WITH_LIST4("WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
+/* CALL */
+ else if (Matches1("CALL"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (Matches2("CALL", MatchAny))
+ COMPLETE_WITH_CONST("(");
/* CLUSTER */
else if (Matches1("CLUSTER"))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, "UNION SELECT 'VERBOSE'");
@@ -2176,6 +2213,7 @@ psql_completion(const char *text, int start, int end)
"SERVER", "INDEX", "LANGUAGE", "POLICY", "PUBLICATION", "RULE",
"SCHEMA", "SEQUENCE", "STATISTICS", "SUBSCRIPTION",
"TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
+ "PROCEDURE", "ROUTINE",
"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
"TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
@@ -2685,7 +2723,7 @@ psql_completion(const char *text, int start, int end)
"COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
MatchAny) ||
Matches4("DROP", "ACCESS", "METHOD", MatchAny) ||
- (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, MatchAny) &&
+ (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
ends_with(prev_wd, ')')) ||
Matches4("DROP", "EVENT", "TRIGGER", MatchAny) ||
Matches5("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
@@ -2694,9 +2732,9 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
/* help completing some of the variants */
- else if (Matches3("DROP", "AGGREGATE|FUNCTION", MatchAny))
+ else if (Matches3("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- else if (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, "("))
+ else if (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
else if (Matches2("DROP", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
@@ -2893,10 +2931,12 @@ psql_completion(const char *text, int start, int end)
* objects supported.
*/
if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES"))
- COMPLETE_WITH_LIST5("TABLES", "SEQUENCES", "FUNCTIONS", "TYPES", "SCHEMAS");
+ COMPLETE_WITH_LIST7("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS");
else
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf,
" UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
+ " UNION SELECT 'ALL PROCEDURES IN SCHEMA'"
+ " UNION SELECT 'ALL ROUTINES IN SCHEMA'"
" UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
" UNION SELECT 'ALL TABLES IN SCHEMA'"
" UNION SELECT 'DATABASE'"
@@ -2906,6 +2946,8 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'FUNCTION'"
" UNION SELECT 'LANGUAGE'"
" UNION SELECT 'LARGE OBJECT'"
+ " UNION SELECT 'PROCEDURE'"
+ " UNION SELECT 'ROUTINE'"
" UNION SELECT 'SCHEMA'"
" UNION SELECT 'SEQUENCE'"
" UNION SELECT 'TABLE'"
@@ -2913,7 +2955,10 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'TYPE'");
}
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "ALL"))
- COMPLETE_WITH_LIST3("FUNCTIONS IN SCHEMA", "SEQUENCES IN SCHEMA",
+ COMPLETE_WITH_LIST5("FUNCTIONS IN SCHEMA",
+ "PROCEDURES IN SCHEMA",
+ "ROUTINES IN SCHEMA",
+ "SEQUENCES IN SCHEMA",
"TABLES IN SCHEMA");
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "SERVER");
@@ -2934,6 +2979,10 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (TailMatches1("LANGUAGE"))
COMPLETE_WITH_QUERY(Query_for_list_of_languages);
+ else if (TailMatches1("PROCEDURE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (TailMatches1("ROUTINE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
else if (TailMatches1("SCHEMA"))
COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
else if (TailMatches1("SEQUENCE"))
@@ -3163,7 +3212,7 @@ psql_completion(const char *text, int start, int end)
static const char *const list_SECURITY_LABEL[] =
{"TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
"EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION", "LARGE OBJECT",
- "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "ROLE", "SCHEMA",
+ "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
"SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW", NULL};
COMPLETE_WITH_LIST(list_SECURITY_LABEL);
@@ -3233,8 +3282,8 @@ psql_completion(const char *text, int start, int end)
/* Complete SET <var> with "TO" */
else if (Matches2("SET", MatchAny))
COMPLETE_WITH_CONST("TO");
- /* Complete ALTER DATABASE|FUNCTION|ROLE|USER ... SET <name> */
- else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|ROLE|USER") &&
+ /* Complete ALTER DATABASE|FUNCTION||PROCEDURE|ROLE|ROUTINE|USER ... SET <name> */
+ else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER") &&
TailMatches2("SET", MatchAny))
COMPLETE_WITH_LIST2("FROM CURRENT", "TO");
/* Suggest possible variable values */
diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
index bfead9af3d..52cbf61ccb 100644
--- a/src/include/commands/defrem.h
+++ b/src/include/commands/defrem.h
@@ -59,12 +59,13 @@ extern void DropTransformById(Oid transformOid);
extern void IsThereFunctionInNamespace(const char *proname, int pronargs,
oidvector *proargtypes, Oid nspOid);
extern void ExecuteDoStmt(DoStmt *stmt);
+extern void ExecuteCallStmt(ParseState *pstate, CallStmt *stmt);
extern Oid get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok);
extern Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok);
extern void interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h
index ffeeb4919b..43ee88bd39 100644
--- a/src/include/nodes/nodes.h
+++ b/src/include/nodes/nodes.h
@@ -413,6 +413,7 @@ typedef enum NodeTag
T_DropSubscriptionStmt,
T_CreateStatsStmt,
T_AlterCollationStmt,
+ T_CallStmt,
/*
* TAGS FOR PARSE TREE NODES (parsenodes.h)
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 34d6afc80f..c4ff1c5544 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -355,6 +355,7 @@ typedef struct FuncCall
bool agg_distinct; /* arguments were labeled DISTINCT */
bool func_variadic; /* last argument was labeled VARIADIC */
struct WindowDef *over; /* OVER clause, if any */
+ bool proc_call; /* CALL statement */
int location; /* token location, or -1 if unknown */
} FuncCall;
@@ -1642,9 +1643,11 @@ typedef enum ObjectType
OBJECT_OPERATOR,
OBJECT_OPFAMILY,
OBJECT_POLICY,
+ OBJECT_PROCEDURE,
OBJECT_PUBLICATION,
OBJECT_PUBLICATION_REL,
OBJECT_ROLE,
+ OBJECT_ROUTINE,
OBJECT_RULE,
OBJECT_SCHEMA,
OBJECT_SEQUENCE,
@@ -1856,6 +1859,8 @@ typedef enum GrantObjectType
ACL_OBJECT_LANGUAGE, /* procedural language */
ACL_OBJECT_LARGEOBJECT, /* largeobject */
ACL_OBJECT_NAMESPACE, /* namespace */
+ ACL_OBJECT_PROCEDURE, /* procedure */
+ ACL_OBJECT_ROUTINE, /* routine */
ACL_OBJECT_TABLESPACE, /* tablespace */
ACL_OBJECT_TYPE /* type */
} GrantObjectType;
@@ -2749,6 +2754,7 @@ typedef struct CreateFunctionStmt
List *funcname; /* qualified name of function to create */
List *parameters; /* a list of FunctionParameter */
TypeName *returnType; /* the return type */
+ bool is_procedure;
List *options; /* a list of DefElem */
List *withClause; /* a list of DefElem */
} CreateFunctionStmt;
@@ -2775,6 +2781,7 @@ typedef struct FunctionParameter
typedef struct AlterFunctionStmt
{
NodeTag type;
+ ObjectType objtype;
ObjectWithArgs *func; /* name and args of function */
List *actions; /* list of DefElem */
} AlterFunctionStmt;
@@ -2799,6 +2806,16 @@ typedef struct InlineCodeBlock
bool langIsTrusted; /* trusted property of the language */
} InlineCodeBlock;
+/* ----------------------
+ * CALL statement
+ * ----------------------
+ */
+typedef struct CallStmt
+{
+ NodeTag type;
+ FuncCall *funccall;
+} CallStmt;
+
/* ----------------------
* Alter Object Rename Statement
* ----------------------
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index f50e45e886..a932400058 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -63,6 +63,7 @@ PG_KEYWORD("boolean", BOOLEAN_P, COL_NAME_KEYWORD)
PG_KEYWORD("both", BOTH, RESERVED_KEYWORD)
PG_KEYWORD("by", BY, UNRESERVED_KEYWORD)
PG_KEYWORD("cache", CACHE, UNRESERVED_KEYWORD)
+PG_KEYWORD("call", CALL, UNRESERVED_KEYWORD)
PG_KEYWORD("called", CALLED, UNRESERVED_KEYWORD)
PG_KEYWORD("cascade", CASCADE, UNRESERVED_KEYWORD)
PG_KEYWORD("cascaded", CASCADED, UNRESERVED_KEYWORD)
@@ -310,6 +311,7 @@ PG_KEYWORD("prior", PRIOR, UNRESERVED_KEYWORD)
PG_KEYWORD("privileges", PRIVILEGES, UNRESERVED_KEYWORD)
PG_KEYWORD("procedural", PROCEDURAL, UNRESERVED_KEYWORD)
PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD)
+PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD)
@@ -340,6 +342,8 @@ PG_KEYWORD("right", RIGHT, TYPE_FUNC_NAME_KEYWORD)
PG_KEYWORD("role", ROLE, UNRESERVED_KEYWORD)
PG_KEYWORD("rollback", ROLLBACK, UNRESERVED_KEYWORD)
PG_KEYWORD("rollup", ROLLUP, UNRESERVED_KEYWORD)
+PG_KEYWORD("routine", ROUTINE, UNRESERVED_KEYWORD)
+PG_KEYWORD("routines", ROUTINES, UNRESERVED_KEYWORD)
PG_KEYWORD("row", ROW, COL_NAME_KEYWORD)
PG_KEYWORD("rows", ROWS, UNRESERVED_KEYWORD)
PG_KEYWORD("rule", RULE, UNRESERVED_KEYWORD)
diff --git a/src/include/parser/parse_func.h b/src/include/parser/parse_func.h
index b4b6084b1b..fccccd21ed 100644
--- a/src/include/parser/parse_func.h
+++ b/src/include/parser/parse_func.h
@@ -24,6 +24,7 @@ typedef enum
FUNCDETAIL_NOTFOUND, /* no matching function */
FUNCDETAIL_MULTIPLE, /* too many matching functions */
FUNCDETAIL_NORMAL, /* found a matching regular function */
+ FUNCDETAIL_PROCEDURE, /* found a matching procedure */
FUNCDETAIL_AGGREGATE, /* found a matching aggregate function */
FUNCDETAIL_WINDOWFUNC, /* found a matching window function */
FUNCDETAIL_COERCION /* it's a type coercion request */
@@ -31,7 +32,8 @@ typedef enum
extern Node *ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location);
+ Node *last_srf, FuncCall *fn, bool proc_call,
+ int location);
extern FuncDetailCode func_get_detail(List *funcname,
List *fargs, List *fargnames,
@@ -62,10 +64,8 @@ extern const char *func_signature_string(List *funcname, int nargs,
extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes,
bool noError);
-extern Oid LookupFuncWithArgs(ObjectWithArgs *func,
+extern Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func,
bool noError);
-extern Oid LookupAggWithArgs(ObjectWithArgs *agg,
- bool noError);
extern void check_srf_call_placement(ParseState *pstate, Node *last_srf,
int location);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f0e210ad8d..565bb3dc6c 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -67,7 +67,8 @@ typedef enum ParseExprKind
EXPR_KIND_EXECUTE_PARAMETER, /* parameter value in EXECUTE */
EXPR_KIND_TRIGGER_WHEN, /* WHEN condition in CREATE TRIGGER */
EXPR_KIND_POLICY, /* USING or WITH CHECK expr in policy */
- EXPR_KIND_PARTITION_EXPRESSION /* PARTITION BY expression */
+ EXPR_KIND_PARTITION_EXPRESSION, /* PARTITION BY expression */
+ EXPR_KIND_CALL /* CALL argument */
} ParseExprKind;
diff --git a/src/include/utils/lsyscache.h b/src/include/utils/lsyscache.h
index 07208b56ce..b316cc594c 100644
--- a/src/include/utils/lsyscache.h
+++ b/src/include/utils/lsyscache.h
@@ -118,6 +118,7 @@ extern bool get_func_retset(Oid funcid);
extern bool func_strict(Oid funcid);
extern char func_volatile(Oid funcid);
extern char func_parallel(Oid funcid);
+extern bool get_func_isagg(Oid funcid);
extern bool get_func_leakproof(Oid funcid);
extern float4 get_func_cost(Oid funcid);
extern float4 get_func_rows(Oid funcid);
diff --git a/src/interfaces/ecpg/preproc/ecpg.tokens b/src/interfaces/ecpg/preproc/ecpg.tokens
index 68ba925efe..1d613af02f 100644
--- a/src/interfaces/ecpg/preproc/ecpg.tokens
+++ b/src/interfaces/ecpg/preproc/ecpg.tokens
@@ -2,7 +2,7 @@
/* special embedded SQL tokens */
%token SQL_ALLOCATE SQL_AUTOCOMMIT SQL_BOOL SQL_BREAK
- SQL_CALL SQL_CARDINALITY SQL_CONNECT
+ SQL_CARDINALITY SQL_CONNECT
SQL_COUNT
SQL_DATETIME_INTERVAL_CODE
SQL_DATETIME_INTERVAL_PRECISION SQL_DESCRIBE
diff --git a/src/interfaces/ecpg/preproc/ecpg.trailer b/src/interfaces/ecpg/preproc/ecpg.trailer
index f60a62099d..19dc781885 100644
--- a/src/interfaces/ecpg/preproc/ecpg.trailer
+++ b/src/interfaces/ecpg/preproc/ecpg.trailer
@@ -1460,13 +1460,13 @@ action : CONTINUE_P
$<action>$.command = NULL;
$<action>$.str = mm_strdup("continue");
}
- | SQL_CALL name '(' c_args ')'
+ | CALL name '(' c_args ')'
{
$<action>$.code = W_DO;
$<action>$.command = cat_str(4, $2, mm_strdup("("), $4, mm_strdup(")"));
$<action>$.str = cat2_str(mm_strdup("call"), mm_strdup($<action>$.command));
}
- | SQL_CALL name
+ | CALL name
{
$<action>$.code = W_DO;
$<action>$.command = cat2_str($2, mm_strdup("()"));
@@ -1482,7 +1482,6 @@ ECPGKeywords: ECPGKeywords_vanames { $$ = $1; }
;
ECPGKeywords_vanames: SQL_BREAK { $$ = mm_strdup("break"); }
- | SQL_CALL { $$ = mm_strdup("call"); }
| SQL_CARDINALITY { $$ = mm_strdup("cardinality"); }
| SQL_COUNT { $$ = mm_strdup("count"); }
| SQL_DATETIME_INTERVAL_CODE { $$ = mm_strdup("datetime_interval_code"); }
diff --git a/src/interfaces/ecpg/preproc/ecpg_keywords.c b/src/interfaces/ecpg/preproc/ecpg_keywords.c
index 3b52b8f3a2..848b2d4849 100644
--- a/src/interfaces/ecpg/preproc/ecpg_keywords.c
+++ b/src/interfaces/ecpg/preproc/ecpg_keywords.c
@@ -33,7 +33,6 @@ static const ScanKeyword ECPGScanKeywords[] = {
{"autocommit", SQL_AUTOCOMMIT, 0},
{"bool", SQL_BOOL, 0},
{"break", SQL_BREAK, 0},
- {"call", SQL_CALL, 0},
{"cardinality", SQL_CARDINALITY, 0},
{"connect", SQL_CONNECT, 0},
{"count", SQL_COUNT, 0},
diff --git a/src/pl/plperl/GNUmakefile b/src/pl/plperl/GNUmakefile
index 91d1296b21..b829027d05 100644
--- a/src/pl/plperl/GNUmakefile
+++ b/src/pl/plperl/GNUmakefile
@@ -55,7 +55,7 @@ endif # win32
SHLIB_LINK = $(perl_embed_ldflags)
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=plperl --load-extension=plperlu
-REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array
+REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array plperl_call
# if Perl can support two interpreters in one backend,
# test plperl-and-plperlu cases
ifneq ($(PERL),)
diff --git a/src/pl/plperl/expected/plperl_call.out b/src/pl/plperl/expected/plperl_call.out
new file mode 100644
index 0000000000..4bccfcb7c8
--- /dev/null
+++ b/src/pl/plperl/expected/plperl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index a57393fbdd..9f5313235f 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -1915,7 +1915,7 @@ plperl_inline_handler(PG_FUNCTION_ARGS)
desc.fn_retistuple = false;
desc.fn_retisset = false;
desc.fn_retisarray = false;
- desc.result_oid = VOIDOID;
+ desc.result_oid = InvalidOid;
desc.nargs = 0;
desc.reference = NULL;
@@ -2481,7 +2481,7 @@ plperl_func_handler(PG_FUNCTION_ARGS)
}
retval = (Datum) 0;
}
- else
+ else if (prodesc->result_oid)
{
retval = plperl_sv_to_datum(perlret,
prodesc->result_oid,
@@ -2826,7 +2826,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -3343,7 +3343,7 @@ plperl_return_next_internal(SV *sv)
tuplestore_puttuple(current_call_data->tuple_store, tuple);
}
- else
+ else if (prodesc->result_oid)
{
Datum ret[1];
bool isNull[1];
diff --git a/src/pl/plperl/sql/plperl_call.sql b/src/pl/plperl/sql/plperl_call.sql
new file mode 100644
index 0000000000..bd2b63b418
--- /dev/null
+++ b/src/pl/plperl/sql/plperl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/plpgsql/src/pl_comp.c b/src/pl/plpgsql/src/pl_comp.c
index d0afa59242..f459c02f7b 100644
--- a/src/pl/plpgsql/src/pl_comp.c
+++ b/src/pl/plpgsql/src/pl_comp.c
@@ -275,7 +275,6 @@ do_compile(FunctionCallInfo fcinfo,
bool isnull;
char *proc_source;
HeapTuple typeTup;
- Form_pg_type typeStruct;
PLpgSQL_variable *var;
PLpgSQL_rec *rec;
int i;
@@ -531,53 +530,58 @@ do_compile(FunctionCallInfo fcinfo,
/*
* Lookup the function's return type
*/
- typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
- if (!HeapTupleIsValid(typeTup))
- elog(ERROR, "cache lookup failed for type %u", rettypeid);
- typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
-
- /* Disallow pseudotype result, except VOID or RECORD */
- /* (note we already replaced polymorphic types) */
- if (typeStruct->typtype == TYPTYPE_PSEUDO)
+ if (rettypeid)
{
- if (rettypeid == VOIDOID ||
- rettypeid == RECORDOID)
- /* okay */ ;
- else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("trigger functions can only be called as triggers")));
- else
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("PL/pgSQL functions cannot return type %s",
- format_type_be(rettypeid))));
- }
+ Form_pg_type typeStruct;
- if (typeStruct->typrelid != InvalidOid ||
- rettypeid == RECORDOID)
- function->fn_retistuple = true;
- else
- {
- function->fn_retbyval = typeStruct->typbyval;
- function->fn_rettyplen = typeStruct->typlen;
+ typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
+ if (!HeapTupleIsValid(typeTup))
+ elog(ERROR, "cache lookup failed for type %u", rettypeid);
+ typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
- /*
- * install $0 reference, but only for polymorphic return
- * types, and not when the return is specified through an
- * output parameter.
- */
- if (IsPolymorphicType(procStruct->prorettype) &&
- num_out_args == 0)
+ /* Disallow pseudotype result, except VOID or RECORD */
+ /* (note we already replaced polymorphic types) */
+ if (typeStruct->typtype == TYPTYPE_PSEUDO)
{
- (void) plpgsql_build_variable("$0", 0,
- build_datatype(typeTup,
- -1,
- function->fn_input_collation),
- true);
+ if (rettypeid == VOIDOID ||
+ rettypeid == RECORDOID)
+ /* okay */ ;
+ else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("trigger functions can only be called as triggers")));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("PL/pgSQL functions cannot return type %s",
+ format_type_be(rettypeid))));
+ }
+
+ if (typeStruct->typrelid != InvalidOid ||
+ rettypeid == RECORDOID)
+ function->fn_retistuple = true;
+ else
+ {
+ function->fn_retbyval = typeStruct->typbyval;
+ function->fn_rettyplen = typeStruct->typlen;
+
+ /*
+ * install $0 reference, but only for polymorphic return
+ * types, and not when the return is specified through an
+ * output parameter.
+ */
+ if (IsPolymorphicType(procStruct->prorettype) &&
+ num_out_args == 0)
+ {
+ (void) plpgsql_build_variable("$0", 0,
+ build_datatype(typeTup,
+ -1,
+ function->fn_input_collation),
+ true);
+ }
}
+ ReleaseSysCache(typeTup);
}
- ReleaseSysCache(typeTup);
break;
case PLPGSQL_DML_TRIGGER:
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 7a6dd15460..882b16e2b1 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -462,7 +462,7 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
estate.err_text = NULL;
estate.err_stmt = (PLpgSQL_stmt *) (func->action);
rc = exec_stmt_block(&estate, func->action);
- if (rc != PLPGSQL_RC_RETURN)
+ if (rc != PLPGSQL_RC_RETURN && func->fn_rettype)
{
estate.err_stmt = NULL;
estate.err_text = NULL;
@@ -509,6 +509,12 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
}
else if (!estate.retisnull)
{
+ if (!func->fn_rettype)
+ {
+ ereport(ERROR,
+ (errmsg("cannot return a value from a procedure")));
+ }
+
if (estate.retistuple)
{
/*
diff --git a/src/pl/plpython/Makefile b/src/pl/plpython/Makefile
index 7680d49cb6..cc91afebde 100644
--- a/src/pl/plpython/Makefile
+++ b/src/pl/plpython/Makefile
@@ -78,6 +78,7 @@ REGRESS = \
plpython_spi \
plpython_newline \
plpython_void \
+ plpython_call \
plpython_params \
plpython_setof \
plpython_record \
diff --git a/src/pl/plpython/expected/plpython_call.out b/src/pl/plpython/expected/plpython_call.out
new file mode 100644
index 0000000000..58c184e2ea
--- /dev/null
+++ b/src/pl/plpython/expected/plpython_call.out
@@ -0,0 +1,35 @@
+--
+-- Tests for procedures / CALL syntax
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+CALL test_proc1();
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+CALL test_proc2();
+ERROR: PL/Python procedure did not return None
+CONTEXT: PL/Python function "test_proc2"
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plpython/plpy_exec.c b/src/pl/plpython/plpy_exec.c
index 26f61dd0f3..1b7a9470d4 100644
--- a/src/pl/plpython/plpy_exec.c
+++ b/src/pl/plpython/plpy_exec.c
@@ -197,12 +197,19 @@ PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
error_context_stack = &plerrcontext;
/*
- * If the function is declared to return void, the Python return value
+ * For a procedure or function declared to return void, the Python return value
* must be None. For void-returning functions, we also treat a None
* return value as a special "void datum" rather than NULL (as is the
* case for non-void-returning functions).
*/
- if (proc->result.out.d.typoid == VOIDOID)
+ if (proc->is_procedure)
+ {
+ if (plrv != Py_None)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("PL/Python procedure did not return None")));
+ }
+ else if (proc->result.out.d.typoid == VOIDOID)
{
if (plrv != Py_None)
ereport(ERROR,
@@ -715,7 +722,8 @@ plpython_return_error_callback(void *arg)
{
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
- if (exec_ctx->curr_proc)
+ if (exec_ctx->curr_proc &&
+ !exec_ctx->curr_proc->is_procedure)
errcontext("while creating return value");
}
diff --git a/src/pl/plpython/plpy_procedure.c b/src/pl/plpython/plpy_procedure.c
index 26acc88b27..7b04a60e90 100644
--- a/src/pl/plpython/plpy_procedure.c
+++ b/src/pl/plpython/plpy_procedure.c
@@ -188,6 +188,7 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
proc->fn_tid = procTup->t_self;
proc->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
proc->is_setof = procStruct->proretset;
+ proc->is_procedure = (procStruct->prorettype == InvalidOid);
PLy_typeinfo_init(&proc->result, proc->mcxt);
proc->src = NULL;
proc->argnames = NULL;
@@ -207,9 +208,9 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
/*
* get information required for output conversion of the return value,
- * but only if this isn't a trigger.
+ * but only if this isn't a trigger or procedure.
*/
- if (!is_trigger)
+ if (!is_trigger && procStruct->prorettype)
{
HeapTuple rvTypeTup;
Form_pg_type rvTypeStruct;
diff --git a/src/pl/plpython/plpy_procedure.h b/src/pl/plpython/plpy_procedure.h
index d05944fc39..0bb1b652b0 100644
--- a/src/pl/plpython/plpy_procedure.h
+++ b/src/pl/plpython/plpy_procedure.h
@@ -30,7 +30,8 @@ typedef struct PLyProcedure
TransactionId fn_xmin;
ItemPointerData fn_tid;
bool fn_readonly;
- bool is_setof; /* true, if procedure returns result set */
+ bool is_setof; /* true, if function returns result set */
+ bool is_procedure;
PLyTypeInfo result; /* also used to store info for trigger tuple
* type */
char *src; /* textual procedure code, after mangling */
diff --git a/src/pl/plpython/sql/plpython_call.sql b/src/pl/plpython/sql/plpython_call.sql
new file mode 100644
index 0000000000..3fb74de5f0
--- /dev/null
+++ b/src/pl/plpython/sql/plpython_call.sql
@@ -0,0 +1,41 @@
+--
+-- Tests for procedures / CALL syntax
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/tcl/Makefile b/src/pl/tcl/Makefile
index b8971d3cc8..6a92a9b6aa 100644
--- a/src/pl/tcl/Makefile
+++ b/src/pl/tcl/Makefile
@@ -28,7 +28,7 @@ DATA = pltcl.control pltcl--1.0.sql pltcl--unpackaged--1.0.sql \
pltclu.control pltclu--1.0.sql pltclu--unpackaged--1.0.sql
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=pltcl
-REGRESS = pltcl_setup pltcl_queries pltcl_start_proc pltcl_subxact pltcl_unicode
+REGRESS = pltcl_setup pltcl_queries pltcl_call pltcl_start_proc pltcl_subxact pltcl_unicode
# Tcl on win32 ships with import libraries only for Microsoft Visual C++,
# which are not compatible with mingw gcc. Therefore we need to build a
diff --git a/src/pl/tcl/expected/pltcl_call.out b/src/pl/tcl/expected/pltcl_call.out
new file mode 100644
index 0000000000..7221a37ad0
--- /dev/null
+++ b/src/pl/tcl/expected/pltcl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 6d97ddc99b..e0792d93e1 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -146,6 +146,7 @@ typedef struct pltcl_proc_desc
Oid result_typid; /* OID of fn's result type */
FmgrInfo result_in_func; /* input function for fn's result type */
Oid result_typioparam; /* param to pass to same */
+ bool fn_is_procedure;/* true if this is a procedure */
bool fn_retisset; /* true if function returns a set */
bool fn_retistuple; /* true if function returns composite */
bool fn_retisdomain; /* true if function returns domain */
@@ -968,7 +969,7 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
retval = (Datum) 0;
fcinfo->isnull = true;
}
- else if (fcinfo->isnull)
+ else if (fcinfo->isnull && !prodesc->fn_is_procedure)
{
retval = InputFunctionCall(&prodesc->result_in_func,
NULL,
@@ -1026,11 +1027,13 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
call_state);
retval = HeapTupleGetDatum(tup);
}
- else
+ else if (!prodesc->fn_is_procedure)
retval = InputFunctionCall(&prodesc->result_in_func,
utf_u2e(Tcl_GetStringResult(interp)),
prodesc->result_typioparam,
-1);
+ else
+ retval = 0;
return retval;
}
@@ -1506,7 +1509,9 @@ compile_pltcl_function(Oid fn_oid, Oid tgreloid,
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ prodesc->fn_is_procedure = (procStruct->prorettype == InvalidOid);
+
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -2199,7 +2204,7 @@ pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
tuplestore_puttuple(call_state->tuple_store, tuple);
}
}
- else
+ else if (!prodesc->fn_is_procedure)
{
Datum retval;
bool isNull = false;
diff --git a/src/pl/tcl/sql/pltcl_call.sql b/src/pl/tcl/sql/pltcl_call.sql
new file mode 100644
index 0000000000..ef1f540f50
--- /dev/null
+++ b/src/pl/tcl/sql/pltcl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/test/regress/expected/create_procedure.out b/src/test/regress/expected/create_procedure.out
new file mode 100644
index 0000000000..eeb129d71f
--- /dev/null
+++ b/src/test/regress/expected/create_procedure.out
@@ -0,0 +1,86 @@
+CALL nonexistent(); -- error
+ERROR: function nonexistent() does not exist
+LINE 1: CALL nonexistent();
+ ^
+HINT: No function matches the given name and argument types. You might need to add explicit type casts.
+CALL random(); -- error
+ERROR: random() is not a procedure
+LINE 1: CALL random();
+ ^
+HINT: To call a function, use SELECT.
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+CREATE TABLE cp_test (a int, b text);
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+SELECT ptest1('x'); -- error
+ERROR: ptest1(unknown) is a procedure
+LINE 1: SELECT ptest1('x');
+ ^
+HINT: To call a procedure, use CALL.
+CALL ptest1('a'); -- ok
+\df ptest1
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+--------+------------------+---------------------+------
+ public | ptest1 | | x text | proc
+(1 row)
+
+SELECT * FROM cp_test ORDER BY a;
+ a | b
+---+---
+ 1 | a
+(1 row)
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+CALL ptest2();
+-- various error cases
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedure cannot have WINDOW attribute
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedure cannot be declared as strict
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedures cannot have OUT parameters
+ALTER PROCEDURE ptest1(text) STRICT;
+ERROR: procedure strictness cannot be changed
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ERROR: ptest1(text) is not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+ERROR: procedure nonexistent() does not exist
+DROP FUNCTION ptest1(text); -- error: not a function
+ERROR: ptest1(text) is not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+DROP PROCEDURE nonexistent();
+ERROR: procedure nonexistent() does not exist
+-- privileges
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+ERROR: permission denied for function ptest1
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+-- ROUTINE syntax
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+DROP ROUTINE testfunc1(int);
+-- cleanup
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+DROP TABLE cp_test;
+DROP USER regress_user1;
diff --git a/src/test/regress/expected/object_address.out b/src/test/regress/expected/object_address.out
index 1fdadbc9ef..bfd9d54c11 100644
--- a/src/test/regress/expected/object_address.out
+++ b/src/test/regress/expected/object_address.out
@@ -29,6 +29,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -88,7 +89,7 @@ BEGIN
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -171,6 +172,12 @@ WARNING: error for function,{addr_nsp,zwei},{}: function addr_nsp.zwei() does n
WARNING: error for function,{addr_nsp,zwei},{integer}: function addr_nsp.zwei(integer) does not exist
WARNING: error for function,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for function,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins},{}: procedure eins() does not exist
+WARNING: error for procedure,{eins},{integer}: procedure eins(integer) does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{}: procedure addr_nsp.zwei() does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{integer}: procedure addr_nsp.zwei(integer) does not exist
+WARNING: error for procedure,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for type,{eins},{}: type "eins" does not exist
WARNING: error for type,{eins},{integer}: type "eins" does not exist
WARNING: error for type,{addr_nsp,zwei},{}: name list length must be exactly 1
@@ -371,6 +378,7 @@ WITH objects (type, name, args) AS (VALUES
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
@@ -431,6 +439,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
type | addr_nsp | gendomain | addr_nsp.gendomain | t
function | pg_catalog | | pg_catalog.pg_identify_object(pg_catalog.oid,pg_catalog.oid,integer) | t
aggregate | addr_nsp | | addr_nsp.genaggr(integer) | t
+ procedure | addr_nsp | | addr_nsp.proc(integer) | t
sequence | addr_nsp | gentable_a_seq | addr_nsp.gentable_a_seq | t
table | addr_nsp | gentable | addr_nsp.gentable | t
table column | addr_nsp | gentable | addr_nsp.gentable.b | t
@@ -469,7 +478,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
subscription | | addr_sub | addr_sub | t
publication | | addr_pub | addr_pub | t
publication relation | | | gentable in publication addr_pub | t
-(46 rows)
+(47 rows)
---
--- Cleanup resources
@@ -480,6 +489,6 @@ NOTICE: drop cascades to 4 other objects
DROP PUBLICATION addr_pub;
DROP SUBSCRIPTION addr_sub;
DROP SCHEMA addr_nsp CASCADE;
-NOTICE: drop cascades to 12 other objects
+NOTICE: drop cascades to 13 other objects
DROP OWNED BY regress_addr_user;
DROP USER regress_addr_user;
diff --git a/src/test/regress/expected/plpgsql.out b/src/test/regress/expected/plpgsql.out
index bb3532676b..d6e5bc3353 100644
--- a/src/test/regress/expected/plpgsql.out
+++ b/src/test/regress/expected/plpgsql.out
@@ -6040,3 +6040,44 @@ END; $$ LANGUAGE plpgsql;
ERROR: "x" is not a scalar variable
LINE 3: GET DIAGNOSTICS x = ROW_COUNT;
^
+--
+-- Procedures
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+CALL test_proc1();
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+CALL test_proc2();
+ERROR: cannot return a value from a procedure
+CONTEXT: PL/pgSQL function test_proc2() while casting return value to function's return type
+CREATE TABLE proc_test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+CALL test_proc3(55);
+SELECT * FROM proc_test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE proc_test1;
diff --git a/src/test/regress/expected/polymorphism.out b/src/test/regress/expected/polymorphism.out
index 91cfb743b6..66e35a6a5c 100644
--- a/src/test/regress/expected/polymorphism.out
+++ b/src/test/regress/expected/polymorphism.out
@@ -915,10 +915,10 @@ select dfunc();
-- verify it lists properly
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-----------------------------------------------------------+--------
- public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-----------------------------------------------------------+------
+ public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | func
(1 row)
drop function dfunc(int, int);
@@ -1083,10 +1083,10 @@ $$ select array_upper($1, 1) $$ language sql;
ERROR: cannot remove parameter defaults from existing function
HINT: Use DROP FUNCTION dfunc(integer[]) first.
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-------------------------------------------------+--------
- public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-------------------------------------------------+------
+ public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | func
(1 row)
drop function dfunc(a variadic int[]);
diff --git a/src/test/regress/expected/privileges.out b/src/test/regress/expected/privileges.out
index 771971a095..e6994f0490 100644
--- a/src/test/regress/expected/privileges.out
+++ b/src/test/regress/expected/privileges.out
@@ -651,13 +651,25 @@ GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
WARNING: no privileges were granted for "sql"
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testproc1(int) AS 'select $1;' LANGUAGE sql;
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
+REVOKE ALL ON FUNCTION testproc1(int) FROM PUBLIC; -- fail, not a function
+ERROR: testproc1(integer) is not a function
+REVOKE ALL ON PROCEDURE testproc1(int) FROM PUBLIC;
+GRANT EXECUTE ON PROCEDURE testproc1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
ERROR: invalid privilege type USAGE for function
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
+ERROR: invalid privilege type USAGE for function
+GRANT USAGE ON PROCEDURE testproc1(int) TO regress_user3; -- semantic error
+ERROR: invalid privilege type USAGE for procedure
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
ERROR: function testfunc_nosuch(integer) does not exist
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON PROCEDURE testproc1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
LANGUAGE sql SECURITY DEFINER;
@@ -671,9 +683,20 @@ SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
ERROR: permission denied for language sql
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
+CALL testproc1(6); -- ok
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
ERROR: permission denied for function testfunc1
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
+ERROR: permission denied for function testagg1
+CALL testproc1(6); -- fail
+ERROR: permission denied for function testproc1
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
ERROR: permission denied for relation atest2
SELECT testfunc4(true); -- ok
@@ -689,8 +712,19 @@ SELECT testfunc1(5); -- ok
10
(1 row)
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
+CALL testproc1(6); -- ok
DROP FUNCTION testfunc1(int); -- fail
ERROR: must be owner of function testfunc1
+DROP AGGREGATE testagg1(int); -- fail
+ERROR: must be owner of function testagg1
+DROP PROCEDURE testproc1(int); -- fail
+ERROR: must be owner of function testproc1
\c -
DROP FUNCTION testfunc1(int); -- ok
-- restore to sanity
@@ -1537,22 +1571,54 @@ SELECT has_schema_privilege('regress_user2', 'testns5', 'CREATE'); -- no
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
has_function_privilege
------------------------
f
(1 row)
-ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- no
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON ROUTINES to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+DROP PROCEDURE testns.bar();
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- yes (counts as function here)
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
+DROP PROCEDURE testns.bar();
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
CREATE DOMAIN testns.testdomain1 AS int;
SELECT has_type_privilege('regress_user2', 'testns.testdomain1', 'USAGE'); -- no
@@ -1631,12 +1697,26 @@ SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
(1 row)
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.testproc(int) AS 'select 3' LANGUAGE sql;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true by default
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
has_function_privilege
@@ -1644,9 +1724,47 @@ SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'
f
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- still true, not a function
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+REVOKE ALL ON ALL PROCEDURES IN SCHEMA testns FROM PUBLIC;
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- now false
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+GRANT ALL ON ALL ROUTINES IN SCHEMA testns TO PUBLIC;
+SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
-NOTICE: drop cascades to 3 other objects
+NOTICE: drop cascades to 5 other objects
\set VERBOSITY default
-- Change owner of the schema & and rename of new schema owner
\c -
@@ -1729,8 +1847,10 @@ drop table dep_priv_test;
-- clean up
\c
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
+DROP PROCEDURE testproc1(int);
DROP VIEW atestv0;
DROP VIEW atestv1;
DROP VIEW atestv2;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index aa5e6af621..9343aa02c7 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -53,7 +53,7 @@ test: copy copyselect copydml
# ----------
# More groups of parallel tests
# ----------
-test: create_misc create_operator
+test: create_misc create_operator create_procedure
# These depend on the above two
test: create_index create_view
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index 3866314a92..8dd4b7ba0c 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -63,6 +63,7 @@ test: copyselect
test: copydml
test: create_misc
test: create_operator
+test: create_procedure
test: create_index
test: create_view
test: create_aggregate
diff --git a/src/test/regress/sql/create_procedure.sql b/src/test/regress/sql/create_procedure.sql
new file mode 100644
index 0000000000..f09ba2ad30
--- /dev/null
+++ b/src/test/regress/sql/create_procedure.sql
@@ -0,0 +1,79 @@
+CALL nonexistent(); -- error
+CALL random(); -- error
+
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+
+CREATE TABLE cp_test (a int, b text);
+
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+
+SELECT ptest1('x'); -- error
+CALL ptest1('a'); -- ok
+
+\df ptest1
+
+SELECT * FROM cp_test ORDER BY a;
+
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+
+CALL ptest2();
+
+
+-- various error cases
+
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+
+ALTER PROCEDURE ptest1(text) STRICT;
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+
+DROP FUNCTION ptest1(text); -- error: not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+DROP PROCEDURE nonexistent();
+
+
+-- privileges
+
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+
+
+-- ROUTINE syntax
+
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+
+DROP ROUTINE testfunc1(int);
+
+
+-- cleanup
+
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+
+DROP TABLE cp_test;
+
+DROP USER regress_user1;
diff --git a/src/test/regress/sql/object_address.sql b/src/test/regress/sql/object_address.sql
index 63821b8008..55faa71edf 100644
--- a/src/test/regress/sql/object_address.sql
+++ b/src/test/regress/sql/object_address.sql
@@ -32,6 +32,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -81,7 +82,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -147,6 +148,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
diff --git a/src/test/regress/sql/plpgsql.sql b/src/test/regress/sql/plpgsql.sql
index 6620ea6172..1c355132b7 100644
--- a/src/test/regress/sql/plpgsql.sql
+++ b/src/test/regress/sql/plpgsql.sql
@@ -4820,3 +4820,52 @@ CREATE FUNCTION fx(x WSlot) RETURNS void AS $$
GET DIAGNOSTICS x = ROW_COUNT;
RETURN;
END; $$ LANGUAGE plpgsql;
+
+
+--
+-- Procedures
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE proc_test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM proc_test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE proc_test1;
diff --git a/src/test/regress/sql/privileges.sql b/src/test/regress/sql/privileges.sql
index a900ba2f84..ea8dd028cd 100644
--- a/src/test/regress/sql/privileges.sql
+++ b/src/test/regress/sql/privileges.sql
@@ -442,12 +442,21 @@ CREATE TABLE atestc (fz int) INHERITS (atestp1, atestp2);
GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
-
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testproc1(int) AS 'select $1;' LANGUAGE sql;
+
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
+REVOKE ALL ON FUNCTION testproc1(int) FROM PUBLIC; -- fail, not a function
+REVOKE ALL ON PROCEDURE testproc1(int) FROM PUBLIC;
+GRANT EXECUTE ON PROCEDURE testproc1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
+GRANT USAGE ON PROCEDURE testproc1(int) TO regress_user3; -- semantic error
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON PROCEDURE testproc1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
@@ -457,16 +466,24 @@ CREATE FUNCTION testfunc4(boolean) RETURNS text
SET SESSION AUTHORIZATION regress_user2;
SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+CALL testproc1(6); -- ok
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
+CALL testproc1(6); -- fail
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
SELECT testfunc4(true); -- ok
SET SESSION AUTHORIZATION regress_user4;
SELECT testfunc1(5); -- ok
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+CALL testproc1(6); -- ok
DROP FUNCTION testfunc1(int); -- fail
+DROP AGGREGATE testagg1(int); -- fail
+DROP PROCEDURE testproc1(int); -- fail
\c -
@@ -931,17 +948,29 @@ CREATE SCHEMA testns5;
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- no
-ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
+ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON ROUTINES to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+DROP PROCEDURE testns.bar();
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- yes (counts as function here)
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
+DROP PROCEDURE testns.bar();
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
@@ -995,12 +1024,28 @@ CREATE TABLE testns.t2 (f1 int);
SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.testproc(int) AS 'select 3' LANGUAGE sql;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true by default
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- still true, not a function
+
+REVOKE ALL ON ALL PROCEDURES IN SCHEMA testns FROM PUBLIC;
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- now false
+
+GRANT ALL ON ALL ROUTINES IN SCHEMA testns TO PUBLIC;
+
+SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
@@ -1064,8 +1109,10 @@ CREATE SCHEMA testns;
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
+DROP PROCEDURE testproc1(int);
DROP VIEW atestv0;
DROP VIEW atestv1;
base-commit: 591c504fad0de88b559bf28e929d23672179a857
--
2.15.0
0001-Add-tests-for-privileges-on-aggregate-functions.patchtext/plain; charset=UTF-8; name=0001-Add-tests-for-privileges-on-aggregate-functions.patch; x-mac-creator=0; x-mac-type=0Download
From aae07883d89de72a76efc49ce7239bc83a3ef95f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Thu, 9 Nov 2017 13:25:17 -0500
Subject: [PATCH] Add tests for privileges on aggregate functions
---
src/test/regress/expected/privileges.out | 56 ++++++++++++++++++++++++++++++--
src/test/regress/sql/privileges.sql | 21 ++++++++++--
2 files changed, 72 insertions(+), 5 deletions(-)
diff --git a/src/test/regress/expected/privileges.out b/src/test/regress/expected/privileges.out
index 65d950f15b..fe43f464d7 100644
--- a/src/test/regress/expected/privileges.out
+++ b/src/test/regress/expected/privileges.out
@@ -651,13 +651,17 @@ GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
WARNING: no privileges were granted for "sql"
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
ERROR: invalid privilege type USAGE for function
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
+ERROR: invalid privilege type USAGE for function
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
ERROR: function testfunc_nosuch(integer) does not exist
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
LANGUAGE sql SECURITY DEFINER;
@@ -671,9 +675,17 @@ SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
ERROR: permission denied for language sql
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
ERROR: permission denied for function testfunc1
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
+ERROR: permission denied for function testagg1
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
ERROR: permission denied for relation atest2
SELECT testfunc4(true); -- ok
@@ -689,8 +701,16 @@ SELECT testfunc1(5); -- ok
10
(1 row)
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
DROP FUNCTION testfunc1(int); -- fail
ERROR: must be owner of function testfunc1
+DROP AGGREGATE testagg1(int); -- fail
+ERROR: must be owner of function testagg1
\c -
DROP FUNCTION testfunc1(int); -- ok
-- restore to sanity
@@ -1535,22 +1555,38 @@ SELECT has_schema_privilege('regress_user2', 'testns5', 'CREATE'); -- no
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
has_function_privilege
------------------------
f
(1 row)
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
CREATE DOMAIN testns.testdomain1 AS int;
SELECT has_type_privilege('regress_user2', 'testns.testdomain1', 'USAGE'); -- no
@@ -1629,12 +1665,19 @@ SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
(1 row)
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
has_function_privilege
@@ -1642,9 +1685,15 @@ SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'
f
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
-NOTICE: drop cascades to 3 other objects
+NOTICE: drop cascades to 4 other objects
\set VERBOSITY default
-- Change owner of the schema & and rename of new schema owner
\c -
@@ -1727,6 +1776,7 @@ drop table dep_priv_test;
-- clean up
\c
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
DROP VIEW atestv0;
diff --git a/src/test/regress/sql/privileges.sql b/src/test/regress/sql/privileges.sql
index 902f64c747..d7761994b6 100644
--- a/src/test/regress/sql/privileges.sql
+++ b/src/test/regress/sql/privileges.sql
@@ -442,12 +442,15 @@ CREATE TABLE atestc (fz int) INHERITS (atestp1, atestp2);
GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
@@ -457,16 +460,20 @@ CREATE FUNCTION testfunc4(boolean) RETURNS text
SET SESSION AUTHORIZATION regress_user2;
SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
SELECT testfunc4(true); -- ok
SET SESSION AUTHORIZATION regress_user4;
SELECT testfunc1(5); -- ok
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
DROP FUNCTION testfunc1(int); -- fail
+DROP AGGREGATE testagg1(int); -- fail
\c -
@@ -929,17 +936,23 @@ CREATE SCHEMA testns5;
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
@@ -993,12 +1006,15 @@ CREATE TABLE testns.t2 (f1 int);
SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
@@ -1062,6 +1078,7 @@ CREATE SCHEMA testns;
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
--
2.15.0
On 11/8/17 09:54, Tom Lane wrote:
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 10/31/17 14:23, Tom Lane wrote:
Why not use VOIDOID for the prorettype value?
We need a way to distinguish functions that are callable by SELECT and
procedures that are callable by CALL.Do procedures of this ilk belong in pg_proc at all? It seems like a large
fraction of the attributes tracked in pg_proc are senseless for this
purpose. A new catalog might be a better approach.
The common functionality between functions and procedures is like 98%
[citation needed], so they definitely belong there, even more so than
aggregates, for example.
In any case, I buy none of your arguments that 0 is a better choice than a
new pseudotype.
Well, I haven't heard any reasons for doing it differently, so I can't
judge the relative merits of either approach. Ultimately, it would be a
minor detail as far as the code is concerned, I think.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 11/8/17 09:54, Tom Lane wrote:
Do procedures of this ilk belong in pg_proc at all? It seems like a large
fraction of the attributes tracked in pg_proc are senseless for this
purpose. A new catalog might be a better approach.
The common functionality between functions and procedures is like 98%
[citation needed], so they definitely belong there, even more so than
aggregates, for example.
No, I don't think so. The core reason why not is that in
SELECT foo(...) FROM ...
foo() might be either a plain function or an aggregate, so it's important
that functions and aggregates share the same namespace. *That* is why
they are in the same catalog. On the other hand, since the above syntax
is not usable to call a SQL procedure, putting SQL procedures into pg_proc
just creates namespacing conflicts. Do we really want the existence of
a function foo(int) to mean that you can't create a SQL procedure named
foo and taking one int argument?
regards, tom lane
2017-11-14 17:14 GMT+01:00 Tom Lane <tgl@sss.pgh.pa.us>:
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 11/8/17 09:54, Tom Lane wrote:
Do procedures of this ilk belong in pg_proc at all? It seems like a
large
fraction of the attributes tracked in pg_proc are senseless for this
purpose. A new catalog might be a better approach.The common functionality between functions and procedures is like 98%
[citation needed], so they definitely belong there, even more so than
aggregates, for example.No, I don't think so. The core reason why not is that in
SELECT foo(...) FROM ...
foo() might be either a plain function or an aggregate, so it's important
that functions and aggregates share the same namespace. *That* is why
they are in the same catalog. On the other hand, since the above syntax
is not usable to call a SQL procedure, putting SQL procedures into pg_proc
just creates namespacing conflicts. Do we really want the existence of
a function foo(int) to mean that you can't create a SQL procedure named
foo and taking one int argument?
It is good point.
I agree so catalogue should be separate. Because procedures should not be
used in query, then lot of attributes has not sense there. Maybe in future,
we would to implement new features for procedures and it can be a problem
when we share catalogue with functions.
Show quoted text
regards, tom lane
Tom Lane wrote:
Do we really want the existence of a function foo(int) to mean
that you can't create a SQL procedure named
foo and taking one int argument?
Isn't it pretty much implied by the
ALTER | DROP ROUTINE foo(...)
commands where foo(...) may be either a procedure
or a function? It doesn't look like it could be both.
Best regards,
--
Daniel Vérité
PostgreSQL-powered mailer: http://www.manitou-mail.org
Twitter: @DanielVerite
On 14 November 2017 at 12:56, Daniel Verite <daniel@manitou-mail.org> wrote:
Tom Lane wrote:
Do we really want the existence of a function foo(int) to mean
that you can't create a SQL procedure named
foo and taking one int argument?Isn't it pretty much implied by the
ALTER | DROP ROUTINE foo(...)
commands where foo(...) may be either a procedure
or a function? It doesn't look like it could be both.
It doesn't seem particularly troublesome to create another catalog
table, if needed, so that shouldn't drive our thinking.
It would seem to be implied by the SQLStandard that Functions and
Procedures occupy the same namespace, since they are both Routines.
I can't see any benefit from having foo() function AND foo() procedure
at same time. It would certainly confuse most people that come from
programming languages without that distinction, but maybe someone
knows some Oracle-foo that I don't?
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/14/17 11:14, Tom Lane wrote:
The common functionality between functions and procedures is like 98%
[citation needed], so they definitely belong there, even more so than
aggregates, for example.No, I don't think so. The core reason why not is that in
SELECT foo(...) FROM ...
foo() might be either a plain function or an aggregate, so it's important
that functions and aggregates share the same namespace. *That* is why
they are in the same catalog. On the other hand, since the above syntax
is not usable to call a SQL procedure, putting SQL procedures into pg_proc
just creates namespacing conflicts. Do we really want the existence of
a function foo(int) to mean that you can't create a SQL procedure named
foo and taking one int argument?
Yes, that is defined that way by the SQL standard.
The point about the overlap refers more to the internals. The entire
parsing, look-up, type-resolution, DDL handling, and other things are
the same.
So for both of these reasons I think it's appropriate to use the same
catalog.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 11/14/17 11:14, Tom Lane wrote:
... Do we really want the existence of
a function foo(int) to mean that you can't create a SQL procedure named
foo and taking one int argument?
Yes, that is defined that way by the SQL standard.
Meh. OK, then it has to be one catalog.
regards, tom lane
Simon Riggs wrote:
It would seem to be implied by the SQLStandard that Functions and
Procedures occupy the same namespace, since they are both Routines.I can't see any benefit from having foo() function AND foo() procedure
at same time. It would certainly confuse most people that come from
programming languages without that distinction, but maybe someone
knows some Oracle-foo that I don't?
The question already has been decided on the (better) basis of
the SQL standard, but for what it is worth:
Oracle has functions and procedures in the same name space.
Yours,
Laurenz Albe
On 11/14/2017 10:54 AM, Peter Eisentraut wrote:
Here is an updated patch. It's updated for the recent documentation
format changes. I added some more documentation as suggested by reviewers.I also added more tests about how the various privilege commands (GRANT,
GRANT on ALL, default privileges) would work with the new object type.
I had not looked at that in much detail with the previous version of the
patch, but it seems to work the way I would have wanted without any code
changes, so it's all documentation additions and new tests.As part of this I have also developed additional tests for how the same
privilege commands apply to aggregates, which didn't appear to be
covered yet, and I was worried that I might have broken it, which it
seems I did not. This is included in the big patch, but I have also
included it here as a separate patch, as it could be committed
independently as additional tests for existing functionality.It this point, this patch has no more open TODOs or
need-to-think-about-this-later's that I'm aware of.
I've been through this fairly closely, and I think it's pretty much
committable. The only big item that stands out for me is the issue of
OUT parameters.
While returning multiple result sets will be a useful feature, it's also
very common in my experience for stored procedures to have scalar out
params as well. I'm not sure how we should go about providing for it,
but I think we need to be sure we're not closing any doors.
Here, for example, is how the MySQL stored procedure feature works with
JDBC:
<https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-statements-callable.html>
I think it will be OK if we use cursors to return multiple result sets,
along the lines of Peter's next patch, but we shouldn't regard that as
the end of the story. Even if we don't provide for it in this go round
we should aim at eventually providing for stored procedure OUT params.
Apart from that here are a few fairly minor nitpicks:
Default Privileges docs: although FUNCTIONS and ROUTINES are equivalent
here, we should probably advise using ROUTINES, as FUNCTIONS could
easily be take to mean "functions but not procedures".
CREATE/ALTER PROCEDURE: It seems more than a little odd to allow
attributes that are irrelevant to procedures in these statements. The
docco states "for compatibility with ALTER FUNCTION" but why do we want
such compatibility if it's meaningless? If we can manage it without too
much violence I'd prefer to see an exception raised if these are used.
In create_function.sgml, we have:
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
+ 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 of different argument types can share a name (this is
called <firstterm>overloading</firstterm>).
The last sentence should probably say "functions and procedures of
different argument types" There's a similar issue in create_procedure.sqml.
In grant.sgml, there is:
+ The <literal>FUNCTION</literal> syntax also works for aggregate
+ functions. Or use <literal>ROUTINE</literal> to refer to a
function,
+ aggregate function, or procedure regardless of what it is.
I would replace "Or" by "Alternatively,". I think it reads better that way.
In functions.c, there is:
/* Should only get here for VOID functions */
- Assert(fcache->rettype == VOIDOID);
+ Assert(fcache->rettype == InvalidOid || fcache->rettype
== VOIDOID);
fcinfo->isnull = true;
result = (Datum) 0;
The comment should also refer to procedures.
It took me a minute to work out what is going on with the new code in
aclchk.c:objectsInSchemaToOids(). It probably merits a comment or two.
We should document where returned values in PL procedures are ignored
(plperl, pltcl) and where they are not (plpython, plpgsql). Maybe we
should think about possibly being more consistent here, too.
The context line here looks odd:
CREATE PROCEDURE test_proc2()
LANGUAGE plpythonu
AS $$
return 5
$$;
CALL test_proc2();
ERROR: PL/Python procedure did not return None
CONTEXT: PL/Python function "test_proc2"
Perhaps we need to change plpython_error_callback() so that "function"
isn't hardcoded.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/20/2017 04:25 PM, I wrote:
I've been through this fairly closely, and I think it's pretty much
committable. The only big item that stands out for me is the issue of
OUT parameters.While returning multiple result sets will be a useful feature, it's also
very common in my experience for stored procedures to have scalar out
params as well. I'm not sure how we should go about providing for it,
but I think we need to be sure we're not closing any doors.Here, for example, is how the MySQL stored procedure feature works with
JDBC:
<https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-statements-callable.html>
I think it will be OK if we use cursors to return multiple result sets,
along the lines of Peter's next patch, but we shouldn't regard that as
the end of the story. Even if we don't provide for it in this go round
we should aim at eventually providing for stored procedure OUT params.
Of course it's true that we could replace a scalar OUT parameter with a
one row resultset if we have return of multiple resultsets from SPs. But
it's different from the common use pattern and a darn sight more
cumbersome to use.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/20/17 16:25, Andrew Dunstan wrote:
I've been through this fairly closely, and I think it's pretty much
committable. The only big item that stands out for me is the issue of
OUT parameters.
I figured that that's something that would come up. I had intentionally
prohibited OUT parameters for now so that we can come up with something
for them without having to break any backward compatibility.
From reading some of the references so far, I think it could be
sufficient to return a one-row result set and have the drivers adapt the
returned data into their interfaces. The only thing that would be a bit
weird about that is that a CALL command with OUT parameters would return
a result set and a CALL command without any OUT parameters would return
CommandComplete instead. Maybe that's OK.
Default Privileges docs: although FUNCTIONS and ROUTINES are equivalent
here, we should probably advise using ROUTINES, as FUNCTIONS could
easily be take to mean "functions but not procedures".
OK, I'll update the documentation a bit more.
CREATE/ALTER PROCEDURE: It seems more than a little odd to allow
attributes that are irrelevant to procedures in these statements. The
docco states "for compatibility with ALTER FUNCTION" but why do we want
such compatibility if it's meaningless? If we can manage it without too
much violence I'd prefer to see an exception raised if these are used.
We can easily be more restrictive here. I'm open to suggestions. There
is a difference between options that don't make sense for procedures
(e.g., RETURNS NULL ON NULL INPUT), which are prohibited, and those that
might make sense sometime, but are currently not used. But maybe that's
too confusing and we should just prohibit options that are not currently
used.
In create_function.sgml, we have:
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 + 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 of different argument types can share a name (this is called <firstterm>overloading</firstterm>).The last sentence should probably say "functions and procedures of
different argument types" There's a similar issue in create_procedure.sqml.
fixing that
In grant.sgml, there is:
+ The <literal>FUNCTION</literal> syntax also works for aggregate + functions. Or use <literal>ROUTINE</literal> to refer to a function, + aggregate function, or procedure regardless of what it is.I would replace "Or" by "Alternatively,". I think it reads better that way.
fixing that
In functions.c, there is:
/* Should only get here for VOID functions */ - Assert(fcache->rettype == VOIDOID); + Assert(fcache->rettype == InvalidOid || fcache->rettype == VOIDOID); fcinfo->isnull = true; result = (Datum) 0;The comment should also refer to procedures.
fixing that
It took me a minute to work out what is going on with the new code in
aclchk.c:objectsInSchemaToOids(). It probably merits a comment or two.
improving that
We should document where returned values in PL procedures are ignored
(plperl, pltcl) and where they are not (plpython, plpgsql). Maybe we
should think about possibly being more consistent here, too.
Yeah, suggestions? I think it makes sense in PL/pgSQL and PL/Python to
disallow return values that would end up being ignored, because the only
way a return value could arise is if user code explicit calls
RETURN/return. However, in Perl, the return value is the result of the
last statement, so prohibiting a return value would be very
inconvenient. (Don't know about Tcl.) So maybe the current behavior
makes sense. Documentation is surely needed.
The context line here looks odd:
CREATE PROCEDURE test_proc2()
LANGUAGE plpythonu
AS $$
return 5
$$;
CALL test_proc2();
ERROR: PL/Python procedure did not return None
CONTEXT: PL/Python function "test_proc2"Perhaps we need to change plpython_error_callback() so that "function"
isn't hardcoded.
fixing that
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 11/20/17 16:25, Andrew Dunstan wrote:
We should document where returned values in PL procedures are ignored
(plperl, pltcl) and where they are not (plpython, plpgsql). Maybe we
should think about possibly being more consistent here, too.
Yeah, suggestions? I think it makes sense in PL/pgSQL and PL/Python to
disallow return values that would end up being ignored, because the only
way a return value could arise is if user code explicit calls
RETURN/return. However, in Perl, the return value is the result of the
last statement, so prohibiting a return value would be very
inconvenient. (Don't know about Tcl.) So maybe the current behavior
makes sense. Documentation is surely needed.
Tcl has the same approach as Perl: the return value of a proc is the
same as the value of its last command. There's no such thing as a
proc that doesn't return a value.
regards, tom lane
2017-11-22 19:01 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:
On 11/20/17 16:25, Andrew Dunstan wrote:
I've been through this fairly closely, and I think it's pretty much
committable. The only big item that stands out for me is the issue of
OUT parameters.I figured that that's something that would come up. I had intentionally
prohibited OUT parameters for now so that we can come up with something
for them without having to break any backward compatibility.From reading some of the references so far, I think it could be
sufficient to return a one-row result set and have the drivers adapt the
returned data into their interfaces. The only thing that would be a bit
weird about that is that a CALL command with OUT parameters would return
a result set and a CALL command without any OUT parameters would return
CommandComplete instead. Maybe that's OK.
T-SQL procedures returns data or OUT variables.
I remember, it was very frustrating
Maybe first result can be reserved for OUT variables, others for multi
result set
Regards
Pavel
Show quoted text
Default Privileges docs: although FUNCTIONS and ROUTINES are equivalent
here, we should probably advise using ROUTINES, as FUNCTIONS could
easily be take to mean "functions but not procedures".OK, I'll update the documentation a bit more.
CREATE/ALTER PROCEDURE: It seems more than a little odd to allow
attributes that are irrelevant to procedures in these statements. The
docco states "for compatibility with ALTER FUNCTION" but why do we want
such compatibility if it's meaningless? If we can manage it without too
much violence I'd prefer to see an exception raised if these are used.We can easily be more restrictive here. I'm open to suggestions. There
is a difference between options that don't make sense for procedures
(e.g., RETURNS NULL ON NULL INPUT), which are prohibited, and those that
might make sense sometime, but are currently not used. But maybe that's
too confusing and we should just prohibit options that are not currently
used.In create_function.sgml, we have:
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 + 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 of different argument types can share a name (this is called <firstterm>overloading</firstterm>).The last sentence should probably say "functions and procedures of
different argument types" There's a similar issue increate_procedure.sqml.
fixing that
In grant.sgml, there is:
+ The <literal>FUNCTION</literal> syntax also works for
aggregate
+ functions. Or use <literal>ROUTINE</literal> to refer to a function, + aggregate function, or procedure regardless of what it is.I would replace "Or" by "Alternatively,". I think it reads better that
way.
fixing that
In functions.c, there is:
/* Should only get here for VOID functions */ - Assert(fcache->rettype == VOIDOID); + Assert(fcache->rettype == InvalidOid || fcache->rettype == VOIDOID); fcinfo->isnull = true; result = (Datum) 0;The comment should also refer to procedures.
fixing that
It took me a minute to work out what is going on with the new code in
aclchk.c:objectsInSchemaToOids(). It probably merits a comment or two.improving that
We should document where returned values in PL procedures are ignored
(plperl, pltcl) and where they are not (plpython, plpgsql). Maybe we
should think about possibly being more consistent here, too.Yeah, suggestions? I think it makes sense in PL/pgSQL and PL/Python to
disallow return values that would end up being ignored, because the only
way a return value could arise is if user code explicit calls
RETURN/return. However, in Perl, the return value is the result of the
last statement, so prohibiting a return value would be very
inconvenient. (Don't know about Tcl.) So maybe the current behavior
makes sense. Documentation is surely needed.The context line here looks odd:
CREATE PROCEDURE test_proc2()
LANGUAGE plpythonu
AS $$
return 5
$$;
CALL test_proc2();
ERROR: PL/Python procedure did not return None
CONTEXT: PL/Python function "test_proc2"Perhaps we need to change plpython_error_callback() so that "function"
isn't hardcoded.fixing that
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/22/2017 01:10 PM, Tom Lane wrote:
Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:
On 11/20/17 16:25, Andrew Dunstan wrote:
We should document where returned values in PL procedures are ignored
(plperl, pltcl) and where they are not (plpython, plpgsql). Maybe we
should think about possibly being more consistent here, too.Yeah, suggestions? I think it makes sense in PL/pgSQL and PL/Python to
disallow return values that would end up being ignored, because the only
way a return value could arise is if user code explicit calls
RETURN/return. However, in Perl, the return value is the result of the
last statement, so prohibiting a return value would be very
inconvenient. (Don't know about Tcl.) So maybe the current behavior
makes sense. Documentation is surely needed.Tcl has the same approach as Perl: the return value of a proc is the
same as the value of its last command. There's no such thing as a
proc that doesn't return a value.
Right. We probably just need to document the behaviour here. I'd be
satisfied with that.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
T-SQL procedures returns data or OUT variables.
I remember, it was very frustrating
Maybe first result can be reserved for OUT variables, others for multi
result set
It's been many years, but if I recall correctly, T-SQL returns a series of
result sets, with no description of the result sets to be returned, each of
which must be consumed fully before the client can move onto the next
result set. Then and only then can the output parameters be read. Which was
very frustrating because the OUT parameters seemed like a good place to put
values for things like "result set 1 has 205 rows" and "X was false so we
omitted one result set entirely" so you couldn't, y'know easily omit entire
result sets.
On 11/22/2017 02:39 PM, Corey Huinker wrote:
T-SQL procedures returns data or OUT variables.
I remember, it was very frustrating
Maybe first result can be reserved for OUT variables, others for
multi result setIt's been many years, but if I recall correctly, T-SQL returns a
series of result sets, with no description of the result sets to be
returned, each of which must be consumed fully before the client can
move onto the next result set. Then and only then can the output
parameters be read. Which was very frustrating because the OUT
parameters seemed like a good place to put values for things like
"result set 1 has 205 rows" and "X was false so we omitted one result
set entirely" so you couldn't, y'know easily omit entire result sets.
Exactly. If we want to handle OUT params this way they really need to be
the first resultset for just this reason. That could possibly be done by
the glue code reserving a spot in the resultset list and filling it in
at the end of the procedure.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 23 November 2017 at 03:47, Andrew Dunstan <andrew.dunstan@2ndquadrant.com
wrote:
On 11/22/2017 02:39 PM, Corey Huinker wrote:
T-SQL procedures returns data or OUT variables.
I remember, it was very frustrating
Maybe first result can be reserved for OUT variables, others for
multi result setIt's been many years, but if I recall correctly, T-SQL returns a
series of result sets, with no description of the result sets to be
returned, each of which must be consumed fully before the client can
move onto the next result set. Then and only then can the output
parameters be read. Which was very frustrating because the OUT
parameters seemed like a good place to put values for things like
"result set 1 has 205 rows" and "X was false so we omitted one result
set entirely" so you couldn't, y'know easily omit entire result sets.Exactly. If we want to handle OUT params this way they really need to be
the first resultset for just this reason. That could possibly be done by
the glue code reserving a spot in the resultset list and filling it in
at the end of the procedure.
I fail to understand how that can work though. Wouldn't we have to buffer
all the resultset contents on the server in tuplestores or similar, so we
can send the parameters and then the result sets?
Isn't that going to cause a whole different set of painful difficulties
instead?
What it comes down to is that if we want to see output params before result
sets, but the output params are only emitted when the proc returns, then
someone has to buffer. We get to choose if it's the client or the server.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 11/23/17 00:59, Craig Ringer wrote:
Exactly. If we want to handle OUT params this way they really need to be
the first resultset for just this reason. That could possibly be done by
the glue code reserving a spot in the resultset list and filling it in
at the end of the procedure.I fail to understand how that can work though. Wouldn't we have to
buffer all the resultset contents on the server in tuplestores or
similar, so we can send the parameters and then the result sets?
The current PoC in the other thread puts the extra result sets in
cursors. That's essentially the buffer you are referring to. So it
seems possible, but there are some details to be worked out.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Here is a new patch that addresses the previous review comments.
If there are no new comments, I think this might be ready to go.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Attachments:
v3-0001-SQL-procedures.patchtext/plain; charset=UTF-8; name=v3-0001-SQL-procedures.patch; x-mac-creator=0; x-mac-type=0Download
From 29d9779ce89757e48016586c4e8f491fe3b91373 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 28 Nov 2017 10:00:59 -0500
Subject: [PATCH v3] SQL procedures
CREATE/ALTER/DROP PROCEDURE, ALTER/DROP ROUTINE, CALL statement, utility
statement support, support in the built-in PLs, support in pg_dump and
psql
---
doc/src/sgml/catalogs.sgml | 2 +-
doc/src/sgml/ddl.sgml | 2 +-
doc/src/sgml/ecpg.sgml | 4 +-
doc/src/sgml/information_schema.sgml | 18 +-
doc/src/sgml/plperl.sgml | 4 +
doc/src/sgml/plpgsql.sgml | 17 +-
doc/src/sgml/plpython.sgml | 6 +-
doc/src/sgml/pltcl.sgml | 3 +-
doc/src/sgml/ref/allfiles.sgml | 6 +
doc/src/sgml/ref/alter_default_privileges.sgml | 12 +-
doc/src/sgml/ref/alter_extension.sgml | 12 +-
doc/src/sgml/ref/alter_function.sgml | 2 +
doc/src/sgml/ref/alter_procedure.sgml | 281 ++++++++++++++++++++
doc/src/sgml/ref/alter_routine.sgml | 102 ++++++++
doc/src/sgml/ref/call.sgml | 97 +++++++
doc/src/sgml/ref/comment.sgml | 13 +-
doc/src/sgml/ref/create_function.sgml | 10 +-
doc/src/sgml/ref/create_procedure.sgml | 341 +++++++++++++++++++++++++
doc/src/sgml/ref/drop_function.sgml | 2 +
doc/src/sgml/ref/drop_procedure.sgml | 162 ++++++++++++
doc/src/sgml/ref/drop_routine.sgml | 94 +++++++
doc/src/sgml/ref/grant.sgml | 25 +-
doc/src/sgml/ref/revoke.sgml | 4 +-
doc/src/sgml/ref/security_label.sgml | 12 +-
doc/src/sgml/reference.sgml | 6 +
doc/src/sgml/xfunc.sgml | 33 +++
src/backend/catalog/aclchk.c | 68 ++++-
src/backend/catalog/information_schema.sql | 25 +-
src/backend/catalog/objectaddress.c | 19 +-
src/backend/catalog/pg_proc.c | 3 +-
src/backend/commands/aggregatecmds.c | 2 +-
src/backend/commands/alter.c | 6 +
src/backend/commands/dropcmds.c | 38 ++-
src/backend/commands/event_trigger.c | 14 +
src/backend/commands/functioncmds.c | 164 +++++++++++-
src/backend/commands/opclasscmds.c | 4 +-
src/backend/executor/functions.c | 15 +-
src/backend/nodes/copyfuncs.c | 15 ++
src/backend/nodes/equalfuncs.c | 13 +
src/backend/optimizer/util/clauses.c | 1 +
src/backend/parser/gram.y | 255 +++++++++++++++++-
src/backend/parser/parse_agg.c | 11 +
src/backend/parser/parse_expr.c | 8 +
src/backend/parser/parse_func.c | 201 +++++++++------
src/backend/tcop/utility.c | 44 +++-
src/backend/utils/adt/ruleutils.c | 6 +
src/backend/utils/cache/lsyscache.c | 19 ++
src/bin/pg_dump/dumputils.c | 5 +-
src/bin/pg_dump/pg_backup_archiver.c | 7 +-
src/bin/pg_dump/pg_dump.c | 32 ++-
src/bin/pg_dump/t/002_pg_dump.pl | 38 +++
src/bin/psql/describe.c | 8 +-
src/bin/psql/tab-complete.c | 77 +++++-
src/include/commands/defrem.h | 3 +-
src/include/nodes/nodes.h | 1 +
src/include/nodes/parsenodes.h | 17 ++
src/include/parser/kwlist.h | 4 +
src/include/parser/parse_func.h | 8 +-
src/include/parser/parse_node.h | 3 +-
src/include/utils/lsyscache.h | 1 +
src/interfaces/ecpg/preproc/ecpg.tokens | 2 +-
src/interfaces/ecpg/preproc/ecpg.trailer | 5 +-
src/interfaces/ecpg/preproc/ecpg_keywords.c | 1 -
src/pl/plperl/GNUmakefile | 2 +-
src/pl/plperl/expected/plperl_call.out | 29 +++
src/pl/plperl/plperl.c | 8 +-
src/pl/plperl/sql/plperl_call.sql | 36 +++
src/pl/plpgsql/src/pl_comp.c | 88 ++++---
src/pl/plpgsql/src/pl_exec.c | 8 +-
src/pl/plpython/Makefile | 1 +
src/pl/plpython/expected/plpython_call.out | 35 +++
src/pl/plpython/plpy_exec.c | 14 +-
src/pl/plpython/plpy_main.c | 10 +-
src/pl/plpython/plpy_procedure.c | 5 +-
src/pl/plpython/plpy_procedure.h | 3 +-
src/pl/plpython/sql/plpython_call.sql | 41 +++
src/pl/tcl/Makefile | 2 +-
src/pl/tcl/expected/pltcl_call.out | 29 +++
src/pl/tcl/pltcl.c | 13 +-
src/pl/tcl/sql/pltcl_call.sql | 36 +++
src/test/regress/expected/create_procedure.out | 92 +++++++
src/test/regress/expected/object_address.out | 15 +-
src/test/regress/expected/plpgsql.out | 41 +++
src/test/regress/expected/polymorphism.out | 16 +-
src/test/regress/expected/privileges.out | 128 +++++++++-
src/test/regress/parallel_schedule | 2 +-
src/test/regress/serial_schedule | 1 +
src/test/regress/sql/create_procedure.sql | 79 ++++++
src/test/regress/sql/object_address.sql | 4 +-
src/test/regress/sql/plpgsql.sql | 49 ++++
src/test/regress/sql/privileges.sql | 55 +++-
91 files changed, 2951 insertions(+), 304 deletions(-)
create mode 100644 doc/src/sgml/ref/alter_procedure.sgml
create mode 100644 doc/src/sgml/ref/alter_routine.sgml
create mode 100644 doc/src/sgml/ref/call.sgml
create mode 100644 doc/src/sgml/ref/create_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_procedure.sgml
create mode 100644 doc/src/sgml/ref/drop_routine.sgml
create mode 100644 src/pl/plperl/expected/plperl_call.out
create mode 100644 src/pl/plperl/sql/plperl_call.sql
create mode 100644 src/pl/plpython/expected/plpython_call.out
create mode 100644 src/pl/plpython/sql/plpython_call.sql
create mode 100644 src/pl/tcl/expected/pltcl_call.out
create mode 100644 src/pl/tcl/sql/pltcl_call.sql
create mode 100644 src/test/regress/expected/create_procedure.out
create mode 100644 src/test/regress/sql/create_procedure.sql
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index da881a7737..3f02202caf 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -5241,7 +5241,7 @@ <title><structname>pg_proc</structname> Columns</title>
<entry><structfield>prorettype</structfield></entry>
<entry><type>oid</type></entry>
<entry><literal><link linkend="catalog-pg-type"><structname>pg_type</structname></link>.oid</literal></entry>
- <entry>Data type of the return value</entry>
+ <entry>Data type of the return value, or null for a procedure</entry>
</row>
<row>
diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml
index e6f50ec819..9f583266de 100644
--- a/doc/src/sgml/ddl.sgml
+++ b/doc/src/sgml/ddl.sgml
@@ -3947,7 +3947,7 @@ <title>Other Database Objects</title>
<listitem>
<para>
- Functions and operators
+ Functions, procedures, and operators
</para>
</listitem>
diff --git a/doc/src/sgml/ecpg.sgml b/doc/src/sgml/ecpg.sgml
index d1872c1a5c..5a8d1f1b95 100644
--- a/doc/src/sgml/ecpg.sgml
+++ b/doc/src/sgml/ecpg.sgml
@@ -4778,7 +4778,9 @@ <title>Setting Callbacks</title>
<term><literal>DO <replaceable>name</replaceable> (<replaceable>args</replaceable>)</literal></term>
<listitem>
<para>
- Call the specified C functions with the specified arguments.
+ Call the specified C functions with the specified arguments. (This
+ use is different from the meaning of <literal>CALL</literal>
+ and <literal>DO</literal> in the normal PostgreSQL grammar.)
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/information_schema.sgml b/doc/src/sgml/information_schema.sgml
index 99b0ea8519..0faa72f1d3 100644
--- a/doc/src/sgml/information_schema.sgml
+++ b/doc/src/sgml/information_schema.sgml
@@ -3972,8 +3972,8 @@ <title><literal>routine_privileges</literal> Columns</title>
<title><literal>routines</literal></title>
<para>
- The view <literal>routines</literal> contains all functions in the
- current database. Only those functions are shown that the current
+ The view <literal>routines</literal> contains all functions and procedures in the
+ current database. Only those functions and procedures are shown that the current
user has access to (by way of being the owner or having some
privilege).
</para>
@@ -4037,8 +4037,8 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>routine_type</literal></entry>
<entry><type>character_data</type></entry>
<entry>
- Always <literal>FUNCTION</literal> (In the future there might
- be other types of routines.)
+ <literal>FUNCTION</literal> for a
+ function, <literal>PROCEDURE</literal> for a procedure
</entry>
</row>
@@ -4087,7 +4087,7 @@ <title><literal>routines</literal> Columns</title>
the view <literal>element_types</literal>), else
<literal>USER-DEFINED</literal> (in that case, the type is
identified in <literal>type_udt_name</literal> and associated
- columns).
+ columns). Null for a procedure.
</entry>
</row>
@@ -4180,7 +4180,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the database that the return data type of the function
- is defined in (always the current database)
+ is defined in (always the current database). Null for a procedure.
</entry>
</row>
@@ -4189,7 +4189,7 @@ <title><literal>routines</literal> Columns</title>
<entry><type>sql_identifier</type></entry>
<entry>
Name of the schema that the return data type of the function is
- defined in
+ defined in. Null for a procedure.
</entry>
</row>
@@ -4197,7 +4197,7 @@ <title><literal>routines</literal> Columns</title>
<entry><literal>type_udt_name</literal></entry>
<entry><type>sql_identifier</type></entry>
<entry>
- Name of the return data type of the function
+ Name of the return data type of the function. Null for a procedure.
</entry>
</row>
@@ -4314,7 +4314,7 @@ <title><literal>routines</literal> Columns</title>
<entry>
If the function automatically returns null if any of its
arguments are null, then <literal>YES</literal>, else
- <literal>NO</literal>.
+ <literal>NO</literal>. Null for a procedure.
</entry>
</row>
diff --git a/doc/src/sgml/plperl.sgml b/doc/src/sgml/plperl.sgml
index 33e39d85e4..100162dead 100644
--- a/doc/src/sgml/plperl.sgml
+++ b/doc/src/sgml/plperl.sgml
@@ -67,6 +67,10 @@ <title>PL/Perl Functions and Arguments</title>
as discussed below.
</para>
+ <para>
+ In a PL/Perl procedure, any return value from the Perl code is ignored.
+ </para>
+
<para>
PL/Perl also supports anonymous code blocks called with the
<xref linkend="sql-do"/> statement:
diff --git a/doc/src/sgml/plpgsql.sgml b/doc/src/sgml/plpgsql.sgml
index 6d14b34448..7d23ed437e 100644
--- a/doc/src/sgml/plpgsql.sgml
+++ b/doc/src/sgml/plpgsql.sgml
@@ -156,7 +156,8 @@ <title>Supported Argument and Result Data Types</title>
<para>
Finally, a <application>PL/pgSQL</application> function can be declared to return
- <type>void</type> if it has no useful return value.
+ <type>void</type> if it has no useful return value. (Alternatively, it
+ could be written as a procedure in that case.)
</para>
<para>
@@ -1865,6 +1866,18 @@ <title><command>RETURN NEXT</command> and <command>RETURN QUERY</command></title
</sect3>
</sect2>
+ <sect2 id="plpgsql-statements-returning-procedure">
+ <title>Returning From a Procedure</title>
+
+ <para>
+ A procedure does not have a return value. A procedure can therefore end
+ without a <command>RETURN</command> statement. If
+ a <command>RETURN</command> statement is desired to exit the code early,
+ then <symbol>NULL</symbol> must be returned. Returning any other value
+ will result in an error.
+ </para>
+ </sect2>
+
<sect2 id="plpgsql-conditionals">
<title>Conditionals</title>
@@ -5244,7 +5257,7 @@ <title>Porting a Function that Creates Another Function from <application>PL/SQL
<para>
Here is how this function would end up in <productname>PostgreSQL</productname>:
<programlisting>
-CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
+CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$
DECLARE
referrer_keys CURSOR IS
SELECT * FROM cs_referrer_keys
diff --git a/doc/src/sgml/plpython.sgml b/doc/src/sgml/plpython.sgml
index ec5f671632..0dbeee1fa2 100644
--- a/doc/src/sgml/plpython.sgml
+++ b/doc/src/sgml/plpython.sgml
@@ -207,7 +207,11 @@ <title>PL/Python Functions</title>
<literal>yield</literal> (in case of a result-set statement). If
you do not provide a return value, Python returns the default
<symbol>None</symbol>. <application>PL/Python</application> translates
- Python's <symbol>None</symbol> into the SQL null value.
+ Python's <symbol>None</symbol> into the SQL null value. In a procedure,
+ the result from the Python code must be <symbol>None</symbol> (typically
+ achieved by ending the procedure without a <literal>return</literal>
+ statement or by using a <literal>return</literal> statement without
+ argument); otherwise, an error will be raised.
</para>
<para>
diff --git a/doc/src/sgml/pltcl.sgml b/doc/src/sgml/pltcl.sgml
index 0646a8ba0b..8018783b0a 100644
--- a/doc/src/sgml/pltcl.sgml
+++ b/doc/src/sgml/pltcl.sgml
@@ -97,7 +97,8 @@ <title>PL/Tcl Functions and Arguments</title>
Tcl script as variables named <literal>1</literal>
... <literal><replaceable>n</replaceable></literal>. The result is
returned from the Tcl code in the usual way, with
- a <literal>return</literal> statement.
+ a <literal>return</literal> statement. In a procedure, the return value
+ from the Tcl code is ignored.
</para>
<para>
diff --git a/doc/src/sgml/ref/allfiles.sgml b/doc/src/sgml/ref/allfiles.sgml
index 01acc2ef9d..22e6893211 100644
--- a/doc/src/sgml/ref/allfiles.sgml
+++ b/doc/src/sgml/ref/allfiles.sgml
@@ -26,8 +26,10 @@
<!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">
@@ -48,6 +50,7 @@
<!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">
@@ -75,6 +78,7 @@
<!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">
@@ -122,8 +126,10 @@
<!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">
diff --git a/doc/src/sgml/ref/alter_default_privileges.sgml b/doc/src/sgml/ref/alter_default_privileges.sgml
index ab2c35b4dd..0c09f1db5c 100644
--- a/doc/src/sgml/ref/alter_default_privileges.sgml
+++ b/doc/src/sgml/ref/alter_default_privileges.sgml
@@ -39,7 +39,7 @@
TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
- ON FUNCTIONS
+ ON { FUNCTIONS | ROUTINES }
TO { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
@@ -66,7 +66,7 @@
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
- ON FUNCTIONS
+ ON { FUNCTIONS | ROUTINES }
FROM { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
@@ -93,7 +93,13 @@ <title>Description</title>
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.
+ 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>
diff --git a/doc/src/sgml/ref/alter_extension.sgml b/doc/src/sgml/ref/alter_extension.sgml
index e54925507e..a2d405d6cd 100644
--- a/doc/src/sgml/ref/alter_extension.sgml
+++ b/doc/src/sgml/ref/alter_extension.sgml
@@ -45,6 +45,8 @@
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> |
@@ -170,12 +172,14 @@ <title>Parameters</title>
<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, sequences, text search objects,
+ operator classes, operator families, procedures, routines, sequences, text search objects,
types, and views can be schema-qualified.
</para>
</listitem>
@@ -204,7 +208,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -222,7 +226,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -235,7 +239,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/alter_function.sgml b/doc/src/sgml/ref/alter_function.sgml
index 196d2dde0c..d8747e0748 100644
--- a/doc/src/sgml/ref/alter_function.sgml
+++ b/doc/src/sgml/ref/alter_function.sgml
@@ -359,6 +359,8 @@ <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_procedure.sgml b/doc/src/sgml/ref/alter_procedure.sgml
new file mode 100644
index 0000000000..dae80076d9
--- /dev/null
+++ b/doc/src/sgml/ref/alter_procedure.sgml
@@ -0,0 +1,281 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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> 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 needed 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.
+ </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>
+ The name of the extension that the procedure is to depend on.
+ </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_routine.sgml b/doc/src/sgml/ref/alter_routine.sgml
new file mode 100644
index 0000000000..d1699691e1
--- /dev/null
+++ b/doc/src/sgml/ref/alter_routine.sgml
@@ -0,0 +1,102 @@
+<!--
+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_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> [, ...] ] ) ]
+ 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/call.sgml b/doc/src/sgml/ref/call.sgml
new file mode 100644
index 0000000000..2741d8d15e
--- /dev/null
+++ b/doc/src/sgml/ref/call.sgml
@@ -0,0 +1,97 @@
+<!--
+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>
+ </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 for the procedure call.
+ See <xref linkend="sql-syntax-calling-funcs"/> for the full details on
+ function and procedure call syntax, including use of named parameters.
+ </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>
+ </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.
+ </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/comment.sgml b/doc/src/sgml/ref/comment.sgml
index 7d66c1a34c..965c5a40ad 100644
--- a/doc/src/sgml/ref/comment.sgml
+++ b/doc/src/sgml/ref/comment.sgml
@@ -46,8 +46,10 @@
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> |
@@ -121,13 +123,15 @@ <title>Parameters</title>
<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 tables,
aggregates, collations, conversions, domains, foreign tables, functions,
- indexes, operators, operator classes, operator families, sequences,
+ indexes, operators, operator classes, operator families, procedures, routines, sequences,
statistics, text search objects, types, and views can be
schema-qualified. When commenting on a column,
<replaceable class="parameter">relation_name</replaceable> must refer
@@ -170,7 +174,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argmode</replaceable></term>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -187,7 +191,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argname</replaceable></term>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -199,7 +203,7 @@ <title>Parameters</title>
<term><replaceable class="parameter">argtype</replaceable></term>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
@@ -325,6 +329,7 @@ <title>Examples</title>
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 ROLE my_role IS 'Administration group for finance tables';
COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records';
COMMENT ON SCHEMA my_schema IS 'Departmental data';
diff --git a/doc/src/sgml/ref/create_function.sgml b/doc/src/sgml/ref/create_function.sgml
index 75331165fe..fd229d1193 100644
--- a/doc/src/sgml/ref/create_function.sgml
+++ b/doc/src/sgml/ref/create_function.sgml
@@ -55,9 +55,9 @@ <title>Description</title>
<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
+ 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 of different argument types can share a name (this is
+ functions and procedures of different argument types can share a name (this is
called <firstterm>overloading</firstterm>).
</para>
@@ -450,7 +450,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">execution_cost</replaceable></term>
+ <term><literal>COST</literal> <replaceable class="parameter">execution_cost</replaceable></term>
<listitem>
<para>
@@ -466,7 +466,7 @@ <title>Parameters</title>
</varlistentry>
<varlistentry>
- <term><replaceable class="parameter">result_rows</replaceable></term>
+ <term><literal>ROWS</literal> <replaceable class="parameter">result_rows</replaceable></term>
<listitem>
<para>
@@ -818,7 +818,7 @@ <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>
<title>Compatibility</title>
<para>
- A <command>CREATE FUNCTION</command> command is defined in SQL:1999 and later.
+ A <command>CREATE FUNCTION</command> command is defined in the SQL standard.
The <productname>PostgreSQL</productname> version is similar but
not fully compatible. The attributes are not portable, neither are the
different available languages.
diff --git a/doc/src/sgml/ref/create_procedure.sgml b/doc/src/sgml/ref/create_procedure.sgml
new file mode 100644
index 0000000000..d712043824
--- /dev/null
+++ b/doc/src/sgml/ref/create_procedure.sgml
@@ -0,0 +1,341 @@
+<!--
+doc/src/sgml/ref/create_procedure.sgml
+-->
+
+<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>'
+ } ...
+</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>
+ </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> 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>. 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>
+ </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>
+ 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 <xref linkend="sql-load"/> 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>
+ </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>
+
+<programlisting>
+CREATE PROCEDURE insert_data(a integer, b integer)
+LANGUAGE SQL
+AS $$
+INSERT INTO tbl VALUES (a);
+INSERT INTO tbl VALUES (b);
+$$;
+
+CALL insert_data(1, 2);
+</programlisting>
+ </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> version is similar but
+ not fully compatible. 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/drop_function.sgml b/doc/src/sgml/ref/drop_function.sgml
index eda1a59c84..127fdfe419 100644
--- a/doc/src/sgml/ref/drop_function.sgml
+++ b/doc/src/sgml/ref/drop_function.sgml
@@ -185,6 +185,8 @@ <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>
diff --git a/doc/src/sgml/ref/drop_procedure.sgml b/doc/src/sgml/ref/drop_procedure.sgml
new file mode 100644
index 0000000000..fef61b66ac
--- /dev/null
+++ b/doc/src/sgml/ref/drop_procedure.sgml
@@ -0,0 +1,162 @@
+<!--
+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 an existing
+ procedure. To execute this command the user must be the
+ owner of the procedure. The argument types to the
+ procedure 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. 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> 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 PROCEDURE</command> does not actually pay
+ any attention to argument names, since only the argument data
+ types are needed 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.
+ </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-examples">
+ <title>Examples</title>
+
+<programlisting>
+DROP PROCEDURE do_db_maintenance();
+</programlisting>
+ </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</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-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_routine.sgml b/doc/src/sgml/ref/drop_routine.sgml
new file mode 100644
index 0000000000..5cd1a0f11e
--- /dev/null
+++ b/doc/src/sgml/ref/drop_routine.sgml
@@ -0,0 +1,94 @@
+<!--
+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 an existing
+ routine, which can be an aggregate function, a normal function, or a
+ procedure. 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-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</para>
+ </listitem>
+ <listitem>
+ <para>The ability to specify argument modes and names</para>
+ </listitem>
+ <listitem>
+ <para>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/grant.sgml b/doc/src/sgml/ref/grant.sgml
index a5e895d09d..ff64c7a3ba 100644
--- a/doc/src/sgml/ref/grant.sgml
+++ b/doc/src/sgml/ref/grant.sgml
@@ -55,8 +55,8 @@
TO <replaceable class="parameter">role_specification</replaceable> [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable class="parameter">schema_name</replaceable> [, ...] }
+ 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 ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
@@ -96,7 +96,7 @@ <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,
+ table, sequence, database, foreign-data wrapper, foreign server, function, procedure,
procedural language, schema, or tablespace), and one that grants
membership in a role. These variants are similar in many ways, but
they are different enough to be described separately.
@@ -115,8 +115,11 @@ <title>GRANT on Database Objects</title>
<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, and functions (but note that <literal>ALL
- TABLES</literal> is considered to include views and foreign tables).
+ 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 functions, but not procedures,
+ again just like the specific-object <command>GRANT</command> command.
</para>
<para>
@@ -169,7 +172,7 @@ <title>GRANT on Database Objects</title>
granted to <literal>PUBLIC</literal> are as follows:
<literal>CONNECT</literal> and <literal>TEMPORARY</literal> (create
temporary tables) privileges for databases;
- <literal>EXECUTE</literal> privilege for functions; and
+ <literal>EXECUTE</literal> privilege for functions and procedures; and
<literal>USAGE</literal> privilege for languages and data types
(including domains).
The object owner can, of course, <command>REVOKE</command>
@@ -329,10 +332,12 @@ <title>GRANT on Database Objects</title>
<term><literal>EXECUTE</literal></term>
<listitem>
<para>
- Allows the use of the specified function and the use of any
- operators that are implemented on top of the function. This is
- the only type of privilege that is applicable to functions.
- (This syntax works for aggregate functions, as well.)
+ Allows the use of the specified function or procedure and the use of
+ any operators that are implemented on top of the function. This is the
+ only type of privilege that is applicable to functions and procedures.
+ The <literal>FUNCTION</literal> syntax also works for aggregate
+ functions. Alternatively, use <literal>ROUTINE</literal> to refer to a function,
+ aggregate function, or procedure regardless of what it is.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/revoke.sgml b/doc/src/sgml/ref/revoke.sgml
index 4d133a782b..7018202f14 100644
--- a/doc/src/sgml/ref/revoke.sgml
+++ b/doc/src/sgml/ref/revoke.sgml
@@ -70,8 +70,8 @@
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
- ON { FUNCTION <replaceable>function_name</replaceable> [ ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">arg_name</replaceable> ] <replaceable class="parameter">arg_type</replaceable> [, ...] ] ) ] [, ...]
- | ALL FUNCTIONS IN SCHEMA <replaceable>schema_name</replaceable> [, ...] }
+ 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 { [ GROUP ] <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
diff --git a/doc/src/sgml/ref/security_label.sgml b/doc/src/sgml/ref/security_label.sgml
index d52113e035..e9cfdec9f9 100644
--- a/doc/src/sgml/ref/security_label.sgml
+++ b/doc/src/sgml/ref/security_label.sgml
@@ -34,8 +34,10 @@
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> |
@@ -93,10 +95,12 @@ <title>Parameters</title>
<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 tables,
- aggregates, domains, foreign tables, functions, sequences, types, and
+ aggregates, domains, foreign tables, functions, procedures, routines, sequences, types, and
views can be schema-qualified.
</para>
</listitem>
@@ -119,7 +123,7 @@ <title>Parameters</title>
<listitem>
<para>
- The mode of a function or aggregate
+ 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>.
@@ -137,7 +141,7 @@ <title>Parameters</title>
<listitem>
<para>
- The name of a function or aggregate argument.
+ 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.
@@ -150,7 +154,7 @@ <title>Parameters</title>
<listitem>
<para>
- The data type of a function or aggregate argument.
+ The data type of a function, procedure, or aggregate argument.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/reference.sgml b/doc/src/sgml/reference.sgml
index d20eaa87e7..d27fb414f7 100644
--- a/doc/src/sgml/reference.sgml
+++ b/doc/src/sgml/reference.sgml
@@ -54,8 +54,10 @@ <title>SQL Commands</title>
&alterOperatorClass;
&alterOperatorFamily;
&alterPolicy;
+ &alterProcedure;
&alterPublication;
&alterRole;
+ &alterRoutine;
&alterRule;
&alterSchema;
&alterSequence;
@@ -76,6 +78,7 @@ <title>SQL Commands</title>
&alterView;
&analyze;
&begin;
+ &call;
&checkpoint;
&close;
&cluster;
@@ -103,6 +106,7 @@ <title>SQL Commands</title>
&createOperatorClass;
&createOperatorFamily;
&createPolicy;
+ &createProcedure;
&createPublication;
&createRole;
&createRule;
@@ -150,8 +154,10 @@ <title>SQL Commands</title>
&dropOperatorFamily;
&dropOwned;
&dropPolicy;
+ &dropProcedure;
&dropPublication;
&dropRole;
+ &dropRoutine;
&dropRule;
&dropSchema;
&dropSequence;
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 508ee7a96c..bbc3766cc2 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -72,6 +72,39 @@ <title>User-defined Functions</title>
</para>
</sect1>
+ <sect1 id="xproc">
+ <title>User-defined Procedures</title>
+
+ <indexterm zone="xproc">
+ <primary>procedure</primary>
+ <secondary>user-defined</secondary>
+ </indexterm>
+
+ <para>
+ A procedure is a database object similar to a function. The difference is
+ that a procedure does not return a value, so there is no return type
+ declaration. While a function is called as part of a query or DML
+ command, a procedure is called explicitly using
+ the <xref linkend="sql-call"/> statement.
+ </para>
+
+ <para>
+ The explanations on how to define user-defined functions in the rest of
+ this chapter apply to procedures as well, except that
+ the <xref linkend="sql-createprocedure"/> command is used instead, there is
+ no return type, and some other features such as strictness don't apply.
+ </para>
+
+ <para>
+ Collectively, functions and procedures are also known
+ as <firstterm>routines</firstterm><indexterm><primary>routine</primary></indexterm>.
+ There are commands such as <xref linkend="sql-alterroutine"/>
+ and <xref linkend="sql-droproutine"/> that can operate on functions and
+ procedures without having to know which kind it is. Note, however, that
+ there is no <literal>CREATE ROUTINE</literal> command.
+ </para>
+ </sect1>
+
<sect1 id="xfunc-sql">
<title>Query Language (<acronym>SQL</acronym>) Functions</title>
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index ccde66a7dd..e481cf3d11 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -482,6 +482,14 @@ ExecuteGrantStmt(GrantStmt *stmt)
all_privileges = ACL_ALL_RIGHTS_NAMESPACE;
errormsg = gettext_noop("invalid privilege type %s for schema");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TABLESPACE:
all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
errormsg = gettext_noop("invalid privilege type %s for tablespace");
@@ -584,6 +592,8 @@ ExecGrantStmt_oids(InternalGrant *istmt)
ExecGrant_ForeignServer(istmt);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
ExecGrant_Function(istmt);
break;
case ACL_OBJECT_LANGUAGE:
@@ -671,7 +681,7 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
Oid funcid;
- funcid = LookupFuncWithArgs(func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, func, false);
objects = lappend_oid(objects, funcid);
}
break;
@@ -709,6 +719,26 @@ objectNamesToOids(GrantObjectType objtype, List *objnames)
objects = lappend_oid(objects, oid);
}
break;
+ case ACL_OBJECT_PROCEDURE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid procid;
+
+ procid = LookupFuncWithArgs(OBJECT_PROCEDURE, func, false);
+ objects = lappend_oid(objects, procid);
+ }
+ break;
+ case ACL_OBJECT_ROUTINE:
+ foreach(cell, objnames)
+ {
+ ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
+ Oid routid;
+
+ routid = LookupFuncWithArgs(OBJECT_ROUTINE, func, false);
+ objects = lappend_oid(objects, routid);
+ }
+ break;
case ACL_OBJECT_TABLESPACE:
foreach(cell, objnames)
{
@@ -785,19 +815,39 @@ objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
objects = list_concat(objects, objs);
break;
case ACL_OBJECT_FUNCTION:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
{
- ScanKeyData key[1];
+ ScanKeyData key[2];
+ int keycount;
Relation rel;
HeapScanDesc scan;
HeapTuple tuple;
- ScanKeyInit(&key[0],
+ keycount = 0;
+ ScanKeyInit(&key[keycount++],
Anum_pg_proc_pronamespace,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(namespaceId));
+ /*
+ * When looking for functions, check for return type <>0.
+ * When looking for procedures, check for return type ==0.
+ * When looking for routines, don't check the return type.
+ */
+ if (objtype == ACL_OBJECT_FUNCTION)
+ ScanKeyInit(&key[keycount++],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDNE,
+ InvalidOid);
+ else if (objtype == ACL_OBJECT_PROCEDURE)
+ ScanKeyInit(&key[keycount++],
+ Anum_pg_proc_prorettype,
+ BTEqualStrategyNumber, F_OIDEQ,
+ InvalidOid);
+
rel = heap_open(ProcedureRelationId, AccessShareLock);
- scan = heap_beginscan_catalog(rel, 1, key);
+ scan = heap_beginscan_catalog(rel, keycount, key);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
@@ -955,6 +1005,14 @@ ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *s
all_privileges = ACL_ALL_RIGHTS_FUNCTION;
errormsg = gettext_noop("invalid privilege type %s for function");
break;
+ case ACL_OBJECT_PROCEDURE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for procedure");
+ break;
+ case ACL_OBJECT_ROUTINE:
+ all_privileges = ACL_ALL_RIGHTS_FUNCTION;
+ errormsg = gettext_noop("invalid privilege type %s for routine");
+ break;
case ACL_OBJECT_TYPE:
all_privileges = ACL_ALL_RIGHTS_TYPE;
errormsg = gettext_noop("invalid privilege type %s for type");
@@ -1423,7 +1481,7 @@ RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
istmt.objtype = ACL_OBJECT_TYPE;
break;
case ProcedureRelationId:
- istmt.objtype = ACL_OBJECT_FUNCTION;
+ istmt.objtype = ACL_OBJECT_ROUTINE;
break;
case LanguageRelationId:
istmt.objtype = ACL_OBJECT_LANGUAGE;
diff --git a/src/backend/catalog/information_schema.sql b/src/backend/catalog/information_schema.sql
index 236f6be37e..360725d59a 100644
--- a/src/backend/catalog/information_schema.sql
+++ b/src/backend/catalog/information_schema.sql
@@ -1413,7 +1413,8 @@ CREATE VIEW routines AS
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(n.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
- CAST('FUNCTION' AS character_data) AS routine_type,
+ CAST(CASE WHEN p.prorettype <> 0 THEN 'FUNCTION' ELSE 'PROCEDURE' END
+ AS character_data) AS routine_type,
CAST(null AS sql_identifier) AS module_catalog,
CAST(null AS sql_identifier) AS module_schema,
CAST(null AS sql_identifier) AS module_name,
@@ -1422,7 +1423,8 @@ CREATE VIEW routines AS
CAST(null AS sql_identifier) AS udt_name,
CAST(
- CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
+ CASE WHEN p.prorettype = 0 THEN NULL
+ WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(t.oid, null)
ELSE 'USER-DEFINED' END AS character_data)
AS data_type,
@@ -1440,7 +1442,7 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
- CAST(current_database() AS sql_identifier) AS type_udt_catalog,
+ CAST(CASE WHEN p.prorettype <> 0 THEN current_database() END AS sql_identifier) AS type_udt_catalog,
CAST(nt.nspname AS sql_identifier) AS type_udt_schema,
CAST(t.typname AS sql_identifier) AS type_udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
@@ -1462,7 +1464,8 @@ CREATE VIEW routines AS
CAST('GENERAL' AS character_data) AS parameter_style,
CAST(CASE WHEN p.provolatile = 'i' THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_deterministic,
CAST('MODIFIES' AS character_data) AS sql_data_access,
- CAST(CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_null_call,
+ CAST(CASE WHEN p.prorettype <> 0 THEN
+ CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END END AS yes_or_no) AS is_null_call,
CAST(null AS character_data) AS sql_path,
CAST('YES' AS yes_or_no) AS schema_level_routine,
CAST(0 AS cardinal_number) AS max_dynamic_result_sets,
@@ -1503,13 +1506,15 @@ CREATE VIEW routines AS
CAST(null AS cardinal_number) AS result_cast_maximum_cardinality,
CAST(null AS sql_identifier) AS result_cast_dtd_identifier
- FROM pg_namespace n, pg_proc p, pg_language l,
- pg_type t, pg_namespace nt
+ FROM (pg_namespace n
+ JOIN pg_proc p ON n.oid = p.pronamespace
+ JOIN pg_language l ON p.prolang = l.oid)
+ LEFT JOIN
+ (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid)
+ ON p.prorettype = t.oid
- WHERE n.oid = p.pronamespace AND p.prolang = l.oid
- AND p.prorettype = t.oid AND t.typnamespace = nt.oid
- AND (pg_has_role(p.proowner, 'USAGE')
- OR has_function_privilege(p.oid, 'EXECUTE'));
+ WHERE (pg_has_role(p.proowner, 'USAGE')
+ OR has_function_privilege(p.oid, 'EXECUTE'));
GRANT SELECT ON routines TO PUBLIC;
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index 8d55c76fc4..9553675975 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -566,6 +566,9 @@ static const struct object_type_map
{
"function", OBJECT_FUNCTION
},
+ {
+ "procedure", OBJECT_PROCEDURE
+ },
/* OCLASS_TYPE */
{
"type", OBJECT_TYPE
@@ -884,13 +887,11 @@ get_object_address(ObjectType objtype, Node *object,
address = get_object_address_type(objtype, castNode(TypeName, object), missing_ok);
break;
case OBJECT_AGGREGATE:
- address.classId = ProcedureRelationId;
- address.objectId = LookupAggWithArgs(castNode(ObjectWithArgs, object), missing_ok);
- address.objectSubId = 0;
- break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
address.classId = ProcedureRelationId;
- address.objectId = LookupFuncWithArgs(castNode(ObjectWithArgs, object), missing_ok);
+ address.objectId = LookupFuncWithArgs(objtype, castNode(ObjectWithArgs, object), missing_ok);
address.objectSubId = 0;
break;
case OBJECT_OPERATOR:
@@ -2025,6 +2026,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
*/
if (type == OBJECT_AGGREGATE ||
type == OBJECT_FUNCTION ||
+ type == OBJECT_PROCEDURE ||
+ type == OBJECT_ROUTINE ||
type == OBJECT_OPERATOR ||
type == OBJECT_CAST ||
type == OBJECT_AMOP ||
@@ -2168,6 +2171,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
objnode = (Node *) list_make2(name, args);
break;
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_AGGREGATE:
case OBJECT_OPERATOR:
{
@@ -2253,6 +2258,8 @@ check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address,
break;
case OBJECT_AGGREGATE:
case OBJECT_FUNCTION:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
if (!pg_proc_ownercheck(address.objectId, roleid))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString((castNode(ObjectWithArgs, object))->objname));
@@ -4026,6 +4033,8 @@ getProcedureTypeDescription(StringInfo buffer, Oid procid)
if (procForm->proisagg)
appendStringInfoString(buffer, "aggregate");
+ else if (procForm->prorettype == InvalidOid)
+ appendStringInfoString(buffer, "procedure");
else
appendStringInfoString(buffer, "function");
diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c
index 47916cfb54..7d05e4bdb2 100644
--- a/src/backend/catalog/pg_proc.c
+++ b/src/backend/catalog/pg_proc.c
@@ -857,7 +857,8 @@ fmgr_sql_validator(PG_FUNCTION_ARGS)
/* Disallow pseudotype result */
/* except for RECORD, VOID, or polymorphic */
- if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
+ if (proc->prorettype &&
+ get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
proc->prorettype != RECORDOID &&
proc->prorettype != VOIDOID &&
!IsPolymorphicType(proc->prorettype))
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index adc9877e79..2e2ee883e2 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -307,7 +307,7 @@ DefineAggregate(ParseState *pstate, List *name, List *args, bool oldstyle, List
interpret_function_parameter_list(pstate,
args,
InvalidOid,
- true, /* is an aggregate */
+ OBJECT_AGGREGATE,
¶meterTypes,
&allParameterTypes,
¶meterModes,
diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
index 4f8147907c..21e3f1efe1 100644
--- a/src/backend/commands/alter.c
+++ b/src/backend/commands/alter.c
@@ -378,6 +378,8 @@ ExecRenameStmt(RenameStmt *stmt)
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
case OBJECT_LANGUAGE:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -495,6 +497,8 @@ ExecAlterObjectSchemaStmt(AlterObjectSchemaStmt *stmt,
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TSCONFIGURATION:
case OBJECT_TSDICTIONARY:
@@ -842,6 +846,8 @@ ExecAlterOwnerStmt(AlterOwnerStmt *stmt)
case OBJECT_OPERATOR:
case OBJECT_OPCLASS:
case OBJECT_OPFAMILY:
+ case OBJECT_PROCEDURE:
+ case OBJECT_ROUTINE:
case OBJECT_STATISTIC_EXT:
case OBJECT_TABLESPACE:
case OBJECT_TSDICTIONARY:
diff --git a/src/backend/commands/dropcmds.c b/src/backend/commands/dropcmds.c
index 2b30677d6f..7e6baa1928 100644
--- a/src/backend/commands/dropcmds.c
+++ b/src/backend/commands/dropcmds.c
@@ -26,6 +26,7 @@
#include "nodes/makefuncs.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
+#include "utils/lsyscache.h"
#include "utils/syscache.h"
@@ -91,21 +92,12 @@ RemoveObjects(DropStmt *stmt)
*/
if (stmt->removeType == OBJECT_FUNCTION)
{
- Oid funcOid = address.objectId;
- HeapTuple tup;
-
- tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
- if (!HeapTupleIsValid(tup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", funcOid);
-
- if (((Form_pg_proc) GETSTRUCT(tup))->proisagg)
+ if (get_func_isagg(address.objectId))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function",
NameListToString(castNode(ObjectWithArgs, object)->objname)),
errhint("Use DROP AGGREGATE to drop aggregate functions.")));
-
- ReleaseSysCache(tup);
}
/* Check permissions. */
@@ -338,6 +330,32 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
}
break;
}
+ case OBJECT_PROCEDURE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("procedure %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
+ case OBJECT_ROUTINE:
+ {
+ ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
+
+ if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
+ !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
+ {
+ msg = gettext_noop("routine %s(%s) does not exist, skipping");
+ name = NameListToString(owa->objname);
+ args = TypeNameListToString(owa->objargs);
+ }
+ break;
+ }
case OBJECT_AGGREGATE:
{
ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index fa7d0d015a..a602c20b41 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -106,8 +106,10 @@ static event_trigger_support_data event_trigger_support[] = {
{"OPERATOR CLASS", true},
{"OPERATOR FAMILY", true},
{"POLICY", true},
+ {"PROCEDURE", true},
{"PUBLICATION", true},
{"ROLE", false},
+ {"ROUTINE", true},
{"RULE", true},
{"SCHEMA", true},
{"SEQUENCE", true},
@@ -1103,8 +1105,10 @@ EventTriggerSupportsObjectType(ObjectType obtype)
case OBJECT_OPERATOR:
case OBJECT_OPFAMILY:
case OBJECT_POLICY:
+ case OBJECT_PROCEDURE:
case OBJECT_PUBLICATION:
case OBJECT_PUBLICATION_REL:
+ case OBJECT_ROUTINE:
case OBJECT_RULE:
case OBJECT_SCHEMA:
case OBJECT_SEQUENCE:
@@ -1215,6 +1219,8 @@ EventTriggerSupportsGrantObjectType(GrantObjectType objtype)
case ACL_OBJECT_LANGUAGE:
case ACL_OBJECT_LARGEOBJECT:
case ACL_OBJECT_NAMESPACE:
+ case ACL_OBJECT_PROCEDURE:
+ case ACL_OBJECT_ROUTINE:
case ACL_OBJECT_TYPE:
return true;
@@ -2243,6 +2249,10 @@ stringify_grantobjtype(GrantObjectType objtype)
return "LARGE OBJECT";
case ACL_OBJECT_NAMESPACE:
return "SCHEMA";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURE";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINE";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACE";
case ACL_OBJECT_TYPE:
@@ -2285,6 +2295,10 @@ stringify_adefprivs_objtype(GrantObjectType objtype)
return "LARGE OBJECTS";
case ACL_OBJECT_NAMESPACE:
return "SCHEMAS";
+ case ACL_OBJECT_PROCEDURE:
+ return "PROCEDURES";
+ case ACL_OBJECT_ROUTINE:
+ return "ROUTINES";
case ACL_OBJECT_TABLESPACE:
return "TABLESPACES";
case ACL_OBJECT_TYPE:
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 7de844b2ca..2a9c90133d 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -51,6 +51,8 @@
#include "commands/alter.h"
#include "commands/defrem.h"
#include "commands/proclang.h"
+#include "executor/execdesc.h"
+#include "executor/executor.h"
#include "miscadmin.h"
#include "optimizer/var.h"
#include "parser/parse_coerce.h"
@@ -179,7 +181,7 @@ void
interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
@@ -233,7 +235,7 @@ interpret_function_parameter_list(ParseState *pstate,
errmsg("SQL function cannot accept shell type %s",
TypeNameToString(t))));
/* We don't allow creating aggregates on shell types either */
- else if (is_aggregate)
+ else if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregate cannot accept shell type %s",
@@ -262,16 +264,28 @@ interpret_function_parameter_list(ParseState *pstate,
if (t->setof)
{
- if (is_aggregate)
+ if (objtype == OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("aggregates cannot accept set arguments")));
+ else if (objtype == OBJECT_PROCEDURE)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("procedures cannot accept set arguments")));
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("functions cannot accept set arguments")));
}
+ if (objtype == OBJECT_PROCEDURE)
+ {
+ if (fp->mode == FUNC_PARAM_OUT || fp->mode == FUNC_PARAM_INOUT)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ (errmsg("procedures cannot have OUT parameters"))));
+ }
+
/* handle input parameters */
if (fp->mode != FUNC_PARAM_OUT && fp->mode != FUNC_PARAM_TABLE)
{
@@ -451,6 +465,7 @@ interpret_function_parameter_list(ParseState *pstate,
*/
static bool
compute_common_attribute(ParseState *pstate,
+ bool is_procedure,
DefElem *defel,
DefElem **volatility_item,
DefElem **strict_item,
@@ -463,6 +478,8 @@ compute_common_attribute(ParseState *pstate,
{
if (strcmp(defel->defname, "volatility") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*volatility_item)
goto duplicate_error;
@@ -470,6 +487,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "strict") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*strict_item)
goto duplicate_error;
@@ -484,6 +503,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "leakproof") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*leakproof_item)
goto duplicate_error;
@@ -495,6 +516,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "cost") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*cost_item)
goto duplicate_error;
@@ -502,6 +525,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "rows") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*rows_item)
goto duplicate_error;
@@ -509,6 +534,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "parallel") == 0)
{
+ if (is_procedure)
+ goto procedure_error;
if (*parallel_item)
goto duplicate_error;
@@ -526,6 +553,13 @@ compute_common_attribute(ParseState *pstate,
errmsg("conflicting or redundant options"),
parser_errposition(pstate, defel->location)));
return false; /* keep compiler quiet */
+
+procedure_error:
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("invalid attribute in procedure definition"),
+ parser_errposition(pstate, defel->location)));
+ return false;
}
static char
@@ -603,6 +637,7 @@ update_proconfig_value(ArrayType *a, List *set_items)
*/
static void
compute_attributes_sql_style(ParseState *pstate,
+ bool is_procedure,
List *options,
List **as,
char **language,
@@ -669,9 +704,15 @@ compute_attributes_sql_style(ParseState *pstate,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options"),
parser_errposition(pstate, defel->location)));
+ if (is_procedure)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("invalid attribute in procedure definition"),
+ parser_errposition(pstate, defel->location)));
windowfunc_item = defel;
}
else if (compute_common_attribute(pstate,
+ is_procedure,
defel,
&volatility_item,
&strict_item,
@@ -762,7 +803,7 @@ compute_attributes_sql_style(ParseState *pstate,
*------------
*/
static void
-compute_attributes_with_style(ParseState *pstate, List *parameters, bool *isStrict_p, char *volatility_p)
+compute_attributes_with_style(ParseState *pstate, bool is_procedure, List *parameters, bool *isStrict_p, char *volatility_p)
{
ListCell *pl;
@@ -771,10 +812,22 @@ compute_attributes_with_style(ParseState *pstate, List *parameters, bool *isStri
DefElem *param = (DefElem *) lfirst(pl);
if (pg_strcasecmp(param->defname, "isstrict") == 0)
+ {
+ if (is_procedure)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("invalid attribute in procedure definition"),
+ parser_errposition(pstate, param->location)));
*isStrict_p = defGetBoolean(param);
+ }
else if (pg_strcasecmp(param->defname, "iscachable") == 0)
{
/* obsolete spelling of isImmutable */
+ if (is_procedure)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("invalid attribute in procedure definition"),
+ parser_errposition(pstate, param->location)));
if (defGetBoolean(param))
*volatility_p = PROVOLATILE_IMMUTABLE;
}
@@ -916,6 +969,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
/* override attributes from explicit list */
compute_attributes_sql_style(pstate,
+ stmt->is_procedure,
stmt->options,
&as_clause, &language, &transformDefElem,
&isWindowFunc, &volatility,
@@ -990,7 +1044,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
interpret_function_parameter_list(pstate,
stmt->parameters,
languageOid,
- false, /* not an aggregate */
+ stmt->is_procedure ? OBJECT_PROCEDURE : OBJECT_FUNCTION,
¶meterTypes,
&allParameterTypes,
¶meterModes,
@@ -999,7 +1053,14 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
&variadicArgType,
&requiredResultType);
- if (stmt->returnType)
+ if (stmt->is_procedure)
+ {
+ Assert(!stmt->returnType);
+
+ prorettype = InvalidOid;
+ returnsSet = false;
+ }
+ else if (stmt->returnType)
{
/* explicit RETURNS clause */
compute_return_type(stmt->returnType, languageOid,
@@ -1045,7 +1106,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
trftypes = NULL;
}
- compute_attributes_with_style(pstate, stmt->withClause, &isStrict, &volatility);
+ compute_attributes_with_style(pstate, stmt->is_procedure, stmt->withClause, &isStrict, &volatility);
interpret_AS_clause(languageOid, language, funcname, as_clause,
&prosrc_str, &probin_str);
@@ -1168,6 +1229,7 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
HeapTuple tup;
Oid funcOid;
Form_pg_proc procForm;
+ bool is_procedure;
Relation rel;
ListCell *l;
DefElem *volatility_item = NULL;
@@ -1182,7 +1244,7 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
rel = heap_open(ProcedureRelationId, RowExclusiveLock);
- funcOid = LookupFuncWithArgs(stmt->func, false);
+ funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
if (!HeapTupleIsValid(tup)) /* should not happen */
@@ -1201,12 +1263,15 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
errmsg("\"%s\" is an aggregate function",
NameListToString(stmt->func->objname))));
+ is_procedure = (procForm->prorettype == InvalidOid);
+
/* Examine requested actions. */
foreach(l, stmt->actions)
{
DefElem *defel = (DefElem *) lfirst(l);
if (compute_common_attribute(pstate,
+ is_procedure,
defel,
&volatility_item,
&strict_item,
@@ -1472,7 +1537,7 @@ CreateCast(CreateCastStmt *stmt)
{
Form_pg_proc procstruct;
- funcid = LookupFuncWithArgs(stmt->func, false);
+ funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
if (!HeapTupleIsValid(tuple))
@@ -1853,7 +1918,7 @@ CreateTransform(CreateTransformStmt *stmt)
*/
if (stmt->fromsql)
{
- fromsqlfuncid = LookupFuncWithArgs(stmt->fromsql, false);
+ fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->fromsql->objname));
@@ -1879,7 +1944,7 @@ CreateTransform(CreateTransformStmt *stmt)
if (stmt->tosql)
{
- tosqlfuncid = LookupFuncWithArgs(stmt->tosql, false);
+ tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC, NameListToString(stmt->tosql->objname));
@@ -2168,3 +2233,80 @@ ExecuteDoStmt(DoStmt *stmt)
/* execute the inline handler */
OidFunctionCall1(laninline, PointerGetDatum(codeblock));
}
+
+/*
+ * Execute CALL statement
+ */
+void
+ExecuteCallStmt(ParseState *pstate, CallStmt *stmt)
+{
+ List *targs;
+ ListCell *lc;
+ Node *node;
+ FuncExpr *fexpr;
+ int nargs;
+ int i;
+ AclResult aclresult;
+ FmgrInfo flinfo;
+ FunctionCallInfoData fcinfo;
+
+ targs = NIL;
+ foreach(lc, stmt->funccall->args)
+ {
+ targs = lappend(targs, transformExpr(pstate,
+ (Node *) lfirst(lc),
+ EXPR_KIND_CALL));
+ }
+
+ node = ParseFuncOrColumn(pstate,
+ stmt->funccall->funcname,
+ targs,
+ pstate->p_last_srf,
+ stmt->funccall,
+ true,
+ stmt->funccall->location);
+
+ fexpr = castNode(FuncExpr, node);
+
+ aclresult = pg_proc_aclcheck(fexpr->funcid, GetUserId(), ACL_EXECUTE);
+ if (aclresult != ACLCHECK_OK)
+ aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(fexpr->funcid));
+ InvokeFunctionExecuteHook(fexpr->funcid);
+
+ nargs = list_length(fexpr->args);
+
+ /* safety check; see ExecInitFunc() */
+ if (nargs > FUNC_MAX_ARGS)
+ ereport(ERROR,
+ (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
+ errmsg_plural("cannot pass more than %d argument to a procedure",
+ "cannot pass more than %d arguments to a procedure",
+ FUNC_MAX_ARGS,
+ FUNC_MAX_ARGS)));
+
+ fmgr_info(fexpr->funcid, &flinfo);
+ InitFunctionCallInfoData(fcinfo, &flinfo, nargs, fexpr->inputcollid, NULL, NULL);
+
+ i = 0;
+ foreach (lc, fexpr->args)
+ {
+ EState *estate;
+ ExprState *exprstate;
+ ExprContext *econtext;
+ Datum val;
+ bool isnull;
+
+ estate = CreateExecutorState();
+ exprstate = ExecPrepareExpr(lfirst(lc), estate);
+ econtext = CreateStandaloneExprContext();
+ val = ExecEvalExprSwitchContext(exprstate, econtext, &isnull);
+ FreeExecutorState(estate);
+
+ fcinfo.arg[i] = val;
+ fcinfo.argnull[i] = isnull;
+
+ i++;
+ }
+
+ FunctionCallInvoke(&fcinfo);
+}
diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c
index 1641e68abe..35c7c67bf5 100644
--- a/src/backend/commands/opclasscmds.c
+++ b/src/backend/commands/opclasscmds.c
@@ -520,7 +520,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
@@ -894,7 +894,7 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
errmsg("invalid procedure number %d,"
" must be between 1 and %d",
item->number, maxProcNumber)));
- funcOid = LookupFuncWithArgs(item->name, false);
+ funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Caller must own function */
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 98eb777421..3caa343723 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -390,6 +390,7 @@ sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
list_make1(param),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
@@ -658,7 +659,8 @@ init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
fcache->rettype = rettype;
/* Fetch the typlen and byval info for the result type */
- get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
+ if (rettype)
+ get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
/* Remember whether we're returning setof something */
fcache->returnsSet = procedureStruct->proretset;
@@ -1321,8 +1323,8 @@ fmgr_sql(PG_FUNCTION_ARGS)
}
else
{
- /* Should only get here for VOID functions */
- Assert(fcache->rettype == VOIDOID);
+ /* Should only get here for procedures and VOID functions */
+ Assert(fcache->rettype == InvalidOid || fcache->rettype == VOIDOID);
fcinfo->isnull = true;
result = (Datum) 0;
}
@@ -1546,7 +1548,10 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
if (modifyTargetList)
*modifyTargetList = false; /* initialize for no change */
if (junkFilter)
- *junkFilter = NULL; /* initialize in case of VOID result */
+ *junkFilter = NULL; /* initialize in case of procedure/VOID result */
+
+ if (!rettype)
+ return false;
/*
* Find the last canSetTag query in the list. This isn't necessarily the
@@ -1591,7 +1596,7 @@ check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
else
{
/* Empty function body, or last statement is a utility command */
- if (rettype != VOIDOID)
+ if (rettype && rettype != VOIDOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("return type mismatch in function declared to return %s",
diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
index d9ff8a7e51..aff9a62106 100644
--- a/src/backend/nodes/copyfuncs.c
+++ b/src/backend/nodes/copyfuncs.c
@@ -3210,6 +3210,16 @@ _copyClosePortalStmt(const ClosePortalStmt *from)
return newnode;
}
+static CallStmt *
+_copyCallStmt(const CallStmt *from)
+{
+ CallStmt *newnode = makeNode(CallStmt);
+
+ COPY_NODE_FIELD(funccall);
+
+ return newnode;
+}
+
static ClusterStmt *
_copyClusterStmt(const ClusterStmt *from)
{
@@ -3411,6 +3421,7 @@ _copyCreateFunctionStmt(const CreateFunctionStmt *from)
COPY_NODE_FIELD(funcname);
COPY_NODE_FIELD(parameters);
COPY_NODE_FIELD(returnType);
+ COPY_SCALAR_FIELD(is_procedure);
COPY_NODE_FIELD(options);
COPY_NODE_FIELD(withClause);
@@ -3435,6 +3446,7 @@ _copyAlterFunctionStmt(const AlterFunctionStmt *from)
{
AlterFunctionStmt *newnode = makeNode(AlterFunctionStmt);
+ COPY_SCALAR_FIELD(objtype);
COPY_NODE_FIELD(func);
COPY_NODE_FIELD(actions);
@@ -5104,6 +5116,9 @@ copyObjectImpl(const void *from)
case T_ClosePortalStmt:
retval = _copyClosePortalStmt(from);
break;
+ case T_CallStmt:
+ retval = _copyCallStmt(from);
+ break;
case T_ClusterStmt:
retval = _copyClusterStmt(from);
break;
diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c
index 2866fd7b4a..2e869a9d5d 100644
--- a/src/backend/nodes/equalfuncs.c
+++ b/src/backend/nodes/equalfuncs.c
@@ -1201,6 +1201,14 @@ _equalClosePortalStmt(const ClosePortalStmt *a, const ClosePortalStmt *b)
return true;
}
+static bool
+_equalCallStmt(const CallStmt *a, const CallStmt *b)
+{
+ COMPARE_NODE_FIELD(funccall);
+
+ return true;
+}
+
static bool
_equalClusterStmt(const ClusterStmt *a, const ClusterStmt *b)
{
@@ -1364,6 +1372,7 @@ _equalCreateFunctionStmt(const CreateFunctionStmt *a, const CreateFunctionStmt *
COMPARE_NODE_FIELD(funcname);
COMPARE_NODE_FIELD(parameters);
COMPARE_NODE_FIELD(returnType);
+ COMPARE_SCALAR_FIELD(is_procedure);
COMPARE_NODE_FIELD(options);
COMPARE_NODE_FIELD(withClause);
@@ -1384,6 +1393,7 @@ _equalFunctionParameter(const FunctionParameter *a, const FunctionParameter *b)
static bool
_equalAlterFunctionStmt(const AlterFunctionStmt *a, const AlterFunctionStmt *b)
{
+ COMPARE_SCALAR_FIELD(objtype);
COMPARE_NODE_FIELD(func);
COMPARE_NODE_FIELD(actions);
@@ -3246,6 +3256,9 @@ equal(const void *a, const void *b)
case T_ClosePortalStmt:
retval = _equalClosePortalStmt(a, b);
break;
+ case T_CallStmt:
+ retval = _equalCallStmt(a, b);
+ break;
case T_ClusterStmt:
retval = _equalClusterStmt(a, b);
break;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index d14ef31eae..419c3ccd91 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -4401,6 +4401,7 @@ inline_function(Oid funcid, Oid result_type, Oid result_collid,
if (funcform->prolang != SQLlanguageId ||
funcform->prosecdef ||
funcform->proretset ||
+ funcform->prorettype == InvalidOid ||
funcform->prorettype == RECORDOID ||
!heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
funcform->pronargs != list_length(args))
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index c301ca465d..ebfc94f896 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -253,7 +253,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
AlterCompositeTypeStmt AlterUserMappingStmt
AlterRoleStmt AlterRoleSetStmt AlterPolicyStmt
AlterDefaultPrivilegesStmt DefACLAction
- AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
+ AnalyzeStmt CallStmt ClosePortalStmt ClusterStmt CommentStmt
ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
CreateDomainStmt CreateExtensionStmt CreateGroupStmt CreateOpClassStmt
CreateOpFamilyStmt AlterOpFamilyStmt CreatePLangStmt
@@ -611,7 +611,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
BOOLEAN_P BOTH BY
- CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
+ CACHE CALL CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
CLUSTER COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
@@ -660,14 +660,14 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
PARALLEL PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
- PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROGRAM PUBLICATION
+ PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
QUOTE
RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
- ROW ROWS RULE
+ ROUTINE ROUTINES ROW ROWS RULE
SAVEPOINT SCHEMA SCHEMAS SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
@@ -845,6 +845,7 @@ stmt :
| AlterTSDictionaryStmt
| AlterUserMappingStmt
| AnalyzeStmt
+ | CallStmt
| CheckPointStmt
| ClosePortalStmt
| ClusterStmt
@@ -940,6 +941,20 @@ stmt :
{ $$ = NULL; }
;
+/*****************************************************************************
+ *
+ * CALL statement
+ *
+ *****************************************************************************/
+
+CallStmt: CALL func_application
+ {
+ CallStmt *n = makeNode(CallStmt);
+ n->funccall = castNode(FuncCall, $2);
+ $$ = (Node *)n;
+ }
+ ;
+
/*****************************************************************************
*
* Create a new Postgres DBMS role
@@ -4554,6 +4569,24 @@ AlterExtensionContentsStmt:
n->object = (Node *) lcons(makeString($9), $7);
$$ = (Node *)n;
}
+ | ALTER EXTENSION name add_drop PROCEDURE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
+ | ALTER EXTENSION name add_drop ROUTINE function_with_argtypes
+ {
+ AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
+ n->extname = $3;
+ n->action = $4;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ $$ = (Node *)n;
+ }
| ALTER EXTENSION name add_drop SCHEMA name
{
AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
@@ -6436,6 +6469,22 @@ CommentStmt:
n->comment = $8;
$$ = (Node *) n;
}
+ | COMMENT ON PROCEDURE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
+ | COMMENT ON ROUTINE function_with_argtypes IS comment_text
+ {
+ CommentStmt *n = makeNode(CommentStmt);
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $4;
+ n->comment = $6;
+ $$ = (Node *) n;
+ }
| COMMENT ON RULE name ON any_name IS comment_text
{
CommentStmt *n = makeNode(CommentStmt);
@@ -6614,6 +6663,26 @@ SecLabelStmt:
n->label = $9;
$$ = (Node *) n;
}
+ | SECURITY LABEL opt_provider ON PROCEDURE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_PROCEDURE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
+ | SECURITY LABEL opt_provider ON ROUTINE function_with_argtypes
+ IS security_label
+ {
+ SecLabelStmt *n = makeNode(SecLabelStmt);
+ n->provider = $3;
+ n->objtype = OBJECT_ROUTINE;
+ n->object = (Node *) $6;
+ n->label = $8;
+ $$ = (Node *) n;
+ }
;
opt_provider: FOR NonReservedWord_or_Sconst { $$ = $2; }
@@ -6977,6 +7046,22 @@ privilege_target:
n->objs = $2;
$$ = n;
}
+ | PROCEDURE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $2;
+ $$ = n;
+ }
+ | ROUTINE function_with_argtypes_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_OBJECT;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $2;
+ $$ = n;
+ }
| DATABASE name_list
{
PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
@@ -7057,6 +7142,22 @@ privilege_target:
n->objs = $5;
$$ = n;
}
+ | ALL PROCEDURES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_PROCEDURE;
+ n->objs = $5;
+ $$ = n;
+ }
+ | ALL ROUTINES IN_P SCHEMA name_list
+ {
+ PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
+ n->objtype = ACL_OBJECT_ROUTINE;
+ n->objs = $5;
+ $$ = n;
+ }
;
@@ -7213,6 +7314,7 @@ DefACLAction:
defacl_privilege_target:
TABLES { $$ = ACL_OBJECT_RELATION; }
| FUNCTIONS { $$ = ACL_OBJECT_FUNCTION; }
+ | ROUTINES { $$ = ACL_OBJECT_FUNCTION; }
| SEQUENCES { $$ = ACL_OBJECT_SEQUENCE; }
| TYPES_P { $$ = ACL_OBJECT_TYPE; }
| SCHEMAS { $$ = ACL_OBJECT_NAMESPACE; }
@@ -7413,6 +7515,18 @@ CreateFunctionStmt:
n->withClause = $7;
$$ = (Node *)n;
}
+ | CREATE opt_or_replace PROCEDURE func_name func_args_with_defaults
+ createfunc_opt_list
+ {
+ CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
+ n->replace = $2;
+ n->funcname = $4;
+ n->parameters = $5;
+ n->returnType = NULL;
+ n->is_procedure = true;
+ n->options = $6;
+ $$ = (Node *)n;
+ }
;
opt_or_replace:
@@ -7830,7 +7944,7 @@ table_func_column_list:
;
/*****************************************************************************
- * ALTER FUNCTION
+ * ALTER FUNCTION / ALTER PROCEDURE / ALTER ROUTINE
*
* RENAME and OWNER subcommands are already provided by the generic
* ALTER infrastructure, here we just specify alterations that can
@@ -7841,6 +7955,23 @@ AlterFunctionStmt:
ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
{
AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_FUNCTION;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER PROCEDURE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_PROCEDURE;
+ n->func = $3;
+ n->actions = $4;
+ $$ = (Node *) n;
+ }
+ | ALTER ROUTINE function_with_argtypes alterfunc_opt_list opt_restrict
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+ n->objtype = OBJECT_ROUTINE;
n->func = $3;
n->actions = $4;
$$ = (Node *) n;
@@ -7865,6 +7996,8 @@ opt_restrict:
* QUERY:
*
* DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP PROCEDURE procname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
+ * DROP ROUTINE routname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
* DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
* DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
*
@@ -7891,6 +8024,46 @@ RemoveFuncStmt:
n->concurrent = false;
$$ = (Node *)n;
}
+ | DROP PROCEDURE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP PROCEDURE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_PROCEDURE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $3;
+ n->behavior = $4;
+ n->missing_ok = false;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
+ | DROP ROUTINE IF_P EXISTS function_with_argtypes_list opt_drop_behavior
+ {
+ DropStmt *n = makeNode(DropStmt);
+ n->removeType = OBJECT_ROUTINE;
+ n->objects = $5;
+ n->behavior = $6;
+ n->missing_ok = true;
+ n->concurrent = false;
+ $$ = (Node *)n;
+ }
;
RemoveAggrStmt:
@@ -8348,6 +8521,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = true;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER PUBLICATION name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8357,6 +8539,15 @@ RenameStmt: ALTER AGGREGATE aggregate_with_argtypes RENAME TO name
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER ROUTINE function_with_argtypes RENAME TO name
+ {
+ RenameStmt *n = makeNode(RenameStmt);
+ n->renameType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newname = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name RENAME TO name
{
RenameStmt *n = makeNode(RenameStmt);
@@ -8736,6 +8927,22 @@ AlterObjectDependsStmt:
n->extname = makeString($7);
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes DEPENDS ON EXTENSION name
+ {
+ AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->extname = makeString($7);
+ $$ = (Node *)n;
+ }
| ALTER TRIGGER name ON qualified_name DEPENDS ON EXTENSION name
{
AlterObjectDependsStmt *n = makeNode(AlterObjectDependsStmt);
@@ -8851,6 +9058,24 @@ AlterObjectSchemaStmt:
n->missing_ok = false;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes SET SCHEMA name
+ {
+ AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newschema = $6;
+ n->missing_ok = false;
+ $$ = (Node *)n;
+ }
| ALTER TABLE relation_expr SET SCHEMA name
{
AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
@@ -9126,6 +9351,22 @@ AlterOwnerStmt: ALTER AGGREGATE aggregate_with_argtypes OWNER TO RoleSpec
n->newowner = $9;
$$ = (Node *)n;
}
+ | ALTER PROCEDURE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_PROCEDURE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
+ | ALTER ROUTINE function_with_argtypes OWNER TO RoleSpec
+ {
+ AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
+ n->objectType = OBJECT_ROUTINE;
+ n->object = (Node *) $3;
+ n->newowner = $6;
+ $$ = (Node *)n;
+ }
| ALTER SCHEMA name OWNER TO RoleSpec
{
AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
@@ -14689,6 +14930,7 @@ unreserved_keyword:
| BEGIN_P
| BY
| CACHE
+ | CALL
| CALLED
| CASCADE
| CASCADED
@@ -14848,6 +15090,7 @@ unreserved_keyword:
| PRIVILEGES
| PROCEDURAL
| PROCEDURE
+ | PROCEDURES
| PROGRAM
| PUBLICATION
| QUOTE
@@ -14874,6 +15117,8 @@ unreserved_keyword:
| ROLE
| ROLLBACK
| ROLLUP
+ | ROUTINE
+ | ROUTINES
| ROWS
| RULE
| SAVEPOINT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 64111f315e..4c4f4cdc3d 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -508,6 +508,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
break;
+ case EXPR_KIND_CALL:
+ if (isAgg)
+ err = _("aggregate functions are not allowed in CALL arguments");
+ else
+ err = _("grouping operations are not allowed in CALL arguments");
+
+ break;
+
/*
* There is intentionally no default: case here, so that the
* compiler will warn if we add a new ParseExprKind without
@@ -883,6 +891,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("window functions are not allowed in partition key expression");
break;
+ case EXPR_KIND_CALL:
+ err = _("window functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 86d1da0677..29f9da796f 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -480,6 +480,7 @@ transformIndirection(ParseState *pstate, A_Indirection *ind)
list_make1(result),
last_srf,
NULL,
+ false,
location);
if (newresult == NULL)
unknown_attribute(pstate, result, strVal(n), location);
@@ -629,6 +630,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -676,6 +678,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -736,6 +739,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
list_make1(node),
pstate->p_last_srf,
NULL,
+ false,
cref->location);
}
break;
@@ -1477,6 +1481,7 @@ transformFuncCall(ParseState *pstate, FuncCall *fn)
targs,
last_srf,
fn,
+ false,
fn->location);
}
@@ -1812,6 +1817,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_RETURNING:
case EXPR_KIND_VALUES:
case EXPR_KIND_VALUES_SINGLE:
+ case EXPR_KIND_CALL:
/* okay */
break;
case EXPR_KIND_CHECK_CONSTRAINT:
@@ -3462,6 +3468,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "WHEN";
case EXPR_KIND_PARTITION_EXPRESSION:
return "PARTITION BY";
+ case EXPR_KIND_CALL:
+ return "CALL";
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index a11843332b..2f20516e76 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -71,7 +71,7 @@ static Node *ParseComplexProjection(ParseState *pstate, const char *funcname,
*/
Node *
ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location)
+ Node *last_srf, FuncCall *fn, bool proc_call, int location)
{
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
@@ -263,7 +263,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
actual_arg_types[0], rettype, -1,
COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
}
- else if (fdresult == FUNCDETAIL_NORMAL)
+ else if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
/*
* Normal function found; was there anything indicating it must be an
@@ -306,6 +306,26 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("OVER specified, but %s is not a window function nor an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_NORMAL && proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is not a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a function, use SELECT."),
+ parser_errposition(pstate, location)));
+
+ if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("%s is a procedure",
+ func_signature_string(funcname, nargs,
+ argnames,
+ actual_arg_types)),
+ errhint("To call a procedure, use CALL."),
+ parser_errposition(pstate, location)));
}
else if (fdresult == FUNCDETAIL_AGGREGATE)
{
@@ -635,7 +655,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
check_srf_call_placement(pstate, last_srf, location);
/* build the appropriate output structure */
- if (fdresult == FUNCDETAIL_NORMAL)
+ if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
{
FuncExpr *funcexpr = makeNode(FuncExpr);
@@ -1589,6 +1609,8 @@ func_get_detail(List *funcname,
result = FUNCDETAIL_AGGREGATE;
else if (pform->proiswindow)
result = FUNCDETAIL_WINDOWFUNC;
+ else if (pform->prorettype == InvalidOid)
+ result = FUNCDETAIL_PROCEDURE;
else
result = FUNCDETAIL_NORMAL;
ReleaseSysCache(ftup);
@@ -1984,16 +2006,28 @@ LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
/*
* LookupFuncWithArgs
- * Like LookupFuncName, but the argument types are specified by a
- * ObjectWithArgs node.
+ *
+ * Like LookupFuncName, but the argument types are specified by a
+ * ObjectWithArgs node. Also, this function can check whether the result is a
+ * function, procedure, or aggregate, based on the objtype argument. Pass
+ * OBJECT_ROUTINE to accept any of them.
+ *
+ * For historical reasons, we also accept aggregates when looking for a
+ * function.
*/
Oid
-LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
+LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
{
Oid argoids[FUNC_MAX_ARGS];
int argcount;
int i;
ListCell *args_item;
+ Oid oid;
+
+ Assert(objtype == OBJECT_AGGREGATE ||
+ objtype == OBJECT_FUNCTION ||
+ objtype == OBJECT_PROCEDURE ||
+ objtype == OBJECT_ROUTINE);
argcount = list_length(func->objargs);
if (argcount > FUNC_MAX_ARGS)
@@ -2013,90 +2047,100 @@ LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
args_item = lnext(args_item);
}
- return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
-}
-
-/*
- * LookupAggWithArgs
- * Find an aggregate function from a given ObjectWithArgs node.
- *
- * This is almost like LookupFuncWithArgs, but the error messages refer
- * to aggregates rather than plain functions, and we verify that the found
- * function really is an aggregate.
- */
-Oid
-LookupAggWithArgs(ObjectWithArgs *agg, bool noError)
-{
- Oid argoids[FUNC_MAX_ARGS];
- int argcount;
- int i;
- ListCell *lc;
- Oid oid;
- HeapTuple ftup;
- Form_pg_proc pform;
-
- argcount = list_length(agg->objargs);
- if (argcount > FUNC_MAX_ARGS)
- ereport(ERROR,
- (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
- errmsg_plural("functions cannot have more than %d argument",
- "functions cannot have more than %d arguments",
- FUNC_MAX_ARGS,
- FUNC_MAX_ARGS)));
+ /*
+ * When looking for a function or routine, we pass noError through to
+ * LookupFuncName and let it make any error messages. Otherwise, we make
+ * our own errors for the aggregate and procedure cases.
+ */
+ oid = LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids,
+ (objtype == OBJECT_FUNCTION || objtype == OBJECT_ROUTINE) ? noError : true);
- i = 0;
- foreach(lc, agg->objargs)
+ if (objtype == OBJECT_FUNCTION)
{
- TypeName *t = (TypeName *) lfirst(lc);
-
- argoids[i] = LookupTypeNameOid(NULL, t, noError);
- i++;
+ /* Make sure it's a function, not a procedure */
+ if (oid && get_func_rettype(oid) == InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a function",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
}
-
- oid = LookupFuncName(agg->objname, argcount, argoids, true);
-
- if (!OidIsValid(oid))
+ else if (objtype == OBJECT_PROCEDURE)
{
- if (noError)
- return InvalidOid;
- if (argcount == 0)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s(*) does not exist",
- NameListToString(agg->objname))));
- else
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a procedure named \"%s\"",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("procedure %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+
+ /* Make sure it's a procedure */
+ if (get_func_rettype(oid) != InvalidOid)
+ {
+ if (noError)
+ return InvalidOid;
ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_FUNCTION),
- errmsg("aggregate %s does not exist",
- func_signature_string(agg->objname, argcount,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("%s is not a procedure",
+ func_signature_string(func->objname, argcount,
NIL, argoids))));
+ }
}
-
- /* Make sure it's an aggregate */
- ftup = SearchSysCache1(PROCOID, ObjectIdGetDatum(oid));
- if (!HeapTupleIsValid(ftup)) /* should not happen */
- elog(ERROR, "cache lookup failed for function %u", oid);
- pform = (Form_pg_proc) GETSTRUCT(ftup);
-
- if (!pform->proisagg)
+ else if (objtype == OBJECT_AGGREGATE)
{
- ReleaseSysCache(ftup);
- if (noError)
- return InvalidOid;
- /* we do not use the (*) notation for functions... */
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function %s is not an aggregate",
- func_signature_string(agg->objname, argcount,
- NIL, argoids))));
- }
+ if (!OidIsValid(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ else if (func->args_unspecified)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("could not find a aggregate named \"%s\"",
+ NameListToString(func->objname))));
+ else if (argcount == 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s(*) does not exist",
+ NameListToString(func->objname))));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_FUNCTION),
+ errmsg("aggregate %s does not exist",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
- ReleaseSysCache(ftup);
+ /* Make sure it's an aggregate */
+ if (!get_func_isagg(oid))
+ {
+ if (noError)
+ return InvalidOid;
+ /* we do not use the (*) notation for functions... */
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("function %s is not an aggregate",
+ func_signature_string(func->objname, argcount,
+ NIL, argoids))));
+ }
+ }
return oid;
}
-
/*
* check_srf_call_placement
* Verify that a set-returning function is called in a valid place,
@@ -2236,6 +2280,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("set-returning functions are not allowed in partition key expressions");
break;
+ case EXPR_KIND_CALL:
+ err = _("set-returning functions are not allowed in CALL arguments");
+ break;
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 82a707af7b..4da1f8f643 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -657,6 +657,10 @@ standard_ProcessUtility(PlannedStmt *pstmt,
}
break;
+ case T_CallStmt:
+ ExecuteCallStmt(pstate, castNode(CallStmt, parsetree));
+ break;
+
case T_ClusterStmt:
/* we choose to allow this during "read only" transactions */
PreventCommandDuringRecovery("CLUSTER");
@@ -1957,9 +1961,15 @@ AlterObjectTypeCommandTag(ObjectType objtype)
case OBJECT_POLICY:
tag = "ALTER POLICY";
break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
case OBJECT_ROLE:
tag = "ALTER ROLE";
break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
case OBJECT_RULE:
tag = "ALTER RULE";
break;
@@ -2261,6 +2271,12 @@ CreateCommandTag(Node *parsetree)
case OBJECT_FUNCTION:
tag = "DROP FUNCTION";
break;
+ case OBJECT_PROCEDURE:
+ tag = "DROP PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "DROP ROUTINE";
+ break;
case OBJECT_AGGREGATE:
tag = "DROP AGGREGATE";
break;
@@ -2359,7 +2375,20 @@ CreateCommandTag(Node *parsetree)
break;
case T_AlterFunctionStmt:
- tag = "ALTER FUNCTION";
+ switch (((AlterFunctionStmt *) parsetree)->objtype)
+ {
+ case OBJECT_FUNCTION:
+ tag = "ALTER FUNCTION";
+ break;
+ case OBJECT_PROCEDURE:
+ tag = "ALTER PROCEDURE";
+ break;
+ case OBJECT_ROUTINE:
+ tag = "ALTER ROUTINE";
+ break;
+ default:
+ tag = "???";
+ }
break;
case T_GrantStmt:
@@ -2438,7 +2467,10 @@ CreateCommandTag(Node *parsetree)
break;
case T_CreateFunctionStmt:
- tag = "CREATE FUNCTION";
+ if (((CreateFunctionStmt *) parsetree)->is_procedure)
+ tag = "CREATE PROCEDURE";
+ else
+ tag = "CREATE FUNCTION";
break;
case T_IndexStmt:
@@ -2493,6 +2525,10 @@ CreateCommandTag(Node *parsetree)
tag = "LOAD";
break;
+ case T_CallStmt:
+ tag = "CALL";
+ break;
+
case T_ClusterStmt:
tag = "CLUSTER";
break;
@@ -3116,6 +3152,10 @@ GetCommandLogLevel(Node *parsetree)
lev = LOGSTMT_ALL;
break;
+ case T_CallStmt:
+ lev = LOGSTMT_ALL;
+ break;
+
case T_ClusterStmt:
lev = LOGSTMT_DDL;
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 06cf32f5d7..8514c21c40 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -2691,6 +2691,12 @@ pg_get_function_result(PG_FUNCTION_ARGS)
if (!HeapTupleIsValid(proctup))
PG_RETURN_NULL();
+ if (((Form_pg_proc) GETSTRUCT(proctup))->prorettype == InvalidOid)
+ {
+ ReleaseSysCache(proctup);
+ PG_RETURN_NULL();
+ }
+
initStringInfo(&buf);
print_function_rettype(&buf, proctup);
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index 0ea2f2bc54..5211360777 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -1614,6 +1614,25 @@ func_parallel(Oid funcid)
return result;
}
+/*
+ * get_func_isagg
+ * Given procedure id, return the function's proisagg field.
+ */
+bool
+get_func_isagg(Oid funcid)
+{
+ HeapTuple tp;
+ bool result;
+
+ tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
+ if (!HeapTupleIsValid(tp))
+ elog(ERROR, "cache lookup failed for function %u", funcid);
+
+ result = ((Form_pg_proc) GETSTRUCT(tp))->proisagg;
+ ReleaseSysCache(tp);
+ return result;
+}
+
/*
* get_func_leakproof
* Given procedure id, return the function's leakproof field.
diff --git a/src/bin/pg_dump/dumputils.c b/src/bin/pg_dump/dumputils.c
index 70d8f24d17..12290a1aae 100644
--- a/src/bin/pg_dump/dumputils.c
+++ b/src/bin/pg_dump/dumputils.c
@@ -33,7 +33,7 @@ static void AddAcl(PQExpBuffer aclbuf, const char *keyword,
* name: the object name, in the form to use in the commands (already quoted)
* subname: the sub-object name, if any (already quoted); NULL if none
* type: the object type (as seen in GRANT command: must be one of
- * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
+ * TABLE, SEQUENCE, FUNCTION, PROCEDURE, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
* FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT)
* acls: the ACL string fetched from the database
* racls: the ACL string of any initial-but-now-revoked privileges
@@ -524,6 +524,9 @@ do { \
else if (strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "FUNCTIONS") == 0)
CONVERT_PRIV('X', "EXECUTE");
+ else if (strcmp(type, "PROCEDURE") == 0 ||
+ strcmp(type, "PROCEDURES") == 0)
+ CONVERT_PRIV('X', "EXECUTE");
else if (strcmp(type, "LANGUAGE") == 0)
CONVERT_PRIV('U', "USAGE");
else if (strcmp(type, "SCHEMA") == 0 ||
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index ec2fa8b9b9..41741aefbc 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -2889,7 +2889,8 @@ _tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt)
if (ropt->indexNames.head != NULL && (!(simple_string_list_member(&ropt->indexNames, te->tag))))
return 0;
}
- else if (strcmp(te->desc, "FUNCTION") == 0)
+ else if (strcmp(te->desc, "FUNCTION") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0)
{
if (!ropt->selFunction)
return 0;
@@ -3388,7 +3389,8 @@ _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
strcmp(type, "FUNCTION") == 0 ||
strcmp(type, "OPERATOR") == 0 ||
strcmp(type, "OPERATOR CLASS") == 0 ||
- strcmp(type, "OPERATOR FAMILY") == 0)
+ strcmp(type, "OPERATOR FAMILY") == 0 ||
+ strcmp(type, "PROCEDURE") == 0)
{
/* Chop "DROP " off the front and make a modifiable copy */
char *first = pg_strdup(te->dropStmt + 5);
@@ -3560,6 +3562,7 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData)
strcmp(te->desc, "OPERATOR") == 0 ||
strcmp(te->desc, "OPERATOR CLASS") == 0 ||
strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
+ strcmp(te->desc, "PROCEDURE") == 0 ||
strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
strcmp(te->desc, "SCHEMA") == 0 ||
strcmp(te->desc, "EVENT TRIGGER") == 0 ||
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index d8fb356130..e6701aaa78 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -11349,6 +11349,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char *funcargs;
char *funciargs;
char *funcresult;
+ bool is_procedure;
char *proallargtypes;
char *proargmodes;
char *proargnames;
@@ -11370,6 +11371,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
char **argnames = NULL;
char **configitems = NULL;
int nconfigitems = 0;
+ const char *keyword;
int i;
/* Skip if not to be dumped */
@@ -11513,7 +11515,11 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
{
funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
- funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
+ is_procedure = PQgetisnull(res, 0, PQfnumber(res, "funcresult"));
+ if (is_procedure)
+ funcresult = NULL;
+ else
+ funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
proallargtypes = proargmodes = proargnames = NULL;
}
else
@@ -11522,6 +11528,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
funcargs = funciargs = funcresult = NULL;
+ is_procedure = false;
}
if (PQfnumber(res, "protrftypes") != -1)
protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
@@ -11653,22 +11660,29 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
funcsig_tag = format_function_signature(fout, finfo, false);
+ keyword = is_procedure ? "PROCEDURE" : "FUNCTION";
+
/*
* DROP must be fully qualified in case same name appears in pg_catalog
*/
- appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
+ appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
+ keyword,
fmtId(finfo->dobj.namespace->dobj.name),
funcsig);
- appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
+ appendPQExpBuffer(q, "CREATE %s %s",
+ keyword,
+ funcfullsig ? funcfullsig :
funcsig);
- if (funcresult)
- appendPQExpBuffer(q, "RETURNS %s", funcresult);
+ if (is_procedure)
+ ;
+ else if (funcresult)
+ appendPQExpBuffer(q, " RETURNS %s", funcresult);
else
{
rettypename = getFormattedTypeName(fout, finfo->prorettype,
zeroAsOpaque);
- appendPQExpBuffer(q, "RETURNS %s%s",
+ appendPQExpBuffer(q, " RETURNS %s%s",
(proretset[0] == 't') ? "SETOF " : "",
rettypename);
free(rettypename);
@@ -11775,7 +11789,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
appendPQExpBuffer(q, "\n %s;\n", asPart->data);
- appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
+ appendPQExpBuffer(labelq, "%s %s", keyword, funcsig);
if (dopt->binary_upgrade)
binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
@@ -11786,7 +11800,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.namespace->dobj.name,
NULL,
finfo->rolname, false,
- "FUNCTION", SECTION_PRE_DATA,
+ keyword, SECTION_PRE_DATA,
q->data, delqry->data, NULL,
NULL, 0,
NULL, NULL);
@@ -11803,7 +11817,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
finfo->dobj.catId, 0, finfo->dobj.dumpId);
if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
- dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
+ dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
funcsig, NULL, funcsig_tag,
finfo->dobj.namespace->dobj.name,
finfo->rolname, finfo->proacl, finfo->rproacl,
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index fa3b56a426..7cf9bdadb2 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -3654,6 +3654,44 @@
section_data => 1,
section_post_data => 1, }, },
+ 'CREATE PROCEDURE dump_test.ptest1' => {
+ all_runs => 1,
+ create_order => 41,
+ create_sql => 'CREATE PROCEDURE dump_test.ptest1(a int)
+ LANGUAGE SQL AS $$ INSERT INTO dump_test.test_table (col1) VALUES (a) $$;',
+ regexp => qr/^
+ \QCREATE PROCEDURE ptest1(a integer)\E
+ \n\s+\QLANGUAGE sql\E
+ \n\s+AS\ \$\$\Q INSERT INTO dump_test.test_table (col1) VALUES (a) \E\$\$;
+ /xm,
+ like => {
+ binary_upgrade => 1,
+ clean => 1,
+ clean_if_exists => 1,
+ createdb => 1,
+ defaults => 1,
+ exclude_test_table => 1,
+ exclude_test_table_data => 1,
+ no_blobs => 1,
+ no_privs => 1,
+ no_owner => 1,
+ only_dump_test_schema => 1,
+ pg_dumpall_dbprivs => 1,
+ schema_only => 1,
+ section_pre_data => 1,
+ test_schema_plus_blobs => 1,
+ with_oids => 1, },
+ unlike => {
+ column_inserts => 1,
+ data_only => 1,
+ exclude_dump_test_schema => 1,
+ only_dump_test_table => 1,
+ pg_dumpall_globals => 1,
+ pg_dumpall_globals_clean => 1,
+ role => 1,
+ section_data => 1,
+ section_post_data => 1, }, },
+
'CREATE TYPE dump_test.int42 populated' => {
all_runs => 1,
create_order => 42,
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 99167104d4..dee0311210 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -353,6 +353,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
" CASE\n"
" WHEN p.proisagg THEN '%s'\n"
" WHEN p.proiswindow THEN '%s'\n"
+ " WHEN p.prorettype = 0 THEN '%s'\n"
" WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
" ELSE '%s'\n"
" END as \"%s\"",
@@ -361,8 +362,9 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("window"),
+ gettext_noop("proc"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else if (pset.sversion >= 80100)
appendPQExpBuffer(&buf,
@@ -407,7 +409,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
else
appendPQExpBuffer(&buf,
@@ -424,7 +426,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* translator: "agg" is short for "aggregate" */
gettext_noop("agg"),
gettext_noop("trigger"),
- gettext_noop("normal"),
+ gettext_noop("func"),
gettext_noop("Type"));
if (verbose)
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index b3e3799c13..468e50aa31 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -397,7 +397,7 @@ static const SchemaQuery Query_for_list_of_functions = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
- NULL,
+ "p.prorettype <> 0",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
@@ -423,6 +423,36 @@ static const SchemaQuery Query_for_list_of_indexes = {
NULL
};
+static const SchemaQuery Query_for_list_of_procedures = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ "p.prorettype = 0",
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_routines = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "pg_catalog.pg_function_is_visible(p.oid)",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
static const SchemaQuery Query_for_list_of_sequences = {
/* catname */
"pg_catalog.pg_class c",
@@ -1032,8 +1062,10 @@ static const pgsql_thing_t words_after_create[] = {
{"OWNED", NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
{"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
{"POLICY", NULL, NULL},
+ {"PROCEDURE", NULL, &Query_for_list_of_procedures},
{"PUBLICATION", Query_for_list_of_publications},
{"ROLE", Query_for_list_of_roles},
+ {"ROUTINE", NULL, &Query_for_list_of_routines, THING_NO_CREATE},
{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
{"SCHEMA", Query_for_list_of_schemas},
{"SEQUENCE", NULL, &Query_for_list_of_sequences},
@@ -1407,7 +1439,7 @@ psql_completion(const char *text, int start, int end)
/* Known command-starting keywords. */
static const char *const sql_commands[] = {
- "ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER",
+ "ABORT", "ALTER", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
"COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
"DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
"FETCH", "GRANT", "IMPORT", "INSERT", "LISTEN", "LOAD", "LOCK",
@@ -1520,11 +1552,11 @@ psql_completion(const char *text, int start, int end)
/* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
else if (TailMatches7("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
COMPLETE_WITH_CONST("SET TABLESPACE");
- /* ALTER AGGREGATE,FUNCTION <name> */
- else if (Matches3("ALTER", "AGGREGATE|FUNCTION", MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> */
+ else if (Matches3("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- /* ALTER AGGREGATE,FUNCTION <name> (...) */
- else if (Matches4("ALTER", "AGGREGATE|FUNCTION", MatchAny, MatchAny))
+ /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> (...) */
+ else if (Matches4("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny))
{
if (ends_with(prev_wd, ')'))
COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
@@ -2145,6 +2177,11 @@ psql_completion(const char *text, int start, int end)
/* ROLLBACK */
else if (Matches1("ROLLBACK"))
COMPLETE_WITH_LIST4("WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
+/* CALL */
+ else if (Matches1("CALL"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (Matches2("CALL", MatchAny))
+ COMPLETE_WITH_CONST("(");
/* CLUSTER */
else if (Matches1("CLUSTER"))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, "UNION SELECT 'VERBOSE'");
@@ -2176,6 +2213,7 @@ psql_completion(const char *text, int start, int end)
"SERVER", "INDEX", "LANGUAGE", "POLICY", "PUBLICATION", "RULE",
"SCHEMA", "SEQUENCE", "STATISTICS", "SUBSCRIPTION",
"TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
+ "PROCEDURE", "ROUTINE",
"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
"TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
@@ -2685,7 +2723,7 @@ psql_completion(const char *text, int start, int end)
"COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
MatchAny) ||
Matches4("DROP", "ACCESS", "METHOD", MatchAny) ||
- (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, MatchAny) &&
+ (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
ends_with(prev_wd, ')')) ||
Matches4("DROP", "EVENT", "TRIGGER", MatchAny) ||
Matches5("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
@@ -2694,9 +2732,9 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
/* help completing some of the variants */
- else if (Matches3("DROP", "AGGREGATE|FUNCTION", MatchAny))
+ else if (Matches3("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
COMPLETE_WITH_CONST("(");
- else if (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, "("))
+ else if (Matches4("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
else if (Matches2("DROP", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
@@ -2893,10 +2931,12 @@ psql_completion(const char *text, int start, int end)
* objects supported.
*/
if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES"))
- COMPLETE_WITH_LIST5("TABLES", "SEQUENCES", "FUNCTIONS", "TYPES", "SCHEMAS");
+ COMPLETE_WITH_LIST7("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS");
else
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf,
" UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
+ " UNION SELECT 'ALL PROCEDURES IN SCHEMA'"
+ " UNION SELECT 'ALL ROUTINES IN SCHEMA'"
" UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
" UNION SELECT 'ALL TABLES IN SCHEMA'"
" UNION SELECT 'DATABASE'"
@@ -2906,6 +2946,8 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'FUNCTION'"
" UNION SELECT 'LANGUAGE'"
" UNION SELECT 'LARGE OBJECT'"
+ " UNION SELECT 'PROCEDURE'"
+ " UNION SELECT 'ROUTINE'"
" UNION SELECT 'SCHEMA'"
" UNION SELECT 'SEQUENCE'"
" UNION SELECT 'TABLE'"
@@ -2913,7 +2955,10 @@ psql_completion(const char *text, int start, int end)
" UNION SELECT 'TYPE'");
}
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "ALL"))
- COMPLETE_WITH_LIST3("FUNCTIONS IN SCHEMA", "SEQUENCES IN SCHEMA",
+ COMPLETE_WITH_LIST5("FUNCTIONS IN SCHEMA",
+ "PROCEDURES IN SCHEMA",
+ "ROUTINES IN SCHEMA",
+ "SEQUENCES IN SCHEMA",
"TABLES IN SCHEMA");
else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "FOREIGN"))
COMPLETE_WITH_LIST2("DATA WRAPPER", "SERVER");
@@ -2934,6 +2979,10 @@ psql_completion(const char *text, int start, int end)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (TailMatches1("LANGUAGE"))
COMPLETE_WITH_QUERY(Query_for_list_of_languages);
+ else if (TailMatches1("PROCEDURE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
+ else if (TailMatches1("ROUTINE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
else if (TailMatches1("SCHEMA"))
COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
else if (TailMatches1("SEQUENCE"))
@@ -3163,7 +3212,7 @@ psql_completion(const char *text, int start, int end)
static const char *const list_SECURITY_LABEL[] =
{"TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
"EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION", "LARGE OBJECT",
- "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "ROLE", "SCHEMA",
+ "MATERIALIZED VIEW", "LANGUAGE", "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
"SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW", NULL};
COMPLETE_WITH_LIST(list_SECURITY_LABEL);
@@ -3233,8 +3282,8 @@ psql_completion(const char *text, int start, int end)
/* Complete SET <var> with "TO" */
else if (Matches2("SET", MatchAny))
COMPLETE_WITH_CONST("TO");
- /* Complete ALTER DATABASE|FUNCTION|ROLE|USER ... SET <name> */
- else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|ROLE|USER") &&
+ /* Complete ALTER DATABASE|FUNCTION||PROCEDURE|ROLE|ROUTINE|USER ... SET <name> */
+ else if (HeadMatches2("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER") &&
TailMatches2("SET", MatchAny))
COMPLETE_WITH_LIST2("FROM CURRENT", "TO");
/* Suggest possible variable values */
diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
index bfead9af3d..52cbf61ccb 100644
--- a/src/include/commands/defrem.h
+++ b/src/include/commands/defrem.h
@@ -59,12 +59,13 @@ extern void DropTransformById(Oid transformOid);
extern void IsThereFunctionInNamespace(const char *proname, int pronargs,
oidvector *proargtypes, Oid nspOid);
extern void ExecuteDoStmt(DoStmt *stmt);
+extern void ExecuteCallStmt(ParseState *pstate, CallStmt *stmt);
extern Oid get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok);
extern Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok);
extern void interpret_function_parameter_list(ParseState *pstate,
List *parameters,
Oid languageOid,
- bool is_aggregate,
+ ObjectType objtype,
oidvector **parameterTypes,
ArrayType **allParameterTypes,
ArrayType **parameterModes,
diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h
index 03dc5307e8..c5b5115f5b 100644
--- a/src/include/nodes/nodes.h
+++ b/src/include/nodes/nodes.h
@@ -414,6 +414,7 @@ typedef enum NodeTag
T_DropSubscriptionStmt,
T_CreateStatsStmt,
T_AlterCollationStmt,
+ T_CallStmt,
/*
* TAGS FOR PARSE TREE NODES (parsenodes.h)
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 34d6afc80f..c4ff1c5544 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -355,6 +355,7 @@ typedef struct FuncCall
bool agg_distinct; /* arguments were labeled DISTINCT */
bool func_variadic; /* last argument was labeled VARIADIC */
struct WindowDef *over; /* OVER clause, if any */
+ bool proc_call; /* CALL statement */
int location; /* token location, or -1 if unknown */
} FuncCall;
@@ -1642,9 +1643,11 @@ typedef enum ObjectType
OBJECT_OPERATOR,
OBJECT_OPFAMILY,
OBJECT_POLICY,
+ OBJECT_PROCEDURE,
OBJECT_PUBLICATION,
OBJECT_PUBLICATION_REL,
OBJECT_ROLE,
+ OBJECT_ROUTINE,
OBJECT_RULE,
OBJECT_SCHEMA,
OBJECT_SEQUENCE,
@@ -1856,6 +1859,8 @@ typedef enum GrantObjectType
ACL_OBJECT_LANGUAGE, /* procedural language */
ACL_OBJECT_LARGEOBJECT, /* largeobject */
ACL_OBJECT_NAMESPACE, /* namespace */
+ ACL_OBJECT_PROCEDURE, /* procedure */
+ ACL_OBJECT_ROUTINE, /* routine */
ACL_OBJECT_TABLESPACE, /* tablespace */
ACL_OBJECT_TYPE /* type */
} GrantObjectType;
@@ -2749,6 +2754,7 @@ typedef struct CreateFunctionStmt
List *funcname; /* qualified name of function to create */
List *parameters; /* a list of FunctionParameter */
TypeName *returnType; /* the return type */
+ bool is_procedure;
List *options; /* a list of DefElem */
List *withClause; /* a list of DefElem */
} CreateFunctionStmt;
@@ -2775,6 +2781,7 @@ typedef struct FunctionParameter
typedef struct AlterFunctionStmt
{
NodeTag type;
+ ObjectType objtype;
ObjectWithArgs *func; /* name and args of function */
List *actions; /* list of DefElem */
} AlterFunctionStmt;
@@ -2799,6 +2806,16 @@ typedef struct InlineCodeBlock
bool langIsTrusted; /* trusted property of the language */
} InlineCodeBlock;
+/* ----------------------
+ * CALL statement
+ * ----------------------
+ */
+typedef struct CallStmt
+{
+ NodeTag type;
+ FuncCall *funccall;
+} CallStmt;
+
/* ----------------------
* Alter Object Rename Statement
* ----------------------
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index f50e45e886..a932400058 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -63,6 +63,7 @@ PG_KEYWORD("boolean", BOOLEAN_P, COL_NAME_KEYWORD)
PG_KEYWORD("both", BOTH, RESERVED_KEYWORD)
PG_KEYWORD("by", BY, UNRESERVED_KEYWORD)
PG_KEYWORD("cache", CACHE, UNRESERVED_KEYWORD)
+PG_KEYWORD("call", CALL, UNRESERVED_KEYWORD)
PG_KEYWORD("called", CALLED, UNRESERVED_KEYWORD)
PG_KEYWORD("cascade", CASCADE, UNRESERVED_KEYWORD)
PG_KEYWORD("cascaded", CASCADED, UNRESERVED_KEYWORD)
@@ -310,6 +311,7 @@ PG_KEYWORD("prior", PRIOR, UNRESERVED_KEYWORD)
PG_KEYWORD("privileges", PRIVILEGES, UNRESERVED_KEYWORD)
PG_KEYWORD("procedural", PROCEDURAL, UNRESERVED_KEYWORD)
PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD)
+PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD)
@@ -340,6 +342,8 @@ PG_KEYWORD("right", RIGHT, TYPE_FUNC_NAME_KEYWORD)
PG_KEYWORD("role", ROLE, UNRESERVED_KEYWORD)
PG_KEYWORD("rollback", ROLLBACK, UNRESERVED_KEYWORD)
PG_KEYWORD("rollup", ROLLUP, UNRESERVED_KEYWORD)
+PG_KEYWORD("routine", ROUTINE, UNRESERVED_KEYWORD)
+PG_KEYWORD("routines", ROUTINES, UNRESERVED_KEYWORD)
PG_KEYWORD("row", ROW, COL_NAME_KEYWORD)
PG_KEYWORD("rows", ROWS, UNRESERVED_KEYWORD)
PG_KEYWORD("rule", RULE, UNRESERVED_KEYWORD)
diff --git a/src/include/parser/parse_func.h b/src/include/parser/parse_func.h
index b4b6084b1b..fccccd21ed 100644
--- a/src/include/parser/parse_func.h
+++ b/src/include/parser/parse_func.h
@@ -24,6 +24,7 @@ typedef enum
FUNCDETAIL_NOTFOUND, /* no matching function */
FUNCDETAIL_MULTIPLE, /* too many matching functions */
FUNCDETAIL_NORMAL, /* found a matching regular function */
+ FUNCDETAIL_PROCEDURE, /* found a matching procedure */
FUNCDETAIL_AGGREGATE, /* found a matching aggregate function */
FUNCDETAIL_WINDOWFUNC, /* found a matching window function */
FUNCDETAIL_COERCION /* it's a type coercion request */
@@ -31,7 +32,8 @@ typedef enum
extern Node *ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
- Node *last_srf, FuncCall *fn, int location);
+ Node *last_srf, FuncCall *fn, bool proc_call,
+ int location);
extern FuncDetailCode func_get_detail(List *funcname,
List *fargs, List *fargnames,
@@ -62,10 +64,8 @@ extern const char *func_signature_string(List *funcname, int nargs,
extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes,
bool noError);
-extern Oid LookupFuncWithArgs(ObjectWithArgs *func,
+extern Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func,
bool noError);
-extern Oid LookupAggWithArgs(ObjectWithArgs *agg,
- bool noError);
extern void check_srf_call_placement(ParseState *pstate, Node *last_srf,
int location);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f0e210ad8d..565bb3dc6c 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -67,7 +67,8 @@ typedef enum ParseExprKind
EXPR_KIND_EXECUTE_PARAMETER, /* parameter value in EXECUTE */
EXPR_KIND_TRIGGER_WHEN, /* WHEN condition in CREATE TRIGGER */
EXPR_KIND_POLICY, /* USING or WITH CHECK expr in policy */
- EXPR_KIND_PARTITION_EXPRESSION /* PARTITION BY expression */
+ EXPR_KIND_PARTITION_EXPRESSION, /* PARTITION BY expression */
+ EXPR_KIND_CALL /* CALL argument */
} ParseExprKind;
diff --git a/src/include/utils/lsyscache.h b/src/include/utils/lsyscache.h
index 07208b56ce..b316cc594c 100644
--- a/src/include/utils/lsyscache.h
+++ b/src/include/utils/lsyscache.h
@@ -118,6 +118,7 @@ extern bool get_func_retset(Oid funcid);
extern bool func_strict(Oid funcid);
extern char func_volatile(Oid funcid);
extern char func_parallel(Oid funcid);
+extern bool get_func_isagg(Oid funcid);
extern bool get_func_leakproof(Oid funcid);
extern float4 get_func_cost(Oid funcid);
extern float4 get_func_rows(Oid funcid);
diff --git a/src/interfaces/ecpg/preproc/ecpg.tokens b/src/interfaces/ecpg/preproc/ecpg.tokens
index 68ba925efe..1d613af02f 100644
--- a/src/interfaces/ecpg/preproc/ecpg.tokens
+++ b/src/interfaces/ecpg/preproc/ecpg.tokens
@@ -2,7 +2,7 @@
/* special embedded SQL tokens */
%token SQL_ALLOCATE SQL_AUTOCOMMIT SQL_BOOL SQL_BREAK
- SQL_CALL SQL_CARDINALITY SQL_CONNECT
+ SQL_CARDINALITY SQL_CONNECT
SQL_COUNT
SQL_DATETIME_INTERVAL_CODE
SQL_DATETIME_INTERVAL_PRECISION SQL_DESCRIBE
diff --git a/src/interfaces/ecpg/preproc/ecpg.trailer b/src/interfaces/ecpg/preproc/ecpg.trailer
index f60a62099d..19dc781885 100644
--- a/src/interfaces/ecpg/preproc/ecpg.trailer
+++ b/src/interfaces/ecpg/preproc/ecpg.trailer
@@ -1460,13 +1460,13 @@ action : CONTINUE_P
$<action>$.command = NULL;
$<action>$.str = mm_strdup("continue");
}
- | SQL_CALL name '(' c_args ')'
+ | CALL name '(' c_args ')'
{
$<action>$.code = W_DO;
$<action>$.command = cat_str(4, $2, mm_strdup("("), $4, mm_strdup(")"));
$<action>$.str = cat2_str(mm_strdup("call"), mm_strdup($<action>$.command));
}
- | SQL_CALL name
+ | CALL name
{
$<action>$.code = W_DO;
$<action>$.command = cat2_str($2, mm_strdup("()"));
@@ -1482,7 +1482,6 @@ ECPGKeywords: ECPGKeywords_vanames { $$ = $1; }
;
ECPGKeywords_vanames: SQL_BREAK { $$ = mm_strdup("break"); }
- | SQL_CALL { $$ = mm_strdup("call"); }
| SQL_CARDINALITY { $$ = mm_strdup("cardinality"); }
| SQL_COUNT { $$ = mm_strdup("count"); }
| SQL_DATETIME_INTERVAL_CODE { $$ = mm_strdup("datetime_interval_code"); }
diff --git a/src/interfaces/ecpg/preproc/ecpg_keywords.c b/src/interfaces/ecpg/preproc/ecpg_keywords.c
index 3b52b8f3a2..848b2d4849 100644
--- a/src/interfaces/ecpg/preproc/ecpg_keywords.c
+++ b/src/interfaces/ecpg/preproc/ecpg_keywords.c
@@ -33,7 +33,6 @@ static const ScanKeyword ECPGScanKeywords[] = {
{"autocommit", SQL_AUTOCOMMIT, 0},
{"bool", SQL_BOOL, 0},
{"break", SQL_BREAK, 0},
- {"call", SQL_CALL, 0},
{"cardinality", SQL_CARDINALITY, 0},
{"connect", SQL_CONNECT, 0},
{"count", SQL_COUNT, 0},
diff --git a/src/pl/plperl/GNUmakefile b/src/pl/plperl/GNUmakefile
index 91d1296b21..b829027d05 100644
--- a/src/pl/plperl/GNUmakefile
+++ b/src/pl/plperl/GNUmakefile
@@ -55,7 +55,7 @@ endif # win32
SHLIB_LINK = $(perl_embed_ldflags)
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=plperl --load-extension=plperlu
-REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array
+REGRESS = plperl plperl_lc plperl_trigger plperl_shared plperl_elog plperl_util plperl_init plperlu plperl_array plperl_call
# if Perl can support two interpreters in one backend,
# test plperl-and-plperlu cases
ifneq ($(PERL),)
diff --git a/src/pl/plperl/expected/plperl_call.out b/src/pl/plperl/expected/plperl_call.out
new file mode 100644
index 0000000000..4bccfcb7c8
--- /dev/null
+++ b/src/pl/plperl/expected/plperl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index a57393fbdd..9f5313235f 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -1915,7 +1915,7 @@ plperl_inline_handler(PG_FUNCTION_ARGS)
desc.fn_retistuple = false;
desc.fn_retisset = false;
desc.fn_retisarray = false;
- desc.result_oid = VOIDOID;
+ desc.result_oid = InvalidOid;
desc.nargs = 0;
desc.reference = NULL;
@@ -2481,7 +2481,7 @@ plperl_func_handler(PG_FUNCTION_ARGS)
}
retval = (Datum) 0;
}
- else
+ else if (prodesc->result_oid)
{
retval = plperl_sv_to_datum(perlret,
prodesc->result_oid,
@@ -2826,7 +2826,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -3343,7 +3343,7 @@ plperl_return_next_internal(SV *sv)
tuplestore_puttuple(current_call_data->tuple_store, tuple);
}
- else
+ else if (prodesc->result_oid)
{
Datum ret[1];
bool isNull[1];
diff --git a/src/pl/plperl/sql/plperl_call.sql b/src/pl/plperl/sql/plperl_call.sql
new file mode 100644
index 0000000000..bd2b63b418
--- /dev/null
+++ b/src/pl/plperl/sql/plperl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE plperl
+AS $$
+undef;
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE plperl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plperl
+AS $$
+spi_exec_query("INSERT INTO test1 VALUES ($_[0])");
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/plpgsql/src/pl_comp.c b/src/pl/plpgsql/src/pl_comp.c
index d0afa59242..f459c02f7b 100644
--- a/src/pl/plpgsql/src/pl_comp.c
+++ b/src/pl/plpgsql/src/pl_comp.c
@@ -275,7 +275,6 @@ do_compile(FunctionCallInfo fcinfo,
bool isnull;
char *proc_source;
HeapTuple typeTup;
- Form_pg_type typeStruct;
PLpgSQL_variable *var;
PLpgSQL_rec *rec;
int i;
@@ -531,53 +530,58 @@ do_compile(FunctionCallInfo fcinfo,
/*
* Lookup the function's return type
*/
- typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
- if (!HeapTupleIsValid(typeTup))
- elog(ERROR, "cache lookup failed for type %u", rettypeid);
- typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
-
- /* Disallow pseudotype result, except VOID or RECORD */
- /* (note we already replaced polymorphic types) */
- if (typeStruct->typtype == TYPTYPE_PSEUDO)
+ if (rettypeid)
{
- if (rettypeid == VOIDOID ||
- rettypeid == RECORDOID)
- /* okay */ ;
- else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("trigger functions can only be called as triggers")));
- else
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("PL/pgSQL functions cannot return type %s",
- format_type_be(rettypeid))));
- }
+ Form_pg_type typeStruct;
- if (typeStruct->typrelid != InvalidOid ||
- rettypeid == RECORDOID)
- function->fn_retistuple = true;
- else
- {
- function->fn_retbyval = typeStruct->typbyval;
- function->fn_rettyplen = typeStruct->typlen;
+ typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
+ if (!HeapTupleIsValid(typeTup))
+ elog(ERROR, "cache lookup failed for type %u", rettypeid);
+ typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
- /*
- * install $0 reference, but only for polymorphic return
- * types, and not when the return is specified through an
- * output parameter.
- */
- if (IsPolymorphicType(procStruct->prorettype) &&
- num_out_args == 0)
+ /* Disallow pseudotype result, except VOID or RECORD */
+ /* (note we already replaced polymorphic types) */
+ if (typeStruct->typtype == TYPTYPE_PSEUDO)
{
- (void) plpgsql_build_variable("$0", 0,
- build_datatype(typeTup,
- -1,
- function->fn_input_collation),
- true);
+ if (rettypeid == VOIDOID ||
+ rettypeid == RECORDOID)
+ /* okay */ ;
+ else if (rettypeid == TRIGGEROID || rettypeid == EVTTRIGGEROID)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("trigger functions can only be called as triggers")));
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("PL/pgSQL functions cannot return type %s",
+ format_type_be(rettypeid))));
+ }
+
+ if (typeStruct->typrelid != InvalidOid ||
+ rettypeid == RECORDOID)
+ function->fn_retistuple = true;
+ else
+ {
+ function->fn_retbyval = typeStruct->typbyval;
+ function->fn_rettyplen = typeStruct->typlen;
+
+ /*
+ * install $0 reference, but only for polymorphic return
+ * types, and not when the return is specified through an
+ * output parameter.
+ */
+ if (IsPolymorphicType(procStruct->prorettype) &&
+ num_out_args == 0)
+ {
+ (void) plpgsql_build_variable("$0", 0,
+ build_datatype(typeTup,
+ -1,
+ function->fn_input_collation),
+ true);
+ }
}
+ ReleaseSysCache(typeTup);
}
- ReleaseSysCache(typeTup);
break;
case PLPGSQL_DML_TRIGGER:
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 7a6dd15460..882b16e2b1 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -462,7 +462,7 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
estate.err_text = NULL;
estate.err_stmt = (PLpgSQL_stmt *) (func->action);
rc = exec_stmt_block(&estate, func->action);
- if (rc != PLPGSQL_RC_RETURN)
+ if (rc != PLPGSQL_RC_RETURN && func->fn_rettype)
{
estate.err_stmt = NULL;
estate.err_text = NULL;
@@ -509,6 +509,12 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
}
else if (!estate.retisnull)
{
+ if (!func->fn_rettype)
+ {
+ ereport(ERROR,
+ (errmsg("cannot return a value from a procedure")));
+ }
+
if (estate.retistuple)
{
/*
diff --git a/src/pl/plpython/Makefile b/src/pl/plpython/Makefile
index 7680d49cb6..cc91afebde 100644
--- a/src/pl/plpython/Makefile
+++ b/src/pl/plpython/Makefile
@@ -78,6 +78,7 @@ REGRESS = \
plpython_spi \
plpython_newline \
plpython_void \
+ plpython_call \
plpython_params \
plpython_setof \
plpython_record \
diff --git a/src/pl/plpython/expected/plpython_call.out b/src/pl/plpython/expected/plpython_call.out
new file mode 100644
index 0000000000..90785343b6
--- /dev/null
+++ b/src/pl/plpython/expected/plpython_call.out
@@ -0,0 +1,35 @@
+--
+-- Tests for procedures / CALL syntax
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+CALL test_proc1();
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+CALL test_proc2();
+ERROR: PL/Python procedure did not return None
+CONTEXT: PL/Python procedure "test_proc2"
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/plpython/plpy_exec.c b/src/pl/plpython/plpy_exec.c
index 9d2341a4a3..2c304053c1 100644
--- a/src/pl/plpython/plpy_exec.c
+++ b/src/pl/plpython/plpy_exec.c
@@ -197,12 +197,19 @@ PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
error_context_stack = &plerrcontext;
/*
- * If the function is declared to return void, the Python return value
+ * For a procedure or function declared to return void, the Python return value
* must be None. For void-returning functions, we also treat a None
* return value as a special "void datum" rather than NULL (as is the
* case for non-void-returning functions).
*/
- if (proc->result.typoid == VOIDOID)
+ if (proc->is_procedure)
+ {
+ if (plrv != Py_None)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("PL/Python procedure did not return None")));
+ }
+ else if (proc->result.typoid == VOIDOID)
{
if (plrv != Py_None)
ereport(ERROR,
@@ -670,7 +677,8 @@ plpython_return_error_callback(void *arg)
{
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
- if (exec_ctx->curr_proc)
+ if (exec_ctx->curr_proc &&
+ !exec_ctx->curr_proc->is_procedure)
errcontext("while creating return value");
}
diff --git a/src/pl/plpython/plpy_main.c b/src/pl/plpython/plpy_main.c
index 32d23ae5b6..695de30583 100644
--- a/src/pl/plpython/plpy_main.c
+++ b/src/pl/plpython/plpy_main.c
@@ -389,8 +389,14 @@ plpython_error_callback(void *arg)
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
if (exec_ctx->curr_proc)
- errcontext("PL/Python function \"%s\"",
- PLy_procedure_name(exec_ctx->curr_proc));
+ {
+ if (exec_ctx->curr_proc->is_procedure)
+ errcontext("PL/Python procedure \"%s\"",
+ PLy_procedure_name(exec_ctx->curr_proc));
+ else
+ errcontext("PL/Python function \"%s\"",
+ PLy_procedure_name(exec_ctx->curr_proc));
+ }
}
static void
diff --git a/src/pl/plpython/plpy_procedure.c b/src/pl/plpython/plpy_procedure.c
index faa4977463..b7c24e356f 100644
--- a/src/pl/plpython/plpy_procedure.c
+++ b/src/pl/plpython/plpy_procedure.c
@@ -189,6 +189,7 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
proc->fn_tid = procTup->t_self;
proc->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
proc->is_setof = procStruct->proretset;
+ proc->is_procedure = (procStruct->prorettype == InvalidOid);
proc->src = NULL;
proc->argnames = NULL;
proc->args = NULL;
@@ -206,9 +207,9 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
/*
* get information required for output conversion of the return value,
- * but only if this isn't a trigger.
+ * but only if this isn't a trigger or procedure.
*/
- if (!is_trigger)
+ if (!is_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
HeapTuple rvTypeTup;
diff --git a/src/pl/plpython/plpy_procedure.h b/src/pl/plpython/plpy_procedure.h
index cd1b87fdc3..8968b5c92e 100644
--- a/src/pl/plpython/plpy_procedure.h
+++ b/src/pl/plpython/plpy_procedure.h
@@ -30,7 +30,8 @@ typedef struct PLyProcedure
TransactionId fn_xmin;
ItemPointerData fn_tid;
bool fn_readonly;
- bool is_setof; /* true, if procedure returns result set */
+ bool is_setof; /* true, if function returns result set */
+ bool is_procedure;
PLyObToDatum result; /* Function result output conversion info */
PLyDatumToOb result_in; /* For converting input tuples in a trigger */
char *src; /* textual procedure code, after mangling */
diff --git a/src/pl/plpython/sql/plpython_call.sql b/src/pl/plpython/sql/plpython_call.sql
new file mode 100644
index 0000000000..3fb74de5f0
--- /dev/null
+++ b/src/pl/plpython/sql/plpython_call.sql
@@ -0,0 +1,41 @@
+--
+-- Tests for procedures / CALL syntax
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpythonu
+AS $$
+pass
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-None
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpythonu
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpythonu
+AS $$
+plpy.execute("INSERT INTO test1 VALUES (%s)" % x)
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/pl/tcl/Makefile b/src/pl/tcl/Makefile
index b8971d3cc8..6a92a9b6aa 100644
--- a/src/pl/tcl/Makefile
+++ b/src/pl/tcl/Makefile
@@ -28,7 +28,7 @@ DATA = pltcl.control pltcl--1.0.sql pltcl--unpackaged--1.0.sql \
pltclu.control pltclu--1.0.sql pltclu--unpackaged--1.0.sql
REGRESS_OPTS = --dbname=$(PL_TESTDB) --load-extension=pltcl
-REGRESS = pltcl_setup pltcl_queries pltcl_start_proc pltcl_subxact pltcl_unicode
+REGRESS = pltcl_setup pltcl_queries pltcl_call pltcl_start_proc pltcl_subxact pltcl_unicode
# Tcl on win32 ships with import libraries only for Microsoft Visual C++,
# which are not compatible with mingw gcc. Therefore we need to build a
diff --git a/src/pl/tcl/expected/pltcl_call.out b/src/pl/tcl/expected/pltcl_call.out
new file mode 100644
index 0000000000..7221a37ad0
--- /dev/null
+++ b/src/pl/tcl/expected/pltcl_call.out
@@ -0,0 +1,29 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+CALL test_proc1();
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+CALL test_proc2();
+CREATE TABLE test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+CALL test_proc3(55);
+SELECT * FROM test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE test1;
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 6d97ddc99b..e0792d93e1 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -146,6 +146,7 @@ typedef struct pltcl_proc_desc
Oid result_typid; /* OID of fn's result type */
FmgrInfo result_in_func; /* input function for fn's result type */
Oid result_typioparam; /* param to pass to same */
+ bool fn_is_procedure;/* true if this is a procedure */
bool fn_retisset; /* true if function returns a set */
bool fn_retistuple; /* true if function returns composite */
bool fn_retisdomain; /* true if function returns domain */
@@ -968,7 +969,7 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
retval = (Datum) 0;
fcinfo->isnull = true;
}
- else if (fcinfo->isnull)
+ else if (fcinfo->isnull && !prodesc->fn_is_procedure)
{
retval = InputFunctionCall(&prodesc->result_in_func,
NULL,
@@ -1026,11 +1027,13 @@ pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
call_state);
retval = HeapTupleGetDatum(tup);
}
- else
+ else if (!prodesc->fn_is_procedure)
retval = InputFunctionCall(&prodesc->result_in_func,
utf_u2e(Tcl_GetStringResult(interp)),
prodesc->result_typioparam,
-1);
+ else
+ retval = 0;
return retval;
}
@@ -1506,7 +1509,9 @@ compile_pltcl_function(Oid fn_oid, Oid tgreloid,
* Get the required information for input conversion of the
* return value.
************************************************************/
- if (!is_trigger && !is_event_trigger)
+ prodesc->fn_is_procedure = (procStruct->prorettype == InvalidOid);
+
+ if (!is_trigger && !is_event_trigger && procStruct->prorettype)
{
Oid rettype = procStruct->prorettype;
@@ -2199,7 +2204,7 @@ pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
tuplestore_puttuple(call_state->tuple_store, tuple);
}
}
- else
+ else if (!prodesc->fn_is_procedure)
{
Datum retval;
bool isNull = false;
diff --git a/src/pl/tcl/sql/pltcl_call.sql b/src/pl/tcl/sql/pltcl_call.sql
new file mode 100644
index 0000000000..ef1f540f50
--- /dev/null
+++ b/src/pl/tcl/sql/pltcl_call.sql
@@ -0,0 +1,36 @@
+CREATE PROCEDURE test_proc1()
+LANGUAGE pltcl
+AS $$
+unset
+$$;
+
+CALL test_proc1();
+
+
+CREATE PROCEDURE test_proc2()
+LANGUAGE pltcl
+AS $$
+return 5
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE pltcl
+AS $$
+spi_exec "INSERT INTO test1 VALUES ($1)"
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE test1;
diff --git a/src/test/regress/expected/create_procedure.out b/src/test/regress/expected/create_procedure.out
new file mode 100644
index 0000000000..5538ef2f2b
--- /dev/null
+++ b/src/test/regress/expected/create_procedure.out
@@ -0,0 +1,92 @@
+CALL nonexistent(); -- error
+ERROR: function nonexistent() does not exist
+LINE 1: CALL nonexistent();
+ ^
+HINT: No function matches the given name and argument types. You might need to add explicit type casts.
+CALL random(); -- error
+ERROR: random() is not a procedure
+LINE 1: CALL random();
+ ^
+HINT: To call a function, use SELECT.
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+CREATE TABLE cp_test (a int, b text);
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+SELECT ptest1('x'); -- error
+ERROR: ptest1(unknown) is a procedure
+LINE 1: SELECT ptest1('x');
+ ^
+HINT: To call a procedure, use CALL.
+CALL ptest1('a'); -- ok
+\df ptest1
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+--------+------------------+---------------------+------
+ public | ptest1 | | x text | proc
+(1 row)
+
+SELECT * FROM cp_test ORDER BY a;
+ a | b
+---+---
+ 1 | a
+(1 row)
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+CALL ptest2();
+-- various error cases
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: invalid attribute in procedure definition
+LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT I...
+ ^
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: invalid attribute in procedure definition
+LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT I...
+ ^
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+ERROR: procedures cannot have OUT parameters
+ALTER PROCEDURE ptest1(text) STRICT;
+ERROR: invalid attribute in procedure definition
+LINE 1: ALTER PROCEDURE ptest1(text) STRICT;
+ ^
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ERROR: ptest1(text) is not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+ERROR: procedure nonexistent() does not exist
+DROP FUNCTION ptest1(text); -- error: not a function
+ERROR: ptest1(text) is not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+ERROR: testfunc1(integer) is not a procedure
+DROP PROCEDURE nonexistent();
+ERROR: procedure nonexistent() does not exist
+-- privileges
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+ERROR: permission denied for function ptest1
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+-- ROUTINE syntax
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+DROP ROUTINE testfunc1(int);
+-- cleanup
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+DROP TABLE cp_test;
+DROP USER regress_user1;
diff --git a/src/test/regress/expected/object_address.out b/src/test/regress/expected/object_address.out
index 1fdadbc9ef..bfd9d54c11 100644
--- a/src/test/regress/expected/object_address.out
+++ b/src/test/regress/expected/object_address.out
@@ -29,6 +29,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -88,7 +89,7 @@ BEGIN
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -171,6 +172,12 @@ WARNING: error for function,{addr_nsp,zwei},{}: function addr_nsp.zwei() does n
WARNING: error for function,{addr_nsp,zwei},{integer}: function addr_nsp.zwei(integer) does not exist
WARNING: error for function,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for function,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins},{}: procedure eins() does not exist
+WARNING: error for procedure,{eins},{integer}: procedure eins(integer) does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{}: procedure addr_nsp.zwei() does not exist
+WARNING: error for procedure,{addr_nsp,zwei},{integer}: procedure addr_nsp.zwei(integer) does not exist
+WARNING: error for procedure,{eins,zwei,drei},{}: cross-database references are not implemented: eins.zwei.drei
+WARNING: error for procedure,{eins,zwei,drei},{integer}: cross-database references are not implemented: eins.zwei.drei
WARNING: error for type,{eins},{}: type "eins" does not exist
WARNING: error for type,{eins},{integer}: type "eins" does not exist
WARNING: error for type,{addr_nsp,zwei},{}: name list length must be exactly 1
@@ -371,6 +378,7 @@ WITH objects (type, name, args) AS (VALUES
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
@@ -431,6 +439,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
type | addr_nsp | gendomain | addr_nsp.gendomain | t
function | pg_catalog | | pg_catalog.pg_identify_object(pg_catalog.oid,pg_catalog.oid,integer) | t
aggregate | addr_nsp | | addr_nsp.genaggr(integer) | t
+ procedure | addr_nsp | | addr_nsp.proc(integer) | t
sequence | addr_nsp | gentable_a_seq | addr_nsp.gentable_a_seq | t
table | addr_nsp | gentable | addr_nsp.gentable | t
table column | addr_nsp | gentable | addr_nsp.gentable.b | t
@@ -469,7 +478,7 @@ SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*,
subscription | | addr_sub | addr_sub | t
publication | | addr_pub | addr_pub | t
publication relation | | | gentable in publication addr_pub | t
-(46 rows)
+(47 rows)
---
--- Cleanup resources
@@ -480,6 +489,6 @@ NOTICE: drop cascades to 4 other objects
DROP PUBLICATION addr_pub;
DROP SUBSCRIPTION addr_sub;
DROP SCHEMA addr_nsp CASCADE;
-NOTICE: drop cascades to 12 other objects
+NOTICE: drop cascades to 13 other objects
DROP OWNED BY regress_addr_user;
DROP USER regress_addr_user;
diff --git a/src/test/regress/expected/plpgsql.out b/src/test/regress/expected/plpgsql.out
index bb3532676b..d6e5bc3353 100644
--- a/src/test/regress/expected/plpgsql.out
+++ b/src/test/regress/expected/plpgsql.out
@@ -6040,3 +6040,44 @@ END; $$ LANGUAGE plpgsql;
ERROR: "x" is not a scalar variable
LINE 3: GET DIAGNOSTICS x = ROW_COUNT;
^
+--
+-- Procedures
+--
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+CALL test_proc1();
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+CALL test_proc2();
+ERROR: cannot return a value from a procedure
+CONTEXT: PL/pgSQL function test_proc2() while casting return value to function's return type
+CREATE TABLE proc_test1 (a int);
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+CALL test_proc3(55);
+SELECT * FROM proc_test1;
+ a
+----
+ 55
+(1 row)
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+DROP TABLE proc_test1;
diff --git a/src/test/regress/expected/polymorphism.out b/src/test/regress/expected/polymorphism.out
index 91cfb743b6..66e35a6a5c 100644
--- a/src/test/regress/expected/polymorphism.out
+++ b/src/test/regress/expected/polymorphism.out
@@ -915,10 +915,10 @@ select dfunc();
-- verify it lists properly
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-----------------------------------------------------------+--------
- public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-----------------------------------------------------------+------
+ public | dfunc | integer | a integer DEFAULT 1, OUT sum integer, b integer DEFAULT 2 | func
(1 row)
drop function dfunc(int, int);
@@ -1083,10 +1083,10 @@ $$ select array_upper($1, 1) $$ language sql;
ERROR: cannot remove parameter defaults from existing function
HINT: Use DROP FUNCTION dfunc(integer[]) first.
\df dfunc
- List of functions
- Schema | Name | Result data type | Argument data types | Type
---------+-------+------------------+-------------------------------------------------+--------
- public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | normal
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+--------+-------+------------------+-------------------------------------------------+------
+ public | dfunc | integer | VARIADIC a integer[] DEFAULT ARRAY[]::integer[] | func
(1 row)
drop function dfunc(a variadic int[]);
diff --git a/src/test/regress/expected/privileges.out b/src/test/regress/expected/privileges.out
index 771971a095..e6994f0490 100644
--- a/src/test/regress/expected/privileges.out
+++ b/src/test/regress/expected/privileges.out
@@ -651,13 +651,25 @@ GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
WARNING: no privileges were granted for "sql"
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testproc1(int) AS 'select $1;' LANGUAGE sql;
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
+REVOKE ALL ON FUNCTION testproc1(int) FROM PUBLIC; -- fail, not a function
+ERROR: testproc1(integer) is not a function
+REVOKE ALL ON PROCEDURE testproc1(int) FROM PUBLIC;
+GRANT EXECUTE ON PROCEDURE testproc1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
ERROR: invalid privilege type USAGE for function
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
+ERROR: invalid privilege type USAGE for function
+GRANT USAGE ON PROCEDURE testproc1(int) TO regress_user3; -- semantic error
+ERROR: invalid privilege type USAGE for procedure
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
ERROR: function testfunc_nosuch(integer) does not exist
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON PROCEDURE testproc1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
LANGUAGE sql SECURITY DEFINER;
@@ -671,9 +683,20 @@ SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
ERROR: permission denied for language sql
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
+CALL testproc1(6); -- ok
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
ERROR: permission denied for function testfunc1
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
+ERROR: permission denied for function testagg1
+CALL testproc1(6); -- fail
+ERROR: permission denied for function testproc1
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
ERROR: permission denied for relation atest2
SELECT testfunc4(true); -- ok
@@ -689,8 +712,19 @@ SELECT testfunc1(5); -- ok
10
(1 row)
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+ testagg1
+----------
+ 6
+(1 row)
+
+CALL testproc1(6); -- ok
DROP FUNCTION testfunc1(int); -- fail
ERROR: must be owner of function testfunc1
+DROP AGGREGATE testagg1(int); -- fail
+ERROR: must be owner of function testagg1
+DROP PROCEDURE testproc1(int); -- fail
+ERROR: must be owner of function testproc1
\c -
DROP FUNCTION testfunc1(int); -- ok
-- restore to sanity
@@ -1537,22 +1571,54 @@ SELECT has_schema_privilege('regress_user2', 'testns5', 'CREATE'); -- no
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
has_function_privilege
------------------------
f
(1 row)
-ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- no
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON ROUTINES to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+DROP PROCEDURE testns.bar();
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- yes (counts as function here)
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
+DROP PROCEDURE testns.bar();
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
CREATE DOMAIN testns.testdomain1 AS int;
SELECT has_type_privilege('regress_user2', 'testns.testdomain1', 'USAGE'); -- no
@@ -1631,12 +1697,26 @@ SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
(1 row)
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.testproc(int) AS 'select 3' LANGUAGE sql;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
has_function_privilege
------------------------
t
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true by default
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
has_function_privilege
@@ -1644,9 +1724,47 @@ SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'
f
(1 row)
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- still true, not a function
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+REVOKE ALL ON ALL PROCEDURES IN SCHEMA testns FROM PUBLIC;
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- now false
+ has_function_privilege
+------------------------
+ f
+(1 row)
+
+GRANT ALL ON ALL ROUTINES IN SCHEMA testns TO PUBLIC;
+SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true
+ has_function_privilege
+------------------------
+ t
+(1 row)
+
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
-NOTICE: drop cascades to 3 other objects
+NOTICE: drop cascades to 5 other objects
\set VERBOSITY default
-- Change owner of the schema & and rename of new schema owner
\c -
@@ -1729,8 +1847,10 @@ drop table dep_priv_test;
-- clean up
\c
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
+DROP PROCEDURE testproc1(int);
DROP VIEW atestv0;
DROP VIEW atestv1;
DROP VIEW atestv2;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 1a3ac4c1f9..22f79b1410 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -53,7 +53,7 @@ test: copy copyselect copydml
# ----------
# More groups of parallel tests
# ----------
-test: create_misc create_operator
+test: create_misc create_operator create_procedure
# These depend on the above two
test: create_index create_view
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index a205e5d05c..1dc1ce73ea 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -63,6 +63,7 @@ test: copyselect
test: copydml
test: create_misc
test: create_operator
+test: create_procedure
test: create_index
test: create_view
test: create_aggregate
diff --git a/src/test/regress/sql/create_procedure.sql b/src/test/regress/sql/create_procedure.sql
new file mode 100644
index 0000000000..f09ba2ad30
--- /dev/null
+++ b/src/test/regress/sql/create_procedure.sql
@@ -0,0 +1,79 @@
+CALL nonexistent(); -- error
+CALL random(); -- error
+
+CREATE FUNCTION testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$;
+
+CREATE TABLE cp_test (a int, b text);
+
+CREATE PROCEDURE ptest1(x text)
+LANGUAGE SQL
+AS $$
+INSERT INTO cp_test VALUES (1, x);
+$$;
+
+SELECT ptest1('x'); -- error
+CALL ptest1('a'); -- ok
+
+\df ptest1
+
+SELECT * FROM cp_test ORDER BY a;
+
+
+CREATE PROCEDURE ptest2()
+LANGUAGE SQL
+AS $$
+SELECT 5;
+$$;
+
+CALL ptest2();
+
+
+-- various error cases
+
+CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+CREATE PROCEDURE ptestx(OUT a int) LANGUAGE SQL AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
+
+ALTER PROCEDURE ptest1(text) STRICT;
+ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
+ALTER PROCEDURE testfunc1(int) VOLATILE; -- error: not a procedure
+ALTER PROCEDURE nonexistent() VOLATILE;
+
+DROP FUNCTION ptest1(text); -- error: not a function
+DROP PROCEDURE testfunc1(int); -- error: not a procedure
+DROP PROCEDURE nonexistent();
+
+
+-- privileges
+
+CREATE USER regress_user1;
+GRANT INSERT ON cp_test TO regress_user1;
+REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- error
+RESET ROLE;
+GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_user1;
+SET ROLE regress_user1;
+CALL ptest1('a'); -- ok
+RESET ROLE;
+
+
+-- ROUTINE syntax
+
+ALTER ROUTINE testfunc1(int) RENAME TO testfunc1a;
+ALTER ROUTINE testfunc1a RENAME TO testfunc1;
+
+ALTER ROUTINE ptest1(text) RENAME TO ptest1a;
+ALTER ROUTINE ptest1a RENAME TO ptest1;
+
+DROP ROUTINE testfunc1(int);
+
+
+-- cleanup
+
+DROP PROCEDURE ptest1;
+DROP PROCEDURE ptest2;
+
+DROP TABLE cp_test;
+
+DROP USER regress_user1;
diff --git a/src/test/regress/sql/object_address.sql b/src/test/regress/sql/object_address.sql
index 63821b8008..55faa71edf 100644
--- a/src/test/regress/sql/object_address.sql
+++ b/src/test/regress/sql/object_address.sql
@@ -32,6 +32,7 @@ CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0);
CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$;
CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig();
CREATE POLICY genpol ON addr_nsp.gentable;
+CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$;
CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw;
CREATE USER MAPPING FOR regress_addr_user SERVER "integer";
ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user;
@@ -81,7 +82,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('table'), ('index'), ('sequence'), ('view'),
('materialized view'), ('foreign table'),
('table column'), ('foreign table column'),
- ('aggregate'), ('function'), ('type'), ('cast'),
+ ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'),
('table constraint'), ('domain constraint'), ('conversion'), ('default value'),
('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'),
('text search parser'), ('text search dictionary'),
@@ -147,6 +148,7 @@ CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable;
('foreign table column', '{addr_nsp, genftable, a}', '{}'),
('aggregate', '{addr_nsp, genaggr}', '{int4}'),
('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'),
+ ('procedure', '{addr_nsp, proc}', '{int4}'),
('type', '{pg_catalog._int4}', '{}'),
('type', '{addr_nsp.gendomain}', '{}'),
('type', '{addr_nsp.gencomptype}', '{}'),
diff --git a/src/test/regress/sql/plpgsql.sql b/src/test/regress/sql/plpgsql.sql
index 6620ea6172..1c355132b7 100644
--- a/src/test/regress/sql/plpgsql.sql
+++ b/src/test/regress/sql/plpgsql.sql
@@ -4820,3 +4820,52 @@ CREATE FUNCTION fx(x WSlot) RETURNS void AS $$
GET DIAGNOSTICS x = ROW_COUNT;
RETURN;
END; $$ LANGUAGE plpgsql;
+
+
+--
+-- Procedures
+--
+
+CREATE PROCEDURE test_proc1()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ NULL;
+END;
+$$;
+
+CALL test_proc1();
+
+
+-- error: can't return non-NULL
+CREATE PROCEDURE test_proc2()
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RETURN 5;
+END;
+$$;
+
+CALL test_proc2();
+
+
+CREATE TABLE proc_test1 (a int);
+
+CREATE PROCEDURE test_proc3(x int)
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO proc_test1 VALUES (x);
+END;
+$$;
+
+CALL test_proc3(55);
+
+SELECT * FROM proc_test1;
+
+
+DROP PROCEDURE test_proc1;
+DROP PROCEDURE test_proc2;
+DROP PROCEDURE test_proc3;
+
+DROP TABLE proc_test1;
diff --git a/src/test/regress/sql/privileges.sql b/src/test/regress/sql/privileges.sql
index a900ba2f84..ea8dd028cd 100644
--- a/src/test/regress/sql/privileges.sql
+++ b/src/test/regress/sql/privileges.sql
@@ -442,12 +442,21 @@ CREATE TABLE atestc (fz int) INHERITS (atestp1, atestp2);
GRANT USAGE ON LANGUAGE sql TO regress_user2; -- fail
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
-
-REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
-GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regress_user2;
+CREATE AGGREGATE testagg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testproc1(int) AS 'select $1;' LANGUAGE sql;
+
+REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int), testagg1(int) TO regress_user2;
+REVOKE ALL ON FUNCTION testproc1(int) FROM PUBLIC; -- fail, not a function
+REVOKE ALL ON PROCEDURE testproc1(int) FROM PUBLIC;
+GRANT EXECUTE ON PROCEDURE testproc1(int) TO regress_user2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regress_user3; -- semantic error
+GRANT USAGE ON FUNCTION testagg1(int) TO regress_user3; -- semantic error
+GRANT USAGE ON PROCEDURE testproc1(int) TO regress_user3; -- semantic error
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regress_user4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON FUNCTION testagg1(int) TO regress_user4;
+GRANT ALL PRIVILEGES ON PROCEDURE testproc1(int) TO regress_user4;
CREATE FUNCTION testfunc4(boolean) RETURNS text
AS 'select col1 from atest2 where col2 = $1;'
@@ -457,16 +466,24 @@ CREATE FUNCTION testfunc4(boolean) RETURNS text
SET SESSION AUTHORIZATION regress_user2;
SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+CALL testproc1(6); -- ok
SET SESSION AUTHORIZATION regress_user3;
SELECT testfunc1(5); -- fail
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail
+CALL testproc1(6); -- fail
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
SELECT testfunc4(true); -- ok
SET SESSION AUTHORIZATION regress_user4;
SELECT testfunc1(5); -- ok
+SELECT testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok
+CALL testproc1(6); -- ok
DROP FUNCTION testfunc1(int); -- fail
+DROP AGGREGATE testagg1(int); -- fail
+DROP PROCEDURE testproc1(int); -- fail
\c -
@@ -931,17 +948,29 @@ CREATE SCHEMA testns5;
SET ROLE regress_user1;
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- no
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- no
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- no
-ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON FUNCTIONS to public;
+ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON ROUTINES to public;
DROP FUNCTION testns.foo();
CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql;
+DROP AGGREGATE testns.agg1(int);
+CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4);
+DROP PROCEDURE testns.bar();
+CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql;
SELECT has_function_privilege('regress_user2', 'testns.foo()', 'EXECUTE'); -- yes
+SELECT has_function_privilege('regress_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes
+SELECT has_function_privilege('regress_user2', 'testns.bar()', 'EXECUTE'); -- yes (counts as function here)
DROP FUNCTION testns.foo();
+DROP AGGREGATE testns.agg1(int);
+DROP PROCEDURE testns.bar();
ALTER DEFAULT PRIVILEGES FOR ROLE regress_user1 REVOKE USAGE ON TYPES FROM public;
@@ -995,12 +1024,28 @@ CREATE TABLE testns.t2 (f1 int);
SELECT has_table_privilege('regress_user1', 'testns.t2', 'SELECT'); -- false
CREATE FUNCTION testns.testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql;
+CREATE AGGREGATE testns.testagg(int) (sfunc = int4pl, stype = int4);
+CREATE PROCEDURE testns.testproc(int) AS 'select 3' LANGUAGE sql;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true by default
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true by default
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true by default
REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC;
SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- false
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- false
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- still true, not a function
+
+REVOKE ALL ON ALL PROCEDURES IN SCHEMA testns FROM PUBLIC;
+
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- now false
+
+GRANT ALL ON ALL ROUTINES IN SCHEMA testns TO PUBLIC;
+
+SELECT has_function_privilege('regress_user1', 'testns.testfunc(int)', 'EXECUTE'); -- true
+SELECT has_function_privilege('regress_user1', 'testns.testagg(int)', 'EXECUTE'); -- true
+SELECT has_function_privilege('regress_user1', 'testns.testproc(int)', 'EXECUTE'); -- true
\set VERBOSITY terse \\ -- suppress cascade details
DROP SCHEMA testns CASCADE;
@@ -1064,8 +1109,10 @@ CREATE SCHEMA testns;
drop sequence x_seq;
+DROP AGGREGATE testagg1(int);
DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);
+DROP PROCEDURE testproc1(int);
DROP VIEW atestv0;
DROP VIEW atestv1;
base-commit: 487a0c1518af2f3ae2d05b7fd23d636d687f28f3
--
2.15.0
On 29 November 2017 at 02:03, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
Here is a new patch that addresses the previous review comments.
If there are no new comments, I think this might be ready to go.
Is ERRCODE_INVALID_FUNCTION_DEFINITION still appropriate?
Other than that, looks ready to go.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/28/17 10:34, Simon Riggs wrote:
Is ERRCODE_INVALID_FUNCTION_DEFINITION still appropriate?
Well, maybe not, but changing that is likely more trouble than it's worth.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/28/2017 10:03 AM, Peter Eisentraut wrote:
Here is a new patch that addresses the previous review comments.
If there are no new comments, I think this might be ready to go.
Looks good to me. Marking ready for committer.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 11/29/17 14:17, Andrew Dunstan wrote:
On 11/28/2017 10:03 AM, Peter Eisentraut wrote:
Here is a new patch that addresses the previous review comments.
If there are no new comments, I think this might be ready to go.
Looks good to me. Marking ready for committer.
committed
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On Fri, Dec 1, 2017 at 7:48 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
On 11/29/17 14:17, Andrew Dunstan wrote:
On 11/28/2017 10:03 AM, Peter Eisentraut wrote:
Here is a new patch that addresses the previous review comments.
If there are no new comments, I think this might be ready to go.
Looks good to me. Marking ready for committer.
committed
postgres=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
public | bar | integer | i integer | func
public | foo | | i integer | proc
(2 rows)
Should this now be called a "List of routines"?
--
Thomas Munro
http://www.enterprisedb.com
On 11/30/17 15:50, Thomas Munro wrote:
postgres=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
public | bar | integer | i integer | func
public | foo | | i integer | proc
(2 rows)Should this now be called a "List of routines"?
Maybe, but I hesitate to go around and change all mentions of "function"
like that. That might just confuse people.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On Fri, Dec 1, 2017 at 9:31 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
On 11/30/17 15:50, Thomas Munro wrote:
postgres=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
public | bar | integer | i integer | func
public | foo | | i integer | proc
(2 rows)Should this now be called a "List of routines"?
Maybe, but I hesitate to go around and change all mentions of "function"
like that. That might just confuse people.
Yeah, this is not unlike the problems we have deciding whether to say
"relation" or "table". It's a problem that comes when most foos are
bars but there are multiple types of exotic foo that are not bars.
That's pretty much the case here -- most functions are probably just
functions, but a few might be procedures or aggregates. I think
leaving this and similar cases as "functions" is fine. I wonder
whether it was really necessary for the SQL standards committee (or
Oracle) to invent both procedures and functions to represent very
similar things, but they did.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
On 2 December 2017 at 01:31, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
On 11/30/17 15:50, Thomas Munro wrote:
postgres=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
public | bar | integer | i integer | func
public | foo | | i integer | proc
(2 rows)Should this now be called a "List of routines"?
Maybe, but I hesitate to go around and change all mentions of "function"
like that. That might just confuse people.
Agreed
\dfn shows functions only
so we might want to consider having
\df say "List of functions and procedures"
\dfn say "List of functions"
and a new option to list procedures only
\dfp say "List of procedures"
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On Wed, Nov 8, 2017 at 9:21 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
Why not use VOIDOID for the prorettype value?
We need a way to distinguish functions that are callable by SELECT and
procedures that are callable by CALL.
I agree that we need this, but using prorettype = InvalidOid to do it
might not be the best way, because it only works for procedures that
don't return anything. If a procedure could return, say, an integer,
then it would fail, because we have two ways to say that something in
pg_proc returns nothing (InvalidOid, VOIDOID) but we have only one way
to say that it returns an integer (INT4OID). Similarly, we'd have a
problem if we ever tried to use procedures for handling triggers or
(perhaps more likely) event triggers, since those special kinds of
functions also signal their purpose via the return type - which may
also not have been such a hot idea, but at least in those cases the
idea of returning any sort of real result is more or less known to be
nonsensical.
Anyway, I think it would be better to invent an explicit way to
represent whether something is a procedure rather than relying on
overloading prorettype to tell us.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
Robert Haas <robertmhaas@gmail.com> writes:
I agree that we need this, but using prorettype = InvalidOid to do it
might not be the best way, because it only works for procedures that
don't return anything. If a procedure could return, say, an integer,
Good point, because that is possible in some other systems, and so
somebody is going to ask for it at some point.
Anyway, I think it would be better to invent an explicit way to
represent whether something is a procedure rather than relying on
overloading prorettype to tell us.
+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.
PS: I still strongly disagree with allowing prorettype to be zero.
regards, tom lane
2018-01-02 17:47 GMT+01:00 Tom Lane <tgl@sss.pgh.pa.us>:
Robert Haas <robertmhaas@gmail.com> writes:
I agree that we need this, but using prorettype = InvalidOid to do it
might not be the best way, because it only works for procedures that
don't return anything. If a procedure could return, say, an integer,Good point, because that is possible in some other systems, and so
somebody is going to ask for it at some point.Anyway, I think it would be better to invent an explicit way to
represent whether something is a procedure rather than relying on
overloading prorettype to tell us.+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.
+1
Pavel
Show quoted text
PS: I still strongly disagree with allowing prorettype to be zero.
regards, tom lane
On Tue, Jan 2, 2018 at 11:47 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
Anyway, I think it would be better to invent an explicit way to
represent whether something is a procedure rather than relying on
overloading prorettype to tell us.+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.
Assuming that we're confident that "procedure" is mutually exclusive
with "aggregate" and "window function", that seems like the right way
to go. And I think that's probably the case, both because we're
deciding not to let procedures be called from SELECT statements
(though Oracle apparently does) and because we've chosen syntax that
suggests distinctness: CREATE AGGREGATE, CREATE FUNCTION, CREATE
PROCEDURE. Window functions are less distinct from the others, since
they go through CREATE FUNCTION, but it still seems unlikely that we'd
ever want to try to support a "window procedure".
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
On 01/02/2018 01:45 PM, Robert Haas wrote:
On Tue, Jan 2, 2018 at 11:47 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
Anyway, I think it would be better to invent an explicit way to
represent whether something is a procedure rather than relying on
overloading prorettype to tell us.+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.Assuming that we're confident that "procedure" is mutually exclusive
with "aggregate" and "window function", that seems like the right way
to go. And I think that's probably the case, both because we're
deciding not to let procedures be called from SELECT statements
(though Oracle apparently does) and because we've chosen syntax that
suggests distinctness: CREATE AGGREGATE, CREATE FUNCTION, CREATE
PROCEDURE. Window functions are less distinct from the others, since
they go through CREATE FUNCTION, but it still seems unlikely that we'd
ever want to try to support a "window procedure".
Yeah, but these things don't feel like they belong in the same category.
The fact that we have to ask this question is a symptom of that. A
boolean feels more natural to me here, although I acknowledge it will
result in a tiny amount of catalog bloat. Tom's point about client-side
code is also valid. I don't feel very strongly about it, though.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On Tue, Jan 2, 2018 at 1:57 PM, Andrew Dunstan
<andrew.dunstan@2ndquadrant.com> wrote:
Yeah, but these things don't feel like they belong in the same category.
The fact that we have to ask this question is a symptom of that.
Well, that's got to be asked about any representation we choose - that
question is the motivation for not liking the use of prorettype for
this purpose, so it's only fair to ask whether any alternative has the
same problem.
A
boolean feels more natural to me here, although I acknowledge it will
result in a tiny amount of catalog bloat. Tom's point about client-side
code is also valid. I don't feel very strongly about it, though.
I think the catalog bloat is too minor to care about, but if these
things really are mutually exclusive, it's more natural to have them
use a single flag character rather than a series of Booleans.
Otherwise, it may be unclear to the casual observer (or hacker) that
at most one of the Booleans can be true, possibly leading to user
confusion (or bugs).
It's pretty well impossible to introduce new features without
occasionally changing the catalog representation. We had several
people grumble when I replaced relistemp with relpersistence, and we
(rightly, IMHO) told those people to suck it up and deal. I don't
think we should react any differently here. I recognize that it's a
pain, but it's not that much of a pain, and it may even be helpful to
tool authors who actually need to handle procedures differently than
functions, which is probably a lot of them. pgAdmin for example seems
like it will certainly need to care.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
On 01/02/2018 02:14 PM, Robert Haas wrote:
On Tue, Jan 2, 2018 at 1:57 PM, Andrew Dunstan
<andrew.dunstan@2ndquadrant.com> wrote:Yeah, but these things don't feel like they belong in the same category.
The fact that we have to ask this question is a symptom of that.Well, that's got to be asked about any representation we choose - that
question is the motivation for not liking the use of prorettype for
this purpose, so it's only fair to ask whether any alternative has the
same problem.
I think there's broad agreement about not liking use of prorettype for
this purpose.
A
boolean feels more natural to me here, although I acknowledge it will
result in a tiny amount of catalog bloat. Tom's point about client-side
code is also valid. I don't feel very strongly about it, though.I think the catalog bloat is too minor to care about, but if these
things really are mutually exclusive, it's more natural to have them
use a single flag character rather than a series of Booleans.
Otherwise, it may be unclear to the casual observer (or hacker) that
at most one of the Booleans can be true, possibly leading to user
confusion (or bugs).
Fair point. I don't recall if we discussed anything like this when
window functions were introduced.
It's pretty well impossible to introduce new features without
occasionally changing the catalog representation. We had several
people grumble when I replaced relistemp with relpersistence, and we
(rightly, IMHO) told those people to suck it up and deal. I don't
think we should react any differently here. I recognize that it's a
pain, but it's not that much of a pain, and it may even be helpful to
tool authors who actually need to handle procedures differently than
functions, which is probably a lot of them. pgAdmin for example seems
like it will certainly need to care.
I agree.
cheers
andrew
--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 1/2/18 11:47, Tom Lane wrote:
+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.
prokind sounds good. I'll look into that.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 1/2/18 17:47, Peter Eisentraut wrote:
On 1/2/18 11:47, Tom Lane wrote:
+1 --- seems like a new bool column is the thing. Or may we should merge
"proisprocedure" with proisagg and proiswindow into an enum prokind?
Although that would break some existing client-side code.prokind sounds good. I'll look into that.
Here is a patch set for that. (I just kept the pg_proc.h changes
separate for easier viewing.) It's not quite complete; some frontend
code still needs adjusting; but the idea is clear.
I think this would be a pretty good change. It doesn't appear to save a
ton amount of code, although a couple of cases where inconsistent
settings of proisagg and proiswindow had to be handed could be removed.
Because window functions are a separate kind in pg_proc but not in the
object address system, inconsistencies will remain in the system, but I
guess that's just the way it is.
--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Attachments:
0001-Add-prokind-column-replacing-proisagg-and-proiswindo.patchtext/plain; charset=UTF-8; name=0001-Add-prokind-column-replacing-proisagg-and-proiswindo.patch; x-mac-creator=0; x-mac-type=0Download
From 27dc62f9ec430f0ad6949e6d18c3c7a69f537444 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Wed, 3 Jan 2018 18:21:20 -0500
Subject: [PATCH 1/2] Add prokind column, replacing proisagg and proiswindow
---
doc/src/sgml/catalogs.sgml | 23 +++++------
src/backend/catalog/objectaddress.c | 6 +--
src/backend/catalog/pg_aggregate.c | 3 +-
src/backend/catalog/pg_proc.c | 36 +++--------------
src/backend/catalog/system_views.sql | 8 ++--
src/backend/commands/functioncmds.c | 29 +++++---------
src/backend/commands/proclang.c | 9 ++---
src/backend/commands/typecmds.c | 3 +-
src/backend/parser/parse_coerce.c | 3 +-
src/backend/parser/parse_func.c | 27 +++++++++----
src/backend/utils/adt/ruleutils.c | 6 +--
src/backend/utils/cache/lsyscache.c | 4 +-
src/bin/pg_dump/t/002_pg_dump.pl | 6 +--
src/bin/psql/describe.c | 60 +++++++++++++++++++++++------
src/bin/psql/tab-complete.c | 2 +-
src/include/catalog/pg_class.h | 2 +-
src/include/catalog/pg_proc.h | 54 ++++++++++++++------------
src/include/catalog/pg_proc_fn.h | 3 +-
src/test/regress/expected/alter_generic.out | 2 +-
src/test/regress/expected/opr_sanity.out | 36 ++++++++---------
src/test/regress/expected/rules.out | 8 ++--
src/test/regress/sql/alter_generic.sql | 2 +-
src/test/regress/sql/opr_sanity.sql | 36 ++++++++---------
23 files changed, 191 insertions(+), 177 deletions(-)
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index 3f02202caf..2a50dec06d 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -5039,15 +5039,17 @@ <title><structname>pg_proc</structname></title>
</indexterm>
<para>
- The catalog <structname>pg_proc</structname> stores information about functions (or procedures).
+ The catalog <structname>pg_proc</structname> stores information about
+ functions, procedures, aggregate functions, and window functions
+ (collectively also known as routines).
See <xref linkend="sql-createfunction"/>
and <xref linkend="xfunc"/> for more information.
</para>
<para>
- The table contains data for aggregate functions as well as plain functions.
- If <structfield>proisagg</structfield> is true, there should be a matching
- row in <structfield>pg_aggregate</structfield>.
+ If <structfield>prokind</structfield> indicates that the entry is for an
+ aggregate function, there should be a matching row in
+ <structfield>pg_aggregate</structfield>.
</para>
<table>
@@ -5134,17 +5136,12 @@ <title><structname>pg_proc</structname> Columns</title>
</row>
<row>
- <entry><structfield>proisagg</structfield></entry>
+ <entry><structfield>prokind</structfield></entry>
<entry><type>bool</type></entry>
<entry></entry>
- <entry>Function is an aggregate function</entry>
- </row>
-
- <row>
- <entry><structfield>proiswindow</structfield></entry>
- <entry><type>bool</type></entry>
- <entry></entry>
- <entry>Function is a window function</entry>
+ <entry><literal>f</literal> for a normal function, <literal>p</literal>
+ for a procedure, <literal>a</literal> for an aggregate function,
+ <literal>w</literal> for a window function</entry>
</row>
<row>
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index bc999ca3c4..4397ef932d 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -4031,11 +4031,11 @@ getProcedureTypeDescription(StringInfo buffer, Oid procid)
elog(ERROR, "cache lookup failed for procedure %u", procid);
procForm = (Form_pg_proc) GETSTRUCT(procTup);
- if (procForm->proisagg)
+ if (procForm->prokind == PROKIND_AGGREGATE)
appendStringInfoString(buffer, "aggregate");
- else if (procForm->prorettype == InvalidOid)
+ else if (procForm->prokind == PROKIND_PROCEDURE)
appendStringInfoString(buffer, "procedure");
- else
+ else /* function or window function */
appendStringInfoString(buffer, "function");
ReleaseSysCache(procTup);
diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c
index e801c1ed5c..0080ed4d6d 100644
--- a/src/backend/catalog/pg_aggregate.c
+++ b/src/backend/catalog/pg_aggregate.c
@@ -616,8 +616,7 @@ AggregateCreate(const char *aggName,
InvalidOid, /* no validator */
"aggregate_dummy", /* placeholder proc */
NULL, /* probin */
- true, /* isAgg */
- false, /* isWindowFunc */
+ PROKIND_AGGREGATE,
false, /* security invoker (currently not
* definable for agg) */
false, /* isLeakProof */
diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c
index 39d5172e97..a5c8bf1b3f 100644
--- a/src/backend/catalog/pg_proc.c
+++ b/src/backend/catalog/pg_proc.c
@@ -74,8 +74,7 @@ ProcedureCreate(const char *procedureName,
Oid languageValidator,
const char *prosrc,
const char *probin,
- bool isAgg,
- bool isWindowFunc,
+ char prokind,
bool security_definer,
bool isLeakProof,
bool isStrict,
@@ -335,8 +334,7 @@ ProcedureCreate(const char *procedureName,
values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
values[Anum_pg_proc_protransform - 1] = ObjectIdGetDatum(InvalidOid);
- values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
- values[Anum_pg_proc_proiswindow - 1] = BoolGetDatum(isWindowFunc);
+ values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
@@ -536,32 +534,10 @@ ProcedureCreate(const char *procedureName,
}
/* Can't change aggregate or window-function status, either */
- if (oldproc->proisagg != isAgg)
- {
- if (oldproc->proisagg)
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function \"%s\" is an aggregate function",
- procedureName)));
- else
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function \"%s\" is not an aggregate function",
- procedureName)));
- }
- if (oldproc->proiswindow != isWindowFunc)
- {
- if (oldproc->proiswindow)
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function \"%s\" is a window function",
- procedureName)));
- else
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("function \"%s\" is not a window function",
- procedureName)));
- }
+ if (oldproc->prokind != prokind)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("cannot change routine type")));
/*
* Do not change existing ownership or permissions, either. Note
diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index 5652e9ee6d..5e6e8a64f6 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -332,9 +332,11 @@ CREATE VIEW pg_seclabels AS
UNION ALL
SELECT
l.objoid, l.classoid, l.objsubid,
- CASE WHEN pro.proisagg = true THEN 'aggregate'::text
- WHEN pro.proisagg = false THEN 'function'::text
- END AS objtype,
+ CASE pro.prokind
+ WHEN 'a' THEN 'aggregate'::text
+ WHEN 'f' THEN 'function'::text
+ WHEN 'p' THEN 'procedure'::text
+ WHEN 'w' THEN 'window'::text END AS objtype,
pro.pronamespace AS objnamespace,
CASE WHEN pg_function_is_visible(pro.oid)
THEN quote_ident(pro.proname)
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 12ab33f418..9d4036da8d 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -1151,8 +1151,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
languageValidator,
prosrc_str, /* converted to text later */
probin_str, /* converted to text later */
- false, /* not an aggregate */
- isWindowFunc,
+ stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
security,
isLeakProof,
isStrict,
@@ -1180,7 +1179,7 @@ RemoveFunctionById(Oid funcOid)
{
Relation relation;
HeapTuple tup;
- bool isagg;
+ char prokind;
/*
* Delete the pg_proc tuple.
@@ -1191,7 +1190,7 @@ RemoveFunctionById(Oid funcOid)
if (!HeapTupleIsValid(tup)) /* should not happen */
elog(ERROR, "cache lookup failed for function %u", funcOid);
- isagg = ((Form_pg_proc) GETSTRUCT(tup))->proisagg;
+ prokind = ((Form_pg_proc) GETSTRUCT(tup))->prokind;
CatalogTupleDelete(relation, &tup->t_self);
@@ -1202,7 +1201,7 @@ RemoveFunctionById(Oid funcOid)
/*
* If there's a pg_aggregate tuple, delete that too.
*/
- if (isagg)
+ if (prokind == PROKIND_AGGREGATE)
{
relation = heap_open(AggregateRelationId, RowExclusiveLock);
@@ -1257,13 +1256,13 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(stmt->func->objname));
- if (procForm->proisagg)
+ if (procForm->prokind == PROKIND_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function",
NameListToString(stmt->func->objname))));
- is_procedure = (procForm->prorettype == InvalidOid);
+ is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
/* Examine requested actions. */
foreach(l, stmt->actions)
@@ -1579,14 +1578,10 @@ CreateCast(CreateCastStmt *stmt)
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("cast function must not be volatile")));
#endif
- if (procstruct->proisagg)
+ if (procstruct->prokind != PROKIND_FUNCTION)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
- errmsg("cast function must not be an aggregate function")));
- if (procstruct->proiswindow)
- ereport(ERROR,
- (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
- errmsg("cast function must not be a window function")));
+ errmsg("cast function must be a normal function")));
if (procstruct->proretset)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
@@ -1831,14 +1826,10 @@ check_transform_function(Form_pg_proc procstruct)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("transform function must not be volatile")));
- if (procstruct->proisagg)
- ereport(ERROR,
- (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
- errmsg("transform function must not be an aggregate function")));
- if (procstruct->proiswindow)
+ if (procstruct->prokind != PROKIND_FUNCTION)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
- errmsg("transform function must not be a window function")));
+ errmsg("transform function must be a normal function")));
if (procstruct->proretset)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
diff --git a/src/backend/commands/proclang.c b/src/backend/commands/proclang.c
index 9783a162d7..3ee3c4fdea 100644
--- a/src/backend/commands/proclang.c
+++ b/src/backend/commands/proclang.c
@@ -129,8 +129,7 @@ CreateProceduralLanguage(CreatePLangStmt *stmt)
F_FMGR_C_VALIDATOR,
pltemplate->tmplhandler,
pltemplate->tmpllibrary,
- false, /* isAgg */
- false, /* isWindowFunc */
+ PROKIND_FUNCTION,
false, /* security_definer */
false, /* isLeakProof */
false, /* isStrict */
@@ -169,8 +168,7 @@ CreateProceduralLanguage(CreatePLangStmt *stmt)
F_FMGR_C_VALIDATOR,
pltemplate->tmplinline,
pltemplate->tmpllibrary,
- false, /* isAgg */
- false, /* isWindowFunc */
+ PROKIND_FUNCTION,
false, /* security_definer */
false, /* isLeakProof */
true, /* isStrict */
@@ -212,8 +210,7 @@ CreateProceduralLanguage(CreatePLangStmt *stmt)
F_FMGR_C_VALIDATOR,
pltemplate->tmplvalidator,
pltemplate->tmpllibrary,
- false, /* isAgg */
- false, /* isWindowFunc */
+ PROKIND_FUNCTION,
false, /* security_definer */
false, /* isLeakProof */
true, /* isStrict */
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index a40b3cf752..b368f15d85 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -1672,8 +1672,7 @@ makeRangeConstructors(const char *name, Oid namespace,
F_FMGR_INTERNAL_VALIDATOR, /* language validator */
prosrc[i], /* prosrc */
NULL, /* probin */
- false, /* isAgg */
- false, /* isWindowFunc */
+ PROKIND_FUNCTION,
false, /* security_definer */
false, /* leakproof */
false, /* isStrict */
diff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c
index 085aa8766c..665d3327a0 100644
--- a/src/backend/parser/parse_coerce.c
+++ b/src/backend/parser/parse_coerce.c
@@ -834,8 +834,7 @@ build_coercion_expression(Node *node,
*/
/* Assert(targetTypeId == procstruct->prorettype); */
Assert(!procstruct->proretset);
- Assert(!procstruct->proisagg);
- Assert(!procstruct->proiswindow);
+ Assert(procstruct->prokind == PROKIND_FUNCTION);
nargs = procstruct->pronargs;
Assert(nargs >= 1 && nargs <= 3);
/* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index ffae0f3cf3..e120c0cd84 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -1614,14 +1614,25 @@ func_get_detail(List *funcname,
*argdefaults = defaults;
}
}
- if (pform->proisagg)
- result = FUNCDETAIL_AGGREGATE;
- else if (pform->proiswindow)
- result = FUNCDETAIL_WINDOWFUNC;
- else if (pform->prorettype == InvalidOid)
- result = FUNCDETAIL_PROCEDURE;
- else
- result = FUNCDETAIL_NORMAL;
+
+ switch (pform->prokind)
+ {
+ case PROKIND_AGGREGATE:
+ result = FUNCDETAIL_AGGREGATE;
+ break;
+ case PROKIND_FUNCTION:
+ result = FUNCDETAIL_NORMAL;
+ break;
+ case PROKIND_PROCEDURE:
+ result = FUNCDETAIL_PROCEDURE;
+ break;
+ case PROKIND_WINDOW:
+ result = FUNCDETAIL_WINDOWFUNC;
+ break;
+ default:
+ elog(ERROR, "unrecognized prokind: %c", pform->prokind);
+ }
+
ReleaseSysCache(ftup);
return result;
}
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 9cdbb06add..51acd44517 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -2464,7 +2464,7 @@ pg_get_functiondef(PG_FUNCTION_ARGS)
proc = (Form_pg_proc) GETSTRUCT(proctup);
name = NameStr(proc->proname);
- if (proc->proisagg)
+ if (proc->prokind == PROKIND_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function", name)));
@@ -2488,7 +2488,7 @@ pg_get_functiondef(PG_FUNCTION_ARGS)
/* Emit some miscellaneous options on one line */
oldlen = buf.len;
- if (proc->proiswindow)
+ if (proc->prokind == PROKIND_WINDOW)
appendStringInfoString(&buf, " WINDOW");
switch (proc->provolatile)
{
@@ -2791,7 +2791,7 @@ print_function_arguments(StringInfo buf, HeapTuple proctup,
}
/* Check for special treatment of ordered-set aggregates */
- if (proc->proisagg)
+ if (proc->prokind == PROKIND_AGGREGATE)
{
HeapTuple aggtup;
Form_pg_aggregate agg;
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index e8aa179347..d9463402f2 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -1616,7 +1616,7 @@ func_parallel(Oid funcid)
/*
* get_func_isagg
- * Given procedure id, return the function's proisagg field.
+ * Given procedure id, return whether the function is an aggregate.
*/
bool
get_func_isagg(Oid funcid)
@@ -1628,7 +1628,7 @@ get_func_isagg(Oid funcid)
if (!HeapTupleIsValid(tp))
elog(ERROR, "cache lookup failed for function %u", funcid);
- result = ((Form_pg_proc) GETSTRUCT(tp))->proisagg;
+ result = ((Form_pg_proc) GETSTRUCT(tp))->prokind == PROKIND_AGGREGATE;
ReleaseSysCache(tp);
return result;
}
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index 7cf9bdadb2..95f0b32eee 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -6083,8 +6083,7 @@
prorows,
provariadic,
protransform,
- proisagg,
- proiswindow,
+ prokind,
prosecdef,
proleakproof,
proisstrict,
@@ -6116,8 +6115,7 @@
\QGRANT SELECT(prorows) ON TABLE pg_proc TO PUBLIC;\E\n.*
\QGRANT SELECT(provariadic) ON TABLE pg_proc TO PUBLIC;\E\n.*
\QGRANT SELECT(protransform) ON TABLE pg_proc TO PUBLIC;\E\n.*
- \QGRANT SELECT(proisagg) ON TABLE pg_proc TO PUBLIC;\E\n.*
- \QGRANT SELECT(proiswindow) ON TABLE pg_proc TO PUBLIC;\E\n.*
+ \QGRANT SELECT(prokind) ON TABLE pg_proc TO PUBLIC;\E\n.*
\QGRANT SELECT(prosecdef) ON TABLE pg_proc TO PUBLIC;\E\n.*
\QGRANT SELECT(proleakproof) ON TABLE pg_proc TO PUBLIC;\E\n.*
\QGRANT SELECT(proisstrict) ON TABLE pg_proc TO PUBLIC;\E\n.*
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index f2e62946d8..102001baff 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -100,12 +100,20 @@ describeAggregates(const char *pattern, bool verbose, bool showSystem)
" pg_catalog.format_type(p.proargtypes[0], NULL) AS \"%s\",\n",
gettext_noop("Argument data types"));
- appendPQExpBuffer(&buf,
- " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
- "FROM pg_catalog.pg_proc p\n"
- " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
- "WHERE p.proisagg\n",
- gettext_noop("Description"));
+ if (pset.sversion >= 110000)
+ appendPQExpBuffer(&buf,
+ " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
+ "FROM pg_catalog.pg_proc p\n"
+ " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
+ "WHERE p.prokind = 'a'\n",
+ gettext_noop("Description"));
+ else
+ appendPQExpBuffer(&buf,
+ " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
+ "FROM pg_catalog.pg_proc p\n"
+ " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
+ "WHERE p.proisagg\n",
+ gettext_noop("Description"));
if (!showSystem && !pattern)
appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
@@ -346,7 +354,25 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
gettext_noop("Schema"),
gettext_noop("Name"));
- if (pset.sversion >= 80400)
+ if (pset.sversion >= 110000)
+ appendPQExpBuffer(&buf,
+ " pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
+ " pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
+ " CASE p.prokind\n"
+ " WHEN 'a' THEN '%s'\n"
+ " WHEN 'w' THEN '%s'\n"
+ " WHEN 'p' THEN '%s'\n"
+ " ELSE '%s'\n"
+ " END as \"%s\"",
+ gettext_noop("Result data type"),
+ gettext_noop("Argument data types"),
+ /* translator: "agg" is short for "aggregate" */
+ gettext_noop("agg"),
+ gettext_noop("window"),
+ gettext_noop("proc"),
+ gettext_noop("func"),
+ gettext_noop("Type"));
+ else if (pset.sversion >= 80400)
appendPQExpBuffer(&buf,
" pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
" pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
@@ -494,7 +520,10 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
appendPQExpBufferStr(&buf, "WHERE ");
have_where = true;
}
- appendPQExpBufferStr(&buf, "NOT p.proisagg\n");
+ if (pset.sversion >= 110000)
+ appendPQExpBufferStr(&buf, "p.prokind <> 'a'\n");
+ else
+ appendPQExpBufferStr(&buf, "NOT p.proisagg\n");
}
if (!showTrigger)
{
@@ -516,7 +545,10 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
appendPQExpBufferStr(&buf, "WHERE ");
have_where = true;
}
- appendPQExpBufferStr(&buf, "NOT p.proiswindow\n");
+ if (pset.sversion >= 110000)
+ appendPQExpBufferStr(&buf, "p.prokind <> 'w'\n");
+ else
+ appendPQExpBufferStr(&buf, "NOT p.proiswindow\n");
}
}
else
@@ -528,7 +560,10 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
/* Note: at least one of these must be true ... */
if (showAggregate)
{
- appendPQExpBufferStr(&buf, "p.proisagg\n");
+ if (pset.sversion >= 110000)
+ appendPQExpBufferStr(&buf, "p.prokind = 'a'\n");
+ else
+ appendPQExpBufferStr(&buf, "p.proisagg\n");
needs_or = true;
}
if (showTrigger)
@@ -543,7 +578,10 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
{
if (needs_or)
appendPQExpBufferStr(&buf, " OR ");
- appendPQExpBufferStr(&buf, "p.proiswindow\n");
+ if (pset.sversion >= 110000)
+ appendPQExpBufferStr(&buf, "p.prokind = 'w'\n");
+ else
+ appendPQExpBufferStr(&buf, "p.proiswindow\n");
needs_or = true;
}
appendPQExpBufferStr(&buf, " )\n");
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index b51098deca..1146e82719 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -349,7 +349,7 @@ static const SchemaQuery Query_for_list_of_aggregates = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
- "p.proisagg",
+ "p.prokind = 'a'",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
diff --git a/src/include/catalog/pg_class.h b/src/include/catalog/pg_class.h
index e7049438eb..2e395a3938 100644
--- a/src/include/catalog/pg_class.h
+++ b/src/include/catalog/pg_class.h
@@ -151,7 +151,7 @@ DATA(insert OID = 1247 ( pg_type PGNSP 71 0 PGUID 0 0 0 0 0 0 0 f f p r 30 0 t
DESCR("");
DATA(insert OID = 1249 ( pg_attribute PGNSP 75 0 PGUID 0 0 0 0 0 0 0 f f p r 22 0 f f f f f f f t n f 3 1 _null_ _null_ _null_));
DESCR("");
-DATA(insert OID = 1255 ( pg_proc PGNSP 81 0 PGUID 0 0 0 0 0 0 0 f f p r 29 0 t f f f f f f t n f 3 1 _null_ _null_ _null_));
+DATA(insert OID = 1255 ( pg_proc PGNSP 81 0 PGUID 0 0 0 0 0 0 0 f f p r 28 0 t f f f f f f t n f 3 1 _null_ _null_ _null_));
DESCR("");
DATA(insert OID = 1259 ( pg_class PGNSP 83 0 PGUID 0 0 0 0 0 0 0 f f p r 33 0 t f f f f f f t n f 3 1 _null_ _null_ _null_));
DESCR("");
diff --git a/src/include/catalog/pg_proc.h b/src/include/catalog/pg_proc.h
index 298e0ae2f0..dfe7900341 100644
--- a/src/include/catalog/pg_proc.h
+++ b/src/include/catalog/pg_proc.h
@@ -43,8 +43,7 @@ CATALOG(pg_proc,1255) BKI_BOOTSTRAP BKI_ROWTYPE_OID(81) BKI_SCHEMA_MACRO
float4 prorows; /* estimated # of rows out (if proretset) */
Oid provariadic; /* element type of variadic array, or 0 */
regproc protransform; /* transforms calls to it during planning */
- bool proisagg; /* is it an aggregate? */
- bool proiswindow; /* is it a window function? */
+ char prokind; /* see PROKIND_ categories below */
bool prosecdef; /* security definer */
bool proleakproof; /* is it a leak-proof function? */
bool proisstrict; /* strict with respect to NULLs? */
@@ -86,7 +85,7 @@ typedef FormData_pg_proc *Form_pg_proc;
* compiler constants for pg_proc
* ----------------
*/
-#define Natts_pg_proc 29
+#define Natts_pg_proc 28
#define Anum_pg_proc_proname 1
#define Anum_pg_proc_pronamespace 2
#define Anum_pg_proc_proowner 3
@@ -95,27 +94,26 @@ typedef FormData_pg_proc *Form_pg_proc;
#define Anum_pg_proc_prorows 6
#define Anum_pg_proc_provariadic 7
#define Anum_pg_proc_protransform 8
-#define Anum_pg_proc_proisagg 9
-#define Anum_pg_proc_proiswindow 10
-#define Anum_pg_proc_prosecdef 11
-#define Anum_pg_proc_proleakproof 12
-#define Anum_pg_proc_proisstrict 13
-#define Anum_pg_proc_proretset 14
-#define Anum_pg_proc_provolatile 15
-#define Anum_pg_proc_proparallel 16
-#define Anum_pg_proc_pronargs 17
-#define Anum_pg_proc_pronargdefaults 18
-#define Anum_pg_proc_prorettype 19
-#define Anum_pg_proc_proargtypes 20
-#define Anum_pg_proc_proallargtypes 21
-#define Anum_pg_proc_proargmodes 22
-#define Anum_pg_proc_proargnames 23
-#define Anum_pg_proc_proargdefaults 24
-#define Anum_pg_proc_protrftypes 25
-#define Anum_pg_proc_prosrc 26
-#define Anum_pg_proc_probin 27
-#define Anum_pg_proc_proconfig 28
-#define Anum_pg_proc_proacl 29
+#define Anum_pg_proc_prokind 9
+#define Anum_pg_proc_prosecdef 10
+#define Anum_pg_proc_proleakproof 11
+#define Anum_pg_proc_proisstrict 12
+#define Anum_pg_proc_proretset 13
+#define Anum_pg_proc_provolatile 14
+#define Anum_pg_proc_proparallel 15
+#define Anum_pg_proc_pronargs 16
+#define Anum_pg_proc_pronargdefaults 17
+#define Anum_pg_proc_prorettype 18
+#define Anum_pg_proc_proargtypes 19
+#define Anum_pg_proc_proallargtypes 20
+#define Anum_pg_proc_proargmodes 21
+#define Anum_pg_proc_proargnames 22
+#define Anum_pg_proc_proargdefaults 23
+#define Anum_pg_proc_protrftypes 24
+#define Anum_pg_proc_prosrc 25
+#define Anum_pg_proc_probin 26
+#define Anum_pg_proc_proconfig 27
+#define Anum_pg_proc_proacl 28
/* ----------------
* initial contents of pg_proc
@@ -5531,6 +5529,14 @@ DESCR("list of files in the WAL directory");
DATA(insert OID = 5028 ( satisfies_hash_partition PGNSP PGUID 12 1 0 2276 0 f f f f f f i s 4 0 16 "26 23 23 2276" _null_ "{i,i,i,v}" _null_ _null_ _null_ satisfies_hash_partition _null_ _null_ _null_ ));
DESCR("hash partition CHECK constraint");
+/*
+ * Symbolic values for prokind column
+ */
+#define PROKIND_FUNCTION 'f'
+#define PROKIND_AGGREGATE 'a'
+#define PROKIND_WINDOW 'w'
+#define PROKIND_PROCEDURE 'p'
+
/*
* Symbolic values for provolatile column: these indicate whether the result
* of a function is dependent *only* on the values of its explicit arguments,
diff --git a/src/include/catalog/pg_proc_fn.h b/src/include/catalog/pg_proc_fn.h
index 098e2e6f07..b66871bc46 100644
--- a/src/include/catalog/pg_proc_fn.h
+++ b/src/include/catalog/pg_proc_fn.h
@@ -27,8 +27,7 @@ extern ObjectAddress ProcedureCreate(const char *procedureName,
Oid languageValidator,
const char *prosrc,
const char *probin,
- bool isAgg,
- bool isWindowFunc,
+ char prokind,
bool security_definer,
bool isLeakProof,
bool isStrict,
diff --git a/src/test/regress/expected/alter_generic.out b/src/test/regress/expected/alter_generic.out
index 767c09bec5..c4641af276 100644
--- a/src/test/regress/expected/alter_generic.out
+++ b/src/test/regress/expected/alter_generic.out
@@ -83,7 +83,7 @@ ERROR: must be owner of function alt_agg3
ALTER AGGREGATE alt_agg2(int) SET SCHEMA alt_nsp2; -- failed (name conflict)
ERROR: function alt_agg2(integer) already exists in schema "alt_nsp2"
RESET SESSION AUTHORIZATION;
-SELECT n.nspname, proname, prorettype::regtype, proisagg, a.rolname
+SELECT n.nspname, proname, prorettype::regtype, prokind = 'a' AS proisagg, a.rolname
FROM pg_proc p, pg_namespace n, pg_authid a
WHERE p.pronamespace = n.oid AND p.proowner = a.oid
AND n.nspname IN ('alt_nsp1', 'alt_nsp2')
diff --git a/src/test/regress/expected/opr_sanity.out b/src/test/regress/expected/opr_sanity.out
index 684f7f20a8..25518c9faa 100644
--- a/src/test/regress/expected/opr_sanity.out
+++ b/src/test/regress/expected/opr_sanity.out
@@ -88,10 +88,10 @@ WHERE prosrc IS NULL OR prosrc = '' OR prosrc = '-';
-----+---------
(0 rows)
--- proiswindow shouldn't be set together with proisagg or proretset
+-- proretset should only be set for normal functions
SELECT p1.oid, p1.proname
FROM pg_proc AS p1
-WHERE proiswindow AND (proisagg OR proretset);
+WHERE proretset AND prokind != 'f';
oid | proname
-----+---------
(0 rows)
@@ -154,9 +154,9 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid < p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- (p1.proisagg = false OR p2.proisagg = false) AND
+ (p1.prokind != 'a' OR p2.prokind != 'a') AND
(p1.prolang != p2.prolang OR
- p1.proisagg != p2.proisagg OR
+ p1.prokind != p2.prokind OR
p1.prosecdef != p2.prosecdef OR
p1.proleakproof != p2.proleakproof OR
p1.proisstrict != p2.proisstrict OR
@@ -182,7 +182,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.prorettype < p2.prorettype)
@@ -198,7 +198,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.proargtypes[0] < p2.proargtypes[0])
@@ -216,7 +216,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.proargtypes[1] < p2.proargtypes[1])
@@ -233,7 +233,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[2] < p2.proargtypes[2])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -246,7 +246,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[3] < p2.proargtypes[3])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -259,7 +259,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[4] < p2.proargtypes[4])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -271,7 +271,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[5] < p2.proargtypes[5])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -283,7 +283,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[6] < p2.proargtypes[6])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -295,7 +295,7 @@ FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[7] < p2.proargtypes[7])
ORDER BY 1, 2;
proargtypes | proargtypes
@@ -1286,7 +1286,7 @@ WHERE aggfnoid = 0 OR aggtransfn = 0 OR
SELECT a.aggfnoid::oid, p.proname
FROM pg_aggregate as a, pg_proc as p
WHERE a.aggfnoid = p.oid AND
- (NOT p.proisagg OR p.proretset OR p.pronargs < a.aggnumdirectargs);
+ (p.prokind != 'a' OR p.proretset OR p.pronargs < a.aggnumdirectargs);
aggfnoid | proname
----------+---------
(0 rows)
@@ -1294,7 +1294,7 @@ WHERE a.aggfnoid = p.oid AND
-- Make sure there are no proisagg pg_proc entries without matches.
SELECT oid, proname
FROM pg_proc as p
-WHERE p.proisagg AND
+WHERE p.prokind = 'a' AND
NOT EXISTS (SELECT 1 FROM pg_aggregate a WHERE a.aggfnoid = p.oid);
oid | proname
-----+---------
@@ -1633,7 +1633,7 @@ ORDER BY 1, 2;
SELECT p1.oid::regprocedure, p2.oid::regprocedure
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid < p2.oid AND p1.proname = p2.proname AND
- p1.proisagg AND p2.proisagg AND
+ p1.prokind = 'a' AND p2.prokind = 'a' AND
array_dims(p1.proargtypes) != array_dims(p2.proargtypes)
ORDER BY 1;
oid | oid
@@ -1644,7 +1644,7 @@ ORDER BY 1;
-- For the same reason, built-in aggregates with default arguments are no good.
SELECT oid, proname
FROM pg_proc AS p
-WHERE proisagg AND proargdefaults IS NOT NULL;
+WHERE prokind = 'a' AND proargdefaults IS NOT NULL;
oid | proname
-----+---------
(0 rows)
@@ -1654,7 +1654,7 @@ WHERE proisagg AND proargdefaults IS NOT NULL;
-- that is not subject to the misplaced ORDER BY issue).
SELECT p.oid, proname
FROM pg_proc AS p JOIN pg_aggregate AS a ON a.aggfnoid = p.oid
-WHERE proisagg AND provariadic != 0 AND a.aggkind = 'n';
+WHERE prokind = 'a' AND provariadic != 0 AND a.aggkind = 'n';
oid | proname
-----+---------
(0 rows)
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index f1c1b44d6f..fea84a5415 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1521,9 +1521,11 @@ UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
- CASE
- WHEN (pro.proisagg = true) THEN 'aggregate'::text
- WHEN (pro.proisagg = false) THEN 'function'::text
+ CASE pro.prokind
+ WHEN 'a'::"char" THEN 'aggregate'::text
+ WHEN 'f'::"char" THEN 'function'::text
+ WHEN 'p'::"char" THEN 'procedure'::text
+ WHEN 'w'::"char" THEN 'window'::text
ELSE NULL::text
END AS objtype,
pro.pronamespace AS objnamespace,
diff --git a/src/test/regress/sql/alter_generic.sql b/src/test/regress/sql/alter_generic.sql
index 311812e351..eb61a69a82 100644
--- a/src/test/regress/sql/alter_generic.sql
+++ b/src/test/regress/sql/alter_generic.sql
@@ -81,7 +81,7 @@ CREATE AGGREGATE alt_agg2 (
RESET SESSION AUTHORIZATION;
-SELECT n.nspname, proname, prorettype::regtype, proisagg, a.rolname
+SELECT n.nspname, proname, prorettype::regtype, prokind = 'a' AS proisagg, a.rolname
FROM pg_proc p, pg_namespace n, pg_authid a
WHERE p.pronamespace = n.oid AND p.proowner = a.oid
AND n.nspname IN ('alt_nsp1', 'alt_nsp2')
diff --git a/src/test/regress/sql/opr_sanity.sql b/src/test/regress/sql/opr_sanity.sql
index e8fdf8454d..590257390a 100644
--- a/src/test/regress/sql/opr_sanity.sql
+++ b/src/test/regress/sql/opr_sanity.sql
@@ -90,10 +90,10 @@
FROM pg_proc as p1
WHERE prosrc IS NULL OR prosrc = '' OR prosrc = '-';
--- proiswindow shouldn't be set together with proisagg or proretset
+-- proretset should only be set for normal functions
SELECT p1.oid, p1.proname
FROM pg_proc AS p1
-WHERE proiswindow AND (proisagg OR proretset);
+WHERE proretset AND prokind != 'f';
-- currently, no built-in functions should be SECURITY DEFINER;
-- this might change in future, but there will probably never be many.
@@ -140,9 +140,9 @@
WHERE p1.oid < p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- (p1.proisagg = false OR p2.proisagg = false) AND
+ (p1.prokind != 'a' OR p2.prokind != 'a') AND
(p1.prolang != p2.prolang OR
- p1.proisagg != p2.proisagg OR
+ p1.prokind != p2.prokind OR
p1.prosecdef != p2.prosecdef OR
p1.proleakproof != p2.proleakproof OR
p1.proisstrict != p2.proisstrict OR
@@ -166,7 +166,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.prorettype < p2.prorettype)
@@ -177,7 +177,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.proargtypes[0] < p2.proargtypes[0])
@@ -188,7 +188,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
p1.prosrc NOT LIKE E'range\\_constructor_' AND
p2.prosrc NOT LIKE E'range\\_constructor_' AND
(p1.proargtypes[1] < p2.proargtypes[1])
@@ -199,7 +199,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[2] < p2.proargtypes[2])
ORDER BY 1, 2;
@@ -208,7 +208,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[3] < p2.proargtypes[3])
ORDER BY 1, 2;
@@ -217,7 +217,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[4] < p2.proargtypes[4])
ORDER BY 1, 2;
@@ -226,7 +226,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[5] < p2.proargtypes[5])
ORDER BY 1, 2;
@@ -235,7 +235,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[6] < p2.proargtypes[6])
ORDER BY 1, 2;
@@ -244,7 +244,7 @@
WHERE p1.oid != p2.oid AND
p1.prosrc = p2.prosrc AND
p1.prolang = 12 AND p2.prolang = 12 AND
- NOT p1.proisagg AND NOT p2.proisagg AND
+ p1.prokind != 'a' AND p2.prokind != 'a' AND
(p1.proargtypes[7] < p2.proargtypes[7])
ORDER BY 1, 2;
@@ -804,13 +804,13 @@
SELECT a.aggfnoid::oid, p.proname
FROM pg_aggregate as a, pg_proc as p
WHERE a.aggfnoid = p.oid AND
- (NOT p.proisagg OR p.proretset OR p.pronargs < a.aggnumdirectargs);
+ (p.prokind != 'a' OR p.proretset OR p.pronargs < a.aggnumdirectargs);
-- Make sure there are no proisagg pg_proc entries without matches.
SELECT oid, proname
FROM pg_proc as p
-WHERE p.proisagg AND
+WHERE p.prokind = 'a' AND
NOT EXISTS (SELECT 1 FROM pg_aggregate a WHERE a.aggfnoid = p.oid);
-- If there is no finalfn then the output type must be the transtype.
@@ -1089,7 +1089,7 @@
SELECT p1.oid::regprocedure, p2.oid::regprocedure
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid < p2.oid AND p1.proname = p2.proname AND
- p1.proisagg AND p2.proisagg AND
+ p1.prokind = 'a' AND p2.prokind = 'a' AND
array_dims(p1.proargtypes) != array_dims(p2.proargtypes)
ORDER BY 1;
@@ -1097,7 +1097,7 @@
SELECT oid, proname
FROM pg_proc AS p
-WHERE proisagg AND proargdefaults IS NOT NULL;
+WHERE prokind = 'a' AND proargdefaults IS NOT NULL;
-- For the same reason, we avoid creating built-in variadic aggregates, except
-- that variadic ordered-set aggregates are OK (since they have special syntax
@@ -1105,7 +1105,7 @@
SELECT p.oid, proname
FROM pg_proc AS p JOIN pg_aggregate AS a ON a.aggfnoid = p.oid
-WHERE proisagg AND provariadic != 0 AND a.aggkind = 'n';
+WHERE prokind = 'a' AND provariadic != 0 AND a.aggkind = 'n';
-- **************** pg_opfamily ****************
base-commit: e35dba475a440f73dccf9ed1fd61e3abc6ee61db
--
2.15.1
0002-pg_proc.h-updates.patch.gzapplication/x-gzip; name=0002-pg_proc.h-updates.patch.gzDownload
�y2TZ 0002-pg_proc.h-updates.patch �����Hr��s�_k3u����IpV��J�����F��������d$�$�������~���d����<��t��U�Y����C�x3�m��b�L�x6��&�x�yI���f�F�x��+��'q�e0��F�?�f����_����U���ESe�&�����Z�������h���������wA��Y!� L�������|6��������M�?��w����G�����[�r����t��o��������u��1/6��V����l_�~>���E�?X�����o�0x��"��f�NaFiyQ�����������m�^�����o���K���.o����L��������O��E,W�Y����u�Z&I-3��w�D5���od�����
��I�n�f�������������� {-[��~����&�&��/���?�$U�>X����Q���?�����wFo�o������wA�\���xz
�����~�������H~�L���������?��Q�����~����a�����O���8[�������w�����V��]�q�Z�T��4�6\8�J�*1>>:'e&���,�H��21>>�����g�[��5M���6�
WNF�4S����2!:66��;R�Y����Ubx|p.�����Bu:j�+���P���"�*�&W���Mbx|p.�Lk^4�&��w#�$F�����U�J��(t��m���sPe2�X?��l��HT�`�wr0�8�)]��C+s kr�&K!��tQp�b'�c6��6�����(2�P�5v������sQ���*�S;O�����M������D9]T:�Z��@� �6
C�"�Wk���4�����'�P��`� �d����)��P~Z- ��]oLjy�:o���*i:�E��h9�� ����u��`�{,t����$�ogd�n�ccsq���$������sQ�^l7��b��v��b�"sQ����M�G�mr#T#F������^\�Y#�G� �F����E�a��5���"X#H����H�l������b�"sQb��>`�n;��5btll.��K�2��G���#1�BaJ^F�����{����m�d�tQ��Km��
�9
L����n�����-;������ux�x�/���S�T2���x/�^�R�V�V����#"^�:/���#�CG�b���S��f<��E�G��k����jo ����v�@�K�e����Px�t��U�Ru�
��Zn9�f�Bx�1�����E��w��{�������=��`���Q�)
��I��C{;T{�n� $<!)�M�'�l���s��V8$����mpP��[����3z��!�;g�n�Cbw���
�D��q���9�v+�s��V8$f����p@����r �x�3Z��
��cu�sF���4@���[5����Q���9ct+�sF�V8$Bg��/���*IqM��/�N�����9i5iJM�iac#�������zJi�zD;0Yj*���N|�>�]��@�q^��n�u[c�qJ���~1oU�A�'���8�$�������>�S�� �p����y�X�|�0;%<p����6���N�
�!��H�C��u���<�h7��T�w!�J!�:1@F<��&����G�� �^R�$u^Bgxf������������qH����a���]7��P���?���;��n���M���"P�8����~�)����U����<�i�����~�R�����@<%����,L�Db/�
Om���|��;u�����4ND�|_������Q���D�% R8������f��}���6�o��/��;��� *�?[�BcBA���N�!OZ�a�>(;�WB���F��b/��>��[P�Hn�{A%�Y#�AyU��U=J��J�sg���H�p:��_�5�!z���d{�����OF"�������t���I-"�fM�J]N�Y2h`���v�>����:������ln��K��=���v��sh��{
e�J�����������_�w
j���~�ou<M-�N����.Ec=E���7{�3��t<|�N�;�B��ou"8�Y�Sq�Y��2
����x]B���{q<rA;���#tL���%f����������a��� ��Y�3��j<q|�^��z�D��oN{`/�_b�3���T�\����r��p��@�E�dEt8���1�2�$G��� 8%/�C��P�'���S��%���H�T��bO#1XX�S�2��!�s���:{.?�5)kn1������A�4�u��>�}��j'
�{\��:���:��������(g�f��Q�R��*$��sq���K.�(�b�v#����E�:J��bG2R�
�V�P�����J�Y�������L�(!'��BuLr��W�uByUF�N����E�Q��u:&��R@u���|.
��`�P3Q�!����p������.3�X0M���pk!��H���>��!v������in+h�;)y�,SF���I����Q�:@z>=�� �J�=�
�Y���BC����D�z�Lb�+6`]�%��� �/����r�g��^�}N:���&�����%�����J���D�y�\��3q�������-;<�����N��O6Q4�"�i9��iB� '�D��=�����p���Y1�(�3F��a1g�f��"4������g���
��8c3+��GfVL82�����p\��Y1���=&�b�1oDf%�"2�x�
�c������Xc1+"���������F~�)���k��w���E���������\��pl����d�^��[N'��A_�#Fk^J!�-��u�Lbu����t�L#*Tl����F����U����xP��xi_G�G�����^?]I���@��}yZ�>������y*64P�������C���� �6���'��|��A���5���8��C��7*XX��J�><.���"m���+�N��~�H�w��F�����;""_�_�^>.f��h���C_�.��9"�a�����C�V��CC����$"�a����+���]�nQ��|��`��0~}�
N�a����7�;�C���0����-������)�������B�p�C�14�C8�^��Q>�C����G��b�0��vq�)xp��
^��c�|�$�a�����<�����x��3_c�x��S|�S�7x?"8��|�U���HA�V��/"
��2u���F�i�^Tg����,%d�s�6e�dy������/���h����)G:Mqz:� ��fcTz�0�JH^���@J��.����L�x]���cPi�ri.�M���M��n]�[�n*!��/���*�����R��SK���:k��-��o�r�_^��u��5�^$�\�c���k������+A����,��1��J�$qp�pX���+�����a�C�78�7�pH�g��I��L���A��iV8$m�3i�
�%m0�lX���
��
+�����a���5�5�tX�c���I��L���!��iV:$M�5I�F%i��hX��
�
+�����a�C�3X�3�tHrkj��I�`M���!��iV:$-�5)�J�$e��dX����������a��18�1�|`2g*��L��L���a�|iV8,
�/ �
�%a0�`X�������~a���/��/�pX�c���K�`L�����iV4 ��1���&]��\X ����+&�p��na%��-��-l��d�VT4��9���HH���faE��Y�H�����'YxH����5���b�#����`�%����^�!�b�6�h�ns�n���>!��/�&������I��
L��w�lsd��7_E���t���P�(#+��R��p�H��������4Mm��L��"&z�'�%&~�H ��m�mG�g�=�����������=1��\��s��PJ�q�m6R�`n�,����~�����N�q�!+$������B�>��� fdE=���������Xq����tAQ��Ub�5"h���s]���T������jh�����3}Y`��H;���+�������Q8]�����[a��)�>X;�wtn_�������e�~���>
��>o���_�9� B]2�7&�Y�0�1�l���h%��� �vR@����|K�p����I����ed%tQ�
��}�P��O�$�=QaJ�'!a��$���}%�O�F]N�'��8�O
{�)e�$tHO�p�R�> L��D��C��> ��(�$�'��CVH�q{!+$���}��A����z F�c�C���������yh�d9rR�Myx�]*SN�L��4���u���uwt����h��N�{V$GB��"�z �����j��gEji��B����2w�k����������6�����I0R��?B��Y�Fb@J�KT���tL�����8o[����m+#���}=1�u����S���}�0�� u�����ww��5eP�L����f���&�,���6�%���e������:���������X�������+�V!4.�N�v��>d�����^u�����W�Y����~q,���b6Z-�Z�
mJ�uO��2�:���U"@�"h\`}��>%c�;��������������ih{Gk��3;����������{J
H�� ����YqR�{{��6��E�����s!`k��feC,�����$kNU����B��r�����������7�}����*b�"�T��tV���aR����N]e�����1�u*����2~�*�pM�u�IK������1���k2���RHD��s}]�m�<���1q]���h�f�&u�>�S�Te�N2&.�N��:��7r1,���n�b#(a�"J�����X�g�V��h{C�s����>Y�>,�{1�FaFVB�d?S@��. ��c��� r@�����.����J��������2��(5?`�n���P�0%/��b�2F}�B<���/��OF�4��p�.M#������F��V����P��B�������u5kG[���f�f+�����2��g��'��[��� P�8(7��z��J��h���3[7��$�E���+'x�"v���Xh�B��i��������}� �`mc�)�5���Oj���1�:��8�� L� Y�p�*Q4�VeDd*�D>|��&��������l �9C�f��\��>���(�+B#s�K����
>��[������M����}V��X��z�V�y+�b�K_����[)��5u����� �LG��1S�c|5���q�����a��)�1nn�������1�oDQ�8�K�2>�t�dJ��8G�g�@��vC�����A-t~�����Or/��{��~q(Mkgu3�a��W�a���7����a�R��s���u�����N���v}:�[i����%5��n�
����I��$�j� EovF��Kf+#�df_0[�3�r���-���VFl���T�2bKe����[(�/����2�}�le���Kd#�Df_ [�2�����-���VF�������
/���VLxa��,�b��b?�b+,�(��$���Kb?b+,� ��������~�VX|1�g)l��,���VR|!���^3��/A��d��>��|�fo�o�?����9�z\K ���q��~{�^�yS �7u�=Uy�3��2]i�������~����
~��bYh��$�@Jn��/������t����`Q�k�|��.t=����n��1��$Fu���;wrn0�)G5���;��_%xa�ttW��}aP��o:*�O��s���i4�xju_�����tT�v?W��R �/�JGu�h7t�@q��%��E���s1��G�Oc�~�>���{h�)>�7^�r@e����&������t|[1qeD���F�5mf���?�$�}��M>����������:���w�r@M����F����8���2�#{4�PG6���qTS�:�QFxd�J�SG6��������I�Ln�m�2\���q����w�k�����e_��0��-������n���VHtm����B�+[�u�^���j�����{Mk�D���+Z���V���Y+!���^�Z ��,�Z�F��e�W�VBh%����B�X�U�}4c�X�5��Z�r�`���
�{�j%�����W+!�z�^�Z ��+��ub4c+W�uk�M��_*���X~�� ���������@��F4��W������h����g�E�#��%��xD��v4D �Z��dL�K����x6^�<�!
)��)��9�lIC���F��M0%<��1�/]�c|tG'��L���p6���Kt���S>���u�|��,����Y�q��7r�\K\����� ����u+#6����VFlVg�������>�[��}>�2b�9�lne�fs��������3������q+#6����6Fpg��m���{������tx6W��GQ�$���/�l�^m���M����dJv�������^�;ec"��;��M�)��QH@�=��>�����l��C6���M_���O��'y�!c����EQMj4i�)��Hr�T��=#c��h���!q�x����O�u���^�������u�[z����1q��=hz���U�I����v�Z�5�"Zko�1l������o�WU�+��S�m6����h^�cy�!�^T�zqe������i?���x�V�<V�V�(u�szX`��x��������������<_���k
��GB@}c�������I�A�N���5>jcd&�4�>L�xlZS�{�A�p�p�wAR������_��P�"/` ��l�zk����o����12��fE���);�_���!��?�u!>����K��a������mD���x��'���~�[+���,DPo�"��4��^�l'�
��+��u!��Ti���Fm
"�m�<������?G%3�a�%o�#]�NI�����t�#�~��;k����@?=���� ��eh��4���A�����9�c����R���)�`���zR�sG�q���RvX����X���7'���7p�"������D�������%d���|Q�d &���\<�I�h+�Sz�c
~������v�d��g������8o�c��g��zS4�S6��4��3_wc��������u%[R��$X8_�M��Fin�o������}����=�^�8_���RF=e�AT��h'���`�|���:����&=�~�� P8���Jl}�u��.�M6;z����.{T������)D���[!`�:}f�oc$�|~�oE>���2��goE�8{��
�znGo��8zn�
��y~'o��<���q{l�7�=AIt��c*�u��U� !'��B�+�y���2�6�#����0pLl��`J�Y ;��E]�7���Jd���0R��������t<��@�M�_lYdA
'������O�������NyB���5���6��JH�m��d���m't�� ��l;5�����j�3�WG�H�8#+!����TR���>`�`?���6oH�)�,7n���H��aPvL��G�h�����ki����}!C�>QJ�v�G#I������k���������N���Y��Q�o�a�"p�����fr�Q�;��"���q_�-���t2Kz�� 6MY�>�
[.Lb�H�L�q,?*n��f������:q���=������4c��UD��A�V���ed%$��$�6Ef����U�[��u�2�R����t�W��$/e��$�.�-�}�F|j���k�� S5��J��v47�����m_��N������f���k�i/W�@����N�j���������?���7k�Ea�&���4����/���l�m�n��/�aZ����%h�}w�UU�F�,�EU��UC+T:L��y[��L��6�}-v�m���m�jS}��c��3a����F=���#���PU�`�V����T;���t_��u�l�����_ >Bt�C���=bME1�E�[��}YBO����� r9��9�tSd'�LH��Gc���[����kR�s_)���^g���=��N;oOg�@�p�@�kpBn��(4j{]�%�����H�����Lx����,d��>
++hx3��X��dX� �7��b!o�a��������.�C+"Z0�}4B`�#����a{Pa���
���
����b�d�.vKn\����(x��������������!�X�
��B�z��]��*Q��&��$��1���U���J�[����R�������h�O���
W���BX��^����R���f�S��5�Ge��j���L��A�!�NYo�"���z���]��'1B��w��v�l���d�U�5�����v" �xlp�:�SI�I8���D[u�y�43G-��_��tK����ks�����d�n�d'�-�����h>���m�BB�[�X]��ZJ�[���c�s����n��G$�Da���������Ew��Vw���������N�w}�R,ql�$`��@+&!{v����$�zo�Z2��I�d��9q�W�%C��0��I����,��e�%�n��Z � cp\hN�;��2G,C����B����b�!G�<3g����}3�
��jcXr���%���������n�1W���{�p�Q�D�v���9��rK��b
g�0�����u�����2/�!����N�[�
��n�1,}�����+Q��Rp}�:��~���U{Qd�u=�6�]����A��et�L]�)t�8.�!��R{cv���(n7�V�X3�Lh�N^J'�^\QS-;�����a�M��F���8�_���>o��"�b�|��H�NfJ'�^^R�����;��Y7��#��}�z�9d�l��x�4r_e�R0��!Y�,;�@���$G��Rf�4h_�No�G�"i]�.�ME��b������WcZ��PBc�vmiH��B�b�qo�����
%�@��vr0&p2S��r:�����K�k��U��=r;����KJyA�t��1��8&/��u��������0{��T���A_���kln���E?9y�0���x������r�m�����������-:���0�wI99��S���P|��R�|������AV��#*��k��MjZTY��y��V� t\f�[=!�~���`
m�c*{�q��*���#��Fr�~�1�!��D�sR���rr�u����l����V�f�����~p����M�G�t�.BC��p��1M���Mh�� ���|��\��x�6�hO�j�YO7�+�l��������`I�F��tx���!��=�i����o��m��|R�����/N��.��c|�/��
�c���X���T�PO��9?�����%�~F�����x�����{�s���������g�]s�/
��*�*���I��W� :z��oN�N����������<~�A>���A>���v:��R���n����"l+��c{+*��[���b��U��[���A�p��ob��V ��+��`\}X������
��=8WV8d������A��U�Yup�9�p���s���Yq��7�t�z�u�a�CV�k
+��`]iX����:�J��3XW�Q�2x���t����PS��i��i[��:M���E�I��tR�zn�J"���X]m!mJ����D6e��kR��Cv�Zkb��9j���N�r#[����T=�yWO���B�|q���"������<���+�1P� Y����sdrB��d 9�p.Q4���S��b>xE|�P�a"~�3e��������,�G=����12&.��N�=��S���0��
L��+����`���)�;O���oE�)��e�gt�B���*A|]�~o�2� +�����p���i�y_u��M���o#&�R?�C{7_����r��L��������!�sXX��a�9(�p���V8dHp�l�8� ����� @�*�m�[=>�m(%;c73g�?���������x(��^�f���l�F����U��*+���:@��*S�^�Z�~���'��f��m/�RT��,�J�-c���q]CM ]B��nn06&����$��'���;��I�������bu��\1F�N7i�Ea����s�u�K���.z]����Y�X�g$%�����=z�6]���v�����.k���.~�� &�.�K����'m���nlx��m�q1>�����q���y�[!�Q�<����g�6H|�3�o+$<��G��-�R�%\����j���h�����.����j�����{��}s�*Q4k%�0 ��U��X�M����@>q��lA#���Nv�h��zJj8V��2�kv^�z ����9F�Y� �1j��.*2�t��fmVR�2Gn;"o���() �!�������j�Q�:���r�l�fw�|���U4�E����f�4,�������k�v����%w���?��z��+/��q��F1x�8r������g��O������&0�>f�n1L~�3��V��g�� �=����|;{y��AT?���O�u�7'�K�e��e����M����������I�V�
[��0@\��}0������n�G����V)�������V�tc���q�LC��`1s�}+D\��5U�!���b�#n��q=�2T�t*��4�A��S���Wd���m�8�� �h�h9@Z��!����5�V� *�>������4HBAgcK�t�{d� �u�@���tp����`M:pO�\�n�W�>l�,�e��Q�����pKs��y�����Ks�x�������
����0x�+ ^�VLBp�#�����C���~�
X��vL8��*������1���a!c@a��
�p�J�����������7����i�wr;oa�!�:/�Xh,4���p�'��>W�}���W���t��h1c}���m'i����f�K���C & ��p�$� ��"26�y��J#P�K�x�t����o�Z�t��L>\�������0y���K�9p�~zR�q�!�ex��vBVF� q� +#�����t@�����n�c���au=�]D~V*T���fin<o���g��2*��e��<\a����������z7�
Z��
T&��^'S9
�3�{��r>��J���20f+w�H^��j�fg�n��(���[B�H�[
);��O6�=���GA��x��r- U9L��y�r���*��qL�?`>�T.�t
+?����<���9����E��$�8���a�(����G�L)}9
�29*����_�v�M�*�N�1�0�q�a{�����P�e����AN��jh��tD�+�V�D`�]_t<����T���h1�����I;G9�ohr�u���)�R�m8����3�(�jHze��u���Uf��/<���[��y#��qU������k��W�A�R�i�����"S��[�za��
��Q�9u����������l�b�z�z7����xh$��VG2<�3p�R{bv1�����d��������4�^��!�]�L��OdjO��1drru��16G�v[4y"\M���\=G+S�����P.�&{���L���?zq,�\�������d��a~�d~�N��hNUQK$;�E�����!���tA�W�x K�������M'R� Y�c�{$:������b+>M�����Ny���C/�0:�hK_���]e:��� ��p_a�j���1�Z�+�T�Q~�U�e�.���b����lB��z�'��.����[�j�w��{��]m��.�m�E��{���F�4/��i���q �BK;��������N�t��i���{�.hz��Di�Z!�W����TlA�E��B��R��E��B������2o�S������N�i]|:���Q�\���YU~�J����hQP�C���P��y�c�aq���v����B�ZsBa#t�%C����KU��l�o�q[��l#p9s�\��F(�EDl_�CO���*��(�F�e�����t uu��t���Z$�������e���N�]�G�v����47�L�89o��zi�wL;��Z��;�� ��c�#}2?k��5ss��ph�s�:���t8`/U!���uC����8���/w�V2�G�No_+�1�D�]Xls%��������2�����v�b�58j[)^��&xm ���F����9����N���N���[�*��o������Y���n�H5FI�! ��:�|:�d�GQ���.� d�uY�L�~��}��c�=����+��M.h����r���Gr���J�]$Z���0��Z��r�5�p���nkI�K��K^��y��D��C{D��*�B��|@�?}P��/ee�����,/L*���!� �Y��X����%�5|nox`V8�v�K�w��>����@�B����J��B�K���l�� #������"�X�G�B�;2Z!�.1>F:eF�:-O�<jp����x}����N9������"�����}�<��r��P��?�{d�r�TacW�~Nf���InE����ed%<K.��?�I-0MZ�����o��M$�V���e����y��R�?o#>���k`2�@�����VU��n�����&��
\�F��m��J U��q�u������I�M;�6�������8��
S�2"��Ks��Zb�7�OI�&`2CB����������V�j�����b�8%/#d����'2�O2d�r����9�����tG�e��.�^�K�n�t~�tw�g�4.M^^������-��.�@�.�,�h]�4=����G/(HW���VMCG��1o����o�G���n�����n�G���n�����>��9��K�Ss)�u�RS\z�����i�~�7�CJ�Y���L6c������?��V���q����0W��zP7X} w����{.�f�1�0;,�|��`>�`�+����7�Z�C�%�$T� !#__��;��NO��oT��ye�>���EQJ
��������6��P=rj��j�U���_�]���0�dDno�Z!�-�=�[U���Lz@����} 8����?.�%�b���.�p9h� ��G1���!c�u����:~�x��e�v<d���];2vYG���W�"%j��\��N
��V"9�I� �GN-�Q-��p�M���q��A/6u��,�$����J�����!���|P���M����~��[��A����Y�=g�����;�:9�������% ���k�W�=tOO,��C��_N��w�:���T�g�>��=]4H��N��b�4��X���@|�S��E���4�8^u�i�E�N&zC,r�;�{�>�~7Fp]����]�=�"�
7���l�N��(���1F;��������v�Pc��nB�u��:��^i�n'�]\j7���% � Cq������ ��kN�bu��s={�
���{�e$��`��#W��Iy�8��i��
�o������#�����N�,m�F��M�K��-������~��C
#�{����y����x%�0��d�������2��!��x�Q��d���j�4Y>�q��!����@�~�!� @�B�<q��a�j���T=�S���u��U��H�TkT;,e��a�j7�
����KY�zX��a)�SkS;,em�ae��\�2�K8_��i�u)����Y�2�I�����yEj�V���Q; �e^����(�Z���E�W�v@l%���b�P�U����
������>V�vXt���D�F�c=-?�p4� ���T~P���
W���� ����r��\�dC�����>���F�����YI�>j������ve��J��B���<M���~z�Jd�9i�%�B����C,Y��(�8D�;�����#S��[I�y���C�vXL��
�L�3�����%��R����G�x��#!)��F��u�9R�q��l����B=5c|�t���v��=�^��E�#�E���zG��W�������U23���58��=R
�u��S���i�
,VIHV%\�W% ��fQ��]v�}R����p�Mh+����������|��cDs7E���OY�'AR�2����>����]�J�������\t��a������M��8�^8>��s5��i�5�`���<
������n�T�Ur0����������)�5y��n�e�|�/^�^v��k)�~ABN>�z�3��mk�W"s�`;��H��[�����Y���U�L���J����zGa�v����r@�b���V�g&5�h����gD��8�v4�'3�,P� '?�U������M���� ��Y{������D`�A:���;��s�|?i����nh�L@���8H��g��3S~d���x��Z�\�`�@*�Y q%�L�����; KJh�#�U�]��i�����6�oOm�=3
��xS���r8�uw�4�I�J���&�� �SP�A;���w���G-Y��f�l���ykp�'������3��WH�)��*���Fdh?�I ZA��A�@���o=� ��{B]��^k�n{���F6���v�j T]� <>��ZT�����+7����J�~�� ����!������T7D���L�g��FKP�������{Q�����Xtk��� �~�-�����>��p�������^��]���Q���nmLe�� ���Y��������������5/D�j��AP[����Jw��:A d4@�THg5>u�@�x��?� �T��mg��yp�06T�(�����AbE ���(����b���}�����F�H�����Y�>��V�E#��k��6�c��S�
~��������M�$��/�6g&�C8]A'7���s�i��`�k�[�VJD���,V~R�L�/������y��t-�'��I7�����J�v���w�x�Lm��J�Y��j5������P����&+6�{�g'0$��;��������M=i7E���*=(�J�(�S����O�/Af����)�L6�uz�SI-�x�����AF��t����Tl��k�%�*�u/3�j}(���+��Z�+?��:�O�C����I��k�m���"��+B� p
��B2#���������P�p�6�b��7�J��K5��B �s\�+p��]��~J������u��
J��Q����u�/J�<��TB�����R��X�)�����n����N��Ur�J} �4�����e�������h�1��O�0^=���(��;DP-�����y��2��%�TieD�J�����N������&�'I+#<I�N�VFp��� ����==�(���}r�bR&G/S����'�������h>
QmN��My�}-v���@���7eQ7� �?�8�P^�Z5zV�V��t"�[���+S5Q�v���3ne�.�aQ���=f�����&� ��,v1���HNI�H� �r�S*��7��p u�����i�]zY4�+xIG�0�U�J���x4z%
|��
K����C��H����I����J�w��>*I�f�&Ux�(U�z�&?|�k��n���_�����(JU5(��[��I���l�_���M��LM�� ��<���x-�E�����i[�f��a���a��L�������>_K<�����ixR�������g�^[f�}��~��������vL���)~�rA)3!��'0���':}���������y���dfq��� B7�zQT�����x:n� ������k�U�h�Q���������CU��z ����W��m�:^���$,��Ft�P}��HG�P����^��-B�/�D!��\�u�~�W ��0
.���h.��pG�@��5��W'A����W����2�U�������o�p���������Y��`�S��g�����;����J���/���;�Tq3
����t������]�����V?�����_R���\[4ee~����?�{������x��k�7��^��R!'6�f~���|#��� ��L�����N��>�"x~�B��2]q������1�pf��>UyN����h}�}�Dfm u-[a�CFI=p�D�����.�b��b���e
�rP��������x@�C�PneWa��S_-���!��������OO�:��W����k��A�� �������H/?d�)�������e�A����#p�
�+�A3������#���qy�KA�� ���"�yq� ��\��J�n�V�;���BKG��(.��-�d5`��Q0��F�l>a��K�0�|y���#QL�L���F��� ����p�-�s`��d��b��novE_�u'v}��Y{� �&~�d�=�_�B�~��+�!A�������O��HvH�#��#�+ �?������eCF+�uw��/�J�����;�-G��� gR��R�s��7sQ���/�l�~��O]��jD��e����Q���R ��"�;�po��S��'-��y��W#����w��)�������~�g'6E�9����b+���������E�g*�/d�KS���y��_/:����0G���AM���H�i�|Xe ����6�
�o��=}�cV��N���_~?�:P�gkJ�i���0BN>��xs�[���2�3u��;1�JAFVB'�.z`�Ne4�QiN��g�v>$�Mi���g�V8$�_eR_��n����4�����4 oP�#��Y��$ oO����Y�2��Wq�bwAvD��; ;"�����q?����9v�cGD\���#�������2a<8%?�2W���x��N�������lx����L�`���*�>u[6���)7��$5.�!�� ��x�a
����l>@��$���P-=D!�00�-{Hz�R�a 6��G���c����m��mGDF6���#"��}T��Q�=��+���E��O��m�BH�!�za�^����k_��9��:��-�J=L�u�!��s��@!V��=L9�����N��t�SJB1�`{d>����V8�@�d6L;"h��fi����(���Q����[�0b�H"���fd%t9�3[u��a�'�#����3)�^ �������9���S7�b@������m�dXM�_a�!����8��jNjn�j��l�]����0
�U��V]>�W�n}z���
q�������
qW#�m��n+`��a�vX����[;,�n}X��`�>lv���������X����4!�#���)���]V�L��]KU\��Q*��
�X�5�����R�B
S�� ��Yjm�2�R�*�'h`m2�.�������� �m�y|�[��{�yr��o����!���G��I"��%��#.��1������?\���+��w����0j�x������t=R��������~�����^�����>��������������������������o�����c�y�uP���,3�:��������Y��J���,��3�z����,����0zY�Z���
_m�W������&����{hx�k� ���=����u��Z�g��*��8��E@eu������\�� 5q=�"�Z�uX7��D�:'�����u���P^��7��c��Z��J���
�b-��C}��
oa��D��=���Z,�XwY��������
�;W�����\��z�������@����=(A�G��0\�G���'-�)�%�f�7�u|��vv`�r�/���%8wy�������e�������Y�N
�Z^�,;)8gy�������e������le��g+/s������TvVt��4Ou+/��������6x���hS�c���o��g��4���D-��aV�7:���i�_�l$��u;?�=�:���&��D{���}�������|��`���N�=�%0����7)��-C������m��(��+�H����bw}t����������V���$x-OU�������?�fo��iz�D<3{���,�������|�"#�����Lp��=2�zu����Yc�G=m��EbDa�G<�=�!t��r����n�0����{!#�MV7�}��0�!�U�}���������cp���FY�?�9�Q���=�llz9s�E%���k����� ����I�����x��7i �MT<��R�Sf��A}�t��t�AQ?��MxcEtS���������M �Q��i����}�e���W�1�����R��}�����E�����2�!,e��m�6�r����;���?��g�RV"���J���&�:M�C�_����p>6���8��$���%Wq�1W����^�R;����h�
h��>�����@��v[�L�����:�{��H�b�&���6|�2�d|JY!vA'�g ������t��n��<`��
�� ��}��e@��K@�������PW5�� }��O�=b�e(WWG��[B����*��5V�uu�=�U6�M�z�����2:��B����:�6pdo�����U'I��C��h�>v'����Zom��![+!�?���}�����DV���mD3}�Ft���x����#�aHwQ�=[<C���y
6��6�;���6��Vi������i�&C�e�C~q��� 9�6y}s#
u�X>�q�����j�����%�f7������
z�5g�����&k�}�������?�J������9�U���f�����w�w���|��d�-2�/2�j�_��iP����n���o�����LUV���Z��^��N\4���W(����)P�&]Phj-�����q�rt�_�����/~����+�3s��_M����`����(��u6����Ro�����Z������s��������Y����V��_;��@b�o��N�<_e�:���Z"��P`o�C�-?�3Xo����2�{�eG����N�SR��G��DvR���~X�zf��l�������Is�4���L����o'�=F����Z~�7�����;��n�:�l���q���0��:������g�o��O�Z�p|�$H�Rv�+�}������9����jV�N��y92O�o%��
��s^�9��0��=�4{����� zg���mbf�{gG��3 wH�{ ���z����]����^�8�)���M�I���\:�����BQ��C����L�d;���V]?�+Z?(2�����#z�a�#��$�5�`%������ �+���I ��n�VR���[���`��v:�Y�]���b�H]��fc��*�D:�2��Ul�����4gg�4��� �3�5���gG��}i�n|D�Ep��q'S�bG����R�^�Vw���d;������B��e/m�O��)D�x��0z'�,!���r���r�U{����!�h�oS%G��x!�������= ��w=�-���
��_�&���D)E�r���h�1� WBP�UH�C��t6 �$��0����j��m;�A��7�=�s���@Z��iH�� h�p5 �="BZb�&�Nu��GQ�(��Q=b�����*�z@�b����x $�!H���*I{D�b��G�n[{�2�:������:iS��I8{`������^CW;�r�v@0p�[��X��������1d���!+g�jV�p�"�2�v<,XeU�x`���Z�@�3L�ba*c�j�C�T�������P9�S���S���R�!Uy�������w�x\�4���$�6e����Ev�T��:az#3f�R}:�#����S���f}:�
�z�T���x��*��HER�:���`�+>O{�@k��t�A���~]�~�:8R��.���:2�)�m�f�z���_o�����@�4�A�t|��s��U��QN�mhN�i.��47�V����{|�h�Q�v4H�>48�BJ�U5�m���q?��M�j�D$c����Ob�*�P������(��-�*1>d�`����3�k�����$\h����%\��l>�9�[�Vs���%����|ts8���1��I�0d���
`�2W;��pe�v4���8T�h�C�q������9L��W���/�l�~W 9W�W���A�]A���.~�gd%D��H��A��p��r��@����#�����D�"W�q�|�TW���_E����V�;t_1����gAFW��f*��9��eG���6j5~�~O�]'���~uP��:����(C���p��i�vd����\;8�r}���[��wu�/n�=��D����tn�j.���FB���]K�FS���gN��$T�4b����?|��0�������?�Vt!�=N��y�s�`��q��x����7������:�7s�\��=�d���t�1�wJKz���<��q�?���*7��k���y���/z�)���k���(��)��RR�,7��e����[s{�������l��H�_���B����w�)�X4>�X+�'�����R_����������Q5��������Hr���YKm%'s��u�Kpq4���@�����N[�}c������V���7^Fc��E�,����^��-���(�g���X�E�=��$��+k�/��/�GZ����l�7�ki����{$�97����{n������75���k����|�@�f�HLC+|]�H]���c6����������s�������}-���^�yG��oa���}-�!�fa��C2W������[��A��.RGM�o��C���D�i�w?���`����S��m}�A��Z�KI��qV~��J�V��k>���r����F�>:Q����>pG�������4B��um3���E�j'{�u����y+��V�{hz-�"U8�����N7�m��+�2L�$�y�+<�d���a}�R����'���x����yN.����J��g�M�����+\'��+-A���`���O�����a�"�XaLn���Y����|��fA�']o����F��`�����$�O���*e���W���>�G2c����,:@V�=�*�Q}��T@�q*o������jj`���
��������0��qZ/��5ER��r�@��_�;B�@UBplh��|�j!C�@~<����09��.�sh��R �kR������D�����)���S�nG��L��W��b��O-U(���'[���(��J��n}wc�dj���#YuK���cC��e���V��Q����sjUI@�
�q�����_��[���������<s�RI@U �q�
�����0��=F#\� /���b#�p���,D���J[���"m�����O����UslI~�w�K����1a]�N�F��w���?Q�M�e���y�w��������+u`k+��P���]P��Fy|����%��A���I����.�F����I��*�:���F����_���(�yA)��|��Fd�_�/�q����^^P��}6�X@��q�\�����������O��'S���-������x�av���2�����n�3��������_V��Q���r���������?qPf���U�����j���0��������p���Y8�����X1%�BK{f�A��bn�k�L�|q�,�f'<�d�t� G�}Ng� �.�����2��/�N��A5�������ZU���a��������T�T��^������j��
���1�?����$�b��
VL���1����bJ�Q��.�O$��IF�������w������o������g������_������W������O��H�\���"�j����"�����8T���$���]��H��:xb�b��GK-1{��n���Y.gX��MV7��_��X}�����{���m6��Y$��_u�.�!{��w��>]h�������-y����r(�z^}=����d_
" !Gu����S���u�t�x�P���;Q��AN~J[�z�������e�Lg+__�5��Uy
sj)?��}���J�1Y!;=�O����3����qTv�)]Oy�~��nK��Ks�:�=��*�������������h�'�S*��x��N����}5��1]*^�:������@��3�t����._��Y=�0z�BlnVG]��w����tR���������L���t�b�����T��Ft��1����f�6~�-�5��&;����;5��,�<}���q���3�J���`�������J�o�pB���B �
����P�]
���o��>W��;|~[y�Fw��,����9�)o(����&3�K�;�1���X����I�f����`m����G�n}AZ����OrV_��_^����h���fo��dZ������h^k���Md7f��W�@�m8��pI��e��B�:]������=�R� y��y#��B[�iVx����{d�%�����zf��d�zT���4*�CR1��B�����^�W���}(�@�5��Oy������y�b�g��L���3�;E��,g3��)NQ�����������t4m�:`�T�+�z3��F��/�&�bP�8�:�����4^i���`T_PK����G��
�q��Z]P�9�/��(���Pm.����p�BSmh\`�6S�6�"������������9��/�����[7��������p,�����j��f��`���8�.�r�J�}�Un��}���^�~U����X�2�b��*���T�����mz5��W���)��U2��Y�7W��m��@5
S�2^��j>����&���663S6����B�n���tB��P6����e�&eL�����\=^]�+4��orRw�\Q��a��P/�����zw��)�XV��D)����b7m�s����9��n%��r
���`������Mu�Z��Fm i)�����#������R`k=���0�!;�w<�� ���BL�N��i� �e��I���E�Z�l��������������U*S���P������}_����j#���W�i?9��v��(��� ]�A� r�z���6�������$��s8���P� %7��s��nHv�4�A�a�����%O�9z�Gi �ulA^�#I}p:;�0~����#F�AG�<��!t�#�(����qG��1J���8�������]���B������m�j���P/�Q�������\�rc!��U@�v�@�Wm��T!����������e�HGC��'@�����qq�����^KI��� ��.�l�QZ��Mz�(j���[��c�V�R��`'�;�����PJA ���p�{ �RP�yG��b'�y#���LY�����-/���"���$��O��iI+.�LE����{���6����o�mp�(I�=�3Y(��&�M�
b�V_X�w��A��W�����q� ���� \��B����*c�����Vy���q��.����T^�j�C*�;������9S{pg����i)���#����9Rn7:l5����d�{����Q�3�����w�W��Z�z�Q����(F�[)�nQLfH�0x�6���u���k<�Fm)<�����)��w��:���5����WQ�(��Y����U�l����Y�c43��L��c=�t�'r��X)�`�|�t�JYL=1=$3�a��S���8��rL�S�:�/a�!����q�cFv)7wA(���!�P#M{Pk�5�P�U*�n?�F:��q�<����(�CvLp�� ;&8����?��g"X2�Q�o���UQ.���:m��j��y������M�f��MN���j�H��g�&���\m�&�n Q�/����i�+%��!IJ�k%�S�%�U�1���I;#f��ig�,�����y��I��q�EIA��9o��.�c>��<�Bf�!����������,L�����rG���>|��� ��;�����8�n(��fI����F����L�����Bx��R���u<�����zT�����^�����|���+xb*3W��Yx9��e��|�T�[����wob.�m�L�#�_z
&'��F� 9!���?���4}����y���@���>P[Q(m2���l+�����������
�k'�]\�V�M�/`-%^��
�\jz=����(����N��4����z�G������,��G/��%����,{�����%���)L]1{/�������b<��?%z�u�8��?�����b<i�<Q��4'��Y�I�p�����'J�f�da�~U"w
L�?,�Vb����-p���R��<���b+�u�0�N�_��1�U��5��\���P���
����NKX�xZ��y��������6��2���+/�++�.��*����k;(�&�_��� �z����G�W#vFd5���3"k����Y���C�����UH_�X}�|i���7�os�6��_Bu�P�B�����>�'�k���^e��T������ rvn?���q���&+6���Zq�Y\Z��5�;�805B�xM;�(������t���Fj�x���y;-��_������n-C�����)����b��� q�f� /����{J�S������k-\��Sk��������l�Sk�mo9�����WZ7��V.PZG��JA����f�:hAx��|�Z��^��o)����B�"�Nf+B��Q.(�����B��k�v>���2S;1�L���1RN�������y����\=V�����
���n"��N@��pb`��{1w:V�K��-�MCS���������D����R�?��P-����W�����T/�t�lJ�^LN�I�������)>i2z�!�8c����RR�pB8�\�n���C8�']�z����6���]��NVBPH��Y�{Y��=����*J��I��AWcF���u��H�C]��g���v>w����|�^��'���}"�G���{Dnh��!�7�#B���� 1_�� '�Ds��.��nSJtOmE�Z����ClfwA��e�����pa�{'��a@N<'uF=�����%�;X���Y�U���w�+���F�m��:H������+��Gkn�i�p�R���V�i�MF.K���l3��[I���Qk�����w��P�EO�U��e�]�_�%Wv����jn����z��uF���{�`�a��A���e��Y���c��Q���=�������vL|��zS,["��s9\���$�dU���R�-�����M� /����&�=���E ����kn��?�e��M� /�p�A���b8�w��o0i�C?��|��P�!@^<��|v��*)+OR* ��(5yP�@.I� +��Ji��G�H�(E��:�<x�R�n��i��6�ve��` 3�����-����6������2���T����
(6��!>}c�O��-7��B�I�a�_�{:[-�����w2���o_��d�~������8��a�;+7S����:��o�wb�f�?�
��7V[(����H
��l�����*F� ^P���{�M������~���q��Wf�2����j���r�L ta�p��N�Q�q���|zR����V�}h�R@�����v
O��v��g4@�RG�y������QBPg�N���i��5uU����6������Ff�e���U�A� +^�L.�~%P�u����3���!�*Q����8��f=d�XHf� ����q��������o�����m�r*6���Z������59���~���4����c;��u����0B^��m���$�;9�T ;M����S��SU�*��@Q0B��w�`��(��X�Ik��p4j�������h`d'����o�xi�P����H��d,FL����9�i]d"���Y�
�&kNS;C��=f�[w_�srt���3�~m��dKe���h�.�
��.���.W���?�E����U��-yw���p:t��}�W^l*���������G5!��d2\X�����m�dk���T���VeO�#�����+�;<�.x)��T���-��2��A-1���&3�|0��gu�j��.���{���/����'�� ���"�}F��b/�)1R�.���(A�e�}%�� �;� $3��v�,���F�
�s1�n)�����hxI���kk�B�i+?)�Ejjk�/����J �E�V=�57���N'��Cf�W��ZHanr�']��O�W�+�����<���������r(ssC>�9�'���G��t�wv0���N��^�������0�;��kav,v:g���V�t�n����� ���R�Xf/���\ff���Jd��n�4�$U�����CX���snU%�����������s����a�Z4�[wU��m�*����hE��D���{��^��^�L[��i�['��gd��Z�7�G�\��U0m#d\\����I�U��
uS��J�P%��qq��(?wS�:������ T��d\\#5���D�L�1�h#0��v����#T� +��N���2����?
iW����&�i:s1Q�s���n��3�K��t�b��*������$�M:s1Qu���!M��=��v5������:FKs�]EP[���166����]�r5)�fIu��F�T� �U,���>�`�����`c#�Aw�����:���, ��w7�t���
�x-��f�������*m���J�u'��:�>��l�=^eR�;�E(�������M����N��u���sjoSs������ i��c_|��f���*�W���~�Q��W����?��v��k���^CS�&�?������tFb �4������E�e8�� ����������Pm��^P'4��_69b�]J��10���0���"/yU7��5��0�ZO&��I���V�N�3����u��@�������M�sZ�z;�G���{��$m$�������]��&kDP7U^��"h����)�������j-�Mv�{����!n��\�k*/��E��/�_�d����*�#�����������������H�eH����K��9NM��ON
=�����vB�f������>�z,{�D��D��2(O�����6yuig�u���)���M=�o�q|��Fj���Xx���K;����Q�Xe�&#M�($I����F7�R�/�K�z)��F������y���Q�;f����a1vFp�0����T�S���s����g�k`���Z�F4�i��A�����2���@�5_^��-z�k1O����aQ��V�ZO��^����Z���"s����(^����|�`g%x ��o'%���o%�G?���S�c�}���K�L���� ���9���[���>k�6�����������N�6�o�����������9�x�����(��m�uS���0��H��`�0����r�C��OS������N����T�/?��������Q���^!2�����&����%�����U���Q5"d<\���n�12/E�F�4���
@5 �q��K���7�>��D�y
>��Ta�n��=f[�:���3v�SOJ�X���m8����W�l_��u��BmZ�z�������^������^Q���I���� �&J�^�
�O1T�2W��L���FW���U+�V�'���N`�q��+��8647�k{wU�^�����I�R�T@�6�P�#���]7�5`�n*�>���n����Z�X�-�qk\��i�������L�(P��}&��L����������+<A�rm�����w���w�_���?x�F�������h����z�{�/��@ddJ\���LV���G����g�c�x d�t������b� lR�H��������b]��jlT��Nz���Be�1�3!������b���yU�^�(}NR:8l�I�Ac��':�f"+���C{�����V���t������y4KU�T��3���Ub+f������@9>!?d�}Pn��;����X� �~�
���tH�����d�Dz&3�kO����TP���)�W����}�U_��2�S�����
1�#j����c]��m���
=�0������(��_��|�O����u��*�aN%�K��u6w�cI����m����z�}���"�h���,�
/���,�%j�� q{�>���w����K��]���s�XX��� ���T�����Q�{5�`�m�d�B]����/��>�E��o�7 ��������*����1
GZ�������fb3�� ���I�;,z#�7a��C7�j����
� E;�����=KK���������i���Dl��h���G;��i�B&�EDz�������}���W���������?�*��plh�+r��^�|zZ���C�u���|�[A�"plh����5G'T���G�Y4����wA}:�}_sU��l����Y-�O���S���b���M�\��c��m
�p�X��"
��G������3����������>n�m�����?��Z�Zv{]������}����vk�U���L=i��t$����E�=��IX��9��p����p)�����e����(��!M=3���oZ�b�������!1�H��]���po��F*; C��@���r�j�B��z�.O��b���3�q[�����0���Y������G��n��\E��-����"}�m���7����C�:�F��H��j�2�S�!B\��tl����0�O���|�C���l��[WR��H�����tE���\�l������y ��d����~����8\]6��}Z����j���� >F��}8��)?�A)��M0�i�h�*c�]�Aq���/�����~��
\-�����2�B;���>���Q��ug�Ct��9�����n����\|�7Q^�*�$ss�X��h��i/�����.�[C�����������%�~���zr�hs2�Du��
�:>���Qf�$^��
��R�dr����;�� �<} �S+U?���G����_=��[J� ��������'�{a���7���^��d��*]��t�}i^l�'~��� ����I�#�����l'�'�|�5b���7u��G��u�����GG���m0<�g��r��x>�*{�g���r��H�;d`~��4�����%�p.�b��(������*��F{wX��#��vxn�u�
:�\�X������NT>��H6�P��qGG�g]���Qk���U��ABg�B<����2\��$>������Z%��#I��)�����q�
�"���6��A>hr�=�Y�"�<���~9�Sm�s��j���"2�?��s���� �����������t���h����N��>u���0T^T ���l���M�@x6�u�^�72����P�<� �������^�J��)������k��m�����!�����/��~��>�4<��=���N��_?y��{��pW�y;
�������+�XK���&�����V�
�P=��M���O
�}����t��,�T)���>�,H,�z�d�(Jt���������h�g��;������w��Q������69n������"4�{,�������{��v-9���e�I4 P �3�=��o]pgXO�Ul�:,��p���deee���<��k� =`�GT��j�K�����~�UO�W3�j=@*FOy��Hq��TI�_���cp���L�J�����!6]<���9�����p�T6��;8��oT��J�}����o����"�_ ��x������xtN�.~jw�������]��6K
H{�jP���Q,u=Z�$���A����ab�w� ���:/:^�h�FP~�O������A��v��?|���?}�����O����qLW��c���|s>����:�d( �����y�i�
� �4p����s�r�|����'�����.:Du`S37m��|$�&��.J�P]!%���c����^���q-�������� ]S��@?��B�����n��{E*��X��Z>���i�x��k�k�����)bYw�s���V9���,s��L�9��2���h���`��N�����.ai���Z#c#�y��w���o�\�74��c�*f� �px�{C�}����P�Vq1��������Ab��)I�!�B�:�����FT���������?}����~�;�O���������G�b����,��� By!�����,:���6�E���&���RCC��0;,��������[�_������VO�R�"�?7��
��WI���0�HY�Ud�3�mM�-
���� b����o��O���'=3k����K[����M�*32E���Q!d�o2-I /D�.������������^�����~siIBY�!v����\g%��XNl ��NL[�
�#�H����������FY�#�H"4 2nG��ft����:IC9�l�uD�1;Al������������RM���#
���� b�v��F3�*��^��1.�_��b^nV���%��HO!D����A�D&3j������M�j����B��y��Dxpa���#5B����
��F�
���t}IB���)"�V$�X�6j|@��k���Xc9�����r�Q�C���(��D�1F��1v#Lshb��~9���,
�(k��>�,V��C��[�������4{����Qa��k����z��v�Q�:"��EZ��DXB�jt�7�����aVb����`Z&��8/!~�C��C\���j��=���h��p��,����S����Z�p)w[�u��*.�uV^��]�h�!�{�3 c�;)�(/���k4G9�[1(~�'.�K5B X��j�@��(� �@i1L���a�E�T#������
�H�R�{�.���m����m�>~��r$)�o�&V�p ��g\e���%&�]��F�����[4�D�0
�:�z�n�`T���4�41���I�'���\@#��Oy/M��� ����v�xH�RLl��&��y�`�l��^:o�����n�`�P ���O8����+���[�x=��p���s�
�r����I��fG�l���J���F�\�B�N��ms`T���|�:�z�F�v���U�6���H�VP%��nV����!�����}hBQy�L��^�p�*��
y���T�H�������-:?~�������x7;i�&����W��G��Bk:Ro��L�/e=�!|EX�]�F��^)� P����'7s���\D���)���*U��4
�[�� CE�s����/���$��3�2����{��z��Ab��vTa�d_��������?��6��2y2S��O
���7�Ol�����8
�lKs#"