mayureshagashe2105 commited on
Commit
13fd526
·
1 Parent(s): cb77b29

Add db services and functools

Browse files
backend/services/db/__init__.py ADDED
File without changes
backend/services/db/utils/DBQueries.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fix ObjectId & FastApi conflict
2
+ import pydantic
3
+ from bson.objectid import ObjectId
4
+ pydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
5
+
6
+ from typing import Union, Tuple, List
7
+
8
+ from docguptea.utils import DBConnection
9
+ from docguptea.core.Exceptions import *
10
+
11
+
12
+ class DBQueries:
13
+ @classmethod
14
+ def insert_to_database(cls, table_name:str, data:Union[Tuple, List[Tuple]], cols:List[str]=None):
15
+ con = DBConnection.get_client()
16
+ cursor = con.cursor()
17
+ QUERY = ('INSERT INTO {table_name} '
18
+ f'({",".join(cols)}) '
19
+ 'VALUES '
20
+ ).format(table_name=table_name)
21
+ print(data)
22
+ if isinstance(data, list):
23
+ QUERY+="("+",".join(["%s" for _ in range(len(data[0]))])+")"
24
+ cursor.executemany(QUERY, data)
25
+ else:
26
+ QUERY+="("+",".join(["%s" for _ in range(len(data))])+")"
27
+ cursor.execute(QUERY, data)
28
+ con.commit()
29
+
30
+ @classmethod
31
+ def fetch_data_from_database(cls,table_name:str,cols_to_fetch:Union[str, List[str]], where_clause:str=None):
32
+ con = DBConnection.get_client()
33
+ cursor = con.cursor()
34
+ if isinstance(cols_to_fetch, str):
35
+ cols_to_fetch = [cols_to_fetch]
36
+ cols_to_fetch = ", ".join(cols_to_fetch)
37
+ QUERY = ('SELECT {cols} FROM {table_name}').format(cols=cols_to_fetch, table_name=table_name)
38
+ if where_clause:
39
+ QUERY = QUERY + " WHERE " + where_clause
40
+ cursor.execute(QUERY)
41
+ return cursor.fetchall()
42
+
43
+ @classmethod
44
+ def update_data_in_database(cls, table_name:str, cols_to_update:Union[str, List[str]], where_clause:str=None, new_values:Union[str, List[str]]=None):
45
+ con = DBConnection.get_client()
46
+ cursor = con.cursor()
47
+ if isinstance(cols_to_update, str):
48
+ cols_to_update = cols_to_update + "=%s"
49
+ else:
50
+ cols_to_update = "=%s, ".join(cols_to_update)
51
+
52
+ if isinstance(new_values, str):
53
+ new_values = [new_values]
54
+
55
+ QUERY = ('UPDATE {table_name} SET {cols}').format(table_name=table_name, cols=cols_to_update)
56
+ if where_clause:
57
+ QUERY = QUERY + " WHERE " + where_clause
58
+ cursor.execute(QUERY, new_values)
59
+ con.commit()
60
+ return True
61
+
62
+
63
+
64
+
65
+
66
+