sql.py 12.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
###################################################################
#           Copyright (c) 2016 by TAOS Technologies, Inc.
#                     All rights reserved.
#
#  This file is proprietary and confidential to TAOS Technologies.
#  No part of this file may be reproduced, stored, transmitted,
#  disclosed or used in any form or by any means other than as
#  expressly provided by the written permission from Jianhui Tao
#
###################################################################

# -*- coding: utf-8 -*-

import sys
import os
import time
import datetime
S
Shuduo Sang 已提交
18
import inspect
L
liuyq-617 已提交
19 20
import psutil
import shutil
21
import pandas as pd
22 23 24
from util.log import *


L
liuyq-617 已提交
25

26 27 28 29 30 31
class TDSql:
    def __init__(self):
        self.queryRows = 0
        self.queryCols = 0
        self.affectedRows = 0

32
    def init(self, cursor, log=False):
33 34
        self.cursor = cursor

S
Shuduo Sang 已提交
35
        if (log):
36 37
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            self.cursor.log(caller.filename + ".sql")
S
Shuduo Sang 已提交
38

39 40 41 42 43
    def close(self):
        self.cursor.close()

    def prepare(self):
        tdLog.info("prepare database:db")
L
liu0x54 已提交
44 45 46 47 48 49 50 51
        s = 'reset query cache'
        self.cursor.execute(s)
        s = 'drop database if exists db'
        self.cursor.execute(s)
        s = 'create database db'
        self.cursor.execute(s)
        s = 'use db'
        self.cursor.execute(s)
52 53 54 55 56 57 58 59

    def error(self, sql):
        expectErrNotOccured = True
        try:
            self.cursor.execute(sql)
        except BaseException:
            expectErrNotOccured = False
        if expectErrNotOccured:
60 61
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            tdLog.exit("%s(%d) failed: sql:%s, expect error not occured" % (caller.filename, caller.lineno, sql))
62
        else:
63 64 65
            self.queryRows = 0
            self.queryCols = 0
            self.queryResult = None
S
Shuduo Sang 已提交
66
            tdLog.info("sql:%s, expect error occured" % (sql))
67 68 69

    def query(self, sql):
        self.sql = sql
70 71 72 73 74 75 76 77
        try:
            self.cursor.execute(sql)
            self.queryResult = self.cursor.fetchall()
            self.queryRows = len(self.queryResult)
            self.queryCols = len(self.cursor.description)
        except Exception as e:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, repr(e))
78 79
            tdLog.notice("%s(%d) failed: sql:%s, %s" % args)
            raise Exception(repr(e))
80 81
        return self.queryRows

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    def getColNameList(self, sql):
        self.sql = sql
        try:
            col_name_list = []
            self.cursor.execute(sql)
            self.queryCols = self.cursor.description
            for query_col in self.queryCols:
                col_name_list.append(query_col[0])
        except Exception as e:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, repr(e))
            tdLog.notice("%s(%d) failed: sql:%s, %s" % args)
            raise Exception(repr(e))
        return col_name_list

97 98 99 100 101 102 103 104 105
    def waitedQuery(self, sql, expectRows, timeout):
        tdLog.info("sql: %s, try to retrieve %d rows in %d seconds" % (sql, expectRows, timeout))
        self.sql = sql
        try:
            for i in range(timeout):
                self.cursor.execute(sql)
                self.queryResult = self.cursor.fetchall()
                self.queryRows = len(self.queryResult)
                self.queryCols = len(self.cursor.description)
D
dapan1121 已提交
106
                tdLog.info("sql: %s, try to retrieve %d rows,get %d rows" % (sql, expectRows, self.queryRows))
107 108 109 110 111 112
                if self.queryRows >= expectRows:
                    return (self.queryRows, i)
                time.sleep(1)
        except Exception as e:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, repr(e))
113 114
            tdLog.notice("%s(%d) failed: sql:%s, %s" % args)
            raise Exception(repr(e))
115
        return (self.queryRows, timeout)
116

117 118 119 120 121 122 123
    def checkRows(self, expectRows):
        if self.queryRows == expectRows:
            tdLog.info("sql:%s, queryRows:%d == expect:%d" % (self.sql, self.queryRows, expectRows))
        else:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, self.sql, self.queryRows, expectRows)
            tdLog.exit("%s(%d) failed: sql:%s, queryRows:%d != expect:%d" % args)
124

