How to load extensions into SQLite?

后端 未结 2 1183
感情败类
感情败类 2020-12-31 06:54

I need a standard deviation function in SQLite. I have found one here:

http://www.sqlite.org/contrib?orderby=date

but its part of an extension file to SQLit

2条回答
  •  死守一世寂寞
    2020-12-31 07:23

    You can follow loadext.html:

    1. Download the .c file of the extension
    2. Compile the .c file locally using commands from Section 3, "Compiling A Loadable Extension" in loadext.csv (check a related SO question if you have compilation errors)
    3. Load the library via sqlite3_load_extension(PATH) (.load PATH in the CLI or SELECT load_extension(PATH) in queries), where PATH is a relative or full path to the compiled library, preferably without filename extension for compatibility reasons (i.e., .load csv, not .load csv.dylib or whatever extension your system adds)

    For extension-functions on MacOS, it would be:

    curl --location --output extension-functions.c 'https://www.sqlite.org/contrib/download/extension-functions.c?get=25'
    gcc -g -fPIC -dynamiclib extension-functions.c -o extension-functions.dylib
    

    Testing the extension:

    SELECT load_extension("extension-functions");
    CREATE TABLE test(x REAL);
    INSERT INTO test (x) VALUES
      (1),
      (2),
      (3),
      (4),
      (5);
    SELECT stdev(x) FROM test;
    

    Expected output: 1.58113883008419

    Also Larry Brasfield at sqlite.org explains where you can put the compiled library to make it accessible across the system:

    If you provide an absolute path in the .load command or to the sqlite3_load_extension() call, or to the load_extension() SQLite function from SQL (when extension loading is enabled), then the extension specified by that path will be loaded (if it can be.)

    If you want to name the extension to one of the load mechanisms without an absolute path, then you must arrange that the compiled extension can be located by the search that dlopen(...) conducts. That can vary, but usually it examines directories specified by an environment variable, LD_LIBRARY_PATH, in the order listed by its colon-separated values left-to-right, then /lib and /usr/lib.

    So, you can put your extension somewhere already searched, or you could use the "env" command to launch the SQLite CLI with a modified value for $LD_LIBRARY_PATH that includes where you put the extension. Or you might simply modify that environment variable for a session in which you are using the CLI. (This can lead to subtle problems, so be sure you understand the potential effects going into that.)

提交回复
热议问题