Search code examples
sqlitedelphic-api

Delphi usage of sqlite3_db_config()


I am trying to set the SQLITE_DBCONFIG_MAINDBNAME option via sqlite3_db_config() to a custom one, but I still have problems with these pointers in Delphi 10.3. The connection runs fine, but a later PRAGMA database_list returns not what I previously put into the function. The third argument is what I am experimenting with, which is part of the variable arguments:

// bind method to sqlite3.dll:
sqlite3_db_config: function (ppDb: Psqlite3; op: Integer): Integer; cdecl varargs;

...

var
  FMainDbName: String;
begin
  FMainDbName := 'chinook';
  // shows "" (empty string)
  FLib.sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PAnsiChar(UTF8Encode(FMainDbName)));
  // shows the first character only: "c"
  FLib.sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PChar(FMainDbName));
end;

The SQLite documentation says:

SQLITE_DBCONFIG_MAINDBNAME

This option is used to change the name of the "main" database schema. The sole argument is a pointer to a constant UTF8 string which will become the new schema name in place of "main". SQLite does not make a copy of the new main schema name string, so the application must ensure that the argument passed into this DBCONFIG option is unchanged until after the database connection closes.

So, how do I need to format the third argument for sqlite3_db_config?


Solution

  • UTF8Encode creates a temporay string for its return value. You have to store that value in a variable with a sufficiently long lifetime:

    var
      MainDBNameUTF8: UTF8String;
    
    ...
    MainDBNameUTF8 := ...;
    sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PAnsiChar(MainDBNameUTF8));