db.py 3.39 KB
Newer Older
Wei Shoulin's avatar
Wei Shoulin committed
1
2
3
import os
import datetime
import sqlite3
Wei Shoulin's avatar
Wei Shoulin committed
4
from DBUtils.PersistentDB import PersistentDB
Wei Shoulin's avatar
Wei Shoulin committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from .utils import singleton

import logging

log = logging.getLogger('csst')

@singleton
class DBClient(object):
    def __init__(self):
        db_path = os.path.join(os.getenv("CSST_LOCAL_FILE_ROOT", "/opt/temp/csst"), "csst.sqlite")

        self.inited = os.path.exists(db_path)
        self.pool = PersistentDB(sqlite3, maxusage=2, database=db_path)
        
        log.info("Creating connection pool with host = [%s]", db_path)

        self._conn = None
        self._cursor = None
        self.__get_conn()

        if not self.inited:
            self.__init_db()
    
    def __del__(self):
        self.close()

    def __get_conn(self):
        self._conn = self.pool.connection()
        self._cursor = self._conn.cursor()
        
    def __execute(self, sql, param=()):
        count = self._cursor.execute(sql, param)
        return count
    
    def __init_db(self):
        with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "db.sql")) as f:
Wei Shoulin's avatar
Wei Shoulin committed
41
42
43
            statements = f.read().split(";")
            for s in statements:
                self.execute(s)
Wei Shoulin's avatar
Wei Shoulin committed
44

Wei Shoulin's avatar
c3    
Wei Shoulin committed
45
46
47
    def last_row_id(self):
        return self._cursor.lastrowid

Wei Shoulin's avatar
Wei Shoulin committed
48
49
    def select_one(self, sql, param=()):
        """查询单个结果"""
Wei Shoulin's avatar
Wei Shoulin committed
50
        _ = self.__execute(sql, param)
Wei Shoulin's avatar
Wei Shoulin committed
51
52
        result = self._cursor.fetchone()
        """:type result:dict"""
Xie Zhou's avatar
Xie Zhou committed
53
        # result = self.__dict_datetime_obj_to_str(result)
Wei Shoulin's avatar
Wei Shoulin committed
54
55
        if result is None:
            return None
Xie Zhou's avatar
Xie Zhou committed
56
57
58
        result = {
            key[0]: col for key, col in zip(self._cursor.description, result)
        }
Wei Shoulin's avatar
Wei Shoulin committed
59
        return result
Wei Shoulin's avatar
Wei Shoulin committed
60

Wei Shoulin's avatar
Wei Shoulin committed
61
62
63
64
65
    def exists(self, sql, param=()):
        _ = self.__execute(sql, param)
        result = self._cursor.fetchone()
        return result is not None
   
Wei Shoulin's avatar
Wei Shoulin committed
66
67
68
69
70
71
72
73
74
75
    def select_many(self, sql, param=()):
        """
        查询多个结果
        :param sql: qsl语句
        :param param: sql参数
        :return: 结果数量和查询结果集
        """
        count = self.__execute(sql, param)
        result = self._cursor.fetchall()
        """:type result:list"""
Xie Zhou's avatar
Xie Zhou committed
76
77
78
79
80
81
82
83
        # result = [self.__dict_datetime_obj_to_str(row_dict) for row_dict in result]
        r = []
        for row_dict in result:
            r.append(
                {key[0]:col for key, col in zip(self._cursor.description, row_dict)}
            )
            
        return count, r
Wei Shoulin's avatar
Wei Shoulin committed
84
85
86
87
88
89
90
91

    def execute(self, sql, param=()):
        count = self.__execute(sql, param)
        return count

    def end(self, option='commit'):
        """结束事务"""
        if option == 'commit':
Wei Shoulin's avatar
Wei Shoulin committed
92
            self._conn.commit()
Wei Shoulin's avatar
Wei Shoulin committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        else:
            self._conn.rollback()    
    
    def __dict_datetime_obj_to_str(self, result_dict):
        """把字典里面的datatime对象转成字符串,使json转换不出错"""
        if result_dict and isinstance(result_dict, tuple):
            result_replace = [v.__str__() for  v in result_dict if isinstance(v, datetime.datetime)]
            return result_replace

        if result_dict and isinstance(result_dict, dict):
            result_replace = {k: v.__str__() for k, v in result_dict.items() if isinstance(v, datetime.datetime)}
            result_dict.update(result_replace)            
        return result_dict

    def close(self):
        try:
            self._cursor.close()
            self._conn.close()
        except Exception as e:
            log.error(e)