File: test_sscursor.py

package info (click to toggle)
aiomysql 0.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 912 kB
  • sloc: python: 6,894; makefile: 213
file content (304 lines) | stat: -rw-r--r-- 9,659 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import asyncio

import pytest
from pymysql import NotSupportedError

from aiomysql import ProgrammingError, InterfaceError, OperationalError
from aiomysql.cursors import SSCursor


DATA = [
    ('America', '', 'America/Jamaica'),
    ('America', '', 'America/Los_Angeles'),
    ('America', '', 'America/Lima'),
    ('America', '', 'America/New_York'),
    ('America', '', 'America/Menominee'),
    ('America', '', 'America/Havana'),
    ('America', '', 'America/El_Salvador'),
    ('America', '', 'America/Costa_Rica'),
    ('America', '', 'America/Denver'),
    ('America', '', 'America/Detroit'), ]


async def _prepare(conn):
    cursor = await conn.cursor()
    # Create table
    await cursor.execute('DROP TABLE IF EXISTS tz_data;')
    await cursor.execute('CREATE TABLE tz_data ('
                         'region VARCHAR(64),'
                         'zone VARCHAR(64),'
                         'name VARCHAR(64))')

    await cursor.executemany(
        'INSERT INTO tz_data VALUES (%s, %s, %s)', DATA)
    await conn.commit()
    await cursor.close()


@pytest.mark.run_loop
async def test_ssursor(connection):
    # affected_rows = 18446744073709551615
    conn = connection
    cursor = await conn.cursor(SSCursor)
    # Create table
    await cursor.execute('DROP TABLE IF EXISTS tz_data;')
    await cursor.execute(('CREATE TABLE tz_data ('
                          'region VARCHAR(64),'
                          'zone VARCHAR(64),'
                          'name VARCHAR(64))'))

    # Test INSERT
    for i in DATA:
        await cursor.execute(
            'INSERT INTO tz_data VALUES (%s, %s, %s)', i)
        assert conn.affected_rows() == 1, 'affected_rows does not match'
    await conn.commit()

    # Test update, affected_rows()
    await cursor.execute('UPDATE tz_data SET zone = %s', ['Foo'])
    await conn.commit()

    assert cursor.rowcount == len(DATA), \
        'Update failed. affected_rows != %s' % (str(len(DATA)))

    await cursor.close()
    await cursor.close()


@pytest.mark.run_loop
async def test_sscursor_fetchall(connection):
    conn = connection
    cursor = await conn.cursor(SSCursor)

    await _prepare(conn)
    await cursor.execute('SELECT * FROM tz_data')
    fetched_data = await cursor.fetchall()
    assert len(fetched_data) == len(DATA), \
        'fetchall failed. Number of rows does not match'


@pytest.mark.run_loop
async def test_sscursor_fetchmany(connection):
    conn = connection
    cursor = await conn.cursor(SSCursor)
    await _prepare(conn)
    await cursor.execute('SELECT * FROM tz_data')
    fetched_data = await cursor.fetchmany(2)
    assert len(fetched_data) == 2, \
        'fetchmany failed. Number of rows does not match'

    await cursor.close()
    # test default fetchmany size
    cursor = await conn.cursor(SSCursor)
    await cursor.execute('SELECT * FROM tz_data;')
    fetched_data = await cursor.fetchmany()
    assert len(fetched_data) == 1


@pytest.mark.run_loop
async def test_sscursor_executemany(connection):
    conn = connection
    await _prepare(conn)
    cursor = await conn.cursor(SSCursor)
    # Test executemany
    await cursor.executemany(
        'INSERT INTO tz_data VALUES (%s, %s, %s)', DATA)
    msg = 'executemany failed. cursor.rowcount != %s'
    assert cursor.rowcount == len(DATA), msg % (str(len(DATA)))


@pytest.mark.run_loop
async def test_sscursor_scroll_relative(connection):
    conn = connection
    await _prepare(conn)
    cursor = await conn.cursor(SSCursor)
    await cursor.execute('SELECT * FROM tz_data;')
    await cursor.scroll(1)
    ret = await cursor.fetchone()
    assert ('America', '', 'America/Los_Angeles') == ret


@pytest.mark.run_loop
async def test_sscursor_scroll_absolute(connection):
    conn = connection
    await _prepare(conn)
    cursor = await conn.cursor(SSCursor)
    await cursor.execute('SELECT * FROM tz_data;')
    await cursor.scroll(2, mode='absolute')
    ret = await cursor.fetchone()
    assert ('America', '', 'America/Lima') == ret


@pytest.mark.run_loop
async def test_sscursor_scroll_errors(connection):
    conn = connection
    await _prepare(conn)
    cursor = await conn.cursor(SSCursor)

    await cursor.execute('SELECT * FROM tz_data;')

    with pytest.raises(NotSupportedError):
        await cursor.scroll(-2, mode='relative')

    await cursor.scroll(2, mode='absolute')

    with pytest.raises(NotSupportedError):
        await cursor.scroll(1, mode='absolute')
    with pytest.raises(ProgrammingError):
        await cursor.scroll(2, mode='not_valid_mode')


