Skip to content
Merged
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
7 changes: 4 additions & 3 deletions piccolo/querystring.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABCMeta, abstractmethod
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import date, datetime
from datetime import date, datetime, time
from importlib.util import find_spec
from string import Formatter
from typing import TYPE_CHECKING, Any, Optional
Expand Down Expand Up @@ -155,8 +155,9 @@ def __str__(self):
for arg in combined_args:
_type = type(arg)
if _type == str:
converted_args.append(f"'{arg}'")
elif _type == datetime or _type == date:
escaped = arg.replace("'", "''")
converted_args.append(f"'{escaped}'")
elif _type == datetime or _type == date or _type == time:
dt_string = arg.isoformat()
converted_args.append(f"'{dt_string}'")
elif _type == UUID or _type == apgUUID:
Expand Down
16 changes: 16 additions & 0 deletions tests/query/test_querystring.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import time
from unittest import TestCase

from piccolo.querystring import QueryString
Expand Down Expand Up @@ -29,6 +30,21 @@ def test_querystring_with_no_args(self):
qs = QueryString("SELECT name FROM band")
self.assertEqual(qs.compile_string(), ("SELECT name FROM band", []))

def test_string_escapes_quotes(self):
"""
``Check`` constraints use ``__str__``, so the output must be valid SQL.
"""
qs = QueryString("SELECT id FROM band WHERE genre = {}", "rock'n'roll")
self.assertEqual(
qs.__str__(), "SELECT id FROM band WHERE genre = 'rock''n''roll'"
)

def test_string_time(self):
qs = QueryString("SELECT id FROM shop WHERE opens >= {}", time(9, 0))
self.assertEqual(
qs.__str__(), "SELECT id FROM shop WHERE opens >= '09:00:00'"
)


class TestQueryStringOperators(TestCase):
"""
Expand Down
Loading