插件¶
sqlite-utils
支持插件,可用于为软件添加额外功能。
插件可以添加新命令,例如 sqlite-utils some-command ...
插件可以使用 sqlite-utils install
命令安装
sqlite-utils install sqlite-utils-name-of-plugin
运行此命令可以看到已安装插件的 JSON 列表
sqlite-utils plugins
插件钩子,例如 prepare_connection(conn),影响每个 Database
类实例。您可以通过如下方式创建该类实例来选择不使用这些插件
db = Database(memory=True, execute_plugins=False)
构建插件¶
插件在以插件名称命名的目录中创建。要创建“hello world”插件,首先创建一个 hello-world
目录
mkdir hello-world
cd hello-world
在该文件夹中创建两个文件。第一个是用于描述插件的 pyproject.toml
文件
[project]
name = "sqlite-utils-hello-world"
version = "0.1"
[project.entry-points.sqlite_utils]
hello_world = "sqlite_utils_hello_world"
该 [project.entry-points.sqlite_utils]
部分告诉 sqlite-utils
在执行插件时应加载哪个模块。
然后创建 sqlite_utils_hello_world.py
,内容如下
import click
import sqlite_utils
@sqlite_utils.hookimpl
def register_commands(cli):
@cli.command()
def hello_world():
"Say hello world"
click.echo("Hello world!")
以“可编辑”模式安装插件 - 这样您就可以更改代码,并且 sqlite-utils
会立即反映这些更改 - 如下所示
sqlite-utils install -e .
或者传递您的插件目录路径
sqlite-utils install -e /dev/sqlite-utils-hello-world
现在,运行此命令应该会执行您的新命令
sqlite-utils hello-world
您的命令也会列在 sqlite-utils --help
的输出中。
请参阅 LLM 插件文档,了解分发插件的技巧。
插件钩子¶
插件钩子允许 sqlite-utils
进行自定义。
register_commands(cli)¶
此钩子可用于向 sqlite-utils
CLI 注册额外命令。调用时会传入 cli
对象,该对象是 click.Group
实例。
示例实现
import click
import sqlite_utils
@sqlite_utils.hookimpl
def register_commands(cli):
@cli.command()
def hello_world():
"Say hello world"
click.echo("Hello world!")
插件实现的新命令可以使用 context.invoke 机制调用现有命令。
作为一个特殊的利基功能,如果您的插件需要导入一些文件,然后对包含这些文件的内存数据库进行操作,您可以转发到 sqlite-utils memory 命令 并向其传递 return_db=True
@cli.command()
@click.pass_context
@click.argument(
"paths",
type=click.Path(file_okay=True, dir_okay=False, allow_dash=True),
required=False,
nargs=-1,
)
def show_schema_for_files(ctx, paths):
from sqlite_utils.cli import memory
db = ctx.invoke(memory, paths=paths, return_db=True)
# Now do something with that database
click.echo(db.schema)
prepare_connection(conn)¶
创建新的 SQLite 数据库连接时会调用此钩子。您可以使用它来 注册自定义 SQL 函数、聚合函数和排序规则。例如
import sqlite_utils
@sqlite_utils.hookimpl
def prepare_connection(conn):
conn.create_function(
"hello", 1, lambda name: f"Hello, {name}!"
)
这会注册一个名为 hello
的 SQL 函数,该函数接受一个参数,可以这样调用
select hello("world"); -- "Hello, world!"