1
0

QBMapper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCP\AppFramework\Db;
  8. use Generator;
  9. use OCP\DB\Exception;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\DB\Types;
  12. use OCP\IDBConnection;
  13. /**
  14. * Simple parent class for inheriting your data access layer from. This class
  15. * may be subject to change in the future
  16. *
  17. * @since 14.0.0
  18. *
  19. * @template T of Entity
  20. */
  21. abstract class QBMapper {
  22. /** @var string */
  23. protected $tableName;
  24. /** @var string|class-string<T> */
  25. protected $entityClass;
  26. /** @var IDBConnection */
  27. protected $db;
  28. /**
  29. * @param IDBConnection $db Instance of the Db abstraction layer
  30. * @param string $tableName the name of the table. set this to allow entity
  31. * @param class-string<T>|null $entityClass the name of the entity that the sql should be
  32. * mapped to queries without using sql
  33. * @since 14.0.0
  34. */
  35. public function __construct(IDBConnection $db, string $tableName, ?string $entityClass = null) {
  36. $this->db = $db;
  37. $this->tableName = $tableName;
  38. // if not given set the entity name to the class without the mapper part
  39. // cache it here for later use since reflection is slow
  40. if ($entityClass === null) {
  41. $this->entityClass = str_replace('Mapper', '', \get_class($this));
  42. } else {
  43. $this->entityClass = $entityClass;
  44. }
  45. }
  46. /**
  47. * @return string the table name
  48. * @since 14.0.0
  49. */
  50. public function getTableName(): string {
  51. return $this->tableName;
  52. }
  53. /**
  54. * Deletes an entity from the table
  55. *
  56. * @param Entity $entity the entity that should be deleted
  57. * @psalm-param T $entity the entity that should be deleted
  58. * @return Entity the deleted entity
  59. * @psalm-return T the deleted entity
  60. * @throws Exception
  61. * @since 14.0.0
  62. */
  63. public function delete(Entity $entity): Entity {
  64. $qb = $this->db->getQueryBuilder();
  65. $idType = $this->getParameterTypeForProperty($entity, 'id');
  66. $qb->delete($this->tableName)
  67. ->where(
  68. $qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
  69. );
  70. $qb->executeStatement();
  71. return $entity;
  72. }
  73. /**
  74. * Creates a new entry in the db from an entity
  75. *
  76. * @param Entity $entity the entity that should be created
  77. * @psalm-param T $entity the entity that should be created
  78. * @return Entity the saved entity with the set id
  79. * @psalm-return T the saved entity with the set id
  80. * @throws Exception
  81. * @since 14.0.0
  82. */
  83. public function insert(Entity $entity): Entity {
  84. // get updated fields to save, fields have to be set using a setter to
  85. // be saved
  86. $properties = $entity->getUpdatedFields();
  87. $qb = $this->db->getQueryBuilder();
  88. $qb->insert($this->tableName);
  89. // build the fields
  90. foreach ($properties as $property => $updated) {
  91. $column = $entity->propertyToColumn($property);
  92. $getter = 'get' . ucfirst($property);
  93. $value = $entity->$getter();
  94. $type = $this->getParameterTypeForProperty($entity, $property);
  95. $qb->setValue($column, $qb->createNamedParameter($value, $type));
  96. }
  97. $qb->executeStatement();
  98. if ($entity->id === null) {
  99. // When autoincrement is used id is always an int
  100. $entity->setId($qb->getLastInsertId());
  101. }
  102. return $entity;
  103. }
  104. /**
  105. * Tries to creates a new entry in the db from an entity and
  106. * updates an existing entry if duplicate keys are detected
  107. * by the database
  108. *
  109. * @param Entity $entity the entity that should be created/updated
  110. * @psalm-param T $entity the entity that should be created/updated
  111. * @return Entity the saved entity with the (new) id
  112. * @psalm-return T the saved entity with the (new) id
  113. * @throws Exception
  114. * @throws \InvalidArgumentException if entity has no id
  115. * @since 15.0.0
  116. */
  117. public function insertOrUpdate(Entity $entity): Entity {
  118. try {
  119. return $this->insert($entity);
  120. } catch (Exception $ex) {
  121. if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  122. return $this->update($entity);
  123. }
  124. throw $ex;
  125. }
  126. }
  127. /**
  128. * Updates an entry in the db from an entity
  129. *
  130. * @param Entity $entity the entity that should be created
  131. * @psalm-param T $entity the entity that should be created
  132. * @return Entity the saved entity with the set id
  133. * @psalm-return T the saved entity with the set id
  134. * @throws Exception
  135. * @throws \InvalidArgumentException if entity has no id
  136. * @since 14.0.0
  137. */
  138. public function update(Entity $entity): Entity {
  139. // if entity wasn't changed it makes no sense to run a db query
  140. $properties = $entity->getUpdatedFields();
  141. if (\count($properties) === 0) {
  142. return $entity;
  143. }
  144. // entity needs an id
  145. $id = $entity->getId();
  146. if ($id === null) {
  147. throw new \InvalidArgumentException(
  148. 'Entity which should be updated has no id');
  149. }
  150. // get updated fields to save, fields have to be set using a setter to
  151. // be saved
  152. // do not update the id field
  153. unset($properties['id']);
  154. $qb = $this->db->getQueryBuilder();
  155. $qb->update($this->tableName);
  156. // build the fields
  157. foreach ($properties as $property => $updated) {
  158. $column = $entity->propertyToColumn($property);
  159. $getter = 'get' . ucfirst($property);
  160. $value = $entity->$getter();
  161. $type = $this->getParameterTypeForProperty($entity, $property);
  162. $qb->set($column, $qb->createNamedParameter($value, $type));
  163. }
  164. $idType = $this->getParameterTypeForProperty($entity, 'id');
  165. $qb->where(
  166. $qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
  167. );
  168. $qb->executeStatement();
  169. return $entity;
  170. }
  171. /**
  172. * Returns the type parameter for the QueryBuilder for a specific property
  173. * of the $entity
  174. *
  175. * @param Entity $entity The entity to get the types from
  176. * @psalm-param T $entity
  177. * @param string $property The property of $entity to get the type for
  178. * @return int|string
  179. * @since 16.0.0
  180. */
  181. protected function getParameterTypeForProperty(Entity $entity, string $property) {
  182. $types = $entity->getFieldTypes();
  183. if (!isset($types[ $property ])) {
  184. return IQueryBuilder::PARAM_STR;
  185. }
  186. switch ($types[ $property ]) {
  187. case 'int':
  188. case Types::INTEGER:
  189. case Types::SMALLINT:
  190. return IQueryBuilder::PARAM_INT;
  191. case Types::STRING:
  192. return IQueryBuilder::PARAM_STR;
  193. case 'bool':
  194. case Types::BOOLEAN:
  195. return IQueryBuilder::PARAM_BOOL;
  196. case Types::BLOB:
  197. return IQueryBuilder::PARAM_LOB;
  198. case Types::DATE:
  199. return IQueryBuilder::PARAM_DATETIME_MUTABLE;
  200. case Types::DATETIME:
  201. return IQueryBuilder::PARAM_DATETIME_MUTABLE;
  202. case Types::DATETIME_TZ:
  203. return IQueryBuilder::PARAM_DATETIME_TZ_MUTABLE;
  204. case Types::DATE_IMMUTABLE:
  205. return IQueryBuilder::PARAM_DATE_IMMUTABLE;
  206. case Types::DATETIME_IMMUTABLE:
  207. return IQueryBuilder::PARAM_DATETIME_IMMUTABLE;
  208. case Types::DATETIME_TZ_IMMUTABLE:
  209. return IQueryBuilder::PARAM_DATETIME_TZ_IMMUTABLE;
  210. case Types::TIME:
  211. return IQueryBuilder::PARAM_TIME_MUTABLE;
  212. case Types::TIME_IMMUTABLE:
  213. return IQueryBuilder::PARAM_TIME_IMMUTABLE;
  214. case Types::JSON:
  215. return IQueryBuilder::PARAM_JSON;
  216. }
  217. return IQueryBuilder::PARAM_STR;
  218. }
  219. /**
  220. * Returns an db result and throws exceptions when there are more or less
  221. * results
  222. *
  223. * @param IQueryBuilder $query
  224. * @return array the result as row
  225. * @throws Exception
  226. * @throws MultipleObjectsReturnedException if more than one item exist
  227. * @throws DoesNotExistException if the item does not exist
  228. * @see findEntity
  229. *
  230. * @since 14.0.0
  231. */
  232. protected function findOneQuery(IQueryBuilder $query): array {
  233. $result = $query->executeQuery();
  234. $row = $result->fetch();
  235. if ($row === false) {
  236. $result->closeCursor();
  237. $msg = $this->buildDebugMessage(
  238. 'Did expect one result but found none when executing', $query
  239. );
  240. throw new DoesNotExistException($msg);
  241. }
  242. $row2 = $result->fetch();
  243. $result->closeCursor();
  244. if ($row2 !== false) {
  245. $msg = $this->buildDebugMessage(
  246. 'Did not expect more than one result when executing', $query
  247. );
  248. throw new MultipleObjectsReturnedException($msg);
  249. }
  250. return $row;
  251. }
  252. /**
  253. * @param string $msg
  254. * @param IQueryBuilder $sql
  255. * @return string
  256. * @since 14.0.0
  257. */
  258. private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
  259. return $msg .
  260. ': query "' . $sql->getSQL() . '"; ';
  261. }
  262. /**
  263. * Creates an entity from a row. Automatically determines the entity class
  264. * from the current mapper name (MyEntityMapper -> MyEntity)
  265. *
  266. * @param array $row the row which should be converted to an entity
  267. * @return Entity the entity
  268. * @psalm-return T the entity
  269. * @since 14.0.0
  270. */
  271. protected function mapRowToEntity(array $row): Entity {
  272. unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
  273. return \call_user_func($this->entityClass . '::fromRow', $row);
  274. }
  275. /**
  276. * Runs a sql query and returns an array of entities
  277. *
  278. * @param IQueryBuilder $query
  279. * @return list<Entity> all fetched entities
  280. * @psalm-return list<T> all fetched entities
  281. * @throws Exception
  282. * @since 14.0.0
  283. */
  284. protected function findEntities(IQueryBuilder $query): array {
  285. $result = $query->executeQuery();
  286. try {
  287. $entities = [];
  288. while ($row = $result->fetch()) {
  289. $entities[] = $this->mapRowToEntity($row);
  290. }
  291. return $entities;
  292. } finally {
  293. $result->closeCursor();
  294. }
  295. }
  296. /**
  297. * Runs a sql query and yields each resulting entity to obtain database entries in a memory-efficient way
  298. *
  299. * @param IQueryBuilder $query
  300. * @return Generator Generator of fetched entities
  301. * @psalm-return Generator<T> Generator of fetched entities
  302. * @throws Exception
  303. * @since 30.0.0
  304. */
  305. protected function yieldEntities(IQueryBuilder $query): Generator {
  306. $result = $query->executeQuery();
  307. try {
  308. while ($row = $result->fetch()) {
  309. yield $this->mapRowToEntity($row);
  310. }
  311. } finally {
  312. $result->closeCursor();
  313. }
  314. }
  315. /**
  316. * Returns an db result and throws exceptions when there are more or less
  317. * results
  318. *
  319. * @param IQueryBuilder $query
  320. * @return Entity the entity
  321. * @psalm-return T the entity
  322. * @throws Exception
  323. * @throws MultipleObjectsReturnedException if more than one item exist
  324. * @throws DoesNotExistException if the item does not exist
  325. * @since 14.0.0
  326. */
  327. protected function findEntity(IQueryBuilder $query): Entity {
  328. return $this->mapRowToEntity($this->findOneQuery($query));
  329. }
  330. }