summaryrefslogtreecommitdiff
path: root/test/ext/mypy/plain_files/sessionmakers.py
blob: 2d02f2a3f43f27ab8757a47acf16dd39a2b16ac7 (plain)
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
"""test #7656"""

from sqlalchemy import create_engine
from sqlalchemy import Engine
from sqlalchemy.ext.asyncio import async_scoped_session
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker


async_engine = create_async_engine("...")


class MyAsyncSession(AsyncSession):
    pass


def async_session_factory(
    engine: AsyncEngine,
) -> async_sessionmaker[MyAsyncSession]:
    return async_sessionmaker(engine, class_=MyAsyncSession)


def async_scoped_session_factory(
    engine: AsyncEngine,
) -> async_scoped_session[MyAsyncSession]:
    return async_scoped_session(
        async_sessionmaker(engine, class_=MyAsyncSession),
        scopefunc=lambda: None,
    )


async def async_main() -> None:
    fac = async_session_factory(async_engine)

    async with fac() as sess:
        # EXPECTED_TYPE: MyAsyncSession
        reveal_type(sess)

    async with fac.begin() as sess:
        # EXPECTED_TYPE: MyAsyncSession
        reveal_type(sess)

    scoped_fac = async_scoped_session_factory(async_engine)

    sess = scoped_fac()

    # EXPECTED_TYPE: MyAsyncSession
    reveal_type(sess)


engine = create_engine("...")


class MySession(Session):
    pass


def session_factory(
    engine: Engine,
) -> sessionmaker[MySession]:
    return sessionmaker(engine, class_=MySession)


def scoped_session_factory(engine: Engine) -> scoped_session[MySession]:
    return scoped_session(sessionmaker(engine, class_=MySession))


def main() -> None:
    fac = session_factory(engine)

    with fac() as sess:
        # EXPECTED_TYPE: MySession
        reveal_type(sess)

    with fac.begin() as sess:
        # EXPECTED_TYPE: MySession
        reveal_type(sess)

    scoped_fac = scoped_session_factory(engine)

    sess = scoped_fac()
    # EXPECTED_TYPE: MySession
    reveal_type(sess)


def test_8837_sync() -> None:
    sm = sessionmaker()

    # EXPECTED_TYPE: sessionmaker[Session]
    reveal_type(sm)

    session = sm()

    # EXPECTED_TYPE: Session
    reveal_type(session)


def test_8837_async() -> None:
    as_ = async_sessionmaker()

    # EXPECTED_TYPE: async_sessionmaker[AsyncSession]
    reveal_type(as_)

    async_session = as_()

    # EXPECTED_TYPE: AsyncSession
    reveal_type(async_session)