expressions appear directly in the place where they will be used in the query
(no more forgetting to add a placeholder when adding a field in an INSERT...).
+If you want to convert the template string to a regular string, instead of
+executing it directly, you can use the `sql.as_string()` or `~sql.as_bytes()`
+functions:
+
+.. code:: python
+
+ >>> name = "O'Reilly"
+ >>> dob = datetime.date(1970, 1, 1)
+ >>> print(sql.as_string(t"INSERT INTO tbl VALUES ({name}, {dob})"))
+ INSERT INTO tbl VALUES ('O''Reilly', '1970-01-01'::date)
+
With template strings it is also easy to parametrize parts of the query other
than parameter values, for example tables or fields names:
def as_string(t: Template, context: abc.AdaptContext | None = None) -> str:
+ """Convert a template string to a string.
+
+ This function is exposed as part of psycopg.sql.as_string().
+ """
tx = Transformer(context)
tp = TemplateProcessor(t, tx=tx, server_params=False)
tp.process()
def as_bytes(t: Template, context: abc.AdaptContext | None = None) -> bytes:
+ """Convert a template string to a bytes string.
+
+ This function is exposed as part of psycopg.sql.as_bytes().
+ """
tx = Transformer(context)
tp = TemplateProcessor(t, tx=tx, server_params=False)
tp.process()
def as_string(obj: Any, context: AdaptContext | None = None) -> str:
+ """Convert an object to a string according to SQL rules.
+
+ :param obj: the object to convert
+ :param context: the context in which to convert the object
+ :type context: `~psycopg.abc.AdaptContext` | `!None`
+
+ Adaptation happens according to the type of `!obj`:
+
+ - `Composable` objects are converted according to their
+ `~Composable.as_string()` method;
+ - `~string.templatelib.Template` strings are converted according to the
+ rules documented in :ref:`template-strings`;
+ - every other object is converted as it was :ref:`a parameter passed to a
+ query <types-adaptation>`.
+
+ If `!context` is specified then it is be used to customize the conversion.
+ for example using the encoding of a connection or the dumpers registered.
+ """
if isinstance(obj, Composable):
return obj.as_string(context=context)
elif isinstance(obj, Template):
def as_bytes(obj: Any, context: AdaptContext | None = None) -> bytes:
+ """Convert an object to a bytes string according to SQL rules.
+
+ :param obj: the object to convert
+ :param context: the context in which to convert the object
+ :type context: `~psycopg.abc.AdaptContext` | `!None`
+
+ See `as_string()` for details.
+ """
if isinstance(obj, Composable):
return obj.as_bytes(context=context)
elif isinstance(obj, Template):