Skip to content

Feature request: allow using template strings as query statements #598

@cgranade

Description

@cgranade

Python 3.14 adds template strings, which are written like f-strings, but allow capturing interpolations before they are resolved. This feature was originally designed to support usecases such as parameterized SQL statements, and could be adopted for APSW cursor.execute calls.

As a proof of concept, the following function converts t-strings to (str, Bindings) tuples appropriate for use with cursor.execute:

def template_as_bindings(query: str | Template) -> tuple[str, Bindings]:
    if isinstance(query, str):
        return (query, {})

    query_as_str = ""
    bindings: dict[str, SQLiteValue] = {}
    idx = 0
    for segment in query:
        if isinstance(segment, str):
            query_as_str += segment

        else:
            name = f"param{idx}"
            bindings[name] = segment.value
            query_as_str += f"${name}"
            idx += 1

    return query_as_str, bindings

For example:

>>> user_id = 12
>>> order_id = 42
>>> template_as_bindings(t"select * from foo where foo.user_id = {user_id} and foo.order_id = {order_id};") 
('select * from foo where foo.user_id = $param0 and foo.order_id = $param1;', {'param0': 12, 'param1': 42})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions