Passed
Pull Request — master (#117)
by
unknown
05:28
created

database.base.Base.query()   C

Complexity

Conditions 11

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 22
rs 5.4
c 0
b 0
f 0
cc 11
nop 5

How to fix   Complexity   

Complexity

Complex classes like database.base.Base.query() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import urllib.parse as urlparse
2
3
import psycopg2
4
5
6
class Base:
7
    def __init__(self, db_url, logs=False):
8
        self.logs = logs
9
        url = urlparse.urlparse(db_url)
10
        self.db_auth = {
11
            "user": url.username,
12
            "password": url.password,
13
            "host": url.hostname,
14
            "port": url.port,
15
            "database": url.path[1:],
16
        }
17
        self.conn, self.cur = None, None
18
        self.connect()
19
20
    def create_table(self, name, table: dict):
21
        columns = [f"{column} {_type}" for column, _type in list(table.items())]
22
        self.query(f"CREATE TABLE {name} ({', '.join(columns)}) ")
23
24
    def find_table(self, name):
25
        res = self.query(
26
            f"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{name}'"
27
        )
28
        return len(res) > 0
29
30
    def query(self, query: str, args=None, fetchone=False, fetchall=False):
31
        print(query) if self.logs else None
32
        commit_func = ["create", "insert", "delete", "update"]
33
        result_func = ["select", "returning"]
34
        self.cur.execute(query, args) if args else self.cur.execute(query)
35
36
        if any(func in query.lower() for func in commit_func):
37
            self.commit()
38
39
        if any(func in query.lower() for func in result_func):
40
            if not fetchone and not fetchall:
41
                fetchall = True
42
43
        if fetchone:
44
            exec_result = self.cur.fetchone()
45
        elif fetchall:
46
            exec_result = self.cur.fetchall()
47
        else:
48
            exec_result = None
49
50
        if fetchone or fetchall:
51
            return exec_result
52
53
    def commit(self):
54
        self.conn.commit()
55
56
    def connect(self):
57
        self.conn = psycopg2.connect(**self.db_auth)
58
        self.cur = self.conn.cursor()
59
60
    def close(self):
61
        self.cur.close()
62
        self.conn.close()
63