1
0

Mapper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. /**
  29. * Simple parent class for inheriting your data access layer from. This class
  30. * may be subject to change in the future
  31. * @since 7.0.0
  32. * @deprecated 14.0.0 Move over to QBMapper
  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. * @deprecated 14.0.0 Move over to QBMapper
  45. */
  46. public function __construct(IDBConnection $db, $tableName, $entityClass=null){
  47. $this->db = $db;
  48. $this->tableName = '*PREFIX*' . $tableName;
  49. // if not given set the entity name to the class without the mapper part
  50. // cache it here for later use since reflection is slow
  51. if($entityClass === null) {
  52. $this->entityClass = str_replace('Mapper', '', get_class($this));
  53. } else {
  54. $this->entityClass = $entityClass;
  55. }
  56. }
  57. /**
  58. * @return string the table name
  59. * @since 7.0.0
  60. * @deprecated 14.0.0 Move over to QBMapper
  61. */
  62. public function getTableName(){
  63. return $this->tableName;
  64. }
  65. /**
  66. * Deletes an entity from the table
  67. * @param Entity $entity the entity that should be deleted
  68. * @return Entity the deleted entity
  69. * @since 7.0.0 - return value added in 8.1.0
  70. * @deprecated 14.0.0 Move over to QBMapper
  71. */
  72. public function delete(Entity $entity){
  73. $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
  74. $stmt = $this->execute($sql, [$entity->getId()]);
  75. $stmt->closeCursor();
  76. return $entity;
  77. }
  78. /**
  79. * Creates a new entry in the db from an entity
  80. * @param Entity $entity the entity that should be created
  81. * @return Entity the saved entity with the set id
  82. * @since 7.0.0
  83. * @deprecated 14.0.0 Move over to QBMapper
  84. */
  85. public function insert(Entity $entity){
  86. // get updated fields to save, fields have to be set using a setter to
  87. // be saved
  88. $properties = $entity->getUpdatedFields();
  89. $values = '';
  90. $columns = '';
  91. $params = [];
  92. // build the fields
  93. $i = 0;
  94. foreach($properties as $property => $updated) {
  95. $column = $entity->propertyToColumn($property);
  96. $getter = 'get' . ucfirst($property);
  97. $columns .= '`' . $column . '`';
  98. $values .= '?';
  99. // only append colon if there are more entries
  100. if($i < count($properties)-1){
  101. $columns .= ',';
  102. $values .= ',';
  103. }
  104. $params[] = $entity->$getter();
  105. $i++;
  106. }
  107. $sql = 'INSERT INTO `' . $this->tableName . '`(' .
  108. $columns . ') VALUES(' . $values . ')';
  109. $stmt = $this->execute($sql, $params);
  110. $entity->setId((int) $this->db->lastInsertId($this->tableName));
  111. $stmt->closeCursor();
  112. return $entity;
  113. }
  114. /**
  115. * Updates an entry in the db from an entity
  116. * @throws \InvalidArgumentException if entity has no id
  117. * @param Entity $entity the entity that should be created
  118. * @return Entity the saved entity with the set id
  119. * @since 7.0.0 - return value was added in 8.0.0
  120. * @deprecated 14.0.0 Move over to QBMapper
  121. */
  122. public function update(Entity $entity){
  123. // if entity wasn't changed it makes no sense to run a db query
  124. $properties = $entity->getUpdatedFields();
  125. if(count($properties) === 0) {
  126. return $entity;
  127. }
  128. // entity needs an id
  129. $id = $entity->getId();
  130. if($id === null){
  131. throw new \InvalidArgumentException(
  132. 'Entity which should be updated has no id');
  133. }
  134. // get updated fields to save, fields have to be set using a setter to
  135. // be saved
  136. // do not update the id field
  137. unset($properties['id']);
  138. $columns = '';
  139. $params = [];
  140. // build the fields
  141. $i = 0;
  142. foreach($properties as $property => $updated) {
  143. $column = $entity->propertyToColumn($property);
  144. $getter = 'get' . ucfirst($property);
  145. $columns .= '`' . $column . '` = ?';
  146. // only append colon if there are more entries
  147. if($i < count($properties)-1){
  148. $columns .= ',';
  149. }
  150. $params[] = $entity->$getter();
  151. $i++;
  152. }
  153. $sql = 'UPDATE `' . $this->tableName . '` SET ' .
  154. $columns . ' WHERE `id` = ?';
  155. $params[] = $id;
  156. $stmt = $this->execute($sql, $params);
  157. $stmt->closeCursor();
  158. return $entity;
  159. }
  160. /**
  161. * Checks if an array is associative
  162. * @param array $array
  163. * @return bool true if associative
  164. * @since 8.1.0
  165. * @deprecated 14.0.0 Move over to QBMapper
  166. */
  167. private function isAssocArray(array $array) {
  168. return array_values($array) !== $array;
  169. }
  170. /**
  171. * Returns the correct PDO constant based on the value type
  172. * @param $value
  173. * @return int PDO constant
  174. * @since 8.1.0
  175. * @deprecated 14.0.0 Move over to QBMapper
  176. */
  177. private function getPDOType($value) {
  178. switch (gettype($value)) {
  179. case 'integer':
  180. return \PDO::PARAM_INT;
  181. case 'boolean':
  182. return \PDO::PARAM_BOOL;
  183. default:
  184. return \PDO::PARAM_STR;
  185. }
  186. }
  187. /**
  188. * Runs an sql query
  189. * @param string $sql the prepare string
  190. * @param array $params the params which should replace the ? in the sql query
  191. * @param int $limit the maximum number of rows
  192. * @param int $offset from which row we want to start
  193. * @return \PDOStatement the database query result
  194. * @since 7.0.0
  195. * @deprecated 14.0.0 Move over to QBMapper
  196. */
  197. protected function execute($sql, array $params=[], $limit=null, $offset=null){
  198. $query = $this->db->prepare($sql, $limit, $offset);
  199. if ($this->isAssocArray($params)) {
  200. foreach ($params as $key => $param) {
  201. $pdoConstant = $this->getPDOType($param);
  202. $query->bindValue($key, $param, $pdoConstant);
  203. }
  204. } else {
  205. $index = 1; // bindParam is 1 indexed
  206. foreach ($params as $param) {
  207. $pdoConstant = $this->getPDOType($param);
  208. $query->bindValue($index, $param, $pdoConstant);
  209. $index++;
  210. }
  211. }
  212. $query->execute();
  213. return $query;
  214. }
  215. /**
  216. * Returns an db result and throws exceptions when there are more or less
  217. * results
  218. * @see findEntity
  219. * @param string $sql the sql query
  220. * @param array $params the parameters of the sql query
  221. * @param int $limit the maximum number of rows
  222. * @param int $offset from which row we want to start
  223. * @throws DoesNotExistException if the item does not exist
  224. * @throws MultipleObjectsReturnedException if more than one item exist
  225. * @return array the result as row
  226. * @since 7.0.0
  227. * @deprecated 14.0.0 Move over to QBMapper
  228. */
  229. protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
  230. $stmt = $this->execute($sql, $params, $limit, $offset);
  231. $row = $stmt->fetch();
  232. if($row === false || $row === null){
  233. $stmt->closeCursor();
  234. $msg = $this->buildDebugMessage(
  235. 'Did expect one result but found none when executing', $sql, $params, $limit, $offset
  236. );
  237. throw new DoesNotExistException($msg);
  238. }
  239. $row2 = $stmt->fetch();
  240. $stmt->closeCursor();
  241. //MDB2 returns null, PDO and doctrine false when no row is available
  242. if( ! ($row2 === false || $row2 === null )) {
  243. $msg = $this->buildDebugMessage(
  244. 'Did not expect more than one result when executing', $sql, $params, $limit, $offset
  245. );
  246. throw new MultipleObjectsReturnedException($msg);
  247. } else {
  248. return $row;
  249. }
  250. }
  251. /**
  252. * Builds an error message by prepending the $msg to an error message which
  253. * has the parameters
  254. * @see findEntity
  255. * @param string $sql the sql query
  256. * @param array $params the parameters of the sql query
  257. * @param int $limit the maximum number of rows
  258. * @param int $offset from which row we want to start
  259. * @return string formatted error message string
  260. * @since 9.1.0
  261. * @deprecated 14.0.0 Move over to QBMapper
  262. */
  263. private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
  264. return $msg .
  265. ': query "' . $sql . '"; ' .
  266. 'parameters ' . print_r($params, true) . '; ' .
  267. 'limit "' . $limit . '"; '.
  268. 'offset "' . $offset . '"';
  269. }
  270. /**
  271. * Creates an entity from a row. Automatically determines the entity class
  272. * from the current mapper name (MyEntityMapper -> MyEntity)
  273. * @param array $row the row which should be converted to an entity
  274. * @return Entity the entity
  275. * @since 7.0.0
  276. * @deprecated 14.0.0 Move over to QBMapper
  277. */
  278. protected function mapRowToEntity($row) {
  279. return call_user_func($this->entityClass .'::fromRow', $row);
  280. }
  281. /**
  282. * Runs a sql query and returns an array of entities
  283. * @param string $sql the prepare string
  284. * @param array $params the params which should replace the ? in the sql query
  285. * @param int $limit the maximum number of rows
  286. * @param int $offset from which row we want to start
  287. * @return array all fetched entities
  288. * @since 7.0.0
  289. * @deprecated 14.0.0 Move over to QBMapper
  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. * @deprecated 14.0.0 Move over to QBMapper
  312. */
  313. protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
  314. return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
  315. }
  316. }