{ Simple loadable extension project for DISQLite3 / SQLiteSpy. It implements
  a single collation sequence which mimics SQLite3's built-in NOSORT order.

  Note that extensions must use the "DISQLite3Ext" unit instead of
  "DISQLite3Api". This is an important difference. Dynamically loaded
  extensions should always use "DISQLite3Ext". Only 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, you will need to use $IFDEFS to use the appropriate unit.

  http://www.yunqa.de }
library DISQLite3_Extension_Collate_NOCASE2;

{$I DI.inc}
{$I DISQLite3.inc}

uses
  {$IFDEF FastMM}{$I FastMM_uses.inc}{$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 with regular, non-extension project. }
var
  DISQLite3Api: sqlite3_api_routines_ptr;

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

{ This "nocase" compare function behaves just like SQLite's built-in function. }
function CompareNoCase_func(
  UserData: Pointer;
  l1: Integer;
  const s1: Pointer;
  l2: Integer;
  const s2: Pointer): Integer;
label
  0;
var
  l: Integer;
begin
  if not Assigned(s1) or not Assigned(s2) then goto 0;
  if l1 <= l2 then l := l1 else l := l2;
  Result := DISQLite3Api^.sqlite3_strnicmp(s1, s2, l);
  if Result = 0 then
    0: Result := l1 - l2;
end;

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

{ This is the extension entry point and is usually the only exported function in
  a DISQLite3 loadable library. DISQLite3 / SQLiteSpy 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" global variable. }
  DISQLite3Api := pApi;
  { Register the "reverse" collation sequence. }
  DISQLite3Api.sqlite3_create_collation_v2(
    DB, 'RMNOCASE', SQLITE_UTF8, nil, CompareNoCase_func, nil);
  { Return success. }
  Result := SQLITE_OK;
end;

exports
  sqlite3_extension_init;

begin
  {$IFDEF FastMM}{$I FastMM_init.inc}{$ENDIF}
  // Nothing to initialize here.
end.

