Mapper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  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, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OCP\AppFramework\Db;
  28. use OCP\IDBConnection;
  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. * @deprecated 14.0.0 Move over to QBMapper
  34. */
  35. abstract class Mapper {
  36. protected $tableName;
  37. protected $entityClass;
  38. protected $db;
  39. /**
  40. * @param IDBConnection $db Instance of the Db abstraction layer
  41. * @param string $tableName the name of the table. set this to allow entity
  42. * @param string $entityClass the name of the entity that the sql should be
  43. * mapped to queries without using sql
  44. * @since 7.0.0
  45. * @deprecated 14.0.0 Move over to QBMapper
  46. */
  47. public function __construct(IDBConnection $db, $tableName, $entityClass=null){
  48. $this->db = $db;
  49. $this->tableName = '*PREFIX*' . $tableName;
  50. // if not given set the entity name to the class without the mapper part
  51. // cache it here for later use since reflection is slow
  52. if($entityClass === null) {
  53. $this->entityClass = str_replace('Mapper', '', get_class($this));
  54. } else {
  55. $this->entityClass = $entityClass;
  56. }
  57. }
  58. /**
  59. * @return string the table name
  60. * @since 7.0.0
  61. * @deprecated 14.0.0 Move over to QBMapper
  62. */
  63. public function getTableName(){
  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 7.0.0 - return value added in 8.1.0
  71. * @deprecated 14.0.0 Move over to QBMapper
  72. */
  73. public function delete(Entity $entity){
  74. $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
  75. $stmt = $this->execute($sql, [$entity->getId()]);
  76. $stmt->closeCursor();
  77. return $entity;
  78. }
  79. /**
  80. * Creates a new entry in the db from an entity
  81. * @param Entity $entity the entity that should be created
  82. * @return Entity the saved entity with the set id
  83. * @since 7.0.0
  84. * @deprecated 14.0.0 Move over to QBMapper
  85. */
  86. public function insert(Entity $entity){
  87. // get updated fields to save, fields have to be set using a setter to
  88. // be saved
  89. $properties = $entity->getUpdatedFields();
  90. $values = '';
  91. $columns = '';
  92. $params = [];
  93. // build the fields
  94. $i = 0;
  95. foreach($properties as $property => $updated) {
  96. $column = $entity->propertyToColumn($property);
  97. $getter = 'get' . ucfirst($property);
  98. $columns .= '`' . $column . '`';
  99. $values .= '?';
  100. // only append colon if there are more entries
  101. if($i < count($properties)-1){
  102. $columns .= ',';
  103. $values .= ',';
  104. }
  105. $params[] = $entity->$getter();
  106. $i++;
  107. }
  108. $sql = 'INSERT INTO `' . $this->tableName . '`(' .
  109. $columns . ') VALUES(' . $values . ')';
  110. $stmt = $this->execute($sql, $params);
  111. $entity->setId((int) $this->db->lastInsertId($this->tableName));
  112. $stmt->closeCursor();
  113. return $entity;
  114. }
  115. /**
  116. * Updates an entry in the db from an entity
  117. * @throws \InvalidArgumentException if entity has no id
  118. * @param Entity $entity the entity that should be created
  119. * @return Entity the saved entity with the set id
  120. * @since 7.0.0 - return value was added in 8.0.0
  121. * @deprecated 14.0.0 Move over to QBMapper
  122. */
  123. public function update(Entity $entity){
  124. // if entity wasn't changed it makes no sense to run a db query
  125. $properties = $entity->getUpdatedFields();
  126. if(count($properties) === 0) {
  127. return $entity;
  128. }
  129. // entity needs an id
  130. $id = $entity->getId();
  131. if($id === null){
  132. throw new \InvalidArgumentException(
  133. 'Entity which should be updated has no id');
  134. }
  135. // get updated fields to save, fields have to be set using a setter to
  136. // be saved
  137. // do not update the id field
  138. unset($properties['id']);
  139. $columns = '';
  140. $params = [];
  141. // build the fields
  142. $i = 0;
  143. foreach($properties as $property => $updated) {
  144. $column = $entity->propertyToColumn($property);
  145. $getter = 'get' . ucfirst($property);
  146. $columns .= '`' . $column . '` = ?';
  147. // only append colon if there are more entries
  148. if($i < count($properties)-1){
  149. $columns .= ',';
  150. }
  151. $params[] = $entity->$getter();
  152. $i++;
  153. }
  154. $sql = 'UPDATE `' . $this->tableName . '` SET ' .
  155. $columns . ' WHERE `id` = ?';
  156. $params[] = $id;
  157. $stmt = $this->execute($sql, $params);
  158. $stmt->closeCursor();
  159. return $entity;
  160. }
  161. /**
  162. * Checks if an array is associative
  163. * @param array $array
  164. * @return bool true if associative
  165. * @since 8.1.0
  166. * @deprecated 14.0.0 Move over to QBMapper
  167. */
  168. private function isAssocArray(array $array) {
  169. return array_values($array) !== $array;
  170. }
  171. /**
  172. * Returns the correct PDO constant based on the value type
  173. * @param $value
  174. * @return int PDO constant
  175. * @since 8.1.0
  176. * @deprecated 14.0.0 Move over to QBMapper
  177. */
  178. private function getPDOType($value) {
  179. switch (gettype($value)) {
  180. case 'integer':
  181. return \PDO::PARAM_INT;
  182. case 'boolean':
  183. return \PDO::PARAM_BOOL;
  184. default:
  185. return \PDO::PARAM_STR;
  186. }
  187. }
  188. /**
  189. * Runs an sql query
  190. * @param string $sql the prepare string
  191. * @param array $params the params which should replace the ? in the sql query
  192. * @param int $limit the maximum number of rows
  193. * @param int $offset from which row we want to start
  194. * @return \PDOStatement the database query result
  195. * @since 7.0.0
  196. * @deprecated 14.0.0 Move over to QBMapper
  197. */
  198. protected function execute($sql, array $params=[], $limit=null, $offset=null){
  199. $query = $this->db->prepare($sql, $limit, $offset);
  200. if ($this->isAssocArray($params)) {
  201. foreach ($params as $key => $param) {
  202. $pdoConstant = $this->getPDOType($param);
  203. $query->bindValue($key, $param, $pdoConstant);
  204. }
  205. } else {
  206. $index = 1; // bindParam is 1 indexed
  207. foreach ($params as $param) {
  208. $pdoConstant = $this->getPDOType($param);
  209. $query->bindValue($index, $param, $pdoConstant);
  210. $index++;
  211. }
  212. }
  213. $query->execute();
  214. return $query;
  215. }
  216. /**
  217. * Returns an db result and throws exceptions when there are more or less
  218. * results
  219. * @see findEntity
  220. * @param string $sql the sql query
  221. * @param array $params the parameters of the sql query
  222. * @param int $limit the maximum number of rows
  223. * @param int $offset from which row we want to start
  224. * @throws DoesNotExistException if the item does not exist
  225. * @throws MultipleObjectsReturnedException if more than one item exist
  226. * @return array the result as row
  227. * @since 7.0.0
  228. * @deprecated 14.0.0 Move over to QBMapper
  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. $msg = $this->buildDebugMessage(
  236. 'Did expect one result but found none when executing', $sql, $params, $limit, $offset
  237. );
  238. throw new DoesNotExistException($msg);
  239. }
  240. $row2 = $stmt->fetch();
  241. $stmt->closeCursor();
  242. //MDB2 returns null, PDO and doctrine false when no row is available
  243. if( ! ($row2 === false || $row2 === null )) {
  244. $msg = $this->buildDebugMessage(
  245. 'Did not expect more than one result when executing', $sql, $params, $limit, $offset
  246. );
  247. throw new MultipleObjectsReturnedException($msg);
  248. } else {
  249. return $row;
  250. }
  251. }
  252. /**
  253. * Builds an error message by prepending the $msg to an error message which
  254. * has the parameters
  255. * @see findEntity
  256. * @param string $sql the sql query
  257. * @param array $params the parameters of the sql query
  258. * @param int $limit the maximum number of rows
  259. * @param int $offset from which row we want to start
  260. * @return string formatted error message string
  261. * @since 9.1.0
  262. * @deprecated 14.0.0 Move over to QBMapper
  263. */
  264. private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
  265. return $msg .
  266. ': query "' . $sql . '"; ' .
  267. 'parameters ' . print_r($params, true) . '; ' .
  268. 'limit "' . $limit . '"; '.
  269. 'offset "' . $offset . '"';
  270. }
  271. /**
  272. * Creates an entity from a row. Automatically determines the entity class
  273. * from the current mapper name (MyEntityMapper -> MyEntity)
  274. * @param array $row the row which should be converted to an entity
  275. * @return Entity the entity
  276. * @since 7.0.0
  277. * @deprecated 14.0.0 Move over to QBMapper
  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. * @deprecated 14.0.0 Move over to QBMapper
  291. */
  292. protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
  293. $stmt = $this->execute($sql, $params, $limit, $offset);
  294. $entities = [];
  295. while($row = $stmt->fetch()){
  296. $entities[] = $this->mapRowToEntity($row);
  297. }
  298. $stmt->closeCursor();
  299. return $entities;
  300. }
  301. /**
  302. * Returns an db result and throws exceptions when there are more or less
  303. * results
  304. * @param string $sql the sql query
  305. * @param array $params the parameters of the sql query
  306. * @param int $limit the maximum number of rows
  307. * @param int $offset from which row we want to start
  308. * @throws DoesNotExistException if the item does not exist
  309. * @throws MultipleObjectsReturnedException if more than one item exist
  310. * @return Entity the entity
  311. * @since 7.0.0
  312. * @deprecated 14.0.0 Move over to QBMapper
  313. */
  314. protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
  315. return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
  316. }
  317. }