SQLiteMixin.dbcur()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
#!/usr/bin/env python
2
# -*- encoding: utf-8 -*-
3
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
4
# Author: Binux<[email protected]>
5
#         http://binux.me
6
# Created on 2014-11-22 20:30:44
7
8
import os
9
import time
10
import sqlite3
11
import threading
12
13
14
class SQLiteMixin(object):
15
16
    @property
17
    def dbcur(self):
18
        pid = (os.getpid(), threading.current_thread().ident)
19
        if not (self.conn and pid == self.last_pid):
20
            self.last_pid = pid
21
            self.conn = sqlite3.connect(self.path, isolation_level=None)
22
        return self.conn.cursor()
23
24
25 View Code Duplication
class SplitTableMixin(object):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
26
    UPDATE_PROJECTS_TIME = 10 * 60
27
28
    def _tablename(self, project):
29
        if self.__tablename__:
30
            return '%s_%s' % (self.__tablename__, project)
31
        else:
32
            return project
33
34
    @property
35
    def projects(self):
36
        if time.time() - getattr(self, '_last_update_projects', 0) \
37
                > self.UPDATE_PROJECTS_TIME:
38
            self._list_project()
39
        return self._projects
40
41
    @projects.setter
42
    def projects(self, value):
43
        self._projects = value
44
45
    def _list_project(self):
46
        self._last_update_projects = time.time()
47
        self.projects = set()
48
        if self.__tablename__:
49
            prefix = '%s_' % self.__tablename__
50
        else:
51
            prefix = ''
52
        for project, in self._select('sqlite_master', what='name',
53
                                     where='type = "table"'):
54
            if project.startswith(prefix):
55
                project = project[len(prefix):]
56
                self.projects.add(project)
57
58
    def drop(self, project):
59
        if project not in self.projects:
60
            self._list_project()
61
        if project not in self.projects:
62
            return
63
        tablename = self._tablename(project)
64
        self._execute("DROP TABLE %s" % self.escape(tablename))
65
        self._list_project()
66