1
0

QBMapper.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. $type = $this->getParameterTypeForProperty($entity, $property);
  100. $qb->setValue($column, $qb->createNamedParameter($value, $type));
  101. }
  102. $qb->execute();
  103. if($entity->id === null) {
  104. $entity->setId((int)$qb->getLastInsertId());
  105. }
  106. return $entity;
  107. }
  108. /**
  109. * Tries to creates a new entry in the db from an entity and
  110. * updates an existing entry if duplicate keys are detected
  111. * by the database
  112. *
  113. * @param Entity $entity the entity that should be created/updated
  114. * @return Entity the saved entity with the (new) id
  115. * @throws \InvalidArgumentException if entity has no id
  116. * @since 15.0.0
  117. * @suppress SqlInjectionChecker
  118. */
  119. public function insertOrUpdate(Entity $entity): Entity {
  120. try {
  121. return $this->insert($entity);
  122. } catch (UniqueConstraintViolationException $ex) {
  123. return $this->update($entity);
  124. }
  125. }
  126. /**
  127. * Updates an entry in the db from an entity
  128. * @throws \InvalidArgumentException if entity has no id
  129. * @param Entity $entity the entity that should be created
  130. * @return Entity the saved entity with the set id
  131. * @since 14.0.0
  132. * @suppress SqlInjectionChecker
  133. */
  134. public function update(Entity $entity): Entity {
  135. // if entity wasn't changed it makes no sense to run a db query
  136. $properties = $entity->getUpdatedFields();
  137. if(\count($properties) === 0) {
  138. return $entity;
  139. }
  140. // entity needs an id
  141. $id = $entity->getId();
  142. if($id === null){
  143. throw new \InvalidArgumentException(
  144. 'Entity which should be updated has no id');
  145. }
  146. // get updated fields to save, fields have to be set using a setter to
  147. // be saved
  148. // do not update the id field
  149. unset($properties['id']);
  150. $qb = $this->db->getQueryBuilder();
  151. $qb->update($this->tableName);
  152. // build the fields
  153. foreach($properties as $property => $updated) {
  154. $column = $entity->propertyToColumn($property);
  155. $getter = 'get' . ucfirst($property);
  156. $value = $entity->$getter();
  157. $type = $this->getParameterTypeForProperty($entity, $property);
  158. $qb->set($column, $qb->createNamedParameter($value, $type));
  159. }
  160. $qb->where(
  161. $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))
  162. );
  163. $qb->execute();
  164. return $entity;
  165. }
  166. /**
  167. * Returns the type parameter for the QueryBuilder for a specific property
  168. * of the $entity
  169. *
  170. * @param Entity $entity The entity to get the types from
  171. * @param string $property The property of $entity to get the type for
  172. * @return int
  173. * @since 16.0.0
  174. */
  175. protected function getParameterTypeForProperty(Entity $entity, string $property): int {
  176. $types = $entity->getFieldTypes();
  177. if(!isset($types[ $property ])) {
  178. return IQueryBuilder::PARAM_STR;
  179. }
  180. switch($types[ $property ]) {
  181. case 'int':
  182. case 'integer':
  183. return IQueryBuilder::PARAM_INT;
  184. case 'string':
  185. return IQueryBuilder::PARAM_STR;
  186. case 'bool':
  187. case 'boolean':
  188. return IQueryBuilder::PARAM_BOOL;
  189. }
  190. return IQueryBuilder::PARAM_STR;
  191. }
  192. /**
  193. * Returns an db result and throws exceptions when there are more or less
  194. * results
  195. *
  196. * @see findEntity
  197. *
  198. * @param IQueryBuilder $query
  199. * @throws DoesNotExistException if the item does not exist
  200. * @throws MultipleObjectsReturnedException if more than one item exist
  201. * @return array the result as row
  202. * @since 14.0.0
  203. */
  204. protected function findOneQuery(IQueryBuilder $query): array {
  205. $cursor = $query->execute();
  206. $row = $cursor->fetch();
  207. if($row === false) {
  208. $cursor->closeCursor();
  209. $msg = $this->buildDebugMessage(
  210. 'Did expect one result but found none when executing', $query
  211. );
  212. throw new DoesNotExistException($msg);
  213. }
  214. $row2 = $cursor->fetch();
  215. $cursor->closeCursor();
  216. if($row2 !== false ) {
  217. $msg = $this->buildDebugMessage(
  218. 'Did not expect more than one result when executing', $query
  219. );
  220. throw new MultipleObjectsReturnedException($msg);
  221. }
  222. return $row;
  223. }
  224. /**
  225. * @param string $msg
  226. * @param IQueryBuilder $sql
  227. * @return string
  228. * @since 14.0.0
  229. */
  230. private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
  231. return $msg .
  232. ': query "' . $sql->getSQL() . '"; ';
  233. }
  234. /**
  235. * Creates an entity from a row. Automatically determines the entity class
  236. * from the current mapper name (MyEntityMapper -> MyEntity)
  237. *
  238. * @param array $row the row which should be converted to an entity
  239. * @return Entity the entity
  240. * @since 14.0.0
  241. */
  242. protected function mapRowToEntity(array $row): Entity {
  243. return \call_user_func($this->entityClass .'::fromRow', $row);
  244. }
  245. /**
  246. * Runs a sql query and returns an array of entities
  247. *
  248. * @param IQueryBuilder $query
  249. * @return Entity[] all fetched entities
  250. * @since 14.0.0
  251. */
  252. protected function findEntities(IQueryBuilder $query): array {
  253. $cursor = $query->execute();
  254. $entities = [];
  255. while($row = $cursor->fetch()){
  256. $entities[] = $this->mapRowToEntity($row);
  257. }
  258. $cursor->closeCursor();
  259. return $entities;
  260. }
  261. /**
  262. * Returns an db result and throws exceptions when there are more or less
  263. * results
  264. *
  265. * @param IQueryBuilder $query
  266. * @throws DoesNotExistException if the item does not exist
  267. * @throws MultipleObjectsReturnedException if more than one item exist
  268. * @return Entity the entity
  269. * @since 14.0.0
  270. */
  271. protected function findEntity(IQueryBuilder $query): Entity {
  272. return $this->mapRowToEntity($this->findOneQuery($query));
  273. }
  274. }