wrappers.py 1.89 KB
Newer Older
1
from contextvars import ContextVar
2
from peewee import *
3
4
from peewee import PostgresqlDatabase, InterfaceError as PeeWeeInterfaceError

5
import logging
6
from playhouse.db_url import connect, parse
7
8
9
10
11

from config import SRC_LOG_LEVELS

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["DB"])
12
13
14
15

db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None}
db_state = ContextVar("db_state", default=db_state_default.copy())

16
class PeeweeConnectionState(object):
17
18
19
20
21
22
23
24
    def __init__(self, **kwargs):
        super().__setattr__("_state", db_state)
        super().__init__(**kwargs)

    def __setattr__(self, name, value):
        self._state.get()[name] = value

    def __getattr__(self, name):
25
26
        value = self._state.get()[name]
        return value
27

28
29
30
31
32
33
34
35
36
37
38
39
class CustomReconnectMixin(ReconnectMixin):
    reconnect_errors = (
        # psycopg2
        (OperationalError, 'termin'),
        (InterfaceError, 'closed'),
        # peewee
        (PeeWeeInterfaceError, 'closed'),
    )

class ReconnectingPostgresqlDatabase(CustomReconnectMixin, PostgresqlDatabase):
    pass

40
41
42
def register_connection(db_url):
    db = connect(db_url)
    if isinstance(db, PostgresqlDatabase):
43
        # Enable autoconnect for SQLite databases, managed by Peewee
perf3ct's avatar
perf3ct committed
44
        db.autoconnect = True
45
        db.reuse_if_open = True
46
        log.info("Connected to PostgreSQL database")
47
48
49
        connection = parse(db_url)
        db = ReconnectingPostgresqlDatabase(connection['database'], user=connection['user'], password=connection['password'],host=connection['host'], port=connection['port'])
        db.connect(reuse_if_open=True)
50
    elif isinstance(db, SqliteDatabase):
51
        # Enable autoconnect for SQLite databases, managed by Peewee
perf3ct's avatar
perf3ct committed
52
        db.autoconnect = True
53
        db.reuse_if_open = True
54
        log.info("Connected to SQLite database")
55
56
    else:
        raise ValueError('Unsupported database connection')
57
    return db