125 126 127 128 129 130 131 132
    def checkCols(self, expectCols):
        if self.queryCols == expectCols:
            tdLog.info("sql:%s, queryCols:%d == expect:%d" % (self.sql, self.queryCols, expectCols))
        else:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, self.sql, self.queryCols, expectCols)
            tdLog.exit("%s(%d) failed: sql:%s, queryCols:%d != expect:%d" % args)

133 134
    def checkRowCol(self, row, col):
        caller = inspect.getframeinfo(inspect.stack()[2][0])
135
        if row < 0:
136 137
            args = (caller.filename, caller.lineno, self.sql, row)
            tdLog.exit("%s(%d) failed: sql:%s, row:%d is smaller than zero" % args)
138
        if col < 0:
139 140
            args = (caller.filename, caller.lineno, self.sql, row)
            tdLog.exit("%s(%d) failed: sql:%s, col:%d is smaller than zero" % args)
141
        if row > self.queryRows:
142 143
            args = (caller.filename, caller.lineno, self.sql, row, self.queryRows)
            tdLog.exit("%s(%d) failed: sql:%s, row:%d is larger than queryRows:%d" % args)
144
        if col > self.queryCols:
145 146
            args = (caller.filename, caller.lineno, self.sql, col, self.queryCols)
            tdLog.exit("%s(%d) failed: sql:%s, col:%d is larger than queryCols:%d" % args)
147

148 149
    def checkDataType(self, row, col, dataType):
        self.checkRowCol(row, col)
150 151
        return self.cursor.istype(col, dataType)

152
    def checkData(self, row, col, data):
153 154 155 156 157 158 159 160 161 162 163
        self.checkRowCol(row, col)
        if self.queryResult[row][col] != data:
            if self.cursor.istype(col, "TIMESTAMP"):
                # suppose user want to check nanosecond timestamp if a longer data passed
                if (len(data) >= 28):
                    if pd.to_datetime(self.queryResult[row][col]) == pd.to_datetime(data):
                        tdLog.info("sql:%s, row:%d col:%d data:%d == expect:%s" %
                            (self.sql, row, col, self.queryResult[row][col], data))
                else:
                    if self.queryResult[row][col] == datetime.datetime.fromisoformat(data):
                        tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
164 165 166
                            (self.sql, row, col, self.queryResult[row][col], data))
                return

167
            if str(self.queryResult[row][col]) == str(data):
P
Ping Xiao 已提交
168
                tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
169
                            (self.sql, row, col, self.queryResult[row][col], data))
P
Ping Xiao 已提交
170
                return
171
            elif isinstance(data, float) and abs(self.queryResult[row][col] - data) <= 0.000001:
P
Ping Xiao 已提交
172
                tdLog.info("sql:%s, row:%d col:%d data:%f == expect:%f" %
173
                            (self.sql, row, col, self.queryResult[row][col], data))
P
Ping Xiao 已提交
174 175 176 177
                return
            else:
                caller = inspect.getframeinfo(inspect.stack()[1][0])
                args = (caller.filename, caller.lineno, self.sql, row, col, self.queryResult[row][col], data)
178
                tdLog.exit("%s(%d) failed: sql:%s row:%d col:%d data:%s != expect:%s" % args)
sangshuduo's avatar
sangshuduo 已提交
179 180

        if data is None:
S
Shuduo Sang 已提交
181
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
182
                       (self.sql, row, col, self.queryResult[row][col], data))
183
        elif isinstance(data, str):
S
Shuduo Sang 已提交
184
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
185
                       (self.sql, row, col, self.queryResult[row][col], data))
sangshuduo's avatar
sangshuduo 已提交
186
        elif isinstance(data, datetime.date):
P
Ping Xiao 已提交
187
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
188
                       (self.sql, row, col, self.queryResult[row][col], data))
P
Ping Xiao 已提交
189
        elif isinstance(data, float):
S
Shuduo Sang 已提交
190
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
sangshuduo's avatar
sangshuduo 已提交
191
                       (self.sql, row, col, self.queryResult[row][col], data))
192
        else:
S
Shuduo Sang 已提交
193
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%d" %
194
                       (self.sql, row, col, self.queryResult[row][col], data))
195 196

    def getData(self, row, col):
197
        self.checkRowCol(row, col)
198 199
        return self.queryResult[row][col]

