6
0

Database.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import sqlite3
  2. from contextlib import closing
  3. from time import time
  4. from typing import Optional, Iterator
  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,
  46. configuration_file TEXT NOT NULL,
  47. UNIQUE(root_folder, configuration_file)
  48. )
  49. ''')
  50. cursor.execute('''
  51. CREATE TABLE IF NOT EXISTS projects (
  52. id INTEGER PRIMARY KEY,
  53. name TEXT NOT NULL,
  54. description TEXT,
  55. created INTEGER NOT NULL,
  56. model INTEGER,
  57. label_provider INTEGER,
  58. root_folder TEXT NOT NULL UNIQUE,
  59. external_data BOOL NOT NULL,
  60. data_folder TEXT NOT NULL,
  61. FOREIGN KEY (model) REFERENCES models(id)
  62. ON UPDATE CASCADE ON DELETE SET NULL,
  63. FOREIGN KEY (label_provider) REFERENCES label_providers(id)
  64. ON UPDATE CASCADE ON DELETE SET NULL
  65. )
  66. ''')
  67. cursor.execute('''
  68. CREATE TABLE IF NOT EXISTS labels (
  69. id INTEGER PRIMARY KEY,
  70. project INTEGER NOT NULL,
  71. parent INTEGER,
  72. created INTEGER NOT NULL,
  73. reference TEXT,
  74. name TEXT NOT NULL,
  75. FOREIGN KEY (project) REFERENCES projects(id)
  76. ON UPDATE CASCADE ON DELETE CASCADE,
  77. FOREIGN KEY (parent) REFERENCES labels(id)
  78. ON UPDATE CASCADE ON DELETE SET NULL,
  79. UNIQUE(project, reference)
  80. )
  81. ''')
  82. cursor.execute('''
  83. CREATE TABLE IF NOT EXISTS collections (
  84. id INTEGER PRIMARY KEY,
  85. project INTEGER NOT NULL,
  86. reference TEXT NOT NULL,
  87. name TEXT NOT NULL,
  88. description TEXT,
  89. position INTEGER NOT NULL,
  90. autoselect INTEGER NOT NULL,
  91. FOREIGN KEY (project) REFERENCES projects(id)
  92. ON UPDATE CASCADE ON DELETE CASCADE,
  93. UNIQUE(project, reference)
  94. )
  95. ''')
  96. cursor.execute('''
  97. CREATE TABLE IF NOT EXISTS files (
  98. id INTEGER PRIMARY KEY,
  99. uuid TEXT NOT NULL,
  100. project INTEGER NOT NULL,
  101. collection INTEGER,
  102. type TEXT NOT NULL,
  103. name TEXT NOT NULL,
  104. extension TEXT NOT NULL,
  105. size INTEGER NOT NULL,
  106. created INTEGER NOT NULL,
  107. path TEXT NOT NULL,
  108. frames INTEGER,
  109. fps FLOAT,
  110. FOREIGN KEY (project) REFERENCES projects(id)
  111. ON UPDATE CASCADE ON DELETE CASCADE,
  112. FOREIGN KEY (collection) REFERENCES collections(id)
  113. ON UPDATE CASCADE ON DELETE SET NULL,
  114. UNIQUE(project, path)
  115. )
  116. ''')
  117. cursor.execute('''
  118. CREATE TABLE IF NOT EXISTS results (
  119. id INTEGER PRIMARY KEY,
  120. file INTEGER NOT NULL,
  121. origin TEXT NOT NULL,
  122. type TEXT NOT NULL,
  123. label INTEGER,
  124. data TEXT,
  125. FOREIGN KEY (file) REFERENCES files(id)
  126. ON UPDATE CASCADE ON DELETE CASCADE
  127. )
  128. ''')
  129. if discovery:
  130. # run discovery modules
  131. with self:
  132. discover_models(self.con)
  133. discover_label_providers(self.con)
  134. def close(self):
  135. """
  136. close database file
  137. """
  138. self.con.close()
  139. def copy(self):
  140. """
  141. Create a copy of this database object. This can be used to access the database
  142. from another thread. Table initialization and model and label provider discovery is
  143. disabled to speedup this function.
  144. :return: Database
  145. """
  146. return Database(self.path, initialization=False, discovery=False)
  147. def commit(self):
  148. """
  149. commit changes
  150. """
  151. self.con.commit()
  152. def __enter__(self):
  153. self.con.__enter__()
  154. return self
  155. def __exit__(self, exc_type, exc_val, exc_tb):
  156. self.con.__exit__(exc_type, exc_val, exc_tb)
  157. def models(self) -> Iterator[Model]:
  158. """
  159. get a list of all available models
  160. :return: iterator of models
  161. """
  162. with closing(self.con.cursor()) as cursor:
  163. cursor.execute('SELECT * FROM models')
  164. for row in cursor:
  165. yield Model(self, row)
  166. def model(self, identifier: int) -> Optional[Model]:
  167. """
  168. get a model using its unique identifier
  169. :param identifier: unique identifier
  170. :return: model
  171. """
  172. with closing(self.con.cursor()) as cursor:
  173. cursor.execute('SELECT * FROM models WHERE id = ?', [identifier])
  174. row = cursor.fetchone()
  175. if row is not None:
  176. return Model(self, row)
  177. return None
  178. def label_providers(self) -> Iterator[LabelProvider]:
  179. """
  180. get a list of all available label providers
  181. :return: iterator over label providers
  182. """
  183. with closing(self.con.cursor()) as cursor:
  184. cursor.execute('SELECT * FROM label_providers')
  185. for row in cursor:
  186. yield LabelProvider(self, row)
  187. def label_provider(self, identifier: int) -> Optional[LabelProvider]:
  188. """
  189. get a label provider using its unique identifier
  190. :param identifier: unique identifier
  191. :return: label provider
  192. """
  193. with closing(self.con.cursor()) as cursor:
  194. cursor.execute('SELECT * FROM label_providers WHERE id = ?', [identifier])
  195. row = cursor.fetchone()
  196. if row is not None:
  197. return LabelProvider(self, row)
  198. return None
  199. def projects(self) -> Iterator[Project]:
  200. """
  201. get a list of all available projects
  202. :return: iterator over projects
  203. """
  204. with closing(self.con.cursor()) as cursor:
  205. cursor.execute('SELECT * FROM projects')
  206. for row in cursor:
  207. yield Project(self, row)
  208. def project(self, identifier: int) -> Optional[Project]:
  209. """
  210. get a project using its unique identifier
  211. :param identifier: unique identifier
  212. :return: project
  213. """
  214. with closing(self.con.cursor()) as cursor:
  215. cursor.execute('SELECT * FROM projects WHERE id = ?', [identifier])
  216. row = cursor.fetchone()
  217. if row is not None:
  218. return Project(self, row)
  219. return None
  220. def create_project(self,
  221. name: str,
  222. description: str,
  223. model: Model,
  224. label_provider: Optional[LabelProvider],
  225. root_folder: str,
  226. external_data: bool,
  227. data_folder: str):
  228. """
  229. insert a project into the database
  230. :param name: project name
  231. :param description: project description
  232. :param model: used model
  233. :param label_provider: used label provider (optional)
  234. :param root_folder: path to project folder
  235. :param external_data: whether an external data directory is used
  236. :param data_folder: path to data folder
  237. :return: created project
  238. """
  239. # prepare some values
  240. created = int(time())
  241. label_provider_id = label_provider.identifier if label_provider is not None else None
  242. # insert statement
  243. with closing(self.con.cursor()) as cursor:
  244. cursor.execute('''
  245. INSERT INTO projects (
  246. name, description, created, model, label_provider, root_folder, external_data,
  247. data_folder
  248. )
  249. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  250. ''', (name, description, created, model.identifier, label_provider_id, root_folder,
  251. external_data, data_folder))
  252. return self.project(cursor.lastrowid)
  253. def collection(self, identifier: int) -> Optional[Collection]:
  254. """
  255. get a collection using its unique identifier
  256. :param identifier: unique identifier
  257. :return: collection
  258. """
  259. with closing(self.con.cursor()) as cursor:
  260. cursor.execute('SELECT * FROM collections WHERE id = ?', [identifier])
  261. row = cursor.fetchone()
  262. if row is not None:
  263. return Collection(self, row)
  264. return None
  265. def file(self, identifier) -> Optional[File]:
  266. """
  267. get a file using its unique identifier
  268. :param identifier: unique identifier
  269. :return: file
  270. """
  271. with closing(self.con.cursor()) as cursor:
  272. cursor.execute('SELECT * FROM files WHERE id = ?', [identifier])
  273. row = cursor.fetchone()
  274. if row is not None:
  275. return File(self, row)
  276. return None
  277. def result(self, identifier) -> Optional[Result]:
  278. """
  279. get a result using its unique identifier
  280. :param identifier: unique identifier
  281. :return: result
  282. """
  283. with closing(self.con.cursor()) as cursor:
  284. cursor.execute('SELECT * FROM results WHERE id = ?', [identifier])
  285. row = cursor.fetchone()
  286. if row is not None:
  287. return Result(self, row)
  288. return None