{ Simple example of how to build a loadable extension with DISQLite3. It shows
  a single SQL function that divides its input by 2. Extensions are not limited
  to creating a single function or collating sequence. A real loadable extension
  would probably do something more useful.

  Note that the extension uses the "DISQLite3Ext" unit instead of
  "DISQLite3Api". This is an important difference. Dynamically loaded extensions
  should always use "DISQLite3Ext" and statically linked additions to an
  application should use "DISQLite3Api".

  If you want your code to work as either a statically linked or a dynamically
  loaded module, the you will need to use $IFDEFS to use the appropriate unit.}
library DISQLite3_Extension_Half;

{$I DICompilers.inc}
{$I DISQLite3.inc}

uses
  {$IFDEF FastMM}{$IFDEF COMPILER_6_UP}FastMM4, {$ENDIF}{$ENDIF}
  DISystemCompat, DISQLite3Ext; // Use the extension type definitions.

{ This variable stores the set of DISQLite3 API functions and procedures. The
  variable name "DISQLite3Api" is choosen on purpose so it is easier to reuse
  this code inside a regular, non-extension project. }
var
  DISQLite3Api: sqlite3_api_routines_ptr;

  //----------------------------------------------------------------------------

{ The half() SQL function returns half of its input value. }
procedure halfFunc(
  context: sqlite3_context_ptr;
  argc: Integer;
  argv: sqlite3_value_ptr_array_ptr);
begin
  DISQLite3Api.sqlite3_result_double(
    context, DISQLite3Api.sqlite3_value_double(argv[0]) / 2);
end;

//------------------------------------------------------------------------------

{ This is the extension entry point and is usually the only exported function in
  a DISQLite3 loadable library. DISQLite3 invokes this function once when it
  loads the extension.

  Use this function to create new functions, collating sequences, and virtual
  table modules. }
function sqlite3_extension_init(
  DB: sqlite3_ptr;
  pzErrMsg: PPAnsiChar;
  pApi: sqlite3_api_routines_ptr): Integer;
begin
  { Store the set of published API functions and procedures to the
    "DISQLite3Api" variable. }
  DISQLite3Api := pApi;
  { Register the half() SQL function. }
  DISQLite3Api.sqlite3_create_function_v2(
    DB, 'half', 1, SQLITE_UTF8, nil, halfFunc, nil, nil, nil);
  { Return success. }
  Result := SQLITE_OK;
end;

exports
  sqlite3_extension_init;

begin
  // Nothing to initialize here.
end.

