1
0

QBMapper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 string|null $entityClass the name of the entity that the sql should be
  52. * @psalm-param class-string<T>|null $entityClass the name of the entity that the sql should be
  53. * mapped to queries without using sql
  54. * @since 14.0.0
  55. */
  56. public function __construct(IDBConnection $db, string $tableName, string $entityClass = null) {
  57. $this->db = $db;
  58. $this->tableName = $tableName;
  59. // if not given set the entity name to the class without the mapper part
  60. // cache it here for later use since reflection is slow
  61. if ($entityClass === null) {
  62. $this->entityClass = str_replace('Mapper', '', \get_class($this));
  63. } else {
  64. $this->entityClass = $entityClass;
  65. }
  66. }
  67. /**
  68. * @return string the table name
  69. * @since 14.0.0
  70. */
  71. public function getTableName(): string {
  72. return $this->tableName;
  73. }
  74. /**
  75. * Deletes an entity from the table
  76. *
  77. * @param Entity $entity the entity that should be deleted
  78. * @psalm-param T $entity the entity that should be deleted
  79. * @return Entity the deleted entity
  80. * @psalm-return T the deleted entity
  81. * @throws Exception
  82. * @since 14.0.0
  83. */
  84. public function delete(Entity $entity): Entity {
  85. $qb = $this->db->getQueryBuilder();
  86. $idType = $this->getParameterTypeForProperty($entity, 'id');
  87. $qb->delete($this->tableName)
  88. ->where(
  89. $qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
  90. );
  91. $qb->executeStatement();
  92. return $entity;
  93. }
  94. /**
  95. * Creates a new entry in the db from an entity
  96. *
  97. * @param Entity $entity the entity that should be created
  98. * @psalm-param T $entity the entity that should be created
  99. * @return Entity the saved entity with the set id
  100. * @psalm-return T the saved entity with the set id
  101. * @throws Exception
  102. * @since 14.0.0
  103. */
  104. public function insert(Entity $entity): Entity {
  105. // get updated fields to save, fields have to be set using a setter to
  106. // be saved
  107. $properties = $entity->getUpdatedFields();
  108. $qb = $this->db->getQueryBuilder();
  109. $qb->insert($this->tableName);
  110. // build the fields
  111. foreach ($properties as $property => $updated) {
  112. $column = $entity->propertyToColumn($property);
  113. $getter = 'get' . ucfirst($property);
  114. $value = $entity->$getter();
  115. $type = $this->getParameterTypeForProperty($entity, $property);
  116. $qb->setValue($column, $qb->createNamedParameter($value, $type));
  117. }
  118. $qb->executeStatement();
  119. if ($entity->id === null) {
  120. // When autoincrement is used id is always an int
  121. $entity->setId($qb->getLastInsertId());
  122. }
  123. return $entity;
  124. }
  125. /**
  126. * Tries to creates a new entry in the db from an entity and
  127. * updates an existing entry if duplicate keys are detected
  128. * by the database
  129. *
  130. * @param Entity $entity the entity that should be created/updated
  131. * @psalm-param T $entity the entity that should be created/updated
  132. * @return Entity the saved entity with the (new) id
  133. * @psalm-return T the saved entity with the (new) id
  134. * @throws Exception
  135. * @throws \InvalidArgumentException if entity has no id
  136. * @since 15.0.0
  137. */
  138. public function insertOrUpdate(Entity $entity): Entity {
  139. try {
  140. return $this->insert($entity);
  141. } catch (Exception $ex) {
  142. if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  143. return $this->update($entity);
  144. }
  145. throw $ex;
  146. }
  147. }
  148. /**
  149. * Updates an entry in the db from an entity
  150. *
  151. * @param Entity $entity the entity that should be created
  152. * @psalm-param T $entity the entity that should be created
  153. * @return Entity the saved entity with the set id
  154. * @psalm-return T the saved entity with the set id
  155. * @throws Exception
  156. * @throws \InvalidArgumentException if entity has no id
  157. * @since 14.0.0
  158. */
  159. public function update(Entity $entity): Entity {
  160. // if entity wasn't changed it makes no sense to run a db query
  161. $properties = $entity->getUpdatedFields();
  162. if (\count($properties) === 0) {
  163. return $entity;
  164. }
  165. // entity needs an id
  166. $id = $entity->getId();
  167. if ($id === null) {
  168. throw new \InvalidArgumentException(
  169. 'Entity which should be updated has no id');
  170. }
  171. // get updated fields to save, fields have to be set using a setter to
  172. // be saved
  173. // do not update the id field
  174. unset($properties['id']);
  175. $qb = $this->db->getQueryBuilder();
  176. $qb->update($this->tableName);
  177. // build the fields
  178. foreach ($properties as $property => $updated) {
  179. $column = $entity->propertyToColumn($property);
  180. $getter = 'get' . ucfirst($property);
  181. $value = $entity->$getter();
  182. $type = $this->getParameterTypeForProperty($entity, $property);
  183. $qb->set($column, $qb->createNamedParameter($value, $type));
  184. }
  185. $idType = $this->getParameterTypeForProperty($entity, 'id');
  186. $qb->where(
  187. $qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
  188. );
  189. $qb->executeStatement();
  190. return $entity;
  191. }
  192. /**
  193. * Returns the type parameter for the QueryBuilder for a specific property
  194. * of the $entity
  195. *
  196. * @param Entity $entity The entity to get the types from
  197. * @psalm-param T $entity
  198. * @param string $property The property of $entity to get the type for
  199. * @return int|string
  200. * @since 16.0.0
  201. */
  202. protected function getParameterTypeForProperty(Entity $entity, string $property) {
  203. $types = $entity->getFieldTypes();
  204. if (!isset($types[ $property ])) {
  205. return IQueryBuilder::PARAM_STR;
  206. }
  207. switch ($types[ $property ]) {
  208. case 'int':
  209. case 'integer':
  210. return IQueryBuilder::PARAM_INT;
  211. case 'string':
  212. return IQueryBuilder::PARAM_STR;
  213. case 'bool':
  214. case 'boolean':
  215. return IQueryBuilder::PARAM_BOOL;
  216. case 'blob':
  217. return IQueryBuilder::PARAM_LOB;
  218. case 'datetime':
  219. return IQueryBuilder::PARAM_DATE;
  220. case 'json':
  221. return IQueryBuilder::PARAM_JSON;
  222. }
  223. return IQueryBuilder::PARAM_STR;
  224. }
  225. /**
  226. * Returns an db result and throws exceptions when there are more or less
  227. * results
  228. *
  229. * @param IQueryBuilder $query
  230. * @return array the result as row
  231. * @throws Exception
  232. * @throws MultipleObjectsReturnedException if more than one item exist
  233. * @throws DoesNotExistException if the item does not exist
  234. * @see findEntity
  235. *
  236. * @since 14.0.0
  237. */
  238. protected function findOneQuery(IQueryBuilder $query): array {
  239. $result = $query->executeQuery();
  240. $row = $result->fetch();
  241. if ($row === false) {
  242. $result->closeCursor();
  243. $msg = $this->buildDebugMessage(
  244. 'Did expect one result but found none when executing', $query
  245. );
  246. throw new DoesNotExistException($msg);
  247. }
  248. $row2 = $result->fetch();
  249. $result->closeCursor();
  250. if ($row2 !== false) {
  251. $msg = $this->buildDebugMessage(
  252. 'Did not expect more than one result when executing', $query
  253. );
  254. throw new MultipleObjectsReturnedException($msg);
  255. }
  256. return $row;
  257. }
  258. /**
  259. * @param string $msg
  260. * @param IQueryBuilder $sql
  261. * @return string
  262. * @since 14.0.0
  263. */
  264. private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
  265. return $msg .
  266. ': query "' . $sql->getSQL() . '"; ';
  267. }
  268. /**
  269. * Creates an entity from a row. Automatically determines the entity class
  270. * from the current mapper name (MyEntityMapper -> MyEntity)
  271. *
  272. * @param array $row the row which should be converted to an entity
  273. * @return Entity the entity
  274. * @psalm-return T the entity
  275. * @since 14.0.0
  276. */
  277. protected function mapRowToEntity(array $row): Entity {
  278. unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
  279. return \call_user_func($this->entityClass .'::fromRow', $row);
  280. }
  281. /**
  282. * Runs a sql query and returns an array of entities
  283. *
  284. * @param IQueryBuilder $query
  285. * @return Entity[] all fetched entities
  286. * @psalm-return T[] all fetched entities
  287. * @throws Exception
  288. * @since 14.0.0
  289. */
  290. protected function findEntities(IQueryBuilder $query): array {
  291. $result = $query->executeQuery();
  292. try {
  293. $entities = [];
  294. while ($row = $result->fetch()) {
  295. $entities[] = $this->mapRowToEntity($row);
  296. }
  297. return $entities;
  298. } finally {
  299. $result->closeCursor();
  300. }
  301. }
  302. /**
  303. * Returns an db result and throws exceptions when there are more or less
  304. * results
  305. *
  306. * @param IQueryBuilder $query
  307. * @return Entity the entity
  308. * @psalm-return T the entity
  309. * @throws Exception
  310. * @throws MultipleObjectsReturnedException if more than one item exist
  311. * @throws DoesNotExistException if the item does not exist
  312. * @since 14.0.0
  313. */
  314. protected function findEntity(IQueryBuilder $query): Entity {
  315. return $this->mapRowToEntity($this->findOneQuery($query));
  316. }
  317. }