You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.7 KiB

2 years ago
  1. import logging
  2. import os
  3. import sqlite3 as sqlite
  4. class Store:
  5. database: str
  6. def __init__(self, db_path):
  7. self.database = os.path.join(db_path, "be.db")
  8. self.init_tables()
  9. def init_tables(self):
  10. try:
  11. conn = self.get_db_conn()
  12. conn.execute(
  13. "CREATE TABLE IF NOT EXISTS user ("
  14. "user_id TEXT PRIMARY KEY, password TEXT NOT NULL, "
  15. "balance INTEGER NOT NULL, token TEXT, terminal TEXT);"
  16. )
  17. conn.execute(
  18. "CREATE TABLE IF NOT EXISTS user_store("
  19. "user_id TEXT, store_id, PRIMARY KEY(user_id, store_id));"
  20. )
  21. conn.execute(
  22. "CREATE TABLE IF NOT EXISTS store( "
  23. "store_id TEXT, book_id TEXT, book_info TEXT, stock_level INTEGER,"
  24. " PRIMARY KEY(store_id, book_id))"
  25. )
  26. conn.execute(
  27. "CREATE TABLE IF NOT EXISTS new_order( "
  28. "order_id TEXT PRIMARY KEY, user_id TEXT, store_id TEXT)"
  29. )
  30. conn.execute(
  31. "CREATE TABLE IF NOT EXISTS new_order_detail( "
  32. "order_id TEXT, book_id TEXT, count INTEGER, price INTEGER, "
  33. "PRIMARY KEY(order_id, book_id))"
  34. )
  35. conn.commit()
  36. except sqlite.Error as e:
  37. logging.error(e)
  38. conn.rollback()
  39. def get_db_conn(self) -> sqlite.Connection:
  40. return sqlite.connect(self.database)
  41. database_instance: Store = None
  42. def init_database(db_path):
  43. global database_instance
  44. database_instance = Store(db_path)
  45. def get_db_conn():
  46. global database_instance
  47. return database_instance.get_db_conn()