GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing sqlite.org — Application-Defined SQL Functions
Application-Defined SQL Functions
Table Of Contents1. Executive SummaryApplications that use SQLite can define custom SQL functions that call back into application code to compute their results. The custom SQL function implementations can be embedded in the application code itself, or can be loadable extensions. Application-defined or custom SQL functions are created using the sqlite3_create_function() family of interfaces. Custom SQL functions can be scalar functions, aggregate functions, or window functions. Custom SQL functions can have any number of arguments from 0 up to SQLITE_MAX_FUNCTION_ARG. The sqlite3_create_function() interface specifies callbacks that are invoked to carry out the processing for the new SQL function. SQLite also supports custom table-valued functions, but they are implemented by a different mechanism that is not covered in this document. 2. Defining New SQL FunctionsThe sqlite3_create_function() family of interfaces is used to create new custom SQL functions. Each member of this family is a wrapper around a common core. All family members accomplish the same thing; they merely have different calling signatures.
2.1. Common ParametersMany of the parameters passed to the sqlite3_create_function() family of interfaces are common across the entire family.
2.2. Multiple Calls To sqlite3_create_function() For The Same FunctionIt is common for an application to invoke sqlite3_create_function() multiple times for the same SQL function. For example, if an SQL function can take either 2 or 3 arguments, then sqlite3_create_function() would be invoked once for the 2-argument version and a second time for the 3-argument version. The underlying implementation (the callbacks) can be different for both variants. An application can also register multiple SQL functions with the same name and same number of arguments, but a different preferred text encoding. In that case, SQLite will invoke the function using the callbacks for the version whose preferred text encoding most closely matches the database text encoding. In this way, multiple implementations of the same function can be provided that are optimized for UTF8 or UTF16. If multiple calls to sqlite3_create_function() specify the same function name, and the same number of arguments, and the same preferred text encoding, then the callbacks and other parameters of the second call overwrite the first, and the destructor callback from the first call (if it exists) is invoked. 2.3. CallbacksSQLite evaluates an SQL function by invoking callback routines. 2.3.1. The Scalar Function CallbackScalar SQL functions are implemented by a single callback in the xFunc parameter to sqlite3_create_function(). The following code demonstrates the implementation of a "noop(X)" scalar SQL function that merely returns its argument: static void noopfunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
assert( argc==1 );
sqlite3_result_value(context, argv[0]);
}
The 1st parameter, context, is a pointer to an opaque object that describes the content from which the SQL function was invoked. This context pointer becomes the first parameter to many other routines that the function implementation might want to invoke, including:
The sqlite3_result() family of functions are used to specify the result of the scalar SQL function. One or more of these should be invoked by the callback to set the function return value. If none of these routines are invoked for a specific callback, then the return value will be NULL. The sqlite3_user_data() routine returns a copy of the pArg pointer that was given to sqlite3_create_function() when the SQL function was created. The sqlite3_context_db_handle() routine returns a pointer to the database connection object. The sqlite3_aggregate_context() routine is used only in the implementations of aggregate and window functions. Scalar functions may not use sqlite3_aggregate_context(). The sqlite3_aggregate_context() function is included in the interface list only for completeness. The 2nd and 3rd arguments to the scalar SQL function implementation, argc and argv, are the number of arguments to the SQL function itself and the values for each argument of the SQL function. Argument values can be of any datatype and are thus stored in instances of the sqlite3_value object. Specific C-language values can be extracted from this object using the sqlite3_value() family of interfaces. 2.3.2. The Aggregate Function CallbacksAggregate SQL functions are implemented by using two callback functions, xStep and xFinal. The xStep() function is called for each row of the aggregate and the xFinal() function is invoked to compute the final answer at the end. The following (slightly simplified) version of the built-in count() function illustrates: typedef struct CountCtx CountCtx;
struct CountCtx {
i64 n;
};
static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
CountCtx *p;
p = sqlite3_aggregate_context(context, sizeof(*p));
if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
p->n++;
}
}
static void countFinalize(sqlite3_context *context){
CountCtx *p;
p = sqlite3_aggregate_context(context, 0);
sqlite3_result_int64(context, p ? p->n : 0);
}
Recall that there are two versions of the count() aggregate. With zero arguments, count() returns a count of the number of rows. With one argument, count() returns the number of times that the argument was non-NULL. The countStep() callback is invoked once for each row in the aggregate. As you can see, the count is incremented if either there are no arguments, or if the one argument is not NULL. The step function for an aggregate should always begin with a call to the sqlite3_aggregate_context() routine to fetch the persistent state of the aggregate function. On the first invocation of the step() function, the aggregate context is initialized to a block of memory that is N bytes in size, where N is the second parameter to sqlite3_aggregate_context() and that memory is zeroed. On all subsequent calls to the step() function, the same block of memory is returned. Except, sqlite3_aggregate_context() might return NULL in the case of an out-of-memory error, so aggregate functions should be prepared to deal with that case. After all rows are processed the countFinalize() routine is called exactly once. This routine computes the final result and invokes one of the sqlite3_result() family of functions to set the final result. The aggregate context will be freed automatically by SQLite, though the xFinalize() routine must clean up any substructure associated with the aggregate context before it returns. If the xStep() method is called one or more times, then SQLite guarantees that the xFinal() method will be called at once, even if the query aborts. 2.3.3. The Window Function CallbacksWindow functions use the same xStep() and xFinal() callbacks that aggregate functions use, plus two others: xValue and xInverse. See the documentation on application-defined window functions for further details. 2.3.4. ExamplesThere are dozens and dozens of SQL function implementations scattered throughout the SQLite source code that can be used as example applications. The built-in SQL functions use the same interface as application-defined SQL functions, so built-in functions can be used as examples too. Search for "sqlite3_context" in the SQLite source code to find examples. 3. Security ImplicationsApplication-defined SQL functions can become security vulnerabilities if not carefully managed. Suppose, for example, an application defines a new "system(X)" SQL function that runs its argument X as a command and returns the integer result code. Perhaps the implementation is like this: static void systemFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const char *zCmd = (const char*)sqlite3_value_text(argv[0]);
if( zCmd!=0 ){
int rc = system(zCmd);
sqlite3_result_int(context, rc);
}
}
This is a function with powerful side-effects. Most programmers would be naturally cautious about using it, but probably would not see the harm in merely having it available. But there is great risk in merely defining such a function, even if the application itself never invokes it! Suppose the application normally does a query against table TAB1 when it starts up. If an attacker can gain access to the database file and modify the schema like this: ALTER TABLE tab1 RENAME TO tab1_real;
CREATE VIEW tab1 AS
SELECT * FROM tab1_real
WHERE system('rm -rf *') IS NOT NULL;
Then, when the application attempts to open the database, register the system() function, then run an innocent query against the "tab1" table, it instead deletes all the files in its working directory. Yikes! To prevent this kind of mischief, applications that create their own custom SQL functions should take one or more of the following safety precautions. The more precautions taken the better:
This page was last updated on 2026-04-21 10:28:59Z |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |