1
|
|
|
import urllib.parse as urlparse |
2
|
|
|
|
3
|
|
|
import psycopg2 |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class Base: |
7
|
|
|
def __init__(self, db_url, logs=False): |
8
|
|
|
self.logs = logs |
9
|
|
|
url = urlparse.urlparse(db_url) |
10
|
|
|
self.db_auth = { |
11
|
|
|
"user": url.username, |
12
|
|
|
"password": url.password, |
13
|
|
|
"host": url.hostname, |
14
|
|
|
"port": url.port, |
15
|
|
|
"database": url.path[1:], |
16
|
|
|
} |
17
|
|
|
self.conn, self.cur = None, None |
18
|
|
|
self.connect() |
19
|
|
|
|
20
|
|
|
def create_table(self, name, table: dict): |
21
|
|
|
columns = [f"{column} {_type}" for column, _type in list(table.items())] |
22
|
|
|
self.query(f"CREATE TABLE {name} ({', '.join(columns)}) ") |
23
|
|
|
|
24
|
|
|
def find_table(self, name): |
25
|
|
|
res = self.query( |
26
|
|
|
f"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{name}'" |
27
|
|
|
) |
28
|
|
|
return len(res) > 0 |
29
|
|
|
|
30
|
|
|
def query(self, query: str, args=None, fetchone=False, fetchall=False): |
31
|
|
|
print(query) if self.logs else None |
32
|
|
|
commit_func = ["create", "insert", "delete", "update"] |
33
|
|
|
result_func = ["select", "returning"] |
34
|
|
|
self.cur.execute(query, args) if args else self.cur.execute(query) |
35
|
|
|
|
36
|
|
|
if any(func in query.lower() for func in commit_func): |
37
|
|
|
self.commit() |
38
|
|
|
|
39
|
|
|
if any(func in query.lower() for func in result_func): |
40
|
|
|
if not fetchone and not fetchall: |
41
|
|
|
fetchall = True |
42
|
|
|
|
43
|
|
|
if fetchone: |
44
|
|
|
exec_result = self.cur.fetchone() |
45
|
|
|
elif fetchall: |
46
|
|
|
exec_result = self.cur.fetchall() |
47
|
|
|
else: |
48
|
|
|
exec_result = None |
49
|
|
|
|
50
|
|
|
if fetchone or fetchall: |
51
|
|
|
return exec_result |
52
|
|
|
|
53
|
|
|
def commit(self): |
54
|
|
|
self.conn.commit() |
55
|
|
|
|
56
|
|
|
def connect(self): |
57
|
|
|
self.conn = psycopg2.connect(**self.db_auth) |
58
|
|
|
self.cur = self.conn.cursor() |
59
|
|
|
|
60
|
|
|
def close(self): |
61
|
|
|
self.cur.close() |
62
|
|
|
self.conn.close() |
63
|
|
|
|