blob: 148d9f596a91c8a0af12e5a1c09e7d773b7c00e1 [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001# pysqlite2/test/userfunctions.py: tests for user-defined functions and
2# aggregates.
3#
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +02004# Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005#
6# This file is part of pysqlite.
7#
8# This software is provided 'as-is', without any express or implied
9# warranty. In no event will the authors be held liable for any damages
10# arising from the use of this software.
11#
12# Permission is granted to anyone to use this software for any purpose,
13# including commercial applications, and to alter it and redistribute it
14# freely, subject to the following restrictions:
15#
16# 1. The origin of this software must not be misrepresented; you must not
17# claim that you wrote the original software. If you use this software
18# in a product, an acknowledgment in the product documentation would be
19# appreciated but is not required.
20# 2. Altered source versions must be plainly marked as such, and must not be
21# misrepresented as being the original software.
22# 3. This notice may not be removed or altered from any source distribution.
23
24import unittest
Sergey Fedoseev08308582018-07-08 12:09:20 +050025import unittest.mock
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026import sqlite3 as sqlite
27
28def func_returntext():
29 return "foo"
30def func_returnunicode():
Guido van Rossumef87d6e2007-05-02 19:09:54 +000031 return "bar"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000032def func_returnint():
33 return 42
34def func_returnfloat():
35 return 3.14
36def func_returnnull():
37 return None
38def func_returnblob():
Guido van Rossumbae07c92007-10-08 02:46:15 +000039 return b"blob"
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +020040def func_returnlonglong():
41 return 1<<31
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042def func_raiseexception():
43 5/0
44
45def func_isstring(v):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000046 return type(v) is str
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047def func_isint(v):
48 return type(v) is int
49def func_isfloat(v):
50 return type(v) is float
51def func_isnone(v):
52 return type(v) is type(None)
53def func_isblob(v):
Guido van Rossumbae07c92007-10-08 02:46:15 +000054 return isinstance(v, (bytes, memoryview))
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +020055def func_islonglong(v):
56 return isinstance(v, int) and v >= 1<<31
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057
Berker Peksagfa0f62d2016-03-27 22:39:14 +030058def func(*args):
59 return len(args)
60
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061class AggrNoStep:
62 def __init__(self):
63 pass
64
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065 def finalize(self):
66 return 1
67
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068class AggrNoFinalize:
69 def __init__(self):
70 pass
71
72 def step(self, x):
73 pass
74
75class AggrExceptionInInit:
76 def __init__(self):
77 5/0
78
79 def step(self, x):
80 pass
81
82 def finalize(self):
83 pass
84
85class AggrExceptionInStep:
86 def __init__(self):
87 pass
88
89 def step(self, x):
90 5/0
91
92 def finalize(self):
93 return 42
94
95class AggrExceptionInFinalize:
96 def __init__(self):
97 pass
98
99 def step(self, x):
100 pass
101
102 def finalize(self):
103 5/0
104
105class AggrCheckType:
106 def __init__(self):
107 self.val = None
108
109 def step(self, whichType, val):
Guido van Rossumbae07c92007-10-08 02:46:15 +0000110 theType = {"str": str, "int": int, "float": float, "None": type(None),
111 "blob": bytes}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112 self.val = int(theType[whichType] is type(val))
113
114 def finalize(self):
115 return self.val
116
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300117class AggrCheckTypes:
118 def __init__(self):
119 self.val = 0
120
121 def step(self, whichType, *vals):
122 theType = {"str": str, "int": int, "float": float, "None": type(None),
123 "blob": bytes}
124 for val in vals:
125 self.val += int(theType[whichType] is type(val))
126
127 def finalize(self):
128 return self.val
129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000130class AggrSum:
131 def __init__(self):
132 self.val = 0.0
133
134 def step(self, val):
135 self.val += val
136
137 def finalize(self):
138 return self.val
139
140class FunctionTests(unittest.TestCase):
141 def setUp(self):
142 self.con = sqlite.connect(":memory:")
143
144 self.con.create_function("returntext", 0, func_returntext)
145 self.con.create_function("returnunicode", 0, func_returnunicode)
146 self.con.create_function("returnint", 0, func_returnint)
147 self.con.create_function("returnfloat", 0, func_returnfloat)
148 self.con.create_function("returnnull", 0, func_returnnull)
149 self.con.create_function("returnblob", 0, func_returnblob)
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +0200150 self.con.create_function("returnlonglong", 0, func_returnlonglong)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151 self.con.create_function("raiseexception", 0, func_raiseexception)
152
153 self.con.create_function("isstring", 1, func_isstring)
154 self.con.create_function("isint", 1, func_isint)
155 self.con.create_function("isfloat", 1, func_isfloat)
156 self.con.create_function("isnone", 1, func_isnone)
157 self.con.create_function("isblob", 1, func_isblob)
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +0200158 self.con.create_function("islonglong", 1, func_islonglong)
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300159 self.con.create_function("spam", -1, func)
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +0200160 self.con.execute("create table test(t text)")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000161
162 def tearDown(self):
163 self.con.close()
164
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100165 def test_func_error_on_create(self):
Berker Peksag1003b342016-06-12 22:34:49 +0300166 with self.assertRaises(sqlite.OperationalError):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167 self.con.create_function("bla", -100, lambda x: 2*x)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000168
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100169 def test_func_ref_count(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000170 def getfunc():
171 def f():
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000172 return 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173 return f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174 f = getfunc()
175 globals()["foo"] = f
176 # self.con.create_function("reftest", 0, getfunc())
177 self.con.create_function("reftest", 0, f)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178 cur = self.con.cursor()
179 cur.execute("select reftest()")
180
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100181 def test_func_return_text(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182 cur = self.con.cursor()
183 cur.execute("select returntext()")
184 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000185 self.assertEqual(type(val), str)
186 self.assertEqual(val, "foo")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100188 def test_func_return_unicode(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000189 cur = self.con.cursor()
190 cur.execute("select returnunicode()")
191 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000192 self.assertEqual(type(val), str)
193 self.assertEqual(val, "bar")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100195 def test_func_return_int(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 cur = self.con.cursor()
197 cur.execute("select returnint()")
198 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000199 self.assertEqual(type(val), int)
200 self.assertEqual(val, 42)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100202 def test_func_return_float(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000203 cur = self.con.cursor()
204 cur.execute("select returnfloat()")
205 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000206 self.assertEqual(type(val), float)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207 if val < 3.139 or val > 3.141:
208 self.fail("wrong value")
209
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100210 def test_func_return_null(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211 cur = self.con.cursor()
212 cur.execute("select returnnull()")
213 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000214 self.assertEqual(type(val), type(None))
215 self.assertEqual(val, None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100217 def test_func_return_blob(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218 cur = self.con.cursor()
219 cur.execute("select returnblob()")
220 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000221 self.assertEqual(type(val), bytes)
222 self.assertEqual(val, b"blob")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000223
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100224 def test_func_return_long_long(self):
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +0200225 cur = self.con.cursor()
226 cur.execute("select returnlonglong()")
227 val = cur.fetchone()[0]
228 self.assertEqual(val, 1<<31)
229
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100230 def test_func_exception(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000231 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300232 with self.assertRaises(sqlite.OperationalError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233 cur.execute("select raiseexception()")
234 cur.fetchone()
Berker Peksag1003b342016-06-12 22:34:49 +0300235 self.assertEqual(str(cm.exception), 'user-defined function raised exception')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000236
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100237 def test_param_string(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000238 cur = self.con.cursor()
239 cur.execute("select isstring(?)", ("foo",))
240 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000241 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000242
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100243 def test_param_int(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244 cur = self.con.cursor()
245 cur.execute("select isint(?)", (42,))
246 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000247 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100249 def test_param_float(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000250 cur = self.con.cursor()
251 cur.execute("select isfloat(?)", (3.14,))
252 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000253 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000254
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100255 def test_param_none(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256 cur = self.con.cursor()
257 cur.execute("select isnone(?)", (None,))
258 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000259 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100261 def test_param_blob(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262 cur = self.con.cursor()
Guido van Rossumbae07c92007-10-08 02:46:15 +0000263 cur.execute("select isblob(?)", (memoryview(b"blob"),))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000265 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000266
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100267 def test_param_long_long(self):
Petri Lehtinen4fe85ab2012-02-19 21:38:00 +0200268 cur = self.con.cursor()
269 cur.execute("select islonglong(?)", (1<<42,))
270 val = cur.fetchone()[0]
271 self.assertEqual(val, 1)
272
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100273 def test_any_arguments(self):
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300274 cur = self.con.cursor()
275 cur.execute("select spam(?, ?)", (1, 2))
276 val = cur.fetchone()[0]
277 self.assertEqual(val, 2)
278
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200279 def test_empty_blob(self):
280 cur = self.con.execute("select isblob(x'')")
281 self.assertTrue(cur.fetchone()[0])
282
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +0200283 # Regarding deterministic functions:
284 #
285 # Between 3.8.3 and 3.15.0, deterministic functions were only used to
286 # optimize inner loops, so for those versions we can only test if the
287 # sqlite machinery has factored out a call or not. From 3.15.0 and onward,
288 # deterministic functions were permitted in WHERE clauses of partial
289 # indices, which allows testing based on syntax, iso. the query optimizer.
290 @unittest.skipIf(sqlite.sqlite_version_info < (3, 8, 3), "Requires SQLite 3.8.3 or higher")
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100291 def test_func_non_deterministic(self):
Sergey Fedoseev08308582018-07-08 12:09:20 +0500292 mock = unittest.mock.Mock(return_value=None)
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +0200293 self.con.create_function("nondeterministic", 0, mock, deterministic=False)
294 if sqlite.sqlite_version_info < (3, 15, 0):
295 self.con.execute("select nondeterministic() = nondeterministic()")
296 self.assertEqual(mock.call_count, 2)
297 else:
298 with self.assertRaises(sqlite.OperationalError):
299 self.con.execute("create index t on test(t) where nondeterministic() is not null")
Sergey Fedoseev08308582018-07-08 12:09:20 +0500300
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +0200301 @unittest.skipIf(sqlite.sqlite_version_info < (3, 8, 3), "Requires SQLite 3.8.3 or higher")
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100302 def test_func_deterministic(self):
Sergey Fedoseev08308582018-07-08 12:09:20 +0500303 mock = unittest.mock.Mock(return_value=None)
304 self.con.create_function("deterministic", 0, mock, deterministic=True)
Erlend Egeberg Aaslandc610d972020-05-29 01:27:31 +0200305 if sqlite.sqlite_version_info < (3, 15, 0):
306 self.con.execute("select deterministic() = deterministic()")
307 self.assertEqual(mock.call_count, 1)
308 else:
309 try:
310 self.con.execute("create index t on test(t) where deterministic() is not null")
311 except sqlite.OperationalError:
312 self.fail("Unexpected failure while creating partial index")
Sergey Fedoseev08308582018-07-08 12:09:20 +0500313
314 @unittest.skipIf(sqlite.sqlite_version_info >= (3, 8, 3), "SQLite < 3.8.3 needed")
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100315 def test_func_deterministic_not_supported(self):
Sergey Fedoseev08308582018-07-08 12:09:20 +0500316 with self.assertRaises(sqlite.NotSupportedError):
317 self.con.create_function("deterministic", 0, int, deterministic=True)
318
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100319 def test_func_deterministic_keyword_only(self):
Sergey Fedoseev08308582018-07-08 12:09:20 +0500320 with self.assertRaises(TypeError):
321 self.con.create_function("deterministic", 0, int, True)
322
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300323
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324class AggregateTests(unittest.TestCase):
325 def setUp(self):
326 self.con = sqlite.connect(":memory:")
327 cur = self.con.cursor()
328 cur.execute("""
329 create table test(
330 t text,
331 i integer,
332 f float,
333 n,
334 b blob
335 )
336 """)
337 cur.execute("insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)",
Guido van Rossumbae07c92007-10-08 02:46:15 +0000338 ("foo", 5, 3.14, None, memoryview(b"blob"),))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000339
340 self.con.create_aggregate("nostep", 1, AggrNoStep)
341 self.con.create_aggregate("nofinalize", 1, AggrNoFinalize)
342 self.con.create_aggregate("excInit", 1, AggrExceptionInInit)
343 self.con.create_aggregate("excStep", 1, AggrExceptionInStep)
344 self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize)
345 self.con.create_aggregate("checkType", 2, AggrCheckType)
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300346 self.con.create_aggregate("checkTypes", -1, AggrCheckTypes)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347 self.con.create_aggregate("mysum", 1, AggrSum)
348
349 def tearDown(self):
350 #self.cur.close()
351 #self.con.close()
352 pass
353
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100354 def test_aggr_error_on_create(self):
Berker Peksag1003b342016-06-12 22:34:49 +0300355 with self.assertRaises(sqlite.OperationalError):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 self.con.create_function("bla", -100, AggrSum)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100358 def test_aggr_no_step(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000359 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300360 with self.assertRaises(AttributeError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000361 cur.execute("select nostep(t) from test")
Berker Peksag1003b342016-06-12 22:34:49 +0300362 self.assertEqual(str(cm.exception), "'AggrNoStep' object has no attribute 'step'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100364 def test_aggr_no_finalize(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000365 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300366 with self.assertRaises(sqlite.OperationalError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000367 cur.execute("select nofinalize(t) from test")
368 val = cur.fetchone()[0]
Berker Peksag1003b342016-06-12 22:34:49 +0300369 self.assertEqual(str(cm.exception), "user-defined aggregate's 'finalize' method raised error")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100371 def test_aggr_exception_in_init(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300373 with self.assertRaises(sqlite.OperationalError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 cur.execute("select excInit(t) from test")
375 val = cur.fetchone()[0]
Berker Peksag1003b342016-06-12 22:34:49 +0300376 self.assertEqual(str(cm.exception), "user-defined aggregate's '__init__' method raised error")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000377
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100378 def test_aggr_exception_in_step(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300380 with self.assertRaises(sqlite.OperationalError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000381 cur.execute("select excStep(t) from test")
382 val = cur.fetchone()[0]
Berker Peksag1003b342016-06-12 22:34:49 +0300383 self.assertEqual(str(cm.exception), "user-defined aggregate's 'step' method raised error")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000384
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100385 def test_aggr_exception_in_finalize(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000386 cur = self.con.cursor()
Berker Peksag1003b342016-06-12 22:34:49 +0300387 with self.assertRaises(sqlite.OperationalError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000388 cur.execute("select excFinalize(t) from test")
389 val = cur.fetchone()[0]
Berker Peksag1003b342016-06-12 22:34:49 +0300390 self.assertEqual(str(cm.exception), "user-defined aggregate's 'finalize' method raised error")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000391
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100392 def test_aggr_check_param_str(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393 cur = self.con.cursor()
394 cur.execute("select checkType('str', ?)", ("foo",))
395 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000396 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100398 def test_aggr_check_param_int(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 cur = self.con.cursor()
400 cur.execute("select checkType('int', ?)", (42,))
401 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000402 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000403
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100404 def test_aggr_check_params_int(self):
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300405 cur = self.con.cursor()
406 cur.execute("select checkTypes('int', ?, ?)", (42, 24))
407 val = cur.fetchone()[0]
408 self.assertEqual(val, 2)
409
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100410 def test_aggr_check_param_float(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411 cur = self.con.cursor()
412 cur.execute("select checkType('float', ?)", (3.14,))
413 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000414 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100416 def test_aggr_check_param_none(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 cur = self.con.cursor()
418 cur.execute("select checkType('None', ?)", (None,))
419 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000420 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100422 def test_aggr_check_param_blob(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423 cur = self.con.cursor()
Guido van Rossumbae07c92007-10-08 02:46:15 +0000424 cur.execute("select checkType('blob', ?)", (memoryview(b"blob"),))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000426 self.assertEqual(val, 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100428 def test_aggr_check_aggr_sum(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000429 cur = self.con.cursor()
430 cur.execute("delete from test")
431 cur.executemany("insert into test(i) values (?)", [(10,), (20,), (30,)])
432 cur.execute("select mysum(i) from test")
433 val = cur.fetchone()[0]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000434 self.assertEqual(val, 60)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435
Erlend Egeberg Aasland979b23c2021-02-19 12:20:32 +0100436 def test_aggr_no_match(self):
437 cur = self.con.execute("select mysum(i) from (select 1 as i) where i == 0")
438 val = cur.fetchone()[0]
439 self.assertIsNone(val)
440
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441class AuthorizerTests(unittest.TestCase):
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200442 @staticmethod
443 def authorizer_cb(action, arg1, arg2, dbname, source):
444 if action != sqlite.SQLITE_SELECT:
445 return sqlite.SQLITE_DENY
446 if arg2 == 'c2' or arg1 == 't2':
447 return sqlite.SQLITE_DENY
448 return sqlite.SQLITE_OK
449
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000450 def setUp(self):
451 self.con = sqlite.connect(":memory:")
452 self.con.executescript("""
453 create table t1 (c1, c2);
454 create table t2 (c1, c2);
455 insert into t1 (c1, c2) values (1, 2);
456 insert into t2 (c1, c2) values (4, 5);
457 """)
458
459 # For our security test:
460 self.con.execute("select c2 from t2")
461
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200462 self.con.set_authorizer(self.authorizer_cb)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000463
464 def tearDown(self):
465 pass
466
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200467 def test_table_access(self):
Berker Peksag1003b342016-06-12 22:34:49 +0300468 with self.assertRaises(sqlite.DatabaseError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469 self.con.execute("select * from t2")
Berker Peksag1003b342016-06-12 22:34:49 +0300470 self.assertIn('prohibited', str(cm.exception))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000471
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200472 def test_column_access(self):
Berker Peksag1003b342016-06-12 22:34:49 +0300473 with self.assertRaises(sqlite.DatabaseError) as cm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000474 self.con.execute("select c2 from t1")
Berker Peksag1003b342016-06-12 22:34:49 +0300475 self.assertIn('prohibited', str(cm.exception))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200477class AuthorizerRaiseExceptionTests(AuthorizerTests):
478 @staticmethod
479 def authorizer_cb(action, arg1, arg2, dbname, source):
480 if action != sqlite.SQLITE_SELECT:
481 raise ValueError
482 if arg2 == 'c2' or arg1 == 't2':
483 raise ValueError
484 return sqlite.SQLITE_OK
485
486class AuthorizerIllegalTypeTests(AuthorizerTests):
487 @staticmethod
488 def authorizer_cb(action, arg1, arg2, dbname, source):
489 if action != sqlite.SQLITE_SELECT:
490 return 0.0
491 if arg2 == 'c2' or arg1 == 't2':
492 return 0.0
493 return sqlite.SQLITE_OK
494
495class AuthorizerLargeIntegerTests(AuthorizerTests):
496 @staticmethod
497 def authorizer_cb(action, arg1, arg2, dbname, source):
498 if action != sqlite.SQLITE_SELECT:
499 return 2**32
500 if arg2 == 'c2' or arg1 == 't2':
501 return 2**32
502 return sqlite.SQLITE_OK
503
504
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505def suite():
Erlend Egeberg Aasland849e3392021-01-07 01:05:07 +0100506 tests = [
507 AggregateTests,
508 AuthorizerIllegalTypeTests,
509 AuthorizerLargeIntegerTests,
510 AuthorizerRaiseExceptionTests,
511 AuthorizerTests,
512 FunctionTests,
513 ]
514 return unittest.TestSuite(
515 [unittest.TestLoader().loadTestsFromTestCase(t) for t in tests]
516 )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517
518def test():
519 runner = unittest.TextTestRunner()
520 runner.run(suite())
521
522if __name__ == "__main__":
523 test()