Database.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import sqlite3
  2. from contextlib import closing
  3. from time import time
  4. from typing import Optional, List
  5. from pycs.database.Collection import Collection
  6. from pycs.database.File import File
  7. from pycs.database.LabelProvider import LabelProvider
  8. from pycs.database.Model import Model
  9. from pycs.database.Project import Project
  10. from pycs.database.Result import Result
  11. from pycs.database.discovery.LabelProviderDiscovery import discover as discover_label_providers
  12. from pycs.database.discovery.ModelDiscovery import discover as discover_models
  13. class Database:
  14. """
  15. opens an sqlite database and allows to access several objects
  16. """
  17. def __init__(self, path: str = ':memory:', initialization=True, discovery=True):
  18. """
  19. opens or creates a given sqlite database and creates all required tables
  20. :param path: path to sqlite database
  21. """
  22. # save properties
  23. self.path = path
  24. # initialize database connection
  25. self.con = sqlite3.connect(path)
  26. self.con.execute("PRAGMA foreign_keys = ON")
  27. if initialization:
  28. # create tables
  29. with self:
  30. with closing(self.con.cursor()) as cursor:
  31. cursor.execute('''
  32. CREATE TABLE IF NOT EXISTS models (
  33. id INTEGER PRIMARY KEY,
  34. name TEXT NOT NULL,
  35. description TEXT,
  36. root_folder TEXT NOT NULL UNIQUE,
  37. supports TEXT NOT NULL
  38. )
  39. ''')
  40. cursor.execute('''
  41. CREATE TABLE IF NOT EXISTS label_providers (
  42. id INTEGER PRIMARY KEY,
  43. name TEXT NOT NULL,
  44. description TEXT,
  45. root_folder TEXT NOT NULL UNIQUE
  46. )
  47. ''')
  48. cursor.execute('''
  49. CREATE TABLE IF NOT EXISTS projects (
  50. id INTEGER PRIMARY KEY,
  51. name TEXT NOT NULL,
  52. description TEXT,
  53. created INTEGER NOT NULL,
  54. model INTEGER,
  55. label_provider INTEGER,
  56. root_folder TEXT NOT NULL UNIQUE,
  57. external_data BOOL NOT NULL,
  58. data_folder TEXT NOT NULL,
  59. FOREIGN KEY (model) REFERENCES models(id)
  60. ON UPDATE CASCADE ON DELETE SET NULL,
  61. FOREIGN KEY (label_provider) REFERENCES label_providers(id)
  62. ON UPDATE CASCADE ON DELETE SET NULL
  63. )
  64. ''')
  65. cursor.execute('''
  66. CREATE TABLE IF NOT EXISTS labels (
  67. id INTEGER PRIMARY KEY,
  68. project INTEGER NOT NULL,
  69. parent INTEGER,
  70. created INTEGER NOT NULL,
  71. reference TEXT,
  72. name TEXT NOT NULL,
  73. FOREIGN KEY (project) REFERENCES projects(id)
  74. ON UPDATE CASCADE ON DELETE CASCADE,
  75. FOREIGN KEY (parent) REFERENCES labels(id)
  76. ON UPDATE CASCADE ON DELETE SET NULL,
  77. UNIQUE(project, reference)
  78. )
  79. ''')
  80. cursor.execute('''
  81. CREATE TABLE IF NOT EXISTS collections (
  82. id INTEGER PRIMARY KEY,
  83. project INTEGER NOT NULL,
  84. reference TEXT NOT NULL,
  85. name TEXT NOT NULL,
  86. description TEXT,
  87. position INTEGER NOT NULL,
  88. autoselect INTEGER NOT NULL,
  89. FOREIGN KEY (project) REFERENCES projects(id)
  90. ON UPDATE CASCADE ON DELETE CASCADE,
  91. UNIQUE(project, reference)
  92. )
  93. ''')
  94. cursor.execute('''
  95. CREATE TABLE IF NOT EXISTS files (
  96. id INTEGER PRIMARY KEY,
  97. uuid TEXT NOT NULL,
  98. project INTEGER NOT NULL,
  99. collection INTEGER,
  100. type TEXT NOT NULL,
  101. name TEXT NOT NULL,
  102. extension TEXT NOT NULL,
  103. size INTEGER NOT NULL,
  104. created INTEGER NOT NULL,
  105. path TEXT NOT NULL,
  106. frames INTEGER,
  107. fps FLOAT,
  108. FOREIGN KEY (project) REFERENCES projects(id)
  109. ON UPDATE CASCADE ON DELETE CASCADE,
  110. FOREIGN KEY (collection) REFERENCES collections(id)
  111. ON UPDATE CASCADE ON DELETE SET NULL,
  112. UNIQUE(project, path)
  113. )
  114. ''')
  115. cursor.execute('''
  116. CREATE TABLE IF NOT EXISTS results (
  117. id INTEGER PRIMARY KEY,
  118. file INTEGER NOT NULL,
  119. origin TEXT NOT NULL,
  120. type TEXT NOT NULL,
  121. label INTEGER,
  122. data TEXT,
  123. FOREIGN KEY (file) REFERENCES files(id)
  124. ON UPDATE CASCADE ON DELETE CASCADE
  125. )
  126. ''')
  127. if discovery:
  128. # run discovery modules
  129. with self:
  130. discover_models(self.con)
  131. discover_label_providers(self.con)
  132. def close(self):
  133. self.con.close()
  134. def copy(self):
  135. return Database(self.path, initialization=False, discovery=False)
  136. def commit(self):
  137. self.con.commit()
  138. def __enter__(self):
  139. self.con.__enter__()
  140. return self
  141. def __exit__(self, exc_type, exc_val, exc_tb):
  142. self.con.__exit__(exc_type, exc_val, exc_tb)
  143. def models(self) -> List[Model]:
  144. """
  145. get a list of all available models
  146. :return: list of all available models
  147. """
  148. with closing(self.con.cursor()) as cursor:
  149. cursor.execute('SELECT * FROM models')
  150. return list(map(
  151. lambda row: Model(self, row),
  152. cursor.fetchall()
  153. ))
  154. def model(self, identifier: int) -> Optional[Model]:
  155. """
  156. get a model using its unique identifier
  157. :param identifier: unique identifier
  158. :return: model
  159. """
  160. with closing(self.con.cursor()) as cursor:
  161. cursor.execute('SELECT * FROM models WHERE id = ?', [identifier])
  162. row = cursor.fetchone()
  163. if row is not None:
  164. return Model(self, row)
  165. return None
  166. def label_providers(self) -> List[LabelProvider]:
  167. """
  168. get a list of all available label providers
  169. :return: list of all available label providers
  170. """
  171. with closing(self.con.cursor()) as cursor:
  172. cursor.execute('SELECT * FROM label_providers')
  173. return list(map(
  174. lambda row: LabelProvider(self, row),
  175. cursor.fetchall()
  176. ))
  177. def label_provider(self, identifier: int) -> Optional[LabelProvider]:
  178. """
  179. get a label provider using its unique identifier
  180. :param identifier: unique identifier
  181. :return: label provider
  182. """
  183. with closing(self.con.cursor()) as cursor:
  184. cursor.execute('SELECT * FROM label_providers WHERE id = ?', [identifier])
  185. row = cursor.fetchone()
  186. if row is not None:
  187. return LabelProvider(self, row)
  188. return None
  189. def projects(self) -> List[Project]:
  190. """
  191. get a list of all available projects
  192. :return: list of all available projects
  193. """
  194. with closing(self.con.cursor()) as cursor:
  195. cursor.execute('SELECT * FROM projects')
  196. return list(map(
  197. lambda row: Project(self, row),
  198. cursor.fetchall()
  199. ))
  200. def project(self, identifier: int) -> Optional[Project]:
  201. """
  202. get a project using its unique identifier
  203. :param identifier: unique identifier
  204. :return: project
  205. """
  206. with closing(self.con.cursor()) as cursor:
  207. cursor.execute('SELECT * FROM projects WHERE id = ?', [identifier])
  208. row = cursor.fetchone()
  209. if row is not None:
  210. return Project(self, row)
  211. return None
  212. def create_project(self,
  213. name: str,
  214. description: str,
  215. model: Model,
  216. label_provider: Optional[LabelProvider],
  217. root_folder: str,
  218. external_data: bool,
  219. data_folder: str):
  220. """
  221. insert a project into the database
  222. :param name: project name
  223. :param description: project description
  224. :param model: used model
  225. :param label_provider: used label provider (optional)
  226. :param root_folder: path to project folder
  227. :param external_data: whether an external data directory is used
  228. :param data_folder: path to data folder
  229. :return: created project
  230. """
  231. # prepare some values
  232. created = int(time())
  233. label_provider_id = label_provider.identifier if label_provider is not None else None
  234. # insert statement
  235. with closing(self.con.cursor()) as cursor:
  236. cursor.execute('''
  237. INSERT INTO projects (
  238. name, description, created, model, label_provider, root_folder, external_data,
  239. data_folder
  240. )
  241. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  242. ''', (name, description, created, model.identifier, label_provider_id, root_folder,
  243. external_data, data_folder))
  244. return self.project(cursor.lastrowid)
  245. def collection(self, identifier: int) -> Optional[Collection]:
  246. """
  247. get a collection using its unique identifier
  248. :param identifier: unique identifier
  249. :return: collection
  250. """
  251. with closing(self.con.cursor()) as cursor:
  252. cursor.execute('SELECT * FROM collections WHERE id = ?', [identifier])
  253. row = cursor.fetchone()
  254. if row is not None:
  255. return Collection(self, row)
  256. return None
  257. def file(self, identifier) -> Optional[File]:
  258. """
  259. get a file using its unique identifier
  260. :param identifier: unique identifier
  261. :return: file
  262. """
  263. with closing(self.con.cursor()) as cursor:
  264. cursor.execute('SELECT * FROM files WHERE id = ?', [identifier])
  265. row = cursor.fetchone()
  266. if row is not None:
  267. return File(self, row)
  268. return None
  269. def result(self, identifier) -> Optional[Result]:
  270. """
  271. get a result using its unique identifier
  272. :param identifier: unique identifier
  273. :return: result
  274. """
  275. with closing(self.con.cursor()) as cursor:
  276. cursor.execute('SELECT * FROM results WHERE id = ?', [identifier])
  277. row = cursor.fetchone()
  278. if row is not None:
  279. return Result(self, row)
  280. return None