database.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import sqlite3
  2. import os
  3. import logging
  4. from typing import Optional, Dict, Any
  5. logger = logging.getLogger(__name__)
  6. # Locate db correctly in the same directory
  7. DB_PATH = os.path.join(os.path.dirname(__file__), "localfood.db")
  8. def get_db_connection():
  9. conn = sqlite3.connect(DB_PATH)
  10. conn.row_factory = sqlite3.Row
  11. return conn
  12. def create_tables():
  13. """Initialize the SQLite database with required tables"""
  14. try:
  15. conn = get_db_connection()
  16. cursor = conn.cursor()
  17. # Create users table securely locally
  18. cursor.execute('''
  19. CREATE TABLE IF NOT EXISTS users (
  20. id INTEGER PRIMARY KEY AUTOINCREMENT,
  21. username TEXT UNIQUE NOT NULL,
  22. password_hash TEXT NOT NULL,
  23. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  24. )
  25. ''')
  26. conn.commit()
  27. conn.close()
  28. logger.info("Database and tables initialized successfully.")
  29. except Exception as e:
  30. logger.error(f"Error initializing database: {e}")
  31. raise
  32. def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
  33. """Retrieve user dictionary if they exist"""
  34. try:
  35. conn = get_db_connection()
  36. cursor = conn.cursor()
  37. cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
  38. row = cursor.fetchone()
  39. conn.close()
  40. return dict(row) if row else None
  41. except Exception as e:
  42. logger.error(f"Database error fetching user: {e}")
  43. return None
  44. def create_user(username: str, password_hash: str) -> bool:
  45. """Creates a user securely. Returns True if successful, False if username exists."""
  46. try:
  47. conn = get_db_connection()
  48. cursor = conn.cursor()
  49. cursor.execute(
  50. "INSERT INTO users (username, password_hash) VALUES (?, ?)",
  51. (username, password_hash)
  52. )
  53. conn.commit()
  54. conn.close()
  55. return True
  56. except sqlite3.IntegrityError:
  57. # Prevent duplicate usernames explicitly
  58. return False
  59. except Exception as e:
  60. logger.error(f"Database error during user creation: {e}")
  61. raise