Mapper.php 10 KB

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