]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_function.sgml
Privileges on functions and procedural languages
[postgresql] / doc / src / sgml / ref / create_function.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/ref/create_function.sgml,v 1.31 2002/02/18 23:11:02 petere Exp $
3 -->
4
5 <refentry id="SQL-CREATEFUNCTION">
6  <refmeta>
7   <refentrytitle id="SQL-CREATEFUNCTION-TITLE">CREATE FUNCTION</refentrytitle>
8   <refmiscinfo>SQL - Language Statements</refmiscinfo>
9  </refmeta>
10
11  <refnamediv>
12   <refname>CREATE FUNCTION</refname>
13   <refpurpose>define a new function</refpurpose>
14  </refnamediv>
15
16  <refsynopsisdiv>
17 <synopsis>
18 CREATE [ OR REPLACE ] FUNCTION <replaceable class="parameter">name</replaceable> ( [ <replaceable class="parameter">argtype</replaceable> [, ...] ] )
19     RETURNS <replaceable class="parameter">rettype</replaceable>
20     AS '<replaceable class="parameter">definition</replaceable>'
21     LANGUAGE <replaceable class="parameter">langname</replaceable>
22     [ WITH ( <replaceable class="parameter">attribute</replaceable> [, ...] ) ]
23 CREATE [ OR REPLACE ] FUNCTION <replaceable class="parameter">name</replaceable> ( [ <replaceable class="parameter">argtype</replaceable> [, ...] ] )
24     RETURNS <replaceable class="parameter">rettype</replaceable>
25     AS '<replaceable class="parameter">obj_file</replaceable>', '<replaceable class="parameter">link_symbol</replaceable>'
26     LANGUAGE <replaceable class="parameter">langname</replaceable>
27     [ WITH ( <replaceable class="parameter">attribute</replaceable> [, ...] ) ]
28 </synopsis>
29  </refsynopsisdiv>
30   
31  <refsect1 id="sql-createfunction-description">
32   <title>Description</title>
33
34   <para>
35    <command>CREATE FUNCTION</command> defines a new function.
36    <command>CREATE OR REPLACE FUNCTION</command> will either create
37    a new function, or replace an existing definition.
38
39    <variablelist>
40     <title>Parameters</title>
41
42     <varlistentry>
43      <term><replaceable class="parameter">name</replaceable></term>
44
45      <listitem>
46       <para>
47        The name of a function to create.  The name need not be unique,
48        because functions may be overloaded, but functions with the
49        same name must have different argument types.
50       </para>
51      </listitem>
52     </varlistentry>
53
54     <varlistentry>
55      <term><replaceable class="parameter">argtype</replaceable></term>
56
57      <listitem>
58       <para>
59        The data type(s) of the function's arguments, if any.  The
60        input types may be base or complex types,
61        <literal>opaque</literal>, or the same as the type of an
62        existing column.  <literal>Opaque</literal> indicates
63        that the function accepts arguments of a non-SQL type such as
64        <type>char *</type>.
65         The type of a column is indicated using <replaceable
66         class="parameter">tablename</replaceable>.<replaceable
67         class="parameter">columnname</replaceable><literal>%TYPE</literal>;
68         using this can sometimes help make a function independent from
69         changes to the definition of a table.
70       </para>
71      </listitem>
72     </varlistentry>
73
74     <varlistentry>
75      <term><replaceable class="parameter">rettype</replaceable></term>
76
77      <listitem>
78       <para>
79        The return data type.  The output type may be specified as a
80        base type, complex type, <literal>setof</literal> type,
81        <literal>opaque</literal>, or the same as the type of an
82        existing column.
83        The <literal>setof</literal>
84        modifier indicates that the function will return a set of
85        items, rather than a single item.  Functions with a declared
86        return type of <literal>opaque</literal> do not return a value.
87        These cannot be called directly; trigger functions make use of
88        this feature.
89       </para>
90      </listitem>
91     </varlistentry>
92
93     <varlistentry>
94      <term><replaceable class="parameter">definition</replaceable></term>
95
96      <listitem>
97       <para>
98        A string defining the function; the meaning depends on the
99        language.  It may be an internal function name, the path to an
100        object file, an SQL query, or text in a procedural language.
101       </para>
102      </listitem>
103     </varlistentry>
104
105     <varlistentry>
106      <term><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></term>
107
108      <listitem>
109       <para>
110        This form of the <literal>AS</literal> clause is used for
111        dynamically linked C language functions when the function name
112        in the C language source code is not the same as the name of
113        the SQL function. The string <replaceable
114        class="parameter">obj_file</replaceable> is the name of the
115        file containing the dynamically loadable object, and
116        <replaceable class="parameter">link_symbol</replaceable> is the
117        object's link symbol, that is, the name of the function in the C
118        language source code.
119       </para>
120      </listitem>
121     </varlistentry>
122
123     <varlistentry>
124      <term><replaceable class="parameter">langname</replaceable></term>
125
126      <listitem>
127       <para>
128        May be <literal>SQL</literal>, <literal>C</literal>,
129        <literal>internal</literal>, or <replaceable
130        class="parameter">plname</replaceable>, where <replaceable
131        class="parameter">plname</replaceable> is the name of a
132        created procedural language. See
133        <xref linkend="sql-createlanguage" endterm="sql-createlanguage-title">
134        for details.  For backward compatibility, the name may be
135        enclosed by single quotes.
136       </para>
137      </listitem>
138     </varlistentry>
139
140     <varlistentry>
141      <term><replaceable class="parameter">attribute</replaceable></term>
142
143      <listitem>
144       <para>
145        An optional piece of information about the function, used for
146        optimization.  See below for details.
147       </para>
148      </listitem>
149     </varlistentry>
150
151    </variablelist>
152   </para>
153
154   <para>
155    The user that creates the function becomes the owner of the function.
156   </para>
157
158   <para>
159     The following attributes may appear in the WITH clause:
160
161     <variablelist>
162      <varlistentry>
163       <term>iscachable</term>
164       <listitem>
165        <para>
166         <option>Iscachable</option> indicates that the function always
167         returns the same result when given the same argument values (i.e.,
168         it does not do database lookups or otherwise use information not
169         directly present in its parameter list).  The optimizer uses
170         <option>iscachable</option> to know whether it is safe to
171         pre-evaluate a call of the function.
172        </para>
173       </listitem>
174      </varlistentry>
175
176      <varlistentry>
177       <term>isstrict</term>
178       <listitem>
179        <para>
180         <option>isstrict</option> indicates that the function always
181         returns NULL whenever any of its arguments are NULL.  If this
182         attribute is specified, the function is not executed when there
183         are NULL arguments; instead a NULL result is assumed automatically.
184         When <option>isstrict</option> is not specified, the function will
185         be called for NULL inputs.  It is then the function author's
186         responsibility to check for NULLs if necessary and respond
187         appropriately.
188        </para>
189       </listitem>
190      </varlistentry>
191     </variablelist>
192   </para>
193
194  </refsect1>
195
196  <refsect1 id="sql-createfunction-notes">
197   <title>Notes</title>
198
199    <para>
200     Refer to the chapter in the
201     <citetitle>PostgreSQL Programmer's Guide</citetitle>
202     on the topic of extending
203     <productname>PostgreSQL</productname> via functions 
204     for further information on writing external functions.
205    </para>
206
207    <para>
208     The full <acronym>SQL</acronym> type syntax is allowed for
209     input arguments and return value. However, some details of the
210     type specification (e.g., the precision field for
211     <type>numeric</type> types) are the responsibility of the
212     underlying function implementation and are silently swallowed
213     (i.e., not recognized or
214     enforced) by the <command>CREATE FUNCTION</command> command.
215    </para>
216
217    <para>
218     <productname>PostgreSQL</productname> allows function <firstterm>overloading</firstterm>;
219     that is, the same name can be used for several different functions
220     so long as they have distinct argument types.  This facility must
221     be used with caution for internal and C-language functions, however.    
222    </para>
223
224    <para>
225     Two <literal>internal</literal>
226     functions cannot have the same C name without causing
227     errors at link time.  To get around that, give them different C names
228     (for example, use the argument types as part of the C names), then
229     specify those names in the AS clause of <command>CREATE FUNCTION</command>.
230     If the AS clause is left empty, then <command>CREATE FUNCTION</command>
231     assumes the C name of the function is the same as the SQL name.
232    </para>
233
234    <para>
235     Similarly, when overloading SQL function names with multiple C-language
236     functions, give
237     each C-language instance of the function a distinct name, then use
238     the alternative form of the <command>AS</command> clause in the
239     <command>CREATE FUNCTION</command> syntax to select the appropriate
240     C-language implementation of each overloaded SQL function.
241    </para>
242
243    <para>
244     When repeated <command>CREATE FUNCTION</command> calls refer to
245     the same object file, the file is only loaded once.  To unload and
246     reload the file (perhaps during development), use the <xref
247     linkend="sql-load" endterm="sql-load-title"> command.
248    </para>
249
250    <para>
251     Use <command>DROP FUNCTION</command>
252     to remove user-defined functions.
253    </para>
254
255    <para>
256     To update the definition of an existing function, use
257     <command>CREATE OR REPLACE FUNCTION</command>.  Note that it is
258     not possible to change the name or argument types of a function
259     this way (if you tried, you'd just be creating a new, distinct
260     function).  Also, <command>CREATE OR REPLACE FUNCTION</command>
261     will not let you change the return type of an existing function.
262     To do that, you must drop and re-create the function.
263    </para>
264
265    <para>
266     If you drop and then re-create a function, the new function is not
267     the same entity as the old; you will break existing rules, views,
268     triggers, etc that referred to the old function.  Use 
269     <command>CREATE OR REPLACE FUNCTION</command> to change a function
270     definition without breaking objects that refer to the function.
271    </para>
272
273   <para>
274    To be able to define a function, the user must have the
275    <literal>USAGE</literal> privilege on the language.
276   </para>
277
278   <para>
279    By default, only the owner (creator) of the function has the right
280    to execute it.  Other users must be granted the
281    <literal>EXECUTE</literal> privilege on the function to be able to
282    use it.
283   </para>
284  </refsect1>
285
286   
287  <refsect1 id="sql-createfunction-examples">
288   <title>Examples</title>
289
290   <para>
291    To create a simple SQL function:
292
293 <programlisting>
294 CREATE FUNCTION one() RETURNS integer
295     AS 'SELECT 1 AS RESULT;'
296     LANGUAGE SQL;
297
298 SELECT one() AS answer;
299 <computeroutput>
300  answer 
301 --------
302       1
303 </computeroutput>
304 </programlisting>
305   </para>
306
307   <para>
308    The next example creates a C function by calling a routine from a
309    user-created shared library named <filename>funcs.so</> (the extension
310    may vary across platforms).  The shared library file is sought in the
311    server's dynamic library search path.  This particular routine calculates
312    a check digit and returns TRUE if the check digit in the function
313    parameters is correct.  It is intended for use in a CHECK
314    constraint.
315
316 <programlisting>
317 CREATE FUNCTION ean_checkdigit(char, char) RETURNS boolean
318     AS 'funcs' LANGUAGE C;
319     
320 CREATE TABLE product (
321     id        char(8) PRIMARY KEY,
322     eanprefix char(8) CHECK (eanprefix ~ '[0-9]{2}-[0-9]{5}')
323                       REFERENCES brandname(ean_prefix),
324     eancode   char(6) CHECK (eancode ~ '[0-9]{6}'),
325     CONSTRAINT ean    CHECK (ean_checkdigit(eanprefix, eancode))
326 );
327 </programlisting>
328   </para>
329
330   <para>
331    This example creates a function that does type conversion between the
332    user-defined type complex, and the internal type point.  The
333    function is implemented by a dynamically loaded object that was
334    compiled from C source (we illustrate the now-deprecated alternative
335    of specifying the exact pathname to the shared object file).
336    For <productname>PostgreSQL</productname> to
337    find a type conversion function automatically, the SQL function has
338    to have the same name as the return type, and so overloading is
339    unavoidable.  The function name is overloaded by using the second
340    form of the <command>AS</command> clause in the SQL definition:
341
342 <programlisting>
343 CREATE FUNCTION point(complex) RETURNS point
344     AS '/home/bernie/pgsql/lib/complex.so', 'complex_to_point'
345     LANGUAGE C;
346 </programlisting>
347
348   The C declaration of the function could be:
349
350 <programlisting>
351 Point * complex_to_point (Complex *z)
352 {
353         Point *p;
354
355         p = (Point *) palloc(sizeof(Point));
356         p->x = z->x;
357         p->y = z->y;
358                 
359         return p;
360 }
361 </programlisting>
362   </para>    
363  </refsect1>
364
365  
366  <refsect1 id="sql-createfunction-compat">
367   <title>Compatibility</title>
368
369   <para>
370    A <command>CREATE FUNCTION</command> command is defined in SQL99.
371    The <application>PostgreSQL</application> version is similar but
372    not compatible.  The attributes are not portable, neither are the
373    different available languages.
374   </para>
375  </refsect1>
376
377
378  <refsect1 id="sql-createfunction-seealso">
379   <title>See Also</title>
380
381   <para>
382    <xref linkend="sql-dropfunction">,
383    <xref linkend="sql-grant">,
384    <xref linkend="sql-load">,
385    <xref linkend="sql-revoke">,
386    <citetitle>PostgreSQL Programmer's Guide</citetitle>
387   </para>
388  </refsect1>
389
390 </refentry>
391
392 <!-- Keep this comment at the end of the file
393 Local variables:
394 mode:sgml
395 sgml-omittag:nil
396 sgml-shorttag:t
397 sgml-minimize-attributes:nil
398 sgml-always-quote-attributes:t
399 sgml-indent-step:1
400 sgml-indent-data:t
401 sgml-parent-document:nil
402 sgml-default-dtd-file:"../reference.ced"
403 sgml-exposed-tags:nil
404 sgml-local-catalogs:("/usr/lib/sgml/catalog")
405 sgml-local-ecat-files:nil
406 End:
407 -->