sqlite_create_aggregate

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
Register an aggregating UDF for use in SQL statements
void sqlite_create_aggregate ( resource $dbhandle, string $function_name, callable $step_func, callable $finalize_func [, int $num_args = -1 ] )

Object oriented style (method):

public void SQLiteDatabase::createAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] )

sqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parameters:
dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Function parameters are &$context, $value, ....

finalize_func

Callback function to aggregate the "stepped" data from each row. Function parameter is &$context and the function should return the final result of aggregation.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Returns:

No value is returned.

Examples:
max_length aggregation function example
<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string) 
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context) 
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?>

See also:

sqlite_create_function() -

sqlite_udf_encode_binary() -

sqlite_udf_decode_binary() -

doc_php
2016-02-24 16:18:26
Comments
Leave a Comment

Please login to continue.