Spaces:
Sleeping
Sleeping
File size: 2,373 Bytes
10051fb 0bc89ff f64bce5 650bb90 f64bce5 10051fb 650bb90 f64bce5 650bb90 f64bce5 650bb90 f64bce5 10051fb f64bce5 650bb90 f64bce5 |
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 |
# db_utils.py
import aiosqlite
import os
import logging
DATABASE_NAME = os.getenv("DATABASE_NAME", "data/bot_data.db")
os.makedirs("data", exist_ok=True)
logger = logging.getLogger(__name__)
# --- Initialize DB ---
async def initialize_database():
async with aiosqlite.connect(DATABASE_NAME) as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS user_db (
user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS cache (
short_id TEXT PRIMARY KEY,
file_id TEXT,
filename TEXT,
type TEXT,
size INTEGER
)
""")
await db.commit()
logger.info(f"All tables initialized in database '{DATABASE_NAME}'.")
# --- Add/update user ---
async def add_or_update_user_db(user_id: int, username: str, first_name: str):
async with aiosqlite.connect(DATABASE_NAME) as db:
await db.execute("""
INSERT INTO user_db (user_id, username, first_name)
VALUES (?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
username=excluded.username,
first_name=excluded.first_name
""", (user_id, username, first_name))
await db.commit()
# --- Cache: get ---
async def get_cached_file(short_id: str):
async with aiosqlite.connect(DATABASE_NAME) as db:
async with db.execute("""
SELECT file_id, filename, type, size FROM cache WHERE short_id = ?
""", (short_id,)) as cursor:
row = await cursor.fetchone()
if row:
return {
"file_id": row[0],
"filename": row[1],
"type": row[2],
"size": row[3],
"short_id": short_id
}
return None
# --- Cache: add ---
async def add_to_cache(short_id: str, file_id: str, filename: str, file_type: str, size: int):
async with aiosqlite.connect(DATABASE_NAME) as db:
await db.execute("""
INSERT OR REPLACE INTO cache (short_id, file_id, filename, type, size)
VALUES (?, ?, ?, ?, ?)
""", (short_id, file_id, filename, file_type, size))
await db.commit()
|