@pytest.mark.run_loop
async def test_sscursor_cancel(connection):
    conn = connection
    cur = await conn.cursor(SSCursor)
    # Prepare A LOT of data

    await cur.execute('DROP TABLE IF EXISTS long_seq;')
    await cur.execute(
        """ CREATE TABLE long_seq (
              id int(11)
            )
        """)

    ids = [(x) for x in range(100000)]
    await cur.executemany('INSERT INTO long_seq VALUES (%s)', ids)

    # Will return several results. All we need at this point
    big_str = "x" * 10000
    await cur.execute(
        """SELECT '{}' as id FROM long_seq;
        """.format(big_str))
    first = await cur.fetchone()
    assert first == (big_str,)

    async def read_cursor():
        while True:
            res = await cur.fetchone()
            if res is None:
                break
    task = asyncio.ensure_future(read_cursor())
    await asyncio.sleep(0)
    assert not task.done(), "Test failed to produce needed condition."
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass

    with pytest.raises(InterfaceError):
        await conn.cursor(SSCursor)


@pytest.mark.run_loop
async def test_sscursor_discarded_result(connection):
    conn = connection
    await _prepare(conn)
    async with conn.cursor(SSCursor) as cursor:
        await cursor.execute("select 1")
        await cursor.execute("select 2")
        ret = await cursor.fetchone()
    assert (2,) == ret


@pytest.mark.run_loop
async def test_max_execution_time(mysql_server, connection):
    conn = connection

    async with connection.cursor() as cur:
        await cur.execute("DROP TABLE IF EXISTS tbl;")

        await cur.execute(
            """
            CREATE TABLE tbl (
            id MEDIUMINT NOT NULL AUTO_INCREMENT,
            name VARCHAR(255) NOT NULL,
            PRIMARY KEY (id));
            """
        )

        for i in [(1, "a"), (2, "b"), (3, "c")]:
            await cur.execute("INSERT INTO tbl VALUES(%s, %s)", i)

        await conn.commit()

    async with conn.cursor(SSCursor) as cur:
        # MySQL MAX_EXECUTION_TIME takes ms
        # MariaDB max_statement_time takes seconds as int/float, introduced in 10.1

        # this will sleep 0.01 seconds per row
        if mysql_server["db_type"] == "mysql":
            sql = """
                  SELECT /*+ MAX_EXECUTION_TIME(2000) */
                  name, sleep(0.01) FROM tbl
                  """
        else:
            sql = """
                  SET STATEMENT max_statement_time=2 FOR
                  SELECT name, sleep(0.01) FROM tbl
                  """

        await cur.execute(sql)
        # unlike Cursor, SSCursor returns a list of tuples here

        assert (await cur.fetchall()) == [
            ("a", 0),
            ("b", 0),
            ("c", 0),
        ]

        if mysql_server["db_type"] == "mysql":
            sql = """
                      SELECT /*+ MAX_EXECUTION_TIME(2000) */
                      name, sleep(0.01) FROM tbl
                      """
        else:
            sql = """
                      SET STATEMENT max_statement_time=2 FOR
                      SELECT name, sleep(0.01) FROM tbl
                      """
        await cur.execute(sql)
        assert (await cur.fetchone()) == ("a", 0)

        # this discards the previous unfinished query and raises an
        # incomplete unbuffered query warning
        with pytest.warns(UserWarning):
            await cur.execute("SELECT 1")
        assert (await cur.fetchone()) == (1,)

        # SSCursor will not read the EOF packet until we try to read
        # another row. Skipping this will raise an incomplete unbuffered
        # query warning in the next cur.execute().
        assert (await cur.fetchone()) is None

        if mysql_server["db_type"] == "mysql":
            sql = """
                      SELECT /*+ MAX_EXECUTION_TIME(1) */
                      name, sleep(1) FROM tbl
                      """
        else:
            sql = """
                      SET STATEMENT max_statement_time=0.001 FOR
                      SELECT name, sleep(1) FROM tbl
                      """
        with pytest.raises(OperationalError) as cm:
            # in an unbuffered cursor the OperationalError may not show up
            # until fetching the entire result
            await cur.execute(sql)
            await cur.fetchall()

        if mysql_server["db_type"] == "mysql":
            # this constant was only introduced in MySQL 5.7, not sure
            # what was returned before, may have been ER_QUERY_INTERRUPTED

            # this constant is pending a new PyMySQL release
            # assert cm.value.args[0] == pymysql.constants.ER.QUERY_TIMEOUT
            assert cm.value.args[0] == 3024
        else:
            # this constant is pending a new PyMySQL release
            # assert cm.value.args[0] == pymysql.constants.ER.STATEMENT_TIMEOUT
            assert cm.value.args[0] == 1969

        # connection should still be fine at this point
        await cur.execute("SELECT 1")
        assert (await cur.fetchone()) == (1,)