mapper.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. /**
  3. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  4. * @author Lukas Reschke <lukas@owncloud.com>
  5. * @author Morris Jobke <hey@morrisjobke.de>
  6. * @author Thomas Müller <thomas.mueller@tmit.eu>
  7. *
  8. * @copyright Copyright (c) 2015, ownCloud, Inc.
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  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, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OCP\AppFramework\Db;
  25. use OCP\IDBConnection;
  26. use OCP\IDb;
  27. /**
  28. * Simple parent class for inheriting your data access layer from. This class
  29. * may be subject to change in the future
  30. * @since 7.0.0
  31. */
  32. abstract class Mapper {
  33. protected $tableName;
  34. protected $entityClass;
  35. protected $db;
  36. /**
  37. * @param IDBConnection $db Instance of the Db abstraction layer
  38. * @param string $tableName the name of the table. set this to allow entity
  39. * @param string $entityClass the name of the entity that the sql should be
  40. * mapped to queries without using sql
  41. * @since 7.0.0
  42. */
  43. public function __construct(IDBConnection $db, $tableName, $entityClass=null){
  44. $this->db = $db;
  45. $this->tableName = '*PREFIX*' . $tableName;
  46. // if not given set the entity name to the class without the mapper part
  47. // cache it here for later use since reflection is slow
  48. if($entityClass === null) {
  49. $this->entityClass = str_replace('Mapper', '', get_class($this));
  50. } else {
  51. $this->entityClass = $entityClass;
  52. }
  53. }
  54. /**
  55. * @return string the table name
  56. * @since 7.0.0
  57. */
  58. public function getTableName(){
  59. return $this->tableName;
  60. }
  61. /**
  62. * Deletes an entity from the table
  63. * @param Entity $entity the entity that should be deleted
  64. * @return Entity the deleted entity
  65. * @since 7.0.0 - return value added in 8.1.0
  66. */
  67. public function delete(Entity $entity){
  68. $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
  69. $stmt = $this->execute($sql, [$entity->getId()]);
  70. $stmt->closeCursor();
  71. return $entity;
  72. }
  73. /**
  74. * Creates a new entry in the db from an entity
  75. * @param Entity $entity the entity that should be created
  76. * @return Entity the saved entity with the set id
  77. * @since 7.0.0
  78. */
  79. public function insert(Entity $entity){
  80. // get updated fields to save, fields have to be set using a setter to
  81. // be saved
  82. $properties = $entity->getUpdatedFields();
  83. $values = '';
  84. $columns = '';
  85. $params = [];
  86. // build the fields
  87. $i = 0;
  88. foreach($properties as $property => $updated) {
  89. $column = $entity->propertyToColumn($property);
  90. $getter = 'get' . ucfirst($property);
  91. $columns .= '`' . $column . '`';
  92. $values .= '?';
  93. // only append colon if there are more entries
  94. if($i < count($properties)-1){
  95. $columns .= ',';
  96. $values .= ',';
  97. }
  98. $params[] = $entity->$getter();
  99. $i++;
  100. }
  101. $sql = 'INSERT INTO `' . $this->tableName . '`(' .
  102. $columns . ') VALUES(' . $values . ')';
  103. $stmt = $this->execute($sql, $params);
  104. $entity->setId((int) $this->db->lastInsertId($this->tableName));
  105. $stmt->closeCursor();
  106. return $entity;
  107. }
  108. /**
  109. * Updates an entry in the db from an entity
  110. * @throws \InvalidArgumentException if entity has no id
  111. * @param Entity $entity the entity that should be created
  112. * @return Entity the saved entity with the set id
  113. * @since 7.0.0 - return value was added in 8.0.0
  114. */
  115. public function update(Entity $entity){
  116. // if entity wasn't changed it makes no sense to run a db query
  117. $properties = $entity->getUpdatedFields();
  118. if(count($properties) === 0) {
  119. return $entity;
  120. }
  121. // entity needs an id
  122. $id = $entity->getId();
  123. if($id === null){
  124. throw new \InvalidArgumentException(
  125. 'Entity which should be updated has no id');
  126. }
  127. // get updated fields to save, fields have to be set using a setter to
  128. // be saved
  129. // do not update the id field
  130. unset($properties['id']);
  131. $columns = '';
  132. $params = [];
  133. // build the fields
  134. $i = 0;
  135. foreach($properties as $property => $updated) {
  136. $column = $entity->propertyToColumn($property);
  137. $getter = 'get' . ucfirst($property);
  138. $columns .= '`' . $column . '` = ?';
  139. // only append colon if there are more entries
  140. if($i < count($properties)-1){
  141. $columns .= ',';
  142. }
  143. $params[] = $entity->$getter();
  144. $i++;
  145. }
  146. $sql = 'UPDATE `' . $this->tableName . '` SET ' .
  147. $columns . ' WHERE `id` = ?';
  148. $params[] = $id;
  149. $stmt = $this->execute($sql, $params);
  150. $stmt->closeCursor();
  151. return $entity;
  152. }
  153. /**
  154. * Checks if an array is associative
  155. * @param array $array
  156. * @return bool true if associative
  157. * @since 8.1.0
  158. */
  159. private function isAssocArray(array $array) {
  160. return array_values($array) !== $array;
  161. }
  162. /**
  163. * Returns the correct PDO constant based on the value type
  164. * @param $value
  165. * @return PDO constant
  166. * @since 8.1.0
  167. */
  168. private function getPDOType($value) {
  169. switch (gettype($value)) {
  170. case 'integer':
  171. return \PDO::PARAM_INT;
  172. case 'boolean':
  173. return \PDO::PARAM_BOOL;
  174. default:
  175. return \PDO::PARAM_STR;
  176. }
  177. }
  178. /**
  179. * Runs an sql query
  180. * @param string $sql the prepare string
  181. * @param array $params the params which should replace the ? in the sql query
  182. * @param int $limit the maximum number of rows
  183. * @param int $offset from which row we want to start
  184. * @return \PDOStatement the database query result
  185. * @since 7.0.0
  186. */
  187. protected function execute($sql, array $params=[], $limit=null, $offset=null){
  188. if ($this->db instanceof IDb) {
  189. $query = $this->db->prepareQuery($sql, $limit, $offset);
  190. } else {
  191. $query = $this->db->prepare($sql, $limit, $offset);
  192. }
  193. if ($this->isAssocArray($params)) {
  194. foreach ($params as $key => $param) {
  195. $pdoConstant = $this->getPDOType($param);
  196. $query->bindValue($key, $param, $pdoConstant);
  197. }
  198. } else {
  199. $index = 1; // bindParam is 1 indexed
  200. foreach ($params as $param) {
  201. $pdoConstant = $this->getPDOType($param);
  202. $query->bindValue($index, $param, $pdoConstant);
  203. $index++;
  204. }
  205. }
  206. $result = $query->execute();
  207. // this is only for backwards compatibility reasons and can be removed
  208. // in owncloud 10. IDb returns a StatementWrapper from execute, PDO,
  209. // Doctrine and IDbConnection don't so this needs to be done in order
  210. // to stay backwards compatible for the things that rely on the
  211. // StatementWrapper being returned
  212. if ($result instanceof \OC_DB_StatementWrapper) {
  213. return $result;
  214. }
  215. return $query;
  216. }
  217. /**
  218. * Returns an db result and throws exceptions when there are more or less
  219. * results
  220. * @see findEntity
  221. * @param string $sql the sql query
  222. * @param array $params the parameters of the sql query
  223. * @param int $limit the maximum number of rows
  224. * @param int $offset from which row we want to start
  225. * @throws DoesNotExistException if the item does not exist
  226. * @throws MultipleObjectsReturnedException if more than one item exist
  227. * @return array the result as row
  228. * @since 7.0.0
  229. */
  230. protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
  231. $stmt = $this->execute($sql, $params, $limit, $offset);
  232. $row = $stmt->fetch();
  233. if($row === false || $row === null){
  234. $stmt->closeCursor();
  235. throw new DoesNotExistException('No matching entry found');
  236. }
  237. $row2 = $stmt->fetch();
  238. $stmt->closeCursor();
  239. //MDB2 returns null, PDO and doctrine false when no row is available
  240. if( ! ($row2 === false || $row2 === null )) {
  241. throw new MultipleObjectsReturnedException('More than one result');
  242. } else {
  243. return $row;
  244. }
  245. }
  246. /**
  247. * Creates an entity from a row. Automatically determines the entity class
  248. * from the current mapper name (MyEntityMapper -> MyEntity)
  249. * @param array $row the row which should be converted to an entity
  250. * @return Entity the entity
  251. * @since 7.0.0
  252. */
  253. protected function mapRowToEntity($row) {
  254. return call_user_func($this->entityClass .'::fromRow', $row);
  255. }
  256. /**
  257. * Runs a sql query and returns an array of entities
  258. * @param string $sql the prepare string
  259. * @param array $params the params which should replace the ? in the sql query
  260. * @param int $limit the maximum number of rows
  261. * @param int $offset from which row we want to start
  262. * @return array all fetched entities
  263. * @since 7.0.0
  264. */
  265. protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
  266. $stmt = $this->execute($sql, $params, $limit, $offset);
  267. $entities = [];
  268. while($row = $stmt->fetch()){
  269. $entities[] = $this->mapRowToEntity($row);
  270. }
  271. $stmt->closeCursor();
  272. return $entities;
  273. }
  274. /**
  275. * Returns an db result and throws exceptions when there are more or less
  276. * results
  277. * @param string $sql the sql query
  278. * @param array $params the parameters of the sql query
  279. * @param int $limit the maximum number of rows
  280. * @param int $offset from which row we want to start
  281. * @throws DoesNotExistException if the item does not exist
  282. * @throws MultipleObjectsReturnedException if more than one item exist
  283. * @return Entity the entity
  284. * @since 7.0.0
  285. */
  286. protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
  287. return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
  288. }
  289. }