repositories.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import sqlite3
  2. from abc import abstractmethod
  3. from core import constants
  4. class Repository:
  5. TABLE_NAME = None
  6. MODEL_CLS = None
  7. @abstractmethod
  8. def __init__(self):
  9. self.cnn = sqlite3.connect(constants.DB_PATH)
  10. def execute(self, sql, *parameters):
  11. cur = self.cnn.cursor()
  12. cur.execute(sql, *parameters)
  13. return cur
  14. def get_by_id(self, id_):
  15. cur = self.execute(
  16. f"SELECT * FROM {self.TABLE_NAME} WHERE id=?;",
  17. id_
  18. )
  19. return self.MODEL_CLS(**cur.fetchone())
  20. def get_all(self):
  21. cur = self.execute(f"SELECT * FROM {self.TABLE_NAME};", )
  22. return [self.MODEL_CLS(**row) for row in cur.fetchall()]
  23. def get_by(self, **kwargs):
  24. pass
  25. def get_by_raw_sql(self, sql, parameters=None):
  26. parameters = parameters if parameters is not None else []
  27. cur = self.execute(sql, parameters)
  28. return [self.MODEL_CLS(**row) for row in cur.fetchall()]
  29. def create(self, model, commit=False):
  30. fields, values = model.as_fields_and_values()
  31. self.execute(
  32. f"INSERT INTO {self.TABLE_NAME} ({', '.join(fields)}) VALUES (?);",
  33. *values
  34. )
  35. if commit:
  36. self.commit()
  37. def update(self, model, commit=False):
  38. fields, values = model.as_fields_and_values()
  39. self.execute(
  40. f"UPDATE {self.TABLE_NAME} SET ({'=?,'.join(fields)});",
  41. *values
  42. )
  43. if commit:
  44. self.commit()
  45. def delete(self, model, commit=False, permanent=False):
  46. if commit:
  47. self.commit()
  48. def commit(self):
  49. self.cnn.commit()
  50. def rollback(self):
  51. self.cnn.rollback()
  52. def __del__(self):
  53. self.cnn.close()
  54. class MusicFolderRepository(Repository):
  55. TABLE_NAME = "MusicFolders"
  56. def __init__(self):
  57. super().__init__()
  58. class ProfileRepository(Repository):
  59. TABLE_NAME = "Profiles"
  60. def __init__(self):
  61. super().__init__()
  62. class TagRepository(Repository):
  63. TABLE_NAME = "Tags"
  64. def __init__(self):
  65. super().__init__()
  66. class TrackRepository(Repository):
  67. TABLE_NAME = "Tracks"
  68. def __init__(self):
  69. super().__init__()