File: bench-411.py

package info (click to toggle)
psycopg3 3.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,836 kB
  • sloc: python: 46,657; sh: 403; ansic: 149; makefile: 73
file content (394 lines) | stat: -rw-r--r-- 11,430 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
from __future__ import annotations

import os
import sys
import time
import random
import asyncio
import logging
import selectors
from enum import Enum
from typing import Any
from argparse import ArgumentParser, Namespace
from contextlib import contextmanager
from collections.abc import Generator
from concurrent.futures import ThreadPoolExecutor

logger = logging.getLogger()
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)


class Driver(str, Enum):
    psycopg2 = "psycopg2"
    psycopg2_green = "psycopg2_green"
    psycopg = "psycopg"
    psycopg_async = "psycopg_async"
    asyncpg = "asyncpg"


ids: list[int] = []
data: list[dict[str, Any]] = []


def main() -> None:
    args = parse_cmdline()

    ids[:] = range(args.ntests)
    data[:] = [
        dict(
            id=i,
            name="c%d" % i,
            description="c%d" % i,
            q=i * 10,
            p=i * 20,
            x=i * 30,
            y=i * 40,
        )
        for i in ids
    ]

    # Must be done just on end
    drop_at_the_end = args.drop
    args.drop = False

    for i, name in enumerate(args.drivers):
        if i == len(args.drivers) - 1:
            args.drop = drop_at_the_end

        if name == Driver.psycopg2:
            import psycopg2  # type: ignore

            run_psycopg2(psycopg2, args)

        elif name == Driver.psycopg2_green:
            import psycopg2
            import psycopg2.extras  # type: ignore

            run_psycopg2_green(psycopg2, args)

        elif name == Driver.psycopg:
            import psycopg

            run_psycopg(psycopg, args)

        elif name == Driver.psycopg_async:
            import psycopg

            kwargs: dict[str, Any] = {}
            if sys.platform == "win32":
                if sys.version_info >= (3, 12):
                    kwargs["loop_factory"] = lambda: asyncio.SelectorEventLoop(
                        selectors.SelectSelector()
                    )
                else:
                    asyncio.set_event_loop_policy(
                        asyncio.WindowsSelectorEventLoopPolicy()
                    )

            asyncio.run(run_psycopg_async(psycopg, args), **kwargs)

        elif name == Driver.asyncpg:
            import asyncpg  # type: ignore

            asyncio.run(run_asyncpg(asyncpg, args))

        else:
            raise AssertionError(f"unknown driver: {name!r}")

        # Must be done just on start
        args.create = False


table = """
CREATE TABLE customer (
        id SERIAL NOT NULL,
        name VARCHAR(255),
        description VARCHAR(255),
        q INTEGER,
        p INTEGER,
        x INTEGER,
        y INTEGER,
        z INTEGER,
        PRIMARY KEY (id)
)
"""
drop = "DROP TABLE IF EXISTS customer"

insert = """
INSERT INTO customer (id, name, description, q, p, x, y) VALUES
(%(id)s, %(name)s, %(description)s, %(q)s, %(p)s, %(x)s, %(y)s)
"""

select = """
SELECT customer.id, customer.name, customer.description, customer.q,
    customer.p, customer.x, customer.y, customer.z
FROM customer
WHERE customer.id = %(id)s
"""


@contextmanager
def time_log(message: str) -> Generator[None]:
    start = time.monotonic()
    yield
    end = time.monotonic()
    logger.info(f"Run {message} in {end - start} s")


def run_psycopg2(psycopg2: Any, args: Namespace) -> None:
    logger.info("Running psycopg2")

    if args.create:
        logger.info(f"inserting {args.ntests} test records")
        with psycopg2.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
                cursor.execute(table)
                cursor.executemany(insert, data)
            conn.commit()

    def run(i):
        logger.info(f"thread {i} running {args.ntests} queries")
        to_query = random.choices(ids, k=args.ntests)
        with psycopg2.connect(args.dsn) as conn:
            with time_log("psycopg2"):
                for id_ in to_query:
                    with conn.cursor() as cursor:
                        cursor.execute(select, {"id": id_})
                        cursor.fetchall()
                    # conn.rollback()

    if args.concurrency == 1:
        run(0)
    else:
        with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
            list(executor.map(run, range(args.concurrency)))

    if args.drop:
        logger.info("dropping test records")
        with psycopg2.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
            conn.commit()


def run_psycopg2_green(psycopg2: Any, args: Namespace) -> None:
    logger.info("Running psycopg2_green")

    psycopg2.extensions.set_wait_callback(psycopg2.extras.wait_select)

    if args.create:
        logger.info(f"inserting {args.ntests} test records")
        with psycopg2.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
                cursor.execute(table)
                cursor.executemany(insert, data)
            conn.commit()

    def run(i):
        logger.info(f"thread {i} running {args.ntests} queries")
        to_query = random.choices(ids, k=args.ntests)
        with psycopg2.connect(args.dsn) as conn:
            with time_log("psycopg2"):
                for id_ in to_query:
                    with conn.cursor() as cursor:
                        cursor.execute(select, {"id": id_})
                        cursor.fetchall()
                    # conn.rollback()

    if args.concurrency == 1:
        run(0)
    else:
        with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
            list(executor.map(run, range(args.concurrency)))

    if args.drop:
        logger.info("dropping test records")
        with psycopg2.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
            conn.commit()

    psycopg2.extensions.set_wait_callback(None)


