Browse Source

add DB class and fit to tests

Maxime Alves LIRMM@home 3 years ago
parent
commit
37c0450665

+ 2
- 0
pyheatpump/__init__.py View File

@@ -2,3 +2,5 @@ __version__ = '0.2.0'
2 2
 
3 3
 def version():
4 4
     return 'PyHeatpump version : {}'.format(__version__)
5
+
6
+from .db import DB

+ 0
- 3
pyheatpump/cli.py View File

@@ -14,7 +14,6 @@ from datetime import datetime
14 14
 
15 15
 from pyheatpump.logger import logger_init
16 16
 from pyheatpump.models import *
17
-from pyheatpump.db import commit
18 17
 
19 18
 CONTEXT_SETTINGS={
20 19
     'default_map':{'run': {}}
@@ -142,7 +141,6 @@ def fetch(type):
142 141
                 'value': res[r]})
143 142
             val.insert()
144 143
 
145
-    commit()
146 144
     logger.info('Successfully read all variables')
147 145
 
148 146
 
@@ -225,7 +223,6 @@ def supervise(since):
225 223
 
226 224
     control_data = get_resp.json()
227 225
     if h.control(control_data):
228
-        commit()
229 226
         logger.info('GET to supervisor succeded : updated values')
230 227
         set_last_update(int(datetime.now().strftime('%s')))
231 228
     else:

+ 67
- 30
pyheatpump/db.py View File

@@ -10,40 +10,73 @@ logger = logger_init()
10 10
 
11 11
 conn = None
12 12
 
13
-def connect():
14
-    global conn
15
-    if conn is None:
13
+class DB():
14
+    Conn = None
15
+
16
+    @staticmethod
17
+    def connect():
18
+        if DB.Conn:
19
+            try:
20
+                DB.Conn.cursor()
21
+                return True
22
+            except sqlite3.ProgrammingError:
23
+                pass
24
+            except Exception as e:
25
+                print(e)
26
+                sys.exit(1)
27
+
16 28
         logger.info('Will connect to database {}'.format(
17
-           config['heatpump']['database']))
18
-        conn = sqlite3.connect(config['heatpump']['database'])
19
-        conn.row_factory = sqlite3.Row
20
-    return conn
29
+            config['heatpump']['database']))
30
+        DB.Conn = sqlite3.connect(
31
+            config['heatpump']['database'],
32
+            isolation_level=None)
33
+        DB.Conn.row_factory = sqlite3.Row
34
+        return True
35
+
36
+
37
+    def commit():
38
+        """
39
+            Default mode of connecting is autocommit
40
+        """
41
+        pass
42
+
21 43
 
22
-def commit():
23
-    global conn
24
-    logger.info('Commit database')
25
-    conn.commit()
44
+    @staticmethod
45
+    def initialize(filename):
46
+        if DB.Conn:
47
+            DB.Conn.close()
26 48
 
27
-def initialize(filename):
28
-    p = Popen(
29
-        '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']),
30
-        shell=True
31
-    )
32
-    return True if p.wait() == 0 else False
49
+        p = Popen(
50
+            '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']),
51
+            shell=True)
33 52
 
53
+        return True if p.wait() == 0 else False
34 54
 
35
-def sql(query):
36
-    if conn is None:
37
-        logger.debug(f'Connect to the DB\n')
38
-        connect()
39 55
 
40
-    cursor = conn.cursor()
41
-    logger.debug(f'Will execute query : \n{query}\n')
42
-    cursor.execute(query)
56
+    @staticmethod
57
+    def sql(query, params={}):
58
+        print(query)
59
+        print(params)
60
+        if not DB.connect():
61
+            raise Exception('Can\'t connect to DB')
62
+
63
+        return DB.Conn.execute(query, params or {})
64
+
65
+    @staticmethod
66
+    def sqlf(filename):
67
+        with open(filename) as f:
68
+            if not DB.connect():
69
+                raise Exception('Can\'t connect to DB')
70
+
71
+            try:
72
+                return DB.Conn.execute((' '.join(f.readlines())).replace('\n', ''))
73
+            except StopIteration:
74
+                print('failed')
75
+                return []
76
+            except sqlite3.IntegrityError as e:
77
+                print(e)
78
+                return []
43 79
 
44
-    conn.close()
45
-    logger.debug(f'Connection closed\n')
46
-    return cursor
47 80
 
48 81
 class RowClass(object):
49 82
     def __init__(self, **kwargs):
@@ -54,8 +87,12 @@ class RowClass(object):
54 87
     def select(self, key, tablename):
55 88
         attr = getattr(self, key)
