aboutsummaryrefslogtreecommitdiffstats
path: root/services/database/db_general.py
blob: 2c83fb03d563a5bf6decd938854a005c9e60cf6f (plain)
1
2
3
4
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# ============LICENSE_START==========================================
# org.onap.vvp/test-engine
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless otherwise specified, all software contained herein is licensed
# under the Apache License, Version 2.0 (the “License”);
# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
#
#             http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
# Unless otherwise specified, all documentation contained herein is licensed
# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
# you may not use this documentation except in compliance with the License.
# You may obtain a copy of the License at
#
#             https://creativecommons.org/licenses/by/4.0/
#
# Unless required by applicable law or agreed to in writing, documentation
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ============LICENSE_END============================================
#
# ECOMP is a trademark and service mark of AT&T Intellectual Property.
from datetime import datetime
import sqlite3

from django.conf import settings
from django.db import transaction
import psycopg2

from services.logging_service import LoggingServiceFactory


logger = LoggingServiceFactory.get_logger()


class DBGeneral:

    @staticmethod
    # desigredDB: Use 'default' for CI General and 'em_db' for EM General
    # (according to settings.DATABASES).
    def return_db_native_connection(desigredDB):
        dbConnectionStr = "dbname='" + str(
            settings.SINGLETONE_DB[desigredDB]['NAME']) + \
            "' user='" + str(settings.SINGLETONE_DB[desigredDB]['USER']) + \
            "' host='" + str(settings.SINGLETONE_DB[desigredDB]['HOST']) + \
            "' password='" + str(
                settings.SINGLETONE_DB[desigredDB]['PASSWORD']) + \
            "' port='" + \
            str(settings.SINGLETONE_DB[desigredDB]['PORT']) + "'"
        return dbConnectionStr

    @staticmethod
    def insert_results(
            testType,
            testFeature,
            testResult,
            testName,
            testDuration,
            notes=" "):
        try:
            if settings.DATABASE_TYPE == 'sqlite':
                dbfile = str(settings.DATABASES['default']['TEST_NAME'])
                dbConn = sqlite3.connect(dbfile)
                cur = dbConn.cursor()
            else:
                # Connect to General 'default'.
                dbConn = psycopg2.connect(
                    DBGeneral.return_db_native_connection("default"))
                dbConn = dbConn
                cur = dbConn.cursor()
        except Exception as e:
            errorMsg = "Failed to create connection to General." + str(e)
            raise Exception(errorMsg)
        try:  # Create INSERT query.
            if settings.DATABASE_TYPE == 'sqlite':
                query_str = 'INSERT INTO ice_test_results ' +\
                    '(testType, testFeature, testResult, testName, notes,'\
                            'create_time, build_id, duration) VALUES ' +\
                            '(?, ?, ?, ?, ?, ?, ?, ?);'
            else:
                query_str = 'INSERT INTO ice_test_results ("testType", ' +\
                    '"testFeature", "testResult", "testName", notes,'\
                            'create_time, build_id, duration) VALUES ' +\
                            '(%s, %s, %s, %s, %s, %s, %s, %s);'
            cur.execute(query_str, (testType, testFeature, testResult,
                                    testName, notes,
                                    str(datetime.now()),
                                    settings.ICE_BUILD_REPORT_NUM,
                                    testDuration))
            dbConn.commit()
            logger.debug("Test result in DB - " + testResult)
        except Exception as e:
            logger.error(e)
            errorMsg = "Failed to insert results to DB." + str(e)
            raise Exception(errorMsg)
        dbConn.close()

    @staticmethod
    def select_query(queryStr, return_type="str", fetch_num=1):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            logger.debug("Query: " + queryStr)
            cur.execute(queryStr)
            if return_type == "str":
                if fetch_num == 1:
                    result = str(cur.fetchone())
                else:
                    result = str(cur.fetchall())
                if result != 'None':
                    # formatting strings e.g uuid
                    if(result.find("',)") != -1):
                        result = result.partition('\'')[-1].rpartition('\'')[0]
                    elif(result.find(",)") != -1):  # formatting ints e.g id
                        result = result.partition('(')[-1].rpartition(',')[0]
            if return_type == "list":
                if fetch_num == 1:
                    result = list(cur.fetchone())
                else:
                    result = [item[0] for item in cur.fetchall()]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        except BaseException:
            raise Exception("Couldn't fetch answer using the given query.")

    @staticmethod
    def insert_query(queryStr):
        try:
            nativeIceDb = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = nativeIceDb
            cur = dbConn.cursor()
            logger.debug("Query: " + queryStr)
            cur.execute(queryStr)
            dbConn.commit()
            dbConn.close()
            logger.debug("Insert query success!")
        # If failed - count the failure and add the error to list of errors.
        except Exception as e:
            logger.error(e)
            transaction.rollback()
            raise Exception("Couldn't fetch answer using the given query.")

    @staticmethod
    def update_query(queryStr):
        try:
            nativeIceDb = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = nativeIceDb
            cur = dbConn.cursor()
            logger.debug("Query: " + queryStr)
            cur.execute(queryStr)
            dbConn.commit()
            dbConn.close()
            logger.debug("Update query success!")
        # If failed - count the failure and add the error to list of errors.
        except Exception as e:
            logger.error(e)
            transaction.rollback()
            raise Exception("Couldn't fetch answer using the given query.")

    @staticmethod
    def select_where_email(queryColumnName, queryTableName, email):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "select %s from %s WHERE Email = '%s';" % (
                queryColumnName, queryTableName, email)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            result = str(cur.fetchone())
            if(result.find("',)") != -1):  # formatting strings e.g uuid
                result = result.partition('\'')[-1].rpartition('\'')[0]
            elif(result.find(",)") != -1):  # formatting ints e.g id
                result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where_email FAILED "
            raise Exception(errorMsg, "select_where_email")
            raise

    @staticmethod
    def select_from(queryColumnName, queryTableName, fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            cur = dbConn.cursor()
            queryStr = "select %s from %s;" % (queryColumnName, queryTableName)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = str(cur.fetchall())
            elif (fetchNum == 1):
                result = str(cur.fetchone())
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except Exception as e:
            errorMsg = "select_from FAILED " + str(e)
            raise Exception(errorMsg, "select_from")

    @staticmethod
    def select_where(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            cur = dbConn.cursor()
            queryStr = "select %s from %s Where %s = '%s';" % (
                queryColumnName, queryTableName, whereParametrType,
                whereParametrValue)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = list(cur.fetchall())
            elif (fetchNum == 1):
                result = str(cur.fetchone())
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where FAILED "
            raise Exception(errorMsg, "select_where")

    @staticmethod
    def select_where_order_by_desc(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            order_by):
        dbConn = psycopg2.connect(
            DBGeneral.return_db_native_connection('em_db'))
        cur = dbConn.cursor()
        queryStr = \
            "select %s from %s " % (queryColumnName, queryTableName,) +\
            "Where %s = '%s' " % (whereParametrType, whereParametrValue) +\
            "order by %s desc limit 1;" % order_by
        logger.debug("Query : " + queryStr)
        cur.execute(queryStr)
        result = str(cur.fetchall())
        result = DBGeneral.list_format(result)
        dbConn.close()
        return result

    @staticmethod
    def select_where_dict(queryColumnName, queryTableName, whereParametrType):
        dbConn = psycopg2.connect(
            DBGeneral.return_db_native_connection('em_db'))
        cur = dbConn.cursor()
        x = ""
        count = 0
        for key, val in whereParametrType.items():
            x += "%s='%s'" % (key, val)
            if len(whereParametrType.items()) - count > 1:
                x += ' and '
                count += 1
        queryStr = "select %s from %s Where %s;" \
            % (queryColumnName, queryTableName, x)
        logger.debug("Query : " + queryStr)
        cur.execute(queryStr)
        result = str(cur.fetchall())
        result = DBGeneral.list_format(result)
        dbConn.close()
        return result

    @staticmethod
    def select_where_not_and_order_by_desc(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            parametrTypeAnd,
            parametrAnd,
            order_by):
        dbConn = psycopg2.connect(
            DBGeneral.return_db_native_connection('em_db'))
        cur = dbConn.cursor()
        queryStr = \
            "select %s from %s " % (queryColumnName, queryTableName) +\
            "Where %s = '%s' " % (whereParametrType, whereParametrValue) +\
            "and %s != '%s' " % (parametrTypeAnd, parametrAnd) +\
            "order by %s desc limit 1;" % order_by
        logger.debug("Query : " + queryStr)
        cur.execute(queryStr)
        result = str(cur.fetchall())
        result = DBGeneral.list_format(result)
        dbConn.close()
        return result

    @staticmethod
    def select_where_and(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            parametrTypeAnd,
            parametrAnd,
            fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "select %s from %s Where %s = '%s' and %s = '%s';" % (
                queryColumnName, queryTableName, whereParametrType,
                whereParametrValue, parametrTypeAnd, parametrAnd)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = str(cur.fetchall())
                result = DBGeneral.list_format(result)
            elif (fetchNum == 1):
                result = str(cur.fetchone())
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where_and FAILED "
            raise Exception(errorMsg, "select_where_and")

    @staticmethod
    def select_where_is_bigger(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            parametrTypeAnd,
            parametrAnd,
            fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "select %s from %s Where %s = '%s' and %s > %s;" % (
                queryColumnName, queryTableName, whereParametrType,
                whereParametrValue, parametrTypeAnd, parametrAnd)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = cur.fetchall()
            elif (fetchNum == 1):
                result = cur.fetchone()
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where_is_bigger FAILED "
            raise Exception(errorMsg, "select_where_is_bigger")

    @staticmethod
    def update_where(
            queryTableName,
            setParametrType,
            setparametrValue,
            whereParametrType,
            whereParametrValue):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "UPDATE %s SET %s  = '%s' Where  %s = '%s';" % (
                queryTableName, setParametrType, setparametrValue,
                whereParametrType, whereParametrValue)
            cur.execute(queryStr)
            dbConn.commit()
            logger.debug("Query : " + queryStr)
        # If failed - count the failure and add the error to list of errors.
        except Exception as e:
            errorMsg = "Could not Update User"
            logger.debug(e)
            raise Exception(errorMsg, "Update")
        finally:
            dbConn.close()

    @staticmethod
    def update_by_query(queryStr):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            dbConn.commit()
            dbConn.close()
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "Could not Update User"
            raise Exception(errorMsg, "Update")

    @staticmethod
    def update_where_and(
            queryTableName,
            setParametrType,
            parametrValue,
            changeToValue,
            whereParametrType,
            setParametrType2,
            setParametrValue2,
            whereParametrType2,
            whereParametrValue2):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "UPDATE %s SET " % queryTableName +\
                "%s  = '%s', " % (setParametrType, changeToValue) +\
                "%s  = '%s' Where  " % (setParametrType2, setParametrValue2) +\
                "%s = '%s' " % (whereParametrType, parametrValue) +\
                "and %s = '%s';" % (whereParametrType2, whereParametrValue2)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            dbConn.commit()
            dbConn.close()
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "Could not Update User"
            raise Exception(errorMsg, "Update")

    @staticmethod
    def list_format(un_listed):
        un_listed = un_listed[1:-1]
        un_listed = un_listed.replace("',), ('", "|||")
        un_listed = un_listed.replace("(u'", "")  # Format list
        un_listed = un_listed[1:-1].replace("('", "")  # Format list
        un_listed = un_listed.replace("',)", "")  # Format list
        listed = un_listed[1:-2].split("|||")
        return listed

    @staticmethod
    def get_vendors_list():
        # Select approved vendors from db.
        vendors_list = DBGeneral.select_where(
            "name", "ice_vendor", "public", "TRUE", 0)
        return vendors_list