tursodatabase/turso

Robust support for setting a time limit for a query

Open

#1.913 geöffnet am 1. Juli 2025

Auf GitHub ansehen
 (0 Kommentare) (1 Reaktion) (0 zugewiesene Personen)Rust (1.001 Forks)github user discovery
enhancementhelp wanted

Repository-Metriken

Stars
 (19.103 Stars)
PR-Merge-Metriken
 (PR-Metriken ausstehend)

Beschreibung

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;

Contributor Guide