ยปCore Development>Code coverage>Doc/includes/sqlite3/text_factory.py

Python code coverage for Doc/includes/sqlite3/text_factory.py

#countcontent
1n/aimport sqlite3
2n/a
3n/acon = sqlite3.connect(":memory:")
4n/acur = con.cursor()
5n/a
6n/aAUSTRIA = "\xd6sterreich"
7n/a
8n/a# by default, rows are returned as Unicode
9n/acur.execute("select ?", (AUSTRIA,))
10n/arow = cur.fetchone()
11n/aassert row[0] == AUSTRIA
12n/a
13n/a# but we can make sqlite3 always return bytestrings ...
14n/acon.text_factory = bytes
15n/acur.execute("select ?", (AUSTRIA,))
16n/arow = cur.fetchone()
17n/aassert type(row[0]) is bytes
18n/a# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
19n/a# database ...
20n/aassert row[0] == AUSTRIA.encode("utf-8")
21n/a
22n/a# we can also implement a custom text_factory ...
23n/a# here we implement one that appends "foo" to all strings
24n/acon.text_factory = lambda x: x.decode("utf-8") + "foo"
25n/acur.execute("select ?", ("bar",))
26n/arow = cur.fetchone()
27n/aassert row[0] == "barfoo"