200 201 202 203 204 205 206 207 208 209 210 211 212
    def getResult(self, sql):
        self.sql = sql
        try:
            self.cursor.execute(sql)
            self.queryResult = self.cursor.fetchall()
        except Exception as e:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, repr(e))
            tdLog.notice("%s(%d) failed: sql:%s, %s" % args)
            raise Exception(repr(e))
        return self.queryResult

        
213 214 215 216 217 218 219 220 221 222
    def executeTimes(self, sql, times):
        for i in range(times):
            try:
                return self.cursor.execute(sql)
            except BaseException:
                time.sleep(1)
                continue

    def execute(self, sql):
        self.sql = sql
223 224 225 226 227
        try:
            self.affectedRows = self.cursor.execute(sql)
        except Exception as e:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, repr(e))
228 229
            tdLog.notice("%s(%d) failed: sql:%s, %s" % args)
            raise Exception(repr(e))
230 231 232 233
        return self.affectedRows

    def checkAffectedRows(self, expectAffectedRows):
        if self.affectedRows != expectAffectedRows:
234 235 236 237 238
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, self.sql, self.affectedRows, expectAffectedRows)
            tdLog.exit("%s(%d) failed: sql:%s, affectedRows:%d != expect:%d" % args)

        tdLog.info("sql:%s, affectedRows:%d == expect:%d" % (self.sql, self.affectedRows, expectAffectedRows))
239

240 241 242 243 244 245 246 247
    def checkColNameList(self, col_name_list, expect_col_name_list):
        if col_name_list == expect_col_name_list:
            tdLog.info("sql:%s, col_name_list:%s == expect_col_name_list:%s" % (self.sql, col_name_list, expect_col_name_list))
        else:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, self.sql, col_name_list, expect_col_name_list)
            tdLog.exit("%s(%d) failed: sql:%s, col_name_list:%s != expect_col_name_list:%s" % args)

L
liuyq-617 已提交
248
    def taosdStatus(self, state):
L
liuyq-617 已提交
249
        tdLog.sleep(5)
L
liuyq-617 已提交
250 251
        pstate = 0
        for i in range(30):
L
liuyq-617 已提交
252
            pstate = 0
L
liuyq-617 已提交
253 254
            pl = psutil.pids()
            for pid in pl:
L
liuyq-617 已提交
255 256 257 258 259 260 261
                try:
                    if psutil.Process(pid).name() == 'taosd':
                        print('have already started')
                        pstate = 1
                        break
                except psutil.NoSuchProcess:
                    pass
262 263 264
            if pstate == state :break
            if state or pstate:
                tdLog.sleep(1)
L
liuyq-617 已提交
265 266 267
                continue
            pstate = 0
            break
268

L
liuyq-617 已提交
269
        args=(pstate,state)
L
liuyq-617 已提交
270
        if pstate == state:
L
liuyq-617 已提交
271
            tdLog.info("taosd state is %d == expect:%d" %args)
L
liuyq-617 已提交
272
        else:
L
liuyq-617 已提交
273
            tdLog.exit("taosd state is %d != expect:%d" %args)
L
liuyq-617 已提交
274 275 276 277 278 279
        pass

    def haveFile(self, dir, state):
        if os.path.exists(dir) and os.path.isdir(dir):
            if not os.listdir(dir):
                if state :
L
liuyq-617 已提交
280
                    tdLog.exit("dir: %s is empty, expect: not empty" %dir)
L
liuyq-617 已提交
281
                else:
L
liuyq-617 已提交
282
                    tdLog.info("dir: %s is empty, expect: empty" %dir)
283
            else:
L
liuyq-617 已提交
284
                if state :
285
                    tdLog.info("dir: %s is not empty, expect: not empty" %dir)
L
liuyq-617 已提交
286
                else:
287
                    tdLog.exit("dir: %s is not empty, expect: empty" %dir)
L
liuyq-617 已提交
288
        else:
L
liuyq-617 已提交
289
            tdLog.exit("dir: %s doesn't exist" %dir)
L
liuyq-617 已提交
290 291 292
    def createDir(self, dir):
        if os.path.exists(dir):
            shutil.rmtree(dir)
L
liuyq-617 已提交
293
            tdLog.info("dir: %s is removed" %dir)
L
liuyq-617 已提交
294
        os.makedirs( dir, 755 )
L
liuyq-617 已提交
295
        tdLog.info("dir: %s is created" %dir)
L
liuyq-617 已提交
296
        pass
297

298
tdSql = TDSql()