56 89
         if type(attr) == str:
57
-            q = f"SELECT * FROM {tablename} WHERE {key} LIKE '{attr}'"
90
+            q = ("SELECT * FROM {tablename} WHERE ? LIKE '?'", (key, attr))
58 91
         elif type(attr) == int:
59
-            q = f"SELECT * FROM {tablename} WHERE {key} = {attr}"
92
+            q = ("SELECT * FROM {tablename} WHERE ? LIKE ?", (key, attr))
93
+
94
+        res = []
95
+        for row in DB.sql(*q):
96
+            res.append(res)
60 97
 
61
-        return sql(q)
98
+        return res

+ 0
- 1
pyheatpump/heatpump.py View File

@@ -3,7 +3,6 @@ from datetime import datetime
3 3
 from starlette.routing import Router, Route
4 4
 from starlette.responses import JSONResponse
5 5
 from .config import config
6
-from pyheatpump.db import sql
7 6
 
8 7
 from pyheatpump.models import *
9 8
 

+ 19
- 21
pyheatpump/models/variable.py View File

@@ -1,5 +1,5 @@
1 1
 from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
2
+from pyheatpump.db import DB
3 3
 from datetime import date
4 4
 from pyheatpump.modbus import rtu
5 5
 
@@ -22,14 +22,12 @@ class Variable(RowClass):
22 22
     def insert(self):
23 23
 
24 24
         try:
25
-            sql(
25
+            DB.sql(
26 26
             """INSERT INTO variable
27 27
             (type, address)
28 28
             VALUES
29
-            ('{}', {})
30
-            """.format(
31
-                self.type, self.address
32
-            ))
29
+            (:type, :address)
30
+            """, self.__dict__)
33 31
             return True
34 32
         except Exception as e:
35 33
             print(e)
@@ -38,10 +36,10 @@ class Variable(RowClass):
38 36
 
39 37
     def exists(self):
40 38
         try:
41
-            return bool(next(sql(
39
+            return bool(next(DB.sql(
42 40
             """SELECT 1 FROM variable
43
-            WHERE type = '{}' AND address = {}
44
-            """.format(self.type, self.address))))
41
+            WHERE type=:type AND address=:address
42
+            """, self.__dict__)))
45 43
         except StopIteration:
46 44
             return False
47 45
 
@@ -57,12 +55,12 @@ class Variable(RowClass):
57 55
     def getall_of_type(type: VariableType) -> dict:
58 56
         return {
59 57
             row['address']: Variable(**dict(row))
60
-            for row in sql(
58
+            for row in DB.sql(
61 59
             """SELECT * FROM variable
62
-            WHERE type = '{}'
63
-                AND address >= {}
64
-                AND address <= {}""".format(
65
-            type, type.start_address, type.end_address))
60
+            WHERE type = :slabel
61
+                AND address >= :start_address
62
+                AND address <= :end_address""",
63
+            type.__dict__)
66 64
        }
67 65
 
68 66
 
@@ -75,11 +73,11 @@ class Variable(RowClass):
75 73
     def getall_values_of_type_since(type: VariableType, since: int) -> dict:
76 74
         floatcast = lambda x: round(float(x) / 10, 2)
77 75
         cast_fct = floatcast if type.slabel == 'A' else lambda x: x
76
+        type.__dict__.update({'since': since})
78 77
 
79
-        #offset = 10000 if (type.slabel == 'D') else 0
80 78
         return {
81 79
             row['address']: cast_fct(row['value'])
82
-            for row in sql(
80
+            for row in DB.sql(
83 81
             """SELECT var.address as address, val.value
84 82
             FROM variable var
85 83
             LEFT JOIN var_value val ON
@@ -87,11 +85,11 @@ class Variable(RowClass):
87 85
                 AND var.address = val.address
88 86
                 AND var.last_update = val.time
89 87
             WHERE
90
-                var.type = '{}'
91
-                AND var.address >= {}
92
-                AND var.address <= {}
93
-                AND var.last_update > {}""".format(
94
-            type, type.start_address, type.end_address, since))
88
+                var.type = :slabel
89
+                AND var.address >= :start_address
90
+                AND var.address <= :end_address
91
+                AND var.last_update > :since""",
92
+            type.__dict__)
95 93
         }
96 94
 
97 95
 

+ 9
- 10
pyheatpump/models/variable_type.py View File

@@ -1,5 +1,4 @@
1
-from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
1
+from pyheatpump.db import DB, RowClass
3 2
 
4 3
 
5 4
 class VariableType(RowClass):