def run_psycopg(psycopg: Any, args: Namespace) -> None:
    logger.info("Running psycopg sync")

    if args.create:
        logger.info(f"inserting {args.ntests} test records")
        with psycopg.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
                cursor.execute(table)
                cursor.executemany(insert, data)
            conn.commit()

    def run(i):
        logger.info(f"thread {i} running {args.ntests} queries")
        to_query = random.choices(ids, k=args.ntests)
        with psycopg.connect(args.dsn) as conn:
            with time_log("psycopg"):
                for id_ in to_query:
                    with conn.cursor() as cursor:
                        cursor.execute(select, {"id": id_})
                        cursor.fetchall()
                    # conn.rollback()

    if args.concurrency == 1:
        run(0)
    else:
        with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
            list(executor.map(run, range(args.concurrency)))

    if args.drop:
        logger.info("dropping test records")
        with psycopg.connect(args.dsn) as conn:
            with conn.cursor() as cursor:
                cursor.execute(drop)
            conn.commit()


async def run_psycopg_async(psycopg: Any, args: Namespace) -> None:
    logger.info("Running psycopg async")

    conn: Any

    if args.create:
        logger.info(f"inserting {args.ntests} test records")
        async with await psycopg.AsyncConnection.connect(args.dsn) as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(drop)
                await cursor.execute(table)
                await cursor.executemany(insert, data)
            await conn.commit()

    async def run(i):
        logger.info(f"task {i} running {args.ntests} queries")
        to_query = random.choices(ids, k=args.ntests)
        async with await psycopg.AsyncConnection.connect(args.dsn) as conn:
            with time_log("psycopg_async"):
                for id_ in to_query:
                    cursor = await conn.execute(select, {"id": id_})
                    await cursor.fetchall()
                    await cursor.close()
                    # await conn.rollback()

    if args.concurrency == 1:
        await run(0)
    else:
        tasks = [run(i) for i in range(args.concurrency)]
        await asyncio.gather(*tasks)

    if args.drop:
        logger.info("dropping test records")
        async with await psycopg.AsyncConnection.connect(args.dsn) as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(drop)
            await conn.commit()


async def run_asyncpg(asyncpg: Any, args: Namespace) -> None:
    logger.info("Running asyncpg")

    places = dict(id="$1", name="$2", description="$3", q="$4", p="$5", x="$6", y="$7")
    a_insert = insert % places
    a_select = select % {"id": "$1"}

    conn: Any

    if args.create:
        logger.info(f"inserting {args.ntests} test records")
        conn = await asyncpg.connect(args.dsn)
        async with conn.transaction():
            await conn.execute(drop)
            await conn.execute(table)
            await conn.executemany(a_insert, [tuple(d.values()) for d in data])
        await conn.close()

    async def run(i):
        logger.info(f"task {i} running {args.ntests} queries")
        to_query = random.choices(ids, k=args.ntests)
        conn = await asyncpg.connect(args.dsn)
        with time_log("asyncpg"):
            for id_ in to_query:
                # tr = conn.transaction()
                # await tr.start()
                await conn.fetch(a_select, id_)
                # await tr.rollback()
        await conn.close()

    if args.concurrency == 1:
        await run(0)
    else:
        tasks = [run(i) for i in range(args.concurrency)]
        await asyncio.gather(*tasks)

    if args.drop:
        logger.info("dropping test records")
        conn = await asyncpg.connect(args.dsn)
        async with conn.transaction():
            await conn.execute(drop)
        await conn.close()


def parse_cmdline() -> Namespace:
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "drivers",
        nargs="+",
        metavar="DRIVER",
        type=Driver,
        help=f"the drivers to test [choices: {', '.join(d.value for d in Driver)}]",
    )

    parser.add_argument(
        "--ntests",
        "-n",
        type=int,
        default=10_000,
        help="number of tests to perform [default: %(default)s]",
    )

    parser.add_argument(
        "--concurrency",
        "-c",
        type=int,
        default=1,
        help="number of parallel tasks [default: %(default)s]",
    )

    parser.add_argument(
        "--dsn",
        default=os.environ.get("PSYCOPG_TEST_DSN", ""),
        help="database connection string"
        " [default: %(default)r (from PSYCOPG_TEST_DSN env var)]",
    )

    parser.add_argument(
        "--no-create",
        dest="create",
        action="store_false",
        default="True",
        help="skip data creation before tests (it must exist already)",
    )

    parser.add_argument(
        "--no-drop",
        dest="drop",
        action="store_false",
        default="True",
        help="skip data drop after tests",
    )

    opt = parser.parse_args()

    return opt


if __name__ == "__main__":
    main()