File: python.rst

package info (click to toggle)
sqlfluff 3.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,984 kB
  • sloc: python: 106,138; sql: 34,188; makefile: 52; sh: 8
file content (58 lines) | stat: -rw-r--r-- 1,472 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
.. _python_templater:

Python templater
^^^^^^^^^^^^^^^^

Uses native Python f-strings. As described in
:ref:`generic_variable_templating`, an example usage would look be
configured as follows:

If passed the following *.sql* file:

.. code-block::

    SELECT * FROM {tbl_name}

...and the following configuration in *.sqlfluff* in the same directory:

.. code-block:: cfg

    [sqlfluff]
    templater = python

    [sqlfluff:templater:python:context]
    tbl_name = my_table

...then before parsing, the sql will be transformed to:

.. code-block:: sql

    SELECT * FROM my_table


Complex Python Variable Templating
""""""""""""""""""""""""""""""""""""

`Python string formatting`_ supports accessing object attributes
via dot notation (e.g. :code:`{foo.bar}`).  However, since we cannot create Python
objects within configuration files, we need a workaround in order to provide
dummy values to render templates containing these values.  The SQLFluff
python templater will interpret any variable containing a "." as a
dictionary lookup on the *magic* fixed context key :code:`sqlfluff`.

.. code-block::

    -- this SQL
    SELECT * FROM {foo.bar}

    -- becomes this
    SELECT * FROM {sqlfluff["foo.bar"]}

..which can be populated using the following configuration:

.. code-block:: cfg

    [sqlfluff:templater:python:context]
    sqlfluff = {"foo.bar": "abc"}

.. _`Python string formatting`: https://docs.python.org/3/library/string.html#format-string-syntax