@@ -40,15 +39,15 @@ class VariableType(RowClass):
40 39
         q = ['UPDATE var_type SET']
41 40
         updates = []
42 41
         if self.start_address is not None:
43
-            updates.append(f'start_address = {self.start_address}')
42
+            updates.append(f'start_address = :start_address')
44 43
         if self.end_address is not None:
45
-            updates.append(f'end_address = {self.end_address}')
44
+            updates.append(f'end_address = :end_address')
46 45
         if len(updates) == 0:
47 46
             return
48 47
         q.append(','.join(updates))
49
-        q.append(f"WHERE slabel = '{self.slabel}'")
48
+        q.append(f"WHERE slabel = :slabel'")
50 49
 
51
-        return sql(' '.join(q))
50
+        return DB.sql(' '.join(q), self.__dict__)
52 51
 
53 52
 
54 53
     def get_variables(self):
@@ -108,7 +107,7 @@ class VariableType(RowClass):
108 107
     def getall():
109 108
         return {
110 109
             row['label']: VariableType(**dict(row))
111
-            for row in sql('SELECT * FROM var_type')
110
+            for row in DB.sql('SELECT * FROM var_type')
112 111
         }
113 112
 
114 113
     @staticmethod
@@ -118,11 +117,11 @@ class VariableType(RowClass):
118 117
 
119 118
         try:
120 119
             return VariableType(**dict(
121
-                next(sql(
120
+                next(DB.sql(
122 121
                 """
123 122
                 SELECT * FROM var_type
124
-                WHERE slabel = '{}'
125
-                """.format(slabel)))))
123
+                WHERE slabel = ?
124
+                """, slabel))))
126 125
         except StopIteration:
127 126
             raise NameError
128 127
 

+ 15
- 16
pyheatpump/models/variable_value.py View File

@@ -1,5 +1,4 @@
1
-from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
1
+from pyheatpump.db import DB, RowClass
3 2
 from datetime import datetime
4 3
 from pprint import pprint
5 4
 
@@ -41,13 +40,13 @@ class VariableValue(RowClass):
41 40
             pass
42 41
 
43 42
         try:
44
-            sql(
45
-            """INSERT INTO var_value
46
-            (type, address, value)
47
-            VALUES
48
-            ('{}', {}, {})""".format(
49
-                self.type, self.address, self.value
50
-            ))
43
+            DB.sql(
44
+                """INSERT INTO var_value
45
+                (type, address, value)
46
+                VALUES
47
+                (:type, :address, :value)""",
48
+                self.__dict__
49
+            )
51 50
             return True
52 51
         except Exception as e:
53 52
             print(e)
@@ -71,16 +70,16 @@ class VariableValue(RowClass):
71 70
     @staticmethod
72 71
     def get(type, address, time=datetime.now()):
73 72
         try:
74
-            row = next(sql(
73
+            row = next(DB.sql(
75 74
             """SELECT * FROM var_value
76 75
             WHERE
77
-                type = '{}'
78
-                AND address = {}
79
-                AND time <= {}
76
+                type = :type
77
+                AND address = :address
78
+                AND time <= :time
80 79
             ORDER BY time DESC
81
-            LIMIT 1""".format(
82
-                type, address, int(time.strftime('%s'))+1
83
-            )))
80
+            LIMIT 1""", {
81
+                'type':type, 'address':address, 'time':int(time.strftime('%s'))+1
82
+            }))
84 83
             return VariableValue(**dict(row))
85 84
         except StopIteration as e:
86 85
             raise e

+ 0
- 1
pyheatpump/variable_types.py View File

@@ -9,7 +9,6 @@ import uvicorn
9 9
 import json
10 10
 
11 11
 # pyHeatpump modules
12
-from pyheatpump.db import sql
13 12
 from pyheatpump.models.variable_type import VariableType
14 13
 
15 14
 

+ 0
- 1
pyheatpump/variable_values.py View File

@@ -10,7 +10,6 @@ import uvicorn
10 10
 import json
11 11
 
12 12
 # pyHeatpump modules
13
-from pyheatpump.db import sql
14 13
 from pyheatpump.models.variable import Variable
15 14
 from pyheatpump.models.variable_type import VariableType
16 15
 from pyheatpump.models.variable_value import VariableValue

+ 0
- 1
pyheatpump/variables.py View File

@@ -9,7 +9,6 @@ import uvicorn
9 9
 import json
10 10
 
11 11
 # pyHeatpump modules
12
-from pyheatpump.db import sql
13 12
 from pyheatpump.models.variable import Variable
14 13
 
15 14
 

Loading…
Cancel
Save