Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/src/piccolo/query_types/raw.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ placeholders:
>>> await Band.raw('SELECT * FROM band WHERE name = {}', 'Pythonistas')
[{'name': 'Pythonistas', 'manager': 1, 'popularity': 1000, 'id': 1}]

QueryString
-----------

For more flexibility, you can pass a
:class:`QueryString <piccolo.querystring.QueryString>` to ``raw``.
``QueryString`` objects can be nested, and values are always passed to the
database as parameters. You can also include other Piccolo queries within a
``QueryString``. For example, to count the rows returned by a ``select``:

.. code-block:: python

from piccolo.querystring import QueryString

>>> await Band.raw(
... QueryString(
... "SELECT COUNT(*) AS total FROM ({}) AS sub",
... Band.select(Band.name).where(Band.popularity > 500),
... )
... )
[{'total': 1}]

.. note:: Only queries which consist of a single SQL statement can be nested
within a ``QueryString``.

.. warning:: Be careful to avoid SQL injection attacks. Don't add any user submitted data into your SQL strings, unless it's parameterised.


Expand Down
14 changes: 13 additions & 1 deletion piccolo/querystring.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,26 @@ def process_args(
) -> tuple[Sequence[Any], Sequence[Column]]:
"""
If a Column is passed in, we convert it to the name of the column
(including joins).
(including joins). If a ``Query`` is passed in, we use its underlying
``QueryString``, so queries can be nested within each other.
"""
from piccolo.columns import Column

processed_args = []
columns = []

for arg in args:
# We can't import ``Query`` here, as it causes a circular import
# (``QueryString`` is used when the column types are defined).
if hasattr(arg, "querystrings"):
querystrings = arg.querystrings
if len(querystrings) != 1:
raise ValueError(
"Only queries which consist of a single statement "
"can be used within a QueryString."
)
arg = querystrings[0]

if isinstance(arg, Column):
columns.append(arg)
arg = QueryString(
Expand Down
23 changes: 22 additions & 1 deletion piccolo/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1128,7 +1128,7 @@ def insert(
return query

@classmethod
def raw(cls, sql: str, *args: Any) -> Raw:
def raw(cls, sql: Union[str, QueryString], *args: Any) -> Raw:
"""
Execute raw SQL queries on the underlying engine - use with caution!

Expand All @@ -1142,7 +1142,28 @@ def raw(cls, sql: str, *args: Any) -> Raw:

await Band.raw("SELECT * FROM band WHERE name = {}", 'Pythonistas')

You can also pass in a
:class:`QueryString <piccolo.querystring.QueryString>`, which can
wrap other queries:

.. code-block:: python

await Band.raw(
QueryString(
"SELECT COUNT(*) AS total FROM ({}) AS sub",
Band.select(Band.name),
)
)

"""
if isinstance(sql, QueryString):
if args:
raise ValueError(
"No extra arguments can be passed in when `sql` is a "
"`QueryString`."
)
return Raw(table=cls, querystring=sql)

return Raw(table=cls, querystring=QueryString(sql, *args))

@classmethod
Expand Down
43 changes: 43 additions & 0 deletions tests/table/test_raw.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from piccolo.query.base import Query
from piccolo.querystring import QueryString
from tests.base import DBTestCase, engine_is
from tests.example_apps.music.tables import Band

Expand Down Expand Up @@ -58,3 +60,44 @@ def test_raw_with_args(self):
"popularity": 1000,
},
)


class TestRawQueryString(DBTestCase):
def test_querystring(self):
self.insert_rows()

response = Band.raw(
QueryString("SELECT name FROM band WHERE name = {}", "Rustaceans")
).run_sync()

self.assertListEqual(response, [{"name": "Rustaceans"}])

def test_querystring_with_args(self):
with self.assertRaises(ValueError):
Band.raw(QueryString("SELECT * FROM band"), "Pythonistas")

def test_nested_query(self):
"""
A query can be nested within a ``QueryString``.
"""
self.insert_rows()

query = Band.select(Band.name).where(Band.name == "Rustaceans")
response = Band.raw(
QueryString("SELECT COUNT(*) AS total FROM ({}) AS sub", query)
).run_sync()

self.assertListEqual(response, [{"total": 1}])

def test_nested_query_multiple_statements(self):
with self.assertRaises(ValueError):
QueryString(
"{}",
Query(
Band,
frozen_querystrings=[
QueryString("SELECT 1"),
QueryString("SELECT 2"),
],
),
)