PyCon UK 2025

Building SQL queries using t-strings
2025-09-21 , Space 2

It is painfully difficult to dynamically build SQL queries in Python. Fortunately Python 3.14 introduces t-strings which provide custom string processing of template strings. My library, SQL-tString, builds SQL queries from these template strings, making it easy to build dynamic queries in Python by writing SQL directly.


In this talk I will explain t-strings, as recently accepted into Python and as will be released with Python3.14. I'll then introduce SQL-tString which is my library built on t-strings.

SQL-tString allows for t-string based construction of sql queries without allowing for SQL injection. The basic usage is as follows,

from sql_tstring import sql

a = 1

query, values = sql(
    t"""SELECT a, b, c
          FROM tbl
         WHERE a = {a}""",
)

It allows for query building via the usage of RewritingValues, such as Absent which will remove the expression it is present in,

from sql_tstring import Absent

a = Absent
b = 1
query, values = sql(t"SELECT x FROM y WHERE a = {a} AND b = {b}")
assert query == "SELECT x FROM y WHERE b = ?"
assert values == [1]

Or IsNull which will rewrite the expression to be IS NULL,

from sql_tstring import IsNull

c = IsNull
query, values = sql(t"SELECT x FROM y WHERE c = {c}")
assert query == "SELECT x FROM y WHERE c IS NULL"

What level of experience do you expect from your audience for this session?:

Basic

I am a software engineer based in London and the CTO of Curaleaf International, and Python Software Foundation Fellow. At present I contribute to open source in Python on projects relating to web development, specifically I am a maintainer of Flask, Werkzeug, Quart, and Hypercorn.