You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Feature Request: a few more t-string additions
#798
Thanks for landing template strings in #783 and #787 (as previously discussed in #370). The placement checks and the error notes that map each $n back to its field are really nice. For background, I've been prototyping these ideas in sqltemplatelib, a small spec plus a reference implementation (see SPEC.md), which grew out of #409.
I have five suggestions, mostly about letting code outside DuckDB build pieces of a query. If any of them sound promising to @evertlammerts , I would love to submit a PR, where I can hash out more of the detailed semantics and we can have something concrete to talk about.
1. Let objects describe themselves as SQL with __sql_template__
Right now only a literal t-string can add SQL text to a query. Any other object in a field gets bound as a parameter. So a query builder, a filter object, or a library that generates SQL can't plug in unless DuckDB depends on it or it depends on DuckDB.
A duck-typed method would fix that without either side importing the other:
classMinAge:
def__init__(self, min_age=None):
self.min_age=min_agedef__sql_template__(self, **kwargs):
min_age=self.min_ageifmin_ageisNone:
returnt"true"returnt"age >= {min_age}"filters=MinAge(18)
con.sql(t"SELECT * FROM users WHERE {filters:q}")
# SELECT * FROM users WHERE age >= $1 -- with $1 = 18
Call it with no positional arguments. It must accept **kwargs, and the keyword names are reserved for later use, so DuckDB can pass options in the future without breaking anyone.
Expand whatever it returns exactly as a nested template would be expanded: same refusals, same notes, and the field's text added to within so an error points at {filters}.
Call it while the statement is being compiled, so the SQL reflects the object's state at that moment. Don't promise how many times it is called.
2. Add {x:l} for literals
Some places in a statement don't take a prepared parameter: ATTACH paths, column DEFAULTs, the body of a CREATE VIEW, some options in COPY, and so on. Today a template has no way to fill those, so people will go back to f-strings in exactly the statements that most often take paths and names from user input. psycopg 3 uses :l for this, so DuckDB would match it.
Support None, bool, int, finite float, finite Decimal, and str without NUL characters. Raise for anything else, and for any value that can't be written exactly. Never write an approximation.
Keep the literal a single token wherever it sits. For example, a negative number written after - must not start a -- comment, so write it as (-1).
Apply the placement checks that already exist for :i: refuse a literal inside a string literal, inside a comment, or touching a neighbouring word.
3. Make :q optional on nested templates
A Template has no meaning as a bound value, so a bare {inner} holding a template can only mean "splice it in". Requiring :q doesn't make anything safer, and refusing the bare form costs every caller a few characters, plus I think many users are going to forget to add on the the :q modifier at first and are going to get an error the first time. I'd accept both {inner} and {inner:q}. If the goal is to keep psycopg compatibility, accepting the bare form doesn't break it, since any template written for psycopg would still work.
If (1) is adopted, the same applies to composable objects: {filters} should be enough.
4. Accept objects shaped like templates, not only string.templatelib.Template
is_template() checks for a Template subclass and returns False before Python 3.14, so on 3.11–3.13 the feature doesn't exist at all. Libraries that build queries need to support those versions for a few more years.
Suggestion: also accept any object whose type is marked as a template, and that has strings (a tuple of str) and interpolations (objects with value, expression, conversion, and format_spec), the same shape as string.templatelib. Then a library can construct a template on 3.11 and hand it to DuckDB, and __sql_template__ from (1) can return one. A marker on the type, rather than probing attributes on the instance, keeps to the "no user code runs before the guard" principle from #787.
5. Document the opt-in for table fields, and decide how it interacts with __sql_template__
#787 reads a field as a table when its class is a relation, a pandas DataFrame or Series, or exports __arrow_c_stream__. In practice __arrow_c_stream__ is how a third-party library opts in. I'd say so in the docs, so library authors know it's the supported route and not a side effect of how detection was implemented.
If (1) lands, some objects will have both methods. A lazy dataframe or query-builder table, for example, may be able to export Arrow and also describe itself as SQL. I'd let __sql_template__ win: the object has asked to be inlined as SQL, which DuckDB can optimise together with the outer query. Reading it through Arrow would execute it in the library first. Whichever order you pick, writing it down means libraries can rely on it.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Thanks for landing template strings in #783 and #787 (as previously discussed in #370). The placement checks and the error notes that map each
$nback to its field are really nice. For background, I've been prototyping these ideas in sqltemplatelib, a small spec plus a reference implementation (see SPEC.md), which grew out of #409.I have five suggestions, mostly about letting code outside DuckDB build pieces of a query. If any of them sound promising to @evertlammerts , I would love to submit a PR, where I can hash out more of the detailed semantics and we can have something concrete to talk about.
1. Let objects describe themselves as SQL with
__sql_template__Right now only a literal t-string can add SQL text to a query. Any other object in a field gets bound as a parameter. So a query builder, a filter object, or a library that generates SQL can't plug in unless DuckDB depends on it or it depends on DuckDB.
A duck-typed method would fix that without either side importing the other:
Suggested rules:
__getattr__answers every name doesn't count by accident. This matches how Read relations, DataFrames and Arrow objects in template string fields #787 judges tables from their class alone.**kwargs, and the keyword names are reserved for later use, so DuckDB can pass options in the future without breaking anyone.withinso an error points at{filters}.2. Add
{x:l}for literalsSome places in a statement don't take a prepared parameter:
ATTACHpaths, columnDEFAULTs, the body of aCREATE VIEW, some options inCOPY, and so on. Today a template has no way to fill those, so people will go back to f-strings in exactly the statements that most often take paths and names from user input. psycopg 3 uses:lfor this, so DuckDB would match it.Suggested rules:
None,bool,int, finitefloat, finiteDecimal, andstrwithout NUL characters. Raise for anything else, and for any value that can't be written exactly. Never write an approximation.-must not start a--comment, so write it as(-1).:i: refuse a literal inside a string literal, inside a comment, or touching a neighbouring word.3. Make
:qoptional on nested templatesA
Templatehas no meaning as a bound value, so a bare{inner}holding a template can only mean "splice it in". Requiring:qdoesn't make anything safer, and refusing the bare form costs every caller a few characters, plus I think many users are going to forget to add on the the:qmodifier at first and are going to get an error the first time. I'd accept both{inner}and{inner:q}. If the goal is to keep psycopg compatibility, accepting the bare form doesn't break it, since any template written for psycopg would still work.If (1) is adopted, the same applies to composable objects:
{filters}should be enough.4. Accept objects shaped like templates, not only
string.templatelib.Templateis_template()checks for aTemplatesubclass and returnsFalsebefore Python 3.14, so on 3.11–3.13 the feature doesn't exist at all. Libraries that build queries need to support those versions for a few more years.Suggestion: also accept any object whose type is marked as a template, and that has
strings(a tuple ofstr) andinterpolations(objects withvalue,expression,conversion, andformat_spec), the same shape asstring.templatelib. Then a library can construct a template on 3.11 and hand it to DuckDB, and__sql_template__from (1) can return one. A marker on the type, rather than probing attributes on the instance, keeps to the "no user code runs before the guard" principle from #787.5. Document the opt-in for table fields, and decide how it interacts with
__sql_template__#787 reads a field as a table when its class is a relation, a pandas DataFrame or Series, or exports
__arrow_c_stream__. In practice__arrow_c_stream__is how a third-party library opts in. I'd say so in the docs, so library authors know it's the supported route and not a side effect of how detection was implemented.If (1) lands, some objects will have both methods. A lazy dataframe or query-builder table, for example, may be able to export Arrow and also describe itself as SQL. I'd let
__sql_template__win: the object has asked to be inlined as SQL, which DuckDB can optimise together with the outer query. Reading it through Arrow would execute it in the library first. Whichever order you pick, writing it down means libraries can rely on it.All reactions