]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_function.sgml
df643cd8e8b87ac50904f3292a216bdec4a6e891
[postgresql] / doc / src / sgml / ref / create_function.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/ref/create_function.sgml,v 1.30 2001/12/08 03:24:34 thomas 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  </refsect1>
274
275   
276  <refsect1 id="sql-createfunction-examples">
277   <title>Examples</title>
278
279   <para>
280    To create a simple SQL function:
281
282 <programlisting>
283 CREATE FUNCTION one() RETURNS integer
284     AS 'SELECT 1 AS RESULT;'
285     LANGUAGE SQL;
286
287 SELECT one() AS answer;
288 <computeroutput>
289  answer 
290 --------
291       1
292 </computeroutput>
293 </programlisting>
294   </para>
295
296   <para>
297    The next example creates a C function by calling a routine from a
298    user-created shared library named <filename>funcs.so</> (the extension
299    may vary across platforms).  The shared library file is sought in the
300    server's dynamic library search path.  This particular routine calculates
301    a check digit and returns TRUE if the check digit in the function
302    parameters is correct.  It is intended for use in a CHECK
303    constraint.
304
305 <programlisting>
306 CREATE FUNCTION ean_checkdigit(char, char) RETURNS boolean
307     AS 'funcs' LANGUAGE C;
308     
309 CREATE TABLE product (
310     id        char(8) PRIMARY KEY,
311     eanprefix char(8) CHECK (eanprefix ~ '[0-9]{2}-[0-9]{5}')
312                       REFERENCES brandname(ean_prefix),
313     eancode   char(6) CHECK (eancode ~ '[0-9]{6}'),
314     CONSTRAINT ean    CHECK (ean_checkdigit(eanprefix, eancode))
315 );
316 </programlisting>
317   </para>
318
319   <para>
320    This example creates a function that does type conversion between the
321    user-defined type complex, and the internal type point.  The
322    function is implemented by a dynamically loaded object that was
323    compiled from C source (we illustrate the now-deprecated alternative
324    of specifying the exact pathname to the shared object file).
325    For <productname>PostgreSQL</productname> to
326    find a type conversion function automatically, the SQL function has
327    to have the same name as the return type, and so overloading is
328    unavoidable.  The function name is overloaded by using the second
329    form of the <command>AS</command> clause in the SQL definition:
330
331 <programlisting>
332 CREATE FUNCTION point(complex) RETURNS point
333     AS '/home/bernie/pgsql/lib/complex.so', 'complex_to_point'
334     LANGUAGE C;
335 </programlisting>
336
337   The C declaration of the function could be:
338
339 <programlisting>
340 Point * complex_to_point (Complex *z)
341 {
342         Point *p;
343
344         p = (Point *) palloc(sizeof(Point));
345         p->x = z->x;
346         p->y = z->y;
347                 
348         return p;
349 }
350 </programlisting>
351   </para>    
352  </refsect1>
353
354  
355  <refsect1 id="sql-createfunction-compat">
356   <title>Compatibility</title>
357
358   <para>
359    A <command>CREATE FUNCTION</command> command is defined in SQL99.
360    The <application>PostgreSQL</application> version is similar but
361    not compatible.  The attributes are not portable, neither are the
362    different available languages.
363   </para>
364  </refsect1>
365
366
367  <refsect1 id="sql-createfunction-seealso">
368   <title>See Also</title>
369
370   <para>
371    <xref linkend="sql-dropfunction">,
372    <xref linkend="sql-load">,
373    <citetitle>PostgreSQL Programmer's Guide</citetitle>
374   </para>
375  </refsect1>
376
377 </refentry>
378
379 <!-- Keep this comment at the end of the file
380 Local variables:
381 mode:sgml
382 sgml-omittag:nil
383 sgml-shorttag:t
384 sgml-minimize-attributes:nil
385 sgml-always-quote-attributes:t
386 sgml-indent-step:1
387 sgml-indent-data:t
388 sgml-parent-document:nil
389 sgml-default-dtd-file:"../reference.ced"
390 sgml-exposed-tags:nil
391 sgml-local-catalogs:("/usr/lib/sgml/catalog")
392 sgml-local-ecat-files:nil
393 End:
394 -->