1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
|
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
-
- This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
- project.
-
- Copyright (C) 1998-2018 OpenLink Software
-
- This project is free software; you can redistribute it and/or modify it
- under the terms of the GNU General Public License as published by the
- Free Software Foundation; only version 2 of the License, dated June 1991.
-
- This program is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-
-->
<sect1 id="aggregates">
<title>Standard and User-Defined Aggregate Functions</title>
<para>In addition to whole set of standard SQL aggregate functions,
Virtuoso provides a method to create application-specific aggregate
functions to create complex data structures inside SQL queries.</para>
<para>
The most evident way to calculate some value that depend on number of rows of a table is to
write a stored procedure that opens a cursor, then fetches row after row in a loop and
repeatedly modifies some intermediate values ("accumulators") inside the loop.
When the fetch operation signals that there are no more data, a final result is calculated
from values of "accumulators"</para>
<para>
E.g. to find an average of all values in a table's column COL, one may open a cursor to fetch
values from the COL, then set two "accumulators" TOTAL and CNT to zero, then
fetch row after row adding 1 to CNT and adding current value of COL to TOTAL.
At the end of loop, an error should be signalled if CNT is zero, otherwise the result is
TOTAL divided by CNT.</para>
<para>
Obviously, a competent programmer will use built-in AVG() aggregate function inside a
single SELECT statement: the code is much more readable and
the use of aggregate reduces the overhead in filling in result-set and fetching from it.</para>
<para>
More important advantage of aggregate functions is the ability to process many groups of
records in parallel, performing one table scan instead of many. SQL optimizer may use
sophisticated heuristics to find the fastest way of doing a complex query with aggregates
but it cannot optimize the code of a stored procedure.</para>
<sect2 id="aggcreateaggrstmt1">
<title>Create Aggregate Statement</title>
<programlisting>
CREATE AGGREGATE aggregate_name (parameter, parameter ...) [ RETURNS data_type ]
FROM
init_procedure,
acc_procedure,
final_function
[, merge_procedure ]
parameter : parameter_type name data_type
parameter_type : IN | INOUT
</programlisting>
<para>
The create aggregate statement forces the SQL compiler to treat any call of
the declared aggregate_name as special routine similar to one used for built-in
aggregate functions, so the call produces a single value for resultset instead of
a separate value for every row of the resultset.</para>
<para>
Every occurrence of the aggregate_name in a select statement
creates an invisible "accumulator" column in resultset.
The value of "accumulator" is calculated by init_procedure,
then every row of data causes a call of acc_procedure that may modify
the "accumulator" then the call of final_function should
get data from "accumulator" and return the total result.</para>
<para>
The init_procedure must have one inout parameter and return nothing.
It should set the parameter to the required initial value of the "accumulator".
(The SQL query compiler will use the declared data type of the parameter as
the data type of the "accumulator" so no casting problem may occur)
equal to
</para>
<para>
The acc_procedure must have at least one inout parameter, one or more parameters of any sort and must return nothing.
It should get the previously calculated value of the "accumulator"
from its first parameter, calculate a new value and set the result back to the first parameter.
</para>
<para>
The final_function must have one in or inout parameter and return a value.
It should get the value of the "accumulator" from its parameter
and return the calculated result.
</para>
<para>
The optional merge_procedure must have two inout parameters that
accept values of two "accumulators".
If defined, it may be used by SQL optimizer to split the table scan into
two or more scans through parts of the table. When every 'children' scan
iterates some part of the table, a separate "accumulators"
is used for every part. merge_procedure gets two accumulators and
adds the content of the second accumulator to the content of the first.
If merge_procedure is not defined, no such tricky optimization is used.
This optimization is never tried if the database resides on less than four disks,
if the number of CPUs is less than four and if the query contains
any call of user-defined aggregate with no merge_procedure defined;
thus you will probably never need to write such a function.
</para>
<para>
The declaration of aggregate is persistent.
If create aggregate statement is successful the text is stored into the SYS_PROCEDURES table.
This table is read at startup so user-defined aggregates are thus always available for use
and need be defined only once.
</para>
</sect2>
<sect2 id="aggdropaggrstmt">
<title>Drop Aggregate Statement</title>
<programlisting>
DROP AGGREGATE aggregate_name
</programlisting>
<para>
The drop aggregate statement removes the declaration of aggregate_name from SYS_PROCEDURES table
but does not drop or change any declarations of functions previously listed in create aggregate
statement.
</para>
<para>
The syntax of the 'call' operator is the same for 'plain' and 'aggregate' functions.
If an aggregate name is used in the text of stored procedure before the aggregate is
actually created then it is compiled as plain function call and causes run-time errors.
In order to prevent such confusion, keyword AGGREGATE may be placed right before
the name of aggregate function.
</para>
</sect2>
<sect2 id="createaggrsam">
<title>Examples of User-Defined Aggregates</title>
<sect3 id="createaggruri">
<title>Aggregate for Composing URIs</title>
<para>
Consider a table USER_ATTRIBUTES that contains configuration data for users of some remote web-service.
Every user have a number of parameters that should be passed to that service as a part of
URI when HTTP PUT is used.
Every row of USER_ATTRIBUTES contain a name and a value of some parameter for some type of users.
</para>
<programlisting>
create table USER_ATTRIBUTES (
ID integer not null primary key,
ATTR_NAME varchar,
USER_TYPE char(4),
ATTR_VALUE varchar );
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (1, 'key1', 't1', 'val1');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (2, 'key3', 't1', 'val3');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (3, 'key4', 't1', 'val4');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (4, 'key5', 't2', 'val5');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (5, 'key6', 't2', 'val6');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (6, 'key2', 't1', 'val2');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (7, 'key8', 't3', 'val8');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (8, 'key7', 't2', 'val7');
insert into USER_ATTRIBUTES (ID, ATTR_NAME, USER_TYPE, ATTR_VALUE) values (9, 'key9', 't4', 'val9');
</programlisting>
<para>
The application contains number of places where the resulting URI for a user should be
calculated. The URI is either an empty string (if no attributes are set) or
a string that starts from '?' char and consists of tokens like "attribute_name=attribute_value"
delimited by "&" character.
</para>
<programlisting>
create function ATTR_URI_INIT (inout _env any)
{
_env := string_output(); -- The "accumulator" is a string session. Initially it is empty.
}
create function ATTR_URI_ACC (
inout _env any, -- The first parameter is used for passing "accumulator" value.
in _attrname varchar, -- Second parameter gets the value passed by first parameter of aggregate call.
in _attrvalue varchar ) -- Third parameter gets the value passed by second parameter of aggregate call.
{
if (_attrname is null) -- Attributes with NULL names should not affect the result.
return;
-- The non-NULL name of attribute is appended to "accumulator"
http ('&', _env);
http_url (_attrname, null, _env);
http ('=', _env);
if (_attrvalue is null) -- NULL values of attributes are not printed.
return;
-- The non-null value of attribute is appended to "accumulator"
http_url (_attrvalue, null, _env);
}
create function ATTR_URI_FINAL (inout _env any) returns varchar
{
declare _res varchar;
-- For empty groups in the resultset, the initialization may be bypassed
-- so the value of "accumulator" remains NULL.
-- Finalization function should always handle such case
-- by signalling an error (like built-in AVG function) or
-- by returning some default value (like this function)
if (_env is null)
return '';
_res := string_output_string (_env);
if (_res = '')
return '';
-- In nonempty lists of URI attributes, the first '&' should be replace with '?'
aset (_res, 0, 63);
return _res;
}
create aggregate ATTR_URI (in _key varchar, in _val varchar) returns varchar
from ATTR_URI_INIT, ATTR_URI_ACC, ATTR_URI_FINAL;
</programlisting>
<para>Now we are ready to run some tests. Let's try the typical case:</para>
<programlisting>
select ATTR_URI (ATTR_NAME, ATTR_VALUE) as URI from USER_ATTRIBUTES where USER_TYPE='t1';
URI
VARCHAR
_______________________________________________________________________________
?key1=val1&key2=val2&key3=val3&key4=val4
1 Rows. -- 0 msec.
</programlisting>
<para>Now let's try the case of empty set of rows to aggregate:</para>
<programlisting>
select ATTR_URI (ATTR_NAME, ATTR_VALUE) as URI from USER_ATTRIBUTES where USER_TYPE='nosuchtype';
URI
VARCHAR
_______________________________________________________________________________
1 Rows. -- 0 msec.
<para>OK, we've got an empty string. Now let's try the final case:</para>
select ATTR_URI (ATTR_NAME, NULL) as URI from USER_ATTRIBUTES;
URI
VARCHAR
_______________________________________________________________________________
?key1=&key2=&key3=&key4=&key5=&key6=&key7=&key8=&key9=
1 Rows. -- 0 msec.
</programlisting>
<para>
The created aggregate is very fast but unusable if intermediate results should
be saved in a temporary table. It may happen if the SQL statement contains
clauses such as DISTINCT, ORDER BY, GROUP BY, especially if the grouping columns
are not the first columns of the primary key, or if SQL optimizer thinks that
it is the fastest way to calculate a join.
The following version produces the same results and may work with grouping,
but may be a bit slower because concatenation of long strings is slower than
writing to a string session:
</para>
<programlisting>
create procedure ATTR_URI2_INIT (inout _env varchar)
{
_env := ''; -- The "accumulator" is a string. Initially it is empty.
}
create procedure ATTR_URI2_ACC (
inout _env varchar, in _attrname varchar, in _attrvalue varchar ){
if (_attrname is null)-- Attributes with NULL names should not affect the result.
return;
if (_attrvalue is null)-- NULL values of attributes are not printed.
_env := concat (_env, sprintf('&amp;%U', _attrname));
else -- The non-null value of attribute is appended to "accumulator"
_env := concat (_env, sprintf('&amp;%U=%U', _attrname, _attrvalue));
}
create function ATTR_URI2_FINAL (inout _env any) returns varchar
{
-- For empty groups in the result set, the initialization may be bypassed
-- so the value of "accumulator" remains NULL.
-- Finalization function should always handle such case
-- by signaling an error (like built-in AVG function) or
-- by returning some default value (like this function)
if (_env is null)
return '';
if (_env = '')
return '';
-- In nonempty lists of URI attributes, the first '&amp;' should be replace with '?'
aset (_env, 0, 63);
return _env;
}
create aggregate ATTR_URI2 (in _key varchar, in _val varchar) returns varchar
from ATTR_URI2_INIT, ATTR_URI2_ACC, ATTR_URI2_FINAL;
select ATTR_URI2 (ATTR_NAME, ATTR_VALUE) as URI from USER_ATTRIBUTES where USER_TYPE='t1'
URI
VARCHAR
_______________________________________________________________________________
?key1=val1&key3=val3&key4=val4&key2=val2
1 Rows. -- 0 msec.
select USER_TYPE, ATTR_URI2 (ATTR_NAME, ATTR_VALUE) as URI from USER_ATTRIBUTES group by USER_TYPE
USER_TYPE URI
VARCHAR VARCHAR
_______________________________________________________________________________
t2 ?key5=val5&key6=val6&key7=val7
t1 ?key1=val1&key3=val3&key4=val4&key2=val2
t4 ?key9=val9
t3 ?key8=val8
4 Rows. -- 0 msec.
</programlisting>
</sect3>
<sect3 id="createaggrxml">
<title>Aggregate for Composing XMLs</title>
<para>
Virtuoso offers variety of ways to place relational data into XML documents,
and two best of them are select statements with FOR XML clause and XML views.
But in some rare cases you may prefer to compose XML as an output of
plain select statement, e.g. to get a few percent faster code.
</para>
<para>
Among other things, the CREATE XML VIEW statement creates
set of Virtuoso/PL functions that return various XML trees.
Those functions use special 'node building' vectors to store intermediate results.
NODEBLD (which stands for 'Node Building vector') stores a partially built XML tree.
A xte_nodebld() function returns a new empty NODEBLD that may be converted into an
element of XML tree in the future.
xte_nodebld_acc() appends new children to an existing NODEBLD.
xte_node_from_nodebld() converts NODEBLD into ready-to-use XML tree.
xte_nodebld_final() may work either as xte_node_from_nodebld() or
as a finalization function of user defined aggregate.
</para>
<programlisting>
create aggregate XTE_NODEBLD (in _child any) returns any
from xte_nodebld_init, xte_nodebld_acc, xte_nodebld_final;
</programlisting>
<para>
The use of this aggregate is not as easy as creating XML views, but
it avoids creating persistent objects:
</para>
<programlisting>
select
xml_tree_doc (
xte_node_from_nodebld (
xte_head ('UserAttributes'),
XTE_NODEBLD (
xte_node (xte_head ('Row', 'Id', ID, 'UserType', USER_TYPE),
xte_node (xte_head ('Attr', 'Name', ATTR_NAME),
ATTR_VALUE ) )
) ) )
from USER_ATTRIBUTES;
callret
VARCHAR
_______________________________________________________________________________
<![CDATA[<UserAttributes>
<Row Id="1" UserType="t1"><Attr Name="key1">val1</Attr></Row>
<Row Id="2" UserType="t1"><Attr Name="key2">val2</Attr></Row>
<Row Id="3" UserType="t1"><Attr Name="key3">val3</Attr></Row>
<Row Id="4" UserType="t1"><Attr Name="key4">val4</Attr></Row>
<Row Id="5" UserType="t2"><Attr Name="key5">val5</Attr></Row>
<Row Id="6" UserType="t2"><Attr Name="key6">val6</Attr></Row>
<Row Id="7" UserType="t2"><Attr Name="key7">val7</Attr></Row>
<Row Id="8" UserType="t3"><Attr Name="key8">val8</Attr></Row>
<Row Id="9" UserType="t4"><Attr Name="key9">val9</Attr></Row>
</UserAttributes>]]>
1 Rows. -- 0 msec.
</programlisting>
<para>The function xml_tree_doc() is used because there is no standard way to
print an XML tree without making a complete XML entity whose underlying XML
document consists of the given XML tree.</para>
<programlisting>
select
xml_tree_doc (
xte_node_from_nodebld (
xte_head ('AttrStatistics'),
XTE_NODEBLD (
xte_node (xte_head ('Row', 'UserType', groups.type, 'AttrCount', groups.cnt))
) ) )
from
(select USER_TYPE as type, COUNT (*) as cnt from USER_ATTRIBUTES group by USER_TYPE) groups;
callret
VARCHAR
_______________________________________________________________________________
<![CDATA[<AttrStatistics>
<Row UserType="t2" AttrCount="3" />
<Row UserType="t1" AttrCount="4" />
<Row UserType="t4" AttrCount="1" />
<Row UserType="t3" AttrCount="1" />
</AttrStatistics>]]>
1 Rows. -- 0 msec.
</programlisting>
</sect3>
</sect2>
</sect1>
|