-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtickerstore.py
74 lines (61 loc) · 2.06 KB
/
tickerstore.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
66
67
68
69
70
71
72
73
74
import os
from dotenv import load_dotenv
import psycopg2
class TickerStore:
CHAT_ID_UNINITIALIZED = -1
def __init__(self):
self._chat_id = self.CHAT_ID_UNINITIALIZED
self._tickers = set()
load_dotenv()
def open_db(self):
self._conn = psycopg2.connect(os.environ["TT_DATABASE_URL"])
self._cur = self._conn.cursor()
def close_db(self):
self._conn.commit()
self._cur.close()
self._conn.close()
def chat_id(self):
return self._chat_id
def fetch_tickers(self, chat_id):
self._chat_id = chat_id
# subsequent commands until idle event will work on in-memory data
print("fetching...")
try:
self.open_db()
self._cur.execute(
"SELECT * FROM chatid_vs_tickers WHERE chatid = %s",
[self._chat_id],
)
records = self._cur.fetchall()
if len(records):
self._tickers = set(records[0][1])
print(self._tickers)
finally:
self.close_db()
def commit_tickers(self):
print("committing...")
print(self._tickers)
try:
self.open_db()
self._cur.execute(
"INSERT INTO chatid_vs_tickers (chatid, tickers) VALUES (%s, %s) ON CONFLICT (chatid) DO NOTHING",
(self._chat_id, list(self._tickers)),
)
self._cur.execute(
"UPDATE chatid_vs_tickers SET tickers=(%s) WHERE chatid=(%s)",
(list(self._tickers), self._chat_id),
)
finally:
self.close_db()
# set chat id to uninitialized so the next command fetches from db
self._chat_id = self.CHAT_ID_UNINITIALIZED
def get(self):
return list(self._tickers)
def put(self, ticker):
self._tickers.add(ticker)
def exists(self, ticker):
return ticker in self._tickers
def remove(self, chat_id, ticker):
self._tickers.remove(ticker)
def len(self, chat_id):
return len(self._tickers)