QBMapper.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Roeland Jago Douma <roeland@famdouma.nl>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCP\AppFramework\Db;
  25. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  26. use OCP\DB\QueryBuilder\IQueryBuilder;
  27. use OCP\IDBConnection;
  28. /**
  29. * Simple parent class for inheriting your data access layer from. This class
  30. * may be subject to change in the future
  31. *
  32. * @since 14.0.0
  33. */
  34. abstract class QBMapper {
  35. /** @var string */
  36. protected $tableName;
  37. /** @var string */
  38. protected $entityClass;
  39. /** @var IDBConnection */
  40. protected $db;
  41. /**
  42. * @param IDBConnection $db Instance of the Db abstraction layer
  43. * @param string $tableName the name of the table. set this to allow entity
  44. * @param string $entityClass the name of the entity that the sql should be
  45. * mapped to queries without using sql
  46. * @since 14.0.0
  47. */
  48. public function __construct(IDBConnection $db, string $tableName, string $entityClass=null){
  49. $this->db = $db;
  50. $this->tableName = $tableName;
  51. // if not given set the entity name to the class without the mapper part
  52. // cache it here for later use since reflection is slow
  53. if($entityClass === null) {
  54. $this->entityClass = str_replace('Mapper', '', \get_class($this));
  55. } else {
  56. $this->entityClass = $entityClass;
  57. }
  58. }
  59. /**
  60. * @return string the table name
  61. * @since 14.0.0
  62. */
  63. public function getTableName(): string {
  64. return $this->tableName;
  65. }
  66. /**
  67. * Deletes an entity from the table
  68. * @param Entity $entity the entity that should be deleted
  69. * @return Entity the deleted entity
  70. * @since 14.0.0
  71. */
  72. public function delete(Entity $entity): Entity {
  73. $qb = $this->db->getQueryBuilder();
  74. $qb->delete($this->tableName)
  75. ->where(
  76. $qb->expr()->eq('id', $qb->createNamedParameter($entity->getId()))
  77. );
  78. $qb->execute();
  79. return $entity;
  80. }
  81. /**
  82. * Creates a new entry in the db from an entity
  83. * @param Entity $entity the entity that should be created
  84. * @return Entity the saved entity with the set id
  85. * @since 14.0.0
  86. * @suppress SqlInjectionChecker
  87. */
  88. public function insert(Entity $entity): Entity {
  89. // get updated fields to save, fields have to be set using a setter to
  90. // be saved
  91. $properties = $entity->getUpdatedFields();
  92. $qb = $this->db->getQueryBuilder();
  93. $qb->insert($this->tableName);
  94. // build the fields
  95. foreach($properties as $property => $updated) {
  96. $column = $entity->propertyToColumn($property);
  97. $getter = 'get' . ucfirst($property);
  98. $value = $entity->$getter();
  99. $qb->setValue($column, $qb->createNamedParameter($value));
  100. }
  101. $qb->execute();
  102. if($entity->id === null) {
  103. $entity->setId((int)$qb->getLastInsertId());
  104. }
  105. return $entity;
  106. }
  107. /**
  108. * Tries to creates a new entry in the db from an entity and
  109. * updates an existing entry if duplicate keys are detected
  110. * by the database
  111. *
  112. * @param Entity $entity the entity that should be created/updated
  113. * @return Entity the saved entity with the (new) id
  114. * @throws \InvalidArgumentException if entity has no id
  115. * @since 15.0.0
  116. * @suppress SqlInjectionChecker
  117. */
  118. public function insertOrUpdate(Entity $entity): Entity {
  119. try {
  120. return $this->insert($entity);
  121. } catch (UniqueConstraintViolationException $ex) {
  122. return $this->update($entity);
  123. }
  124. }
  125. /**
  126. * Updates an entry in the db from an entity
  127. * @throws \InvalidArgumentException if entity has no id
  128. * @param Entity $entity the entity that should be created
  129. * @return Entity the saved entity with the set id
  130. * @since 14.0.0
  131. * @suppress SqlInjectionChecker
  132. */
  133. public function update(Entity $entity): Entity {
  134. // if entity wasn't changed it makes no sense to run a db query
  135. $properties = $entity->getUpdatedFields();
  136. if(\count($properties) === 0) {
  137. return $entity;
  138. }
  139. // entity needs an id
  140. $id = $entity->getId();
  141. if($id === null){
  142. throw new \InvalidArgumentException(
  143. 'Entity which should be updated has no id');
  144. }
  145. // get updated fields to save, fields have to be set using a setter to
  146. // be saved
  147. // do not update the id field
  148. unset($properties['id']);
  149. $qb = $this->db->getQueryBuilder();
  150. $qb->update($this->tableName);
  151. // build the fields
  152. foreach($properties as $property => $updated) {
  153. $column = $entity->propertyToColumn($property);
  154. $getter = 'get' . ucfirst($property);
  155. $value = $entity->$getter();
  156. $qb->set($column, $qb->createNamedParameter($value));
  157. }
  158. $qb->where(
  159. $qb->expr()->eq('id', $qb->createNamedParameter($id))
  160. );
  161. $qb->execute();
  162. return $entity;
  163. }
  164. /**
  165. * Returns an db result and throws exceptions when there are more or less
  166. * results
  167. *
  168. * @see findEntity
  169. *
  170. * @param IQueryBuilder $query
  171. * @throws DoesNotExistException if the item does not exist
  172. * @throws MultipleObjectsReturnedException if more than one item exist
  173. * @return array the result as row
  174. * @since 14.0.0
  175. */
  176. protected function findOneQuery(IQueryBuilder $query): array {
  177. $cursor = $query->execute();
  178. $row = $cursor->fetch();
  179. if($row === false) {
  180. $cursor->closeCursor();
  181. $msg = $this->buildDebugMessage(
  182. 'Did expect one result but found none when executing', $query
  183. );
  184. throw new DoesNotExistException($msg);
  185. }
  186. $row2 = $cursor->fetch();
  187. $cursor->closeCursor();
  188. if($row2 !== false ) {
  189. $msg = $this->buildDebugMessage(
  190. 'Did not expect more than one result when executing', $query
  191. );
  192. throw new MultipleObjectsReturnedException($msg);
  193. }
  194. return $row;
  195. }
  196. /**
  197. * @param string $msg
  198. * @param IQueryBuilder $sql
  199. * @return string
  200. * @since 14.0.0
  201. */
  202. private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
  203. return $msg .
  204. ': query "' . $sql->getSQL() . '"; ';
  205. }
  206. /**
  207. * Creates an entity from a row. Automatically determines the entity class
  208. * from the current mapper name (MyEntityMapper -> MyEntity)
  209. *
  210. * @param array $row the row which should be converted to an entity
  211. * @return Entity the entity
  212. * @since 14.0.0
  213. */
  214. protected function mapRowToEntity(array $row): Entity {
  215. return \call_user_func($this->entityClass .'::fromRow', $row);
  216. }
  217. /**
  218. * Runs a sql query and returns an array of entities
  219. *
  220. * @param IQueryBuilder $query
  221. * @return Entity[] all fetched entities
  222. * @since 14.0.0
  223. */
  224. protected function findEntities(IQueryBuilder $query): array {
  225. $cursor = $query->execute();
  226. $entities = [];
  227. while($row = $cursor->fetch()){
  228. $entities[] = $this->mapRowToEntity($row);
  229. }
  230. $cursor->closeCursor();
  231. return $entities;
  232. }
  233. /**
  234. * Returns an db result and throws exceptions when there are more or less
  235. * results
  236. *
  237. * @param IQueryBuilder $query
  238. * @throws DoesNotExistException if the item does not exist
  239. * @throws MultipleObjectsReturnedException if more than one item exist
  240. * @return Entity the entity
  241. * @since 14.0.0
  242. */
  243. protected function findEntity(IQueryBuilder $query): Entity {
  244. return $this->mapRowToEntity($this->findOneQuery($query));
  245. }
  246. }