db.py 3.5 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
from .utils import singleton

import logging

log = logging.getLogger('csst')

@singleton
class DBClient(object):
    def __init__(self):
Wei Shoulin's avatar
Wei Shoulin committed
14
15
16
17
        db_path_dir = os.getenv("CSST_LOCAL_FILE_ROOT", "/opt/temp/csst")
        if not os.path.exists(db_path_dir):
            os.makedirs(db_path_dir)
        db_path = os.path.join(db_path_dir, "csst.sqlite")
Wei Shoulin's avatar
Wei Shoulin committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

        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
44
45
46
            statements = f.read().split(";")
            for s in statements:
                self.execute(s)
Wei Shoulin's avatar
Wei Shoulin committed
47

Wei Shoulin's avatar
c3    
Wei Shoulin committed
48
49
50
    def last_row_id(self):
        return self._cursor.lastrowid

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

Wei Shoulin's avatar
Wei Shoulin committed
64
65
66
67
68
    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
69
70
71
72
73
74
75
76
77
78
    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
79
80
81
82
83
84
85
86
        # 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
87
88
89
90
91
92
93
94

    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
95
            self._conn.commit()
Wei Shoulin's avatar
Wei Shoulin committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        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)