Update Akeno/utils/base_sqlite.py
Browse files- Akeno/utils/base_sqlite.py +39 -30
Akeno/utils/base_sqlite.py
CHANGED
@@ -1,34 +1,43 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
from
|
4 |
-
|
5 |
-
conn = sqlitecloud.connect(SQLITE_CLOUD_URL)
|
6 |
-
cursor = conn.cursor()
|
7 |
-
cursor.execute('USE DATABASE akeno-dev')
|
8 |
-
|
9 |
-
cursor.execute('''
|
10 |
-
CREATE TABLE IF NOT EXISTS prefixes (
|
11 |
-
user_id INTEGER PRIMARY KEY,
|
12 |
-
prefix TEXT NOT NULL
|
13 |
-
)
|
14 |
-
''')
|
15 |
-
conn.commit()
|
16 |
|
17 |
-
|
18 |
-
cursor.execute('''
|
19 |
-
INSERT INTO prefixes (user_id, prefix)
|
20 |
-
VALUES (?, ?)
|
21 |
-
ON CONFLICT(user_id) DO UPDATE SET prefix=excluded.prefix
|
22 |
-
''', (user_id, prefix))
|
23 |
-
conn.commit()
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
else:
|
32 |
-
return None
|
33 |
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sqlalchemy import create_engine, Column, Integer, String
|
2 |
+
from sqlalchemy.ext.declarative import declarative_base
|
3 |
+
from sqlalchemy.orm import sessionmaker, scoped_session
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
from config import DB_URI
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
if DB_URI and DB_URI.startswith("postgres://"):
|
8 |
+
DB_URI = DB_URI.replace("postgres://", "postgresql://", 1)
|
9 |
+
|
10 |
+
engine = create_engine(DB_URI)
|
11 |
+
SessionLocal = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
|
12 |
+
|
13 |
+
Base = declarative_base()
|
14 |
+
|
15 |
+
# Define the Prefix model
|
16 |
+
class Prefix(Base):
|
17 |
+
__tablename__ = "prefixes"
|
18 |
|
19 |
+
user_id = Column(Integer, primary_key=True, index=True)
|
20 |
+
prefix = Column(String, nullable=False)
|
|
|
|
|
21 |
|
22 |
+
Base.metadata.create_all(bind=engine)
|
23 |
+
|
24 |
+
async def set_prefix_in_db(user_id: int, prefix: str):
|
25 |
+
db = SessionLocal()
|
26 |
+
try:
|
27 |
+
user_prefix = db.query(Prefix).filter(Prefix.user_id == user_id).first()
|
28 |
+
if user_prefix:
|
29 |
+
user_prefix.prefix = prefix
|
30 |
+
else:
|
31 |
+
new_prefix = Prefix(user_id=user_id, prefix=prefix)
|
32 |
+
db.add(new_prefix)
|
33 |
+
db.commit()
|
34 |
+
finally:
|
35 |
+
db.close()
|
36 |
+
|
37 |
+
async def get_prefix(user_id: int):
|
38 |
+
db = SessionLocal()
|
39 |
+
try:
|
40 |
+
user_prefix = db.query(Prefix).filter(Prefix.user_id == user_id).first()
|
41 |
+
return user_prefix.prefix if user_prefix else None
|
42 |
+
finally:
|
43 |
+
db.close()
|