summaryrefslogtreecommitdiff
path: root/apps/patchwork/db.py
blob: 26957fcb7c86a824db9490fe5915cb1dd05a3624 (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
113
# Copyright (C) 2013 Linaro
#
# Author: Milo Casagrande <milo.casagrande@linaro.org>
# This file is part of the Patchmetrics package.
#
# Patchmetrics 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 2 of the License, or
# (at your option) any later version.
#
# Patchmetrics 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 Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
here = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(here, '..'))
import django.db
from django.utils.importlib import import_module


class PatchworkDB(object):
    """A cache backed by a SQLite DB to store users.

    This is used to provide a users cache in order to speed up the process
    of analyzing patches from a git repository.

    Users are stored with their email address, and a boolean value indicating
    if the user is a valid Linaro user. A valid Linaro user is a user that
    exists in Linaro Login (Crowd).

    There is no user logic here, it is just used as a cache backend.
    """

    def __init__(self):
        self._db_wrapper = None
        self.cursor = None

    def __enter__(self):
        self._db_wrapper = django.db.connections[django.db.DEFAULT_DB_ALIAS]
        self.cursor = self._db_wrapper.cursor()  # triggers a "connection"
        self.connection = self._db_wrapper.connection

        if not self.table_exists('users'):
            self.cursor.execute('''CREATE TABLE users
                (id TEXT PRIMARY KEY, valid INTEGER, ts TIMESTAMP)''')

    def __exit__(self, type, value, tb):
        """Closes the DB connection."""
        # Force a commit, even if we are in autocommit mode.
        self.connection.commit()
        self.connection.close()

    def table_exists(self, table):
        """Checks if a table exists in the DB.

        :param table: The name of the table to check.
        """
        base = self._db_wrapper.__module__.replace('.base', '')
        module = import_module('.introspection', base)
        introspection = module.DatabaseIntrospection(self.connection)
        return table in introspection.get_table_list(self.cursor)

    def insert_user(self, email, valid, timestamp):
        """Inserts a user in the DB.

        :param email: The user email, this is the unique key in the DB.
        :param valid: If the user is a valid Linaro user.
        :param timestamp: When the user was added in the cache.
        """
        self.cursor.execute('''INSERT INTO users(id, valid, ts)
            VALUES (%s, %s, %s)''', (email, int(valid), timestamp))

    def update_user(self, email, valid, timestamp):
        """Updates a user in the DB."""
        self.cursor.execute('''UPDATE users SET valid=%s, ts=%s WHERE id=%s''',
                            (int(valid), timestamp, email))

    def get_user(self, email):
        """Retrieves a user from the DB.

        :param email: The user email.
        :return A tuple with the data found, None otherwise.
        """
        self.cursor.execute('''SELECT * FROM users where id=%s''', [email])
        return self.cursor.fetchone()

    def user_exists(self, email):
        """Verifies if a user exists in the DB.

        :param email: The user email.
        :return True or False.
        """
        return self.get_user(email) is not None

if __name__ == '__main__':
    import datetime
    db = PatchworkDB()
    with db:
        if not db.user_exists('andy'):
            print "creating user"
            db.insert_user('andy', 1, datetime.datetime.now())
        else:
            print "user exists, updating"
            db.update_user('andy', 0, datetime.datetime.now())