aboutsummaryrefslogtreecommitdiff
path: root/src/mailman_pgp/database/__init__.py
blob: 950c6b18dbd5592df5a6a810be2554a2a3b0ecaf (plain) (blame)
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
# Copyright (C) 2017 Jan Jancar
#
# This file is a part of the Mailman PGP plugin.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.

""""""

from contextlib import contextmanager

from mailman.config import config as mailman_config
from mailman.utilities.string import expand
from public import public
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from mailman_pgp.config import config
from mailman_pgp.model.base import Base


@public
class Database:
    def __init__(self):
        url = config.get('db', 'url')
        self._url = expand(url, None, mailman_config.paths)
        self.engine = create_engine(self._url)
        self._scoped_session = scoped_session(sessionmaker(bind=self.engine))
        Base.metadata.create_all(self.engine)
        self.session.commit()

    @property
    def session(self):
        return self._scoped_session()


@public
@contextmanager
def transaction():
    try:
        yield config.db.session
    except:
        config.db.session.rollback()
        raise
    else:
        config.db.session.commit()


@public
def query(cls):
    return config.db.session.query(cls)