]> begriffs open source - ai-pg/blob - full-docs/txt/plpgsql-declarations.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / plpgsql-declarations.txt
1
2 41.3. Declarations #
3
4    41.3.1. Declaring Function Parameters
5    41.3.2. ALIAS
6    41.3.3. Copying Types
7    41.3.4. Row Types
8    41.3.5. Record Types
9    41.3.6. Collation of PL/pgSQL Variables
10
11    All variables used in a block must be declared in the declarations
12    section of the block. (The only exceptions are that the loop variable
13    of a FOR loop iterating over a range of integer values is automatically
14    declared as an integer variable, and likewise the loop variable of a
15    FOR loop iterating over a cursor's result is automatically declared as
16    a record variable.)
17
18    PL/pgSQL variables can have any SQL data type, such as integer,
19    varchar, and char.
20
21    Here are some examples of variable declarations:
22 user_id integer;
23 quantity numeric(5);
24 url varchar;
25 myrow tablename%ROWTYPE;
26 myfield tablename.columnname%TYPE;
27 arow RECORD;
28
29    The general syntax of a variable declaration is:
30 name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | :=
31 | = } expression ];
32
33    The DEFAULT clause, if given, specifies the initial value assigned to
34    the variable when the block is entered. If the DEFAULT clause is not
35    given then the variable is initialized to the SQL null value. The
36    CONSTANT option prevents the variable from being assigned to after
37    initialization, so that its value will remain constant for the duration
38    of the block. The COLLATE option specifies a collation to use for the
39    variable (see Section 41.3.6). If NOT NULL is specified, an assignment
40    of a null value results in a run-time error. All variables declared as
41    NOT NULL must have a nonnull default value specified. Equal (=) can be
42    used instead of PL/SQL-compliant :=.
43
44    A variable's default value is evaluated and assigned to the variable
45    each time the block is entered (not just once per function call). So,
46    for example, assigning now() to a variable of type timestamp causes the
47    variable to have the time of the current function call, not the time
48    when the function was precompiled.
49
50    Examples:
51 quantity integer DEFAULT 32;
52 url varchar := 'http://mysite.com';
53 transaction_time CONSTANT timestamp with time zone := now();
54
55    Once declared, a variable's value can be used in later initialization
56    expressions in the same block, for example:
57 DECLARE
58   x integer := 1;
59   y integer := x + 1;
60
61 41.3.1. Declaring Function Parameters #
62
63    Parameters passed to functions are named with the identifiers $1, $2,
64    etc. Optionally, aliases can be declared for $n parameter names for
65    increased readability. Either the alias or the numeric identifier can
66    then be used to refer to the parameter value.
67
68    There are two ways to create an alias. The preferred way is to give a
69    name to the parameter in the CREATE FUNCTION command, for example:
70 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
71 BEGIN
72     RETURN subtotal * 0.06;
73 END;
74 $$ LANGUAGE plpgsql;
75
76    The other way is to explicitly declare an alias, using the declaration
77    syntax
78 name ALIAS FOR $n;
79
80    The same example in this style looks like:
81 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
82 DECLARE
83     subtotal ALIAS FOR $1;
84 BEGIN
85     RETURN subtotal * 0.06;
86 END;
87 $$ LANGUAGE plpgsql;
88
89 Note
90
91    These two examples are not perfectly equivalent. In the first case,
92    subtotal could be referenced as sales_tax.subtotal, but in the second
93    case it could not. (Had we attached a label to the inner block,
94    subtotal could be qualified with that label, instead.)
95
96    Some more examples:
97 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
98 DECLARE
99     v_string ALIAS FOR $1;
100     index ALIAS FOR $2;
101 BEGIN
102     -- some computations using v_string and index here
103 END;
104 $$ LANGUAGE plpgsql;
105
106
107 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
108 BEGIN
109     RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
110 END;
111 $$ LANGUAGE plpgsql;
112
113    When a PL/pgSQL function is declared with output parameters, the output
114    parameters are given $n names and optional aliases in just the same way
115    as the normal input parameters. An output parameter is effectively a
116    variable that starts out NULL; it should be assigned to during the
117    execution of the function. The final value of the parameter is what is
118    returned. For instance, the sales-tax example could also be done this
119    way:
120 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
121 BEGIN
122     tax := subtotal * 0.06;
123 END;
124 $$ LANGUAGE plpgsql;
125
126    Notice that we omitted RETURNS real — we could have included it, but it
127    would be redundant.
128
129    To call a function with OUT parameters, omit the output parameter(s) in
130    the function call:
131 SELECT sales_tax(100.00);
132
133    Output parameters are most useful when returning multiple values. A
134    trivial example is:
135 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
136 BEGIN
137     sum := x + y;
138     prod := x * y;
139 END;
140 $$ LANGUAGE plpgsql;
141
142 SELECT * FROM sum_n_product(2, 4);
143  sum | prod
144 -----+------
145    6 |    8
146
147    As discussed in Section 36.5.4, this effectively creates an anonymous
148    record type for the function's results. If a RETURNS clause is given,
149    it must say RETURNS record.
150
151    This also works with procedures, for example:
152 CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
153 BEGIN
154     sum := x + y;
155     prod := x * y;
156 END;
157 $$ LANGUAGE plpgsql;
158
159    In a call to a procedure, all the parameters must be specified. For
160    output parameters, NULL may be specified when calling the procedure
161    from plain SQL:
162 CALL sum_n_product(2, 4, NULL, NULL);
163  sum | prod
164 -----+------
165    6 |    8
166
167    However, when calling a procedure from PL/pgSQL, you should instead
168    write a variable for any output parameter; the variable will receive
169    the result of the call. See Section 41.6.3 for details.
170
171    Another way to declare a PL/pgSQL function is with RETURNS TABLE, for
172    example:
173 CREATE FUNCTION extended_sales(p_itemno int)
174 RETURNS TABLE(quantity int, total numeric) AS $$
175 BEGIN
176     RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
177                  WHERE s.itemno = p_itemno;
178 END;
179 $$ LANGUAGE plpgsql;
180
181    This is exactly equivalent to declaring one or more OUT parameters and
182    specifying RETURNS SETOF sometype.
183
184    When the return type of a PL/pgSQL function is declared as a
185    polymorphic type (see Section 36.2.5), a special parameter $0 is
186    created. Its data type is the actual return type of the function, as
187    deduced from the actual input types. This allows the function to access
188    its actual return type as shown in Section 41.3.3. $0 is initialized to
189    null and can be modified by the function, so it can be used to hold the
190    return value if desired, though that is not required. $0 can also be
191    given an alias. For example, this function works on any data type that
192    has a + operator:
193 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
194 RETURNS anyelement AS $$
195 DECLARE
196     result ALIAS FOR $0;
197 BEGIN
198     result := v1 + v2 + v3;
199     RETURN result;
200 END;
201 $$ LANGUAGE plpgsql;
202
203    The same effect can be obtained by declaring one or more output
204    parameters as polymorphic types. In this case the special $0 parameter
205    is not used; the output parameters themselves serve the same purpose.
206    For example:
207 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
208                                  OUT sum anyelement)
209 AS $$
210 BEGIN
211     sum := v1 + v2 + v3;
212 END;
213 $$ LANGUAGE plpgsql;
214
215    In practice it might be more useful to declare a polymorphic function
216    using the anycompatible family of types, so that automatic promotion of
217    the input arguments to a common type will occur. For example:
218 CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompa
219 tible)
220 RETURNS anycompatible AS $$
221 BEGIN
222     RETURN v1 + v2 + v3;
223 END;
224 $$ LANGUAGE plpgsql;
225
226    With this example, a call such as
227 SELECT add_three_values(1, 2, 4.7);
228
229    will work, automatically promoting the integer inputs to numeric. The
230    function using anyelement would require you to cast the three inputs to
231    the same type manually.
232
233 41.3.2. ALIAS #
234
235 newname ALIAS FOR oldname;
236
237    The ALIAS syntax is more general than is suggested in the previous
238    section: you can declare an alias for any variable, not just function
239    parameters. The main practical use for this is to assign a different
240    name for variables with predetermined names, such as NEW or OLD within
241    a trigger function.
242
243    Examples:
244 DECLARE
245   prior ALIAS FOR old;
246   updated ALIAS FOR new;
247
248    Since ALIAS creates two different ways to name the same object,
249    unrestricted use can be confusing. It's best to use it only for the
250    purpose of overriding predetermined names.
251
252 41.3.3. Copying Types #
253
254 name table.column%TYPE
255 name variable%TYPE
256
257    %TYPE provides the data type of a table column or a previously-declared
258    PL/pgSQL variable. You can use this to declare variables that will hold
259    database values. For example, let's say you have a column named user_id
260    in your users table. To declare a variable with the same data type as
261    users.user_id you write:
262 user_id users.user_id%TYPE;
263
264    It is also possible to write array decoration after %TYPE, thereby
265    creating a variable that holds an array of the referenced type:
266 user_ids users.user_id%TYPE[];
267 user_ids users.user_id%TYPE ARRAY[4];  -- equivalent to the above
268
269    Just as when declaring table columns that are arrays, it doesn't matter
270    whether you write multiple bracket pairs or specific array dimensions:
271    PostgreSQL treats all arrays of a given element type as the same type,
272    regardless of dimensionality. (See Section 8.15.1.)
273
274    By using %TYPE you don't need to know the data type of the structure
275    you are referencing, and most importantly, if the data type of the
276    referenced item changes in the future (for instance: you change the
277    type of user_id from integer to real), you might not need to change
278    your function definition.
279
280    %TYPE is particularly valuable in polymorphic functions, since the data
281    types needed for internal variables can change from one call to the
282    next. Appropriate variables can be created by applying %TYPE to the
283    function's arguments or result placeholders.
284
285 41.3.4. Row Types #
286
287 name table_name%ROWTYPE;
288 name composite_type_name;
289
290    A variable of a composite type is called a row variable (or row-type
291    variable). Such a variable can hold a whole row of a SELECT or FOR
292    query result, so long as that query's column set matches the declared
293    type of the variable. The individual fields of the row value are
294    accessed using the usual dot notation, for example rowvar.field.
295
296    A row variable can be declared to have the same type as the rows of an
297    existing table or view, by using the table_name%ROWTYPE notation; or it
298    can be declared by giving a composite type's name. (Since every table
299    has an associated composite type of the same name, it actually does not
300    matter in PostgreSQL whether you write %ROWTYPE or not. But the form
301    with %ROWTYPE is more portable.)
302
303    As with %TYPE, %ROWTYPE can be followed by array decoration to declare
304    a variable that holds an array of the referenced composite type.
305
306    Parameters to a function can be composite types (complete table rows).
307    In that case, the corresponding identifier $n will be a row variable,
308    and fields can be selected from it, for example $1.user_id.
309
310    Here is an example of using composite types. table1 and table2 are
311    existing tables having at least the mentioned fields:
312 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
313 DECLARE
314     t2_row table2%ROWTYPE;
315 BEGIN
316     SELECT * INTO t2_row FROM table2 WHERE ... ;
317     RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
318 END;
319 $$ LANGUAGE plpgsql;
320
321 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
322
323 41.3.5. Record Types #
324
325 name RECORD;
326
327    Record variables are similar to row-type variables, but they have no
328    predefined structure. They take on the actual row structure of the row
329    they are assigned during a SELECT or FOR command. The substructure of a
330    record variable can change each time it is assigned to. A consequence
331    of this is that until a record variable is first assigned to, it has no
332    substructure, and any attempt to access a field in it will draw a
333    run-time error.
334
335    Note that RECORD is not a true data type, only a placeholder. One
336    should also realize that when a PL/pgSQL function is declared to return
337    type record, this is not quite the same concept as a record variable,
338    even though such a function might use a record variable to hold its
339    result. In both cases the actual row structure is unknown when the
340    function is written, but for a function returning record the actual
341    structure is determined when the calling query is parsed, whereas a
342    record variable can change its row structure on-the-fly.
343
344 41.3.6. Collation of PL/pgSQL Variables #
345
346    When a PL/pgSQL function has one or more parameters of collatable data
347    types, a collation is identified for each function call depending on
348    the collations assigned to the actual arguments, as described in
349    Section 23.2. If a collation is successfully identified (i.e., there
350    are no conflicts of implicit collations among the arguments) then all
351    the collatable parameters are treated as having that collation
352    implicitly. This will affect the behavior of collation-sensitive
353    operations within the function. For example, consider
354 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
355 BEGIN
356     RETURN a < b;
357 END;
358 $$ LANGUAGE plpgsql;
359
360 SELECT less_than(text_field_1, text_field_2) FROM table1;
361 SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
362
363    The first use of less_than will use the common collation of
364    text_field_1 and text_field_2 for the comparison, while the second use
365    will use C collation.
366
367    Furthermore, the identified collation is also assumed as the collation
368    of any local variables that are of collatable types. Thus this function
369    would not work any differently if it were written as
370 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
371 DECLARE
372     local_a text := a;
373     local_b text := b;
374 BEGIN
375     RETURN local_a < local_b;
376 END;
377 $$ LANGUAGE plpgsql;
378
379    If there are no parameters of collatable data types, or no common
380    collation can be identified for them, then parameters and local
381    variables use the default collation of their data type (which is
382    usually the database's default collation, but could be different for
383    variables of domain types).
384
385    A local variable of a collatable data type can have a different
386    collation associated with it by including the COLLATE option in its
387    declaration, for example
388 DECLARE
389     local_a text COLLATE "en_US";
390
391    This option overrides the collation that would otherwise be given to
392    the variable according to the rules above.
393
394    Also, of course explicit COLLATE clauses can be written inside a
395    function if it is desired to force a particular collation to be used in
396    a particular operation. For example,
397 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
398 BEGIN
399     RETURN a < b COLLATE "C";
400 END;
401 $$ LANGUAGE plpgsql;
402
403    This overrides the collations associated with the table columns,
404    parameters, or local variables used in the expression, just as would
405    happen in a plain SQL command.