19

我需要 SQLite 中的标准差函数。我在这里找到了一个:

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

但它是 SQLite 扩展文件的一部分。我以前从未安装过其中之一,也不知道如何安装。我在http://www.sqlite.org/lang_corefunc.html找到了这个现有函数load_extension ,但我不明白参数 X 和 Y 是什么。

基本上,我需要有人给我一个关于如何安装聚合扩展文件的分步指南。谁能做到这一点?

4

2 回答 2

20

SQLite 扩展是具有动态链接的库。您可以在这里找到一些示例(这是一个存储库,单击“登录/填写验证码”以启用超链接)。参见例如md5.c

  • load_extension必须在 SQLite 中启用(pragma IIRC)
  • 它需要库的路径作为第一个参数
  • 第二个参数是入口点函数的名称(在 md5.c 中是sqlite3_extension_init)。它的原型一定是int(sqlite3*, char **, const sqlite3_api_routines *)
  • 在 SQL 中,您可以尝试SELECT load_extension('md5.so', 'sqlite3_extension_init');或简单地SELECT load_extension('md5.so');

您可以尝试编译md5.c,并从 sqlite shell 使用.load md5.so

于 2011-11-30T08:05:52.147 回答
6

您可以关注loadext.html

  1. 下载.c扩展的文件
  2. 使用loadext.csv.c中的第 3 节“编译可加载扩展”中的命令在本地编译文件(如果您有编译错误,请检查相关的 SO 问题)
  3. sqlite3_load_extension(PATH)通过(.load PATH在 CLI 或SELECT load_extension(PATH)查询中)加载库,其中PATH是已编译库的相对或完整路径,出于兼容性原因,最好没有文件扩展名(即.load csv,不.load csv.dylib或系统添加的任何扩展名)

对于extension-functionsMacOS,它将是:

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

测试扩展:

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;

预期输出:1.58113883008419

sqlite.org 的 Larry Brasfield 还解释了您可以将编译后的库放在哪里,以便在整个系统中访问它:

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.

所以,你可以把你的扩展放在已经搜索过的地方,或者你可以使用“env”命令来启动 SQLite CLI,并修改 $LD_LIBRARY_PATH 的值,包括你放置扩展的位置。或者,您可以简单地为使用 CLI 的会话修改该环境变量。(这可能会导致微妙的问题,因此请确保您了解其中的潜在影响。)

于 2020-05-22T00:15:16.040 回答