NAME
SQL::Statement::Functions - built-in & user-defined SQL functions
SYNOPSIS
SELECT Func(args);
SELECT * FROM Func(args);
SELECT * FROM x WHERE Funcs(args);
SELECT * FROM x WHERE y < Funcs(args);
|
DESCRIPTION
This module contains the built-in functions for SQL::Parser and SQL::Statement. All of the functions are also available in any DBDs that subclass those modules (e.g. DBD::CSV, DBD::DBM, DBD::File, DBD::AnyData, DBD::Excel, etc.).
This documentation covers built-in functions and also explains how to create your own functions to supplement the built-in ones. It's easy. If you create one that is generally useful, see below for how to submit it to become a built-in function.
Function syntax
When using SQL::Statement/SQL::Parser directly to parse SQL, functions (either built-in or user-defined) may occur anywhere in a SQL statement that values, column names, table names, or predicates may occur. When using the modules through a DBD or in any other context in which the SQL is both parsed and executed, functions can occur in the same places except that they can not occur in the column selection clause of a SELECT statement that contains a FROM clause.
SELECT MyFunc(args);
SELECT * FROM MyFunc(args);
SELECT * FROM x WHERE MyFuncs(args);
SELECT * FROM x WHERE y < MyFuncs(args);
SELECT MyFunc(args) FROM x WHERE y;
|
User-Defined Functions
Loading User-Defined Functions
In addition to the built-in functions, you can create any number of your own user-defined functions (UDFs). In order to use a UDF in a script, you first have to create a perl subroutine (see below), then you need to make the function available to your database handle with the CREATE FUNCTION or LOAD commands:
$dbh -> do ( " CREATE FUNCTION foo EXTERNAL " );
$dbh -> do ( " CREATE FUNCTION foo EXTERNAL NAME bar" );
$dbh -> do ( ' CREATE FUNCTION foo EXTERNAL NAME "Bar::Baz::foo" ' );
$dbh -> do ( ' LOAD "Bar::Baz" ' );
|
Functions themselves should follow SQL identifier naming rules. Subroutines loaded with CREATE FUNCTION can have any valid perl subroutine name. Subroutines loaded with LOAD must start with SQL_FUNCTION_ and then the actual function name. For example:
sub SQL_FUNCTION_FOO { ... }
sub SQL_FUNCTION_BAR { ... }
sub some_other_perl_subroutine_not_a_function { ... }
1;
$dbh -> do ( "LOAD Qux::Quimble" );
|
Creating User-Defined Functions
User-defined functions (UDFs) are perl subroutines that return values appropriate to the context of the function in a SQL statement. For example the built-in CURRENT_TIME returns a string value and therefore may be used anywhere in a SQL statement that a string value can. Here' the entire perl code for the function:
sub SQL_FUNCTION_CURRENT_TIME {
sprintf "%02s::%02s::%02s" ,( localtime )[2,1,0]
}
|
More complex functions can make use of a number of arguments always passed to functions automatically. Functions always receive these values in @_:
sub FOO {
my ( $self , $sth , @params );
}
|
The first argument, $self, is whatever class the function is defined in, not generally useful unless you have an entire module to support the function.
The second argument, $sth is the active statement handle of the current statement. Like all active statement handles it contains the current database handle in the {Database} attribute so you can have access to the database handle in any function:
sub FOO {
my ( $self , $sth , @params );
my $dbh = $sth ->{Database};
}
|
In actual practice you probably want to use $sth->{Database} directly rather than making a local copy, so $sth->{Database}->do(...).
The remaining arguments, @params, are arguments passed by users to the function, either directly or with placeholders; another silly example which just returns the results of multiplying the arguments passed to it:
sub MULTIPLY {
my ( $self , $sth , @params );
return $params [0] * $params [1];
}
$dbh -> do ( "CREATE FUNCTION MULTIPLY" );
my $sth = $dbh ->prepare( "SELECT col1 FROM tbl1 WHERE col2 = MULTIPLY(col3,7)" );
$sth ->execute;
my $sth = $dbh ->prepare( "SELECT col1 FROM tbl1 WHERE col2 = MULTIPLY(col3,?)" );
$sth ->execute(7);
|
Creating In-Memory Tables with functions
A function can return almost anything, as long is it is an appropriate return for the context the function will be used in. In the special case of table-returning functions, the function should return a reference to an array of array references with the first row being the column names and the remaining rows the data. For example:
1. create a function that returns an AoA,
sub Japh {[
[ qw( id word ) ],
[ qw( 1 Hacker ) ],
[ qw( 2 Perl ) ],
[ qw( 3 Another ) ],
[ qw( 4 Just ) ],
]}
|
2. make your database handle aware of the function
$dbh -> do ("CREATE FUNCTION 'Japh' );
|
3. Access the data in the AoA from SQL
$sth = $dbh ->prepare( "SELECT word FROM Japh ORDER BY id DESC" );
|
Or here's an example that does a join on two in-memory tables:
sub Prof {[ [ qw(pid pname) ],[ qw(1 Sue ) ],[ qw(2 Bob) ],[ qw(3 Tom ) ] ]}
sub Class {[ [ qw(pid cname) ],[ qw(1 Chem) ],[ qw(2 Bio) ],[ qw(2 Math) ] ]}
$dbh -> do ("CREATE FUNCTION $_ ) for qw(Prof Class) ;
$sth = $dbh ->prepare( "SELECT * FROM Prof NATURAL JOIN Class" );
|
The "Prof" and "Class" functions return tables which can be used like any SQL table.
More complex functions might do something like scrape an RSS feed, or search a file system and put the results in AoA. For example, to search a directory with SQL:
sub Dir {
my ( $self , $sth , $dir )= @_ ;
opendir D, $dir or die "'$dir':$!" ;
my @files = readdir D;
my $data = [[ qw(fileName fileExt) ]];
for ( @files ) {
my ( $fn , $ext ) = /^(.*)(\.[^\.]+)$/;
push @$data , [ $fn , $ext ];
}
return $data ;
}
$dbh -> do ( "CREATE FUNCTION Dir" );
printf "%s\n" , join ' ' ,@{ $dbh ->selectcol_arrayref("
SELECT fileName FROM Dir( './' ) WHERE fileExt = '.pl'
")};
|
Obviously, that function could be expanded with File::Find and/or stat to provide more information and it could be made to accept a list of directories rather than a single directory.
Table-Returning functions are a way to turn *anything* that can be modeled as an AoA into a DBI data source.
Built-in Functions
SQL-92/ODBC Compatibility
All ODBC 3.0 functions are available except for the following:
ODBC 3.0 functions that are implemented with differences include:
Aggregate Functions
MIN, MAX, AVG, SUM, COUNT
Aggregate functions are handled elsewhere, see SQL::Parser for documentation.
Date and Time Functions
These functions can be used without parentheses.
CURRENT_DATE aka CURDATE
CURRENT_TIME aka CURTIME
CURRENT_TIMESTAMP aka NOW
UNIX_TIMESTAMP
String Functions
ASCII & CHAR
BIT_LENGTH
CHARACTER_LENGTH aka CHAR_LENGTH
COALESCE aka NVL aka IFNULL
CONCAT
CONV
Valid bases for Y and Z are: 2, 8, 10, 16 and 64
|
DECODE
INSERT
HEX & OCT & BIN
LEFT & RIGHT
LOCATE aka POSITION
within STR2; 0 if it doesn't occur and NULL for any NULL args
|
LOWER & UPPER aka LCASE & UCASE
LTRIM & RTRIM
OCTET_LENGTH
REGEX
REPEAT
REPLACE aka SUBSTITUTE
SOUNDEX
SPACE
SUBSTRING
SUBSTRING( string FROM start_pos [FOR length ] )
|
Returns the substring starting at start_pos and extending for "length" character or until the end of the string, if no "length" is supplied. Examples:
SUBSTRING( 'foobar' FROM 4 )
SUBSTRING( 'foobar' FROM 4 FOR 2)
|
Note: The SUBSTRING function is implemented in SQL::Parser and SQL::Statement and, at the current time, can not be over-ridden.
SUBSTR
words (NULL for any NULL args)
|
TRANSLATE
set of characters (a la tr ///), or NULL for any NULL args
|
TRIM
TRIM ( [ [LEADING|TRAILING|BOTH] [ 'trim_char' ] FROM ] string )
|
Removes all occurrences of <trim_char> from the front, back, or both sides of a string.
BOTH is the default if neither LEADING nor TRAILING is specified.
Space is the default if no trim_char is specified.
Examples:
TRIM( string )
trims leading and trailing spaces from string
TRIM( LEADING FROM str )
trims leading spaces from string
TRIM( 'x' FROM str )
trims leading and trailing x's from string
|
Note: The TRIM function is implemented in SQL::Parser and SQL::Statement and, at the current time, can not be over-ridden.
UNHEX
Numeric Functions
ABS
CEILING (aka CEIL) & FLOOR
EXP
LOG
LN & LOG10
MOD
POWER aka POW
RAND
ROUND
SIGN
SQRT
TRUNCATE aka TRUNC
Trigonometric Functions
All of these functions work exactly like their counterparts in Math::Trig; go there for documentation.
- ACOS
-
- ACOSEC
-
- ACOSECH
-
- ACOSH
-
- ACOT
-
- ACOTAN
-
- ACOTANH
-
- ACOTH
-
- ACSC
-
- ACSCH
-
- ASEC
-
- ASECH
-
- ASIN
-
- ASINH
-
- ATAN
-
- ATANH
-
- COS
-
- COSEC
-
- COSECH
-
- COSH
-
- COT
-
- COTAN
-
- COTANH
-
- COTH
-
- CSC
-
- CSCH
-
- SEC
-
- SECH
-
- SIN
-
- SINH
-
- TAN
-
- TANH
-
Takes a single parameter. All of Math::Trig's aliases are included.
- ATAN2
-
The y,x version of arc tangent.
- DEG2DEG
-
- DEG2GRAD
-
- DEG2RAD
-
Converts out-of-bounds values into its correct range.
- GRAD2DEG
-
- GRAD2GRAD
-
- GRAD2RAD
-
- RAD2DEG
-
- RAD2GRAD
-
- RAD2RAD
-
Like their Math::Trig's counterparts, accepts an optional 2nd boolean parameter (like TRUE) to keep prevent range wrapping.
- DEGREES
-
- RADIANS
-
DEGREES and RADIANS are included for SQL-92 compatibility, and map to RAD2DEG and DEG2RAD, respectively.
- PI
-
PI can be used without parentheses.
System Functions
DBNAME & USERNAME (aka USER)
Special Utility Functions
IMPORT
CREATE TABLE foo AS IMPORT(?) ,{}, $external_executed_sth
CREATE TABLE foo AS IMPORT(?) ,{}, $AoA
|
RUN
Takes the name of a file containing SQL statements and runs the statements; see SQL::Parser for documentation.
Submitting built-in functions
If you make a generally useful UDF, why not submit it to me and have it (and your name) included with the built-in functions? Please follow the format shown in the module including a description of the arguments and return values for the function as well as an example. Send them to the dbi-dev@perl.org mailing list (see http://dbi.perl.org).
Thanks in advance :-).
ACKNOWLEDGEMENTS
Dean Arnold supplied DECODE, COALESCE, REPLACE, many thanks! Brendan Byrd added in the Numeric/Trig/System functions and filled in the SQL92/ODBC gaps for the date/string functions.
AUTHOR & COPYRIGHT
Copyright (c) 2005 by Jeff Zucker: jzuckerATcpan.org Copyright (c) 2009-2020 by Jens Rehsack: rehsackATcpan.org
All rights reserved.
The module may be freely distributed under the same terms as Perl itself using either the "GPL License" or the "Artistic License" as specified in the Perl README file.