-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
65 lines (51 loc) · 1.83 KB
/
test.py
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
import urllib.parse as urlparse
import psycopg2
class Base:
def __init__(self, logs=False):
self.logs = logs
# url = urlparse.urlparse(db_url)
self.db_auth = {
"user": "postgres",
"password": "example",
"host": "185.255.132.17",
"port": "5432",
"database": "postgres",
}
self.conn, self.cur = None, None
self.connect()
def create_table(self, name, table: dict):
columns = [f"{column} {_type}" for column, _type in list(table.items())]
self.query(f"CREATE TABLE {name} ({', '.join(columns)}) ")
def find_table(self, name):
res = self.query(
f"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{name}'"
)
return len(res) > 0
def query(self, query: str, args=None, fetchone=False, fetchall=False):
print(query) if self.logs else None
commit_func = ["create", "insert", "delete", "update"]
result_func = ["select", "returning"]
self.cur.execute(query, args) if args else self.cur.execute(query)
if any(func in query.lower() for func in commit_func):
self.commit()
if any(func in query.lower() for func in result_func):
if not fetchone and not fetchall:
fetchall = True
if fetchone:
exec_result = self.cur.fetchone()
elif fetchall:
exec_result = self.cur.fetchall()
else:
exec_result = None
if fetchone or fetchall:
return exec_result
def commit(self):
self.conn.commit()
def connect(self):
self.conn = psycopg2.connect(**self.db_auth)
self.cur = self.conn.cursor()
def close(self):
self.cur.close()
self.conn.close()
if __name__ == '__main__':
a = Base()