Browse Source

add DB class and fit to tests

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

+ 2
- 0
pyheatpump/__init__.py View File

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

+ 0
- 3
pyheatpump/cli.py View File

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

+ 67
- 30
pyheatpump/db.py View File

10
 
10
 
11
 conn = None
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
         logger.info('Will connect to database {}'.format(
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
 class RowClass(object):
81
 class RowClass(object):
49
     def __init__(self, **kwargs):
82
     def __init__(self, **kwargs):
54
     def select(self, key, tablename):
87
     def select(self, key, tablename):
55
         attr = getattr(self, key)
88
         attr = getattr(self, key)
56
         if type(attr) == str:
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
         elif type(attr) == int:
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
 from starlette.routing import Router, Route
3
 from starlette.routing import Router, Route
4
 from starlette.responses import JSONResponse
4
 from starlette.responses import JSONResponse
5
 from .config import config
5
 from .config import config
6
-from pyheatpump.db import sql
7
 
6
 
8
 from pyheatpump.models import *
7
 from pyheatpump.models import *
9
 
8
 

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

1
 from pyheatpump.db import RowClass
1
 from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
2
+from pyheatpump.db import DB
3
 from datetime import date
3
 from datetime import date
4
 from pyheatpump.modbus import rtu
4
 from pyheatpump.modbus import rtu
5
 
5
 
22
     def insert(self):
22
     def insert(self):
23
 
23
 
24
         try:
24
         try:
25
-            sql(
25
+            DB.sql(
26
             """INSERT INTO variable
26
             """INSERT INTO variable
27
             (type, address)
27
             (type, address)
28
             VALUES
28
             VALUES
29
-            ('{}', {})
30
-            """.format(
31
-                self.type, self.address
32
-            ))
29
+            (:type, :address)
30
+            """, self.__dict__)
33
             return True
31
             return True
34
         except Exception as e:
32
         except Exception as e:
35
             print(e)
33
             print(e)
38
 
36
 
39
     def exists(self):
37
     def exists(self):
40
         try:
38
         try:
41
-            return bool(next(sql(
39
+            return bool(next(DB.sql(
42
             """SELECT 1 FROM variable
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
         except StopIteration:
43
         except StopIteration:
46
             return False
44
             return False
47
 
45
 
57
     def getall_of_type(type: VariableType) -> dict:
55
     def getall_of_type(type: VariableType) -> dict:
58
         return {
56
         return {
59
             row['address']: Variable(**dict(row))
57
             row['address']: Variable(**dict(row))
60
-            for row in sql(
58
+            for row in DB.sql(
61
             """SELECT * FROM variable
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
     def getall_values_of_type_since(type: VariableType, since: int) -> dict:
73
     def getall_values_of_type_since(type: VariableType, since: int) -> dict:
76
         floatcast = lambda x: round(float(x) / 10, 2)
74
         floatcast = lambda x: round(float(x) / 10, 2)
77
         cast_fct = floatcast if type.slabel == 'A' else lambda x: x
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
         return {
78
         return {
81
             row['address']: cast_fct(row['value'])
79
             row['address']: cast_fct(row['value'])
82
-            for row in sql(
80
+            for row in DB.sql(
83
             """SELECT var.address as address, val.value
81
             """SELECT var.address as address, val.value
84
             FROM variable var
82
             FROM variable var
85
             LEFT JOIN var_value val ON
83
             LEFT JOIN var_value val ON
87
                 AND var.address = val.address
85
                 AND var.address = val.address
88
                 AND var.last_update = val.time
86
                 AND var.last_update = val.time
89
             WHERE
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
-from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
1
+from pyheatpump.db import DB, RowClass
3
 
2
 
4
 
3
 
5
 class VariableType(RowClass):
4
 class VariableType(RowClass):
40
         q = ['UPDATE var_type SET']
39
         q = ['UPDATE var_type SET']
41
         updates = []
40
         updates = []
42
         if self.start_address is not None:
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
         if self.end_address is not None:
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
         if len(updates) == 0:
45
         if len(updates) == 0:
47
             return
46
             return
48
         q.append(','.join(updates))
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
     def get_variables(self):
53
     def get_variables(self):
108
     def getall():
107
     def getall():
109
         return {
108
         return {
110
             row['label']: VariableType(**dict(row))
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
     @staticmethod
113
     @staticmethod
118
 
117
 
119
         try:
118
         try:
120
             return VariableType(**dict(
119
             return VariableType(**dict(
121
-                next(sql(
120
+                next(DB.sql(
122
                 """
121
                 """
123
                 SELECT * FROM var_type
122
                 SELECT * FROM var_type
124
-                WHERE slabel = '{}'
125
-                """.format(slabel)))))
123
+                WHERE slabel = ?
124
+                """, slabel))))
126
         except StopIteration:
125
         except StopIteration:
127
             raise NameError
126
             raise NameError
128
 
127
 

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

1
-from pyheatpump.db import RowClass
2
-from pyheatpump.db import sql
1
+from pyheatpump.db import DB, RowClass
3
 from datetime import datetime
2
 from datetime import datetime
4
 from pprint import pprint
3
 from pprint import pprint
5
 
4
 
41
             pass
40
             pass
42
 
41
 
43
         try:
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
             return True
50
             return True
52
         except Exception as e:
51
         except Exception as e:
53
             print(e)
52
             print(e)
71
     @staticmethod
70
     @staticmethod
72
     def get(type, address, time=datetime.now()):
71
     def get(type, address, time=datetime.now()):
73
         try:
72
         try:
74
-            row = next(sql(
73
+            row = next(DB.sql(
75
             """SELECT * FROM var_value
74
             """SELECT * FROM var_value
76
             WHERE
75
             WHERE
77
-                type = '{}'
78
-                AND address = {}
79
-                AND time <= {}
76
+                type = :type
77
+                AND address = :address
78
+                AND time <= :time
80
             ORDER BY time DESC
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
             return VariableValue(**dict(row))
83
             return VariableValue(**dict(row))
85
         except StopIteration as e:
84
         except StopIteration as e:
86
             raise e
85
             raise e

+ 0
- 1
pyheatpump/variable_types.py View File

9
 import json
9
 import json
10
 
10
 
11
 # pyHeatpump modules
11
 # pyHeatpump modules
12
-from pyheatpump.db import sql
13
 from pyheatpump.models.variable_type import VariableType
12
 from pyheatpump.models.variable_type import VariableType
14
 
13
 
15
 
14
 

+ 0
- 1
pyheatpump/variable_values.py View File

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

+ 0
- 1
pyheatpump/variables.py View File

9
 import json
9
 import json
10
 
10
 
11
 # pyHeatpump modules
11
 # pyHeatpump modules
12
-from pyheatpump.db import sql
13
 from pyheatpump.models.variable import Variable
12
 from pyheatpump.models.variable import Variable
14
 
13
 
15
 
14
 

Loading…
Cancel
Save