1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- #!/usr/bin/env python3
- import sqlite3
- from subprocess import Popen
- from .config import config
- import sys
- from pprint import pprint
-
- from pyheatpump.logger import logger_init
- logger = logger_init()
-
- conn = None
-
- def connect():
- global conn
- if conn is None:
- logger.info('Will connect to database {}'.format(
- config['heatpump']['database']))
- conn = sqlite3.connect(config['heatpump']['database'])
- conn.row_factory = sqlite3.Row
- return conn
-
- def commit():
- global conn
- logger.info('Commit database')
- conn.commit()
-
- def initialize(filename):
- p = Popen(
- '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']),
- shell=True
- )
- return True if p.wait() == 0 else False
-
-
- def sql(query):
- global conn
- if conn is None:
- connect()
-
- cursor = conn.cursor()
- logger.debug(f'Will execute query : \n{query}\n')
- cursor.execute(query)
-
- return cursor
-
- class RowClass(object):
- def __init__(self, **kwargs):
- for key in kwargs.keys():
- if hasattr(self, key):
- setattr(self, key, kwargs[key])
-
- def select(self, key, tablename):
- attr = getattr(self, key)
- if type(attr) == str:
- q = f"SELECT * FROM {tablename} WHERE {key} LIKE '{attr}'"
- elif type(attr) == int:
- q = f"SELECT * FROM {tablename} WHERE {key} = {attr}"
-
- return sql(q)
|