Hello,
I have recently started to look into using template strings in psycopg and it seems promising. There is an open conversation in discussion 1044.
Something that would come handy is passing sequence of identifiers to a query. For example, if you have:
fields = ["foo", "bar", "baz-qux"]
and you want to select these fields from a table safely (both thinking about malicious input and thinking about fields names needing escape) you currently need:
>>> fields_list = [sql.Identifier(field) for field in fields]
>>> query = sql.SQL("SELECT {fields} FROM t").format(fields=sql.SQL(", ").join(fields_list))
>>> print(query.as_string())
SELECT "foo", "bar", "baz-qux" FROM t
We are considering to allow nested templates and an i
format string to represent an identifier. The above could be simplified as:
>>> fields_list = [t"{field:i}" for field in fields]
>>> query = t"SELECT {", ".join(fields_list)} FROM t" # I wish
How easy would be to join a sequence of templates? By looking at the PEP 750, Template seems to support +, but "".join()
I assume would return a string? Or it wouldn’t and the virality of + would ensure a Template result? Template.join()
doesn’t seem implemented but it seems a natural extension to Template.__add__
.