QBMapper.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Anna Larch <anna@nextcloud.com>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Marius David Wieschollek <git.public@mdns.eu>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OCP\AppFramework\Db;
  30. use OCP\DB\Exception;
  31. use OCP\DB\QueryBuilder\IQueryBuilder;
  32. use OCP\IDBConnection;
  33. /**
  34. * Simple parent class for inheriting your data access layer from. This class
  35. * may be subject to change in the future
  36. *
  37. * @since 14.0.0
  38. *
  39. * @template T of Entity
  40. */
  41. abstract class QBMapper {
  42. /** @var string */
  43. protected $tableName;
  44. /** @var string|class-string<T> */
  45. protected $entityClass;
  46. /** @var IDBConnection */
  47. protected $db;
  48. /**
  49. * @param IDBConnection $db Instance of the Db abstraction layer
  50. * @param string $tableName the name of the table. set this to allow entity
  51. * @param class-string<T>|null $entityClass the name of the entity that the sql should be
  52. * mapped to queries without using sql
  53. * @since 14.0.0
  54. */
  55. public function __construct(IDBConnection $db, string $tableName, string $entityClass = null) {
  56. $this->db = $db;
  57. $this->tableName = $tableName;
  58. // if not given set the entity name to the class without the mapper part
  59. // cache it here for later use since reflection is slow
  60. if ($entityClass === null) {
  61. $this->entityClass = str_replace('Mapper', '', \get_class($this));
  62. } else {
  63. $this->entityClass = $entityClass;
  64. }
  65. }
  66. /**
  67. * @return string the table name
  68. * @since 14.0.0
  69. */
  70. public function getTableName(): string {
  71. return $this->tableName;
  72. }
  73. /**
  74. * Deletes an entity from the table
  75. *
  76. * @param Entity $entity the entity that should be deleted
  77. * @psalm-param T $entity the entity that should be deleted
  78. * @return Entity the deleted entity
  79. * @psalm-return T the deleted entity
  80. * @throws Exception
  81. * @since 14.0.0
  82. */
  83. public function delete(Entity $entity): Entity {
  84. $qb = $this->db->getQueryBuilder();
  85. $idType = $this->getParameterTypeForProperty($entity, 'id');
  86. $qb->delete($this->tableName)
  87. ->where(
  88. $qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
  89. );
  90. $qb->executeStatement();
  91. return $entity;
  92. }
  93. /**
  94. * Creates a new entry in the db from an entity
  95. *
  96. * @param Entity $entity the entity that should be created
  97. * @psalm-param T $entity the entity that should be created
  98. * @return Entity the saved entity with the set id
  99. * @psalm-return T the saved entity with the set id
  100. * @throws Exception
  101. * @since 14.0.0
  102. */
  103. public function insert(Entity $entity): Entity {
  104. // get updated fields to save, fields have to be set using a setter to
  105. // be saved
  106. $properties = $entity->getUpdatedFields();
  107. $qb = $this->db->getQueryBuilder();
  108. $qb->insert($this->tableName);
  109. // build the fields
  110. foreach ($properties as $property => $updated) {
  111. $column = $entity->propertyToColumn($property);
  112. $getter = 'get' . ucfirst($property);
  113. $value = $entity->$getter();
  114. $type = $this->getParameterTypeForProperty($entity, $property);
  115. $qb->setValue($column, $qb->createNamedParameter($value, $type));
  116. }
  117. $qb->executeStatement();
  118. if ($entity->id === null) {
  119. // When autoincrement is used id is always an int
  120. $entity->setId($qb->getLastInsertId());
  121. }
  122. return $entity;
  123. }
  124. /**
  125. * Tries to creates a new entry in the db from an entity and
  126. * updates an existing entry if duplicate keys are detected
  127. * by the database
  128. *
  129. * @param Entity $entity the entity that should be created/updated
  130. * @psalm-param T $entity the entity that should be created/updated
  131. * @return Entity the saved entity with the (new) id
  132. * @psalm-return T the saved entity with the (new) id
  133. * @throws Exception
  134. * @throws \InvalidArgumentException if entity has no id
  135. * @since 15.0.0
  136. */
  137. public function insertOrUpdate(Entity $entity): Entity {
  138. try {
  139. return $this->insert($entity);
  140. } catch (Exception $ex) {
  141. if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  142. return $this->update($entity);
  143. }
  144. throw $ex;
  145. }
  146. }
  147. /**
  148. * Updates an entry in the db from an entity
  149. *
  150. * @param Entity $entity the entity that should be created
  151. * @psalm-param T $entity the entity that should be created
  152. * @return Entity the saved entity with the set id
  153. * @psalm-return T the saved entity with the set id
  154. * @throws Exception
  155. * @throws \InvalidArgumentException if entity has no id
  156. * @since 14.0.0
  157. */
  158. public function update(Entity $entity): Entity {
  159. // if entity wasn't changed it makes no sense to run a db query
  160. $properties = $entity->getUpdatedFields();
  161. if (\count($properties) === 0) {
  162. return $entity;
  163. }
  164. // entity needs an id
  165. $id = $entity->getId();
  166. if ($id === null) {
  167. throw new \InvalidArgumentException(
  168. 'Entity which should be updated has no id');
  169. }
  170. // get updated fields to save, fields have to be set using a setter to
  171. // be saved
  172. // do not update the id field
  173. unset($properties['id']);
  174. $qb = $this->db->getQueryBuilder();
  175. $qb->update($this->tableName);
  176. // build the fields
  177. foreach ($properties as $property => $updated) {
  178. $column = $entity->propertyToColumn($property);
  179. $getter = 'get' . ucfirst($property);
  180. $value = $entity->$getter();
  181. $type = $this->getParameterTypeForProperty($entity, $property);
  182. $qb->set($column, $qb->createNamedParameter($value, $type));
  183. }
  184. $idType = $this->getParameterTypeForProperty($entity, 'id');
  185. $qb->where(
  186. $qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
  187. );
  188. $qb->executeStatement();
  189. return $entity;
  190. }
  191. /**
  192. * Returns the type parameter for the QueryBuilder for a specific property
  193. * of the $entity
  194. *
  195. * @param Entity $entity The entity to get the types from
  196. * @psalm-param T $entity
  197. * @param string $property The property of $entity to get the type for
  198. * @return int|string
  199. * @since 16.0.0
  200. */
  201. protected function getParameterTypeForProperty(Entity $entity, string $property) {
  202. $types = $entity->getFieldTypes();
  203. if (!isset($types[ $property ])) {
  204. return IQueryBuilder::PARAM_STR;
  205. }
  206. switch ($types[ $property ]) {
  207. case 'int':
  208. case 'integer':
  209. return IQueryBuilder::PARAM_INT;
  210. case 'string':
  211. return IQueryBuilder::PARAM_STR;
  212. case 'bool':
  213. case 'boolean':
  214. return IQueryBuilder::PARAM_BOOL;
  215. case 'blob':
  216. return IQueryBuilder::PARAM_LOB;
  217. case 'datetime':
  218. return IQueryBuilder::PARAM_DATE;
  219. case 'json':
  220. return IQueryBuilder::PARAM_JSON;
  221. }
  222. return IQueryBuilder::PARAM_STR;
  223. }
  224. /**
  225. * Returns an db result and throws exceptions when there are more or less
  226. * results
  227. *
  228. * @param IQueryBuilder $query
  229. * @return array the result as row
  230. * @throws Exception
  231. * @throws MultipleObjectsReturnedException if more than one item exist
  232. * @throws DoesNotExistException if the item does not exist
  233. * @see findEntity
  234. *
  235. * @since 14.0.0
  236. */
  237. protected function findOneQuery(IQueryBuilder $query): array {
  238. $result = $query->executeQuery();
  239. $row = $result->fetch();
  240. if ($row === false) {
  241. $result->closeCursor();
  242. $msg = $this->buildDebugMessage(
  243. 'Did expect one result but found none when executing', $query
  244. );
  245. throw new DoesNotExistException($msg);
  246. }
  247. $row2 = $result->fetch();
  248. $result->closeCursor();
  249. if ($row2 !== false) {
  250. $msg = $this->buildDebugMessage(
  251. 'Did not expect more than one result when executing', $query
  252. );
  253. throw new MultipleObjectsReturnedException($msg);
  254. }
  255. return $row;
  256. }
  257. /**
  258. * @param string $msg
  259. * @param IQueryBuilder $sql
  260. * @return string
  261. * @since 14.0.0
  262. */
  263. private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
  264. return $msg .
  265. ': query "' . $sql->getSQL() . '"; ';
  266. }
  267. /**
  268. * Creates an entity from a row. Automatically determines the entity class
  269. * from the current mapper name (MyEntityMapper -> MyEntity)
  270. *
  271. * @param array $row the row which should be converted to an entity
  272. * @return Entity the entity
  273. * @psalm-return T the entity
  274. * @since 14.0.0
  275. */
  276. protected function mapRowToEntity(array $row): Entity {
  277. unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
  278. return \call_user_func($this->entityClass .'::fromRow', $row);
  279. }
  280. /**
  281. * Runs a sql query and returns an array of entities
  282. *
  283. * @param IQueryBuilder $query
  284. * @return Entity[] all fetched entities
  285. * @psalm-return T[] all fetched entities
  286. * @throws Exception
  287. * @since 14.0.0
  288. */
  289. protected function findEntities(IQueryBuilder $query): array {
  290. $result = $query->executeQuery();
  291. try {
  292. $entities = [];
  293. while ($row = $result->fetch()) {
  294. $entities[] = $this->mapRowToEntity($row);
  295. }
  296. return $entities;
  297. } finally {
  298. $result->closeCursor();
  299. }
  300. }
  301. /**
  302. * Returns an db result and throws exceptions when there are more or less
  303. * results
  304. *
  305. * @param IQueryBuilder $query
  306. * @return Entity the entity
  307. * @psalm-return T the entity
  308. * @throws Exception
  309. * @throws MultipleObjectsReturnedException if more than one item exist
  310. * @throws DoesNotExistException if the item does not exist
  311. * @since 14.0.0
  312. */
  313. protected function findEntity(IQueryBuilder $query): Entity {
  314. return $this->mapRowToEntity($this->findOneQuery($query));
  315. }
  316. }