Passing composite-type arguments

A composite-type, such as a table, or a user-defined type is passed to the PL/Tcl function as an associative array (Hash table). The attribute names of the composite-type are the element names in the array. Attributes with NULL values are not available in the Tcl array.

Let's take a look at an arbitrary example. We will create a function that takes a composite type as an argument and does some calculations based on the attribute values of the type. Let's create our type and the function:

CREATE TABLE orders(orderid int, num_people integer, order_amount decimal);

INSERT INTO orders VALUES(1,1,23);
INSERT INTO orders VALUES(2,3,157);
INSERT INTO orders VALUES(3,5,567.25);
INSERT INTO orders VALUES(4,1,100);

CREATE OR REPLACE FUNCTION tip_calculator(orders, integer) RETURNS decimal
AS $$
  if {$1(order_amount) > 0} {
    set tip [expr (double($1(order_amount) * $2)/100)/$1(num_people)]
    set tip [format "%.2f" $tip]
    return $tip
  }
  return 0;
$$ LANGUAGE pltcl;

The orders table is quite simple to understand: it contains an order ID, the number of people in the orders table (num_people), and the total cost of the order (order_amount).

The function calculates the tip per person, based on the price of the meal (order_amount) and number of people. It takes an argument of the type orders and an integer value that represent the percentage of the tip that should be paid.

The function body calculates the tip and formats the result to two decimal places. If we run our function, this is what we should see:

postgres=# SELECT tip_calculator(orders.*,5) AS "tip per person" FROM orders;
 tip per person 
----------------
      1.15
      2.62
      5.67
      5.00
(4 rows)

You can see that all the attributes of the orders type can be accessed in the function as $1(order_amount), $1(num_people), and so on. This function gets called once for each row of the orders table and calculates the amount of the tip to be paid per person for each order, according to various parameters.

Note

You can see the full list of associative array commands in the official documentation for Tcl at http://www.tcl.tk/man/tcl8.5/tutorial/Tcl22.html.

At this moment, PL/Tcl functions don't allow the returning of a SETOF type, or composite type, from a function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.9.7