QBMapper.php 8.7 KB

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