Example::
- >>> s1 = sql.Literal("foo")
- >>> s2 = sql.Literal("ba'r")
- >>> s3 = sql.Literal(42)
+ >>> s1 = sql.Literal("fo'o")
+ >>> s2 = sql.Literal(42)
+ >>> s3 = sql.Literal(date(2000, 1, 1))
>>> print(sql.SQL(', ').join([s1, s2, s3]).as_string(conn))
- 'foo', 'ba''r', 42
+ 'fo''o', 42, '2000-01-01'::date
"""
def as_bytes(self, context: Optional[AdaptContext]) -> bytes:
tx = Transformer.from_context(context)
dumper = tx.get_dumper(self._obj, PyFormat.TEXT)
- return dumper.quote(self._obj)
+ rv = dumper.quote(self._obj)
+ # If the result is quoted and the oid not unknown,
+ # add an explicit type cast.
+ if rv[-1] == 39 and dumper.oid:
+ ti = tx.adapters.types.get(dumper.oid)
+ if ti:
+ # TODO: ugly encoding just to be decoded by as_string()
+ rv = b"%s::%s" % (rv, ti.name.encode(tx.encoding))
+ return rv
class Placeholder(Composable):
# Verify the libpq behaviour of PQescapeString using the last setting seen.
# Check that we are not affected by it.
good_str = " E'\\\\'"
- good_bytes = " E'\\\\000'"
+ good_bytes = " E'\\\\000'::bytea"
conn.execute("set standard_conforming_strings to on")
assert pq.Escaping().escape_string(b"\\") == b"\\"
assert sql.quote("\\") == good_str
def test_compose_literal(self, conn):
s = sql.SQL("select {0};").format(sql.Literal(dt.date(2016, 12, 31)))
s1 = s.as_string(conn)
- assert s1 == "select '2016-12-31';"
+ assert s1 == "select '2016-12-31'::date;"
def test_compose_empty(self, conn):
s = sql.SQL("select foo;").format()
def test_auto_literal(self, conn):
s = sql.SQL("select {}, {}, {}").format("he'lo", 10, dt.date(2020, 1, 1))
- assert s.as_string(conn) == "select 'he''lo', 10, '2020-01-01'"
+ assert s.as_string(conn) == "select 'he''lo', 10, '2020-01-01'::date"
def test_execute(self, conn):
cur = conn.cursor()
assert sql.Literal(None).as_string(conn) == "NULL"
assert no_e(sql.Literal("foo").as_string(conn)) == "'foo'"
assert sql.Literal(42).as_string(conn) == "42"
- assert sql.Literal(dt.date(2017, 1, 1)).as_string(conn) == "'2017-01-01'"
+ assert sql.Literal(dt.date(2017, 1, 1)).as_string(conn) == "'2017-01-01'::date"
def test_as_bytes(self, conn):
assert sql.Literal(None).as_bytes(conn) == b"NULL"
assert no_e(sql.Literal("foo").as_bytes(conn)) == b"'foo'"
assert sql.Literal(42).as_bytes(conn) == b"42"
- assert sql.Literal(dt.date(2017, 1, 1)).as_bytes(conn) == b"'2017-01-01'"
+ assert sql.Literal(dt.date(2017, 1, 1)).as_bytes(conn) == b"'2017-01-01'::date"
conn.execute("set client_encoding to utf8")
assert sql.Literal(eur).as_bytes(conn) == f"'{eur}'".encode()
obj = sql.Composed(["fo'o", dt.date(2020, 1, 1)])
obj = obj.join(", ")
assert isinstance(obj, sql.Composed)
- assert no_e(obj.as_string(conn)) == "'fo''o', '2020-01-01'"
+ assert no_e(obj.as_string(conn)) == "'fo''o', '2020-01-01'::date"
def test_sum(self, conn):
obj = sql.Composed([sql.SQL("foo ")])