tursodatabase/turso

Robust support for setting a time limit for a query

Open

#1,913 创建于 2025年7月1日

在 GitHub 查看
 (0 评论) (1 反应) (0 负责人)Rust (1,001 fork)github user discovery
enhancementhelp wanted

仓库指标

Star
 (19,103 star)
PR 合并指标
 (PR 指标待抓取)

描述

In Datasette I implement a time limit for untrusted SQL queries on top of SQLite. Here's the code I use for that at the moment: https://github.com/simonw/datasette/blob/e2497fdb595055a63f2c9b7b522e76d501be224c/datasette/utils/__init__.py#L186-L206

@contextmanager
def sqlite_timelimit(conn, ms):
    deadline = time.perf_counter() + (ms / 1000)
    # n is the number of SQLite virtual machine instructions that will be
    # executed between each check. It takes about 0.08ms to execute 1000.
    # https://github.com/simonw/datasette/issues/1679
    n = 1000
    if ms <= 20:
        # This mainly happens while executing our test suite
        n = 1

    def handler():
        if time.perf_counter() >= deadline:
            # Returning 1 terminates the query with an error
            return 1

    conn.set_progress_handler(handler, n)
    try:
        yield
    finally:
        conn.set_progress_handler(None, n)

Ideally I'd like to handle this at the database layer - it would be great if I could do something like this instead:

PRAGMA time_limit_ms = 500;
select * from really_big_table;

贡献者指南