PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Persistence/MysqlAdapter.php

https://github.com/andho/simdal
PHP | 301 lines | 211 code | 69 blank | 21 comment | 26 complexity | 1e18d3e4e9b6036a5f833daa49173a97 MD5 | raw file
  1. <?php
  2. /**
  3. * SimDAL - Simple Domain Abstraction Library.
  4. * This library will help you to separate your domain logic from
  5. * your persistence logic and makes the persistence of your domain
  6. * objects transparent.
  7. *
  8. * Copyright (C) 2011 Andho
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (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 General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. class SimDAL_Persistence_MysqlAdapter extends SimDAL_Persistence_AdapterAbstract {
  24. private $_host;
  25. private $_username;
  26. private $_password;
  27. private $_database;
  28. private $_conn;
  29. protected $_transaction = false;
  30. static protected $_verbose = false;
  31. static public function setVerbose($verbose = true) {
  32. self::$_verbose = $verbose;
  33. }
  34. public function __construct($mapper, array $conf) {
  35. if (!isset($db['host'])) {
  36. throw new Exception("Database configuation doesn't specify database host");
  37. }
  38. if (!isset($db['username'])) {
  39. throw new Exception("Database configuation doesn't specify database username");
  40. }
  41. if (!isset($db['password'])) {
  42. throw new Exception("Database configuation doesn't specify database password");
  43. }
  44. if (!isset($db['database'])) {
  45. throw new Exception("Database configuation doesn't specify database database");
  46. }
  47. parent::__construct($mapper, $conf);
  48. $this->_host = $conf['host'];
  49. $this->_username = $conf['username'];
  50. $this->_password = $conf['password'];
  51. $this->_database = $conf['database'];
  52. }
  53. public function __destruct() {
  54. if (is_resource($this->_conn)) {
  55. mysql_close($this->_conn);
  56. $this->_conn = null;
  57. }
  58. }
  59. protected function _connect() {
  60. if (!is_null($this->_conn)) {
  61. return true;
  62. }
  63. $this->_conn = mysql_pconnect($this->_host, $this->_username, $this->_password);
  64. mysql_select_db($this->_database);
  65. }
  66. public function _delete($table, $id) {
  67. $this->_connect();
  68. $sql = "DELETE FROM `$table` WHERE `id`=$id";
  69. mysql_query($sql, $this->_conn);
  70. return mysql_affected_rows($this->_conn);
  71. }
  72. protected function _processGetAllQuery($class) {
  73. $table = $this->_getMapper()->getTable($class);
  74. return "SELECT * FROM `$table`";
  75. }
  76. protected function _processFindByIdQuery($table, $column, $id) {
  77. return "SELECT * FROM ".$this->_quoteIdentifier($table)." WHERE `$column` = '$id'";
  78. }
  79. protected function _processFindByColumnQuery($table, $key, $value, $limit) {
  80. $sql = "SELECT * FROM `$table` WHERE `{$key}` = $value";
  81. if (is_numeric($limit) && $limit > 0) {
  82. $sql .= " LIMIT $limit";
  83. }
  84. return $sql;
  85. }
  86. protected function _processFindByQuery($table, $where, $limit) {
  87. $sql = "SELECT * FROM `$table` WHERE ".implode(" AND ", $where);
  88. if (is_numeric($limit) && $limit > 0) {
  89. $sql .= " LIMIT $limit";
  90. }
  91. return $sql;
  92. }
  93. protected function _processFindByEither($table, $where, $limit) {
  94. if (!is_null($limit)) {
  95. $limit = " LIMIT $limit";
  96. }
  97. $sql = "SELECT * FROM `$table` WHERE ".implode(" OR ", $where)."$limit";
  98. return $sql;
  99. }
  100. protected function _returnResultRowsAsArray($sql) {
  101. $this->_connect();
  102. $query = mysql_query($sql, $this->_conn) or error_log(mysql_error($this->_conn), 0);
  103. if ($query === false) {
  104. return false;
  105. }
  106. $rows = array();
  107. while ($row = mysql_fetch_assoc($query)) {
  108. $rows[] = $row;
  109. }
  110. mysql_free_result($query);
  111. return $rows;
  112. }
  113. protected function _returnResultRows($sql, $class) {
  114. $this->_connect();
  115. $query = mysql_query($sql, $this->_conn) or error_log(mysql_error($this->_conn), 0);
  116. if ($query === false) {
  117. return false;
  118. }
  119. $rows = array();
  120. while ($row = mysql_fetch_assoc($query)) {
  121. $rows[] = $row;
  122. }
  123. mysql_free_result($query);
  124. return $this->_returnEntities($rows, $class);
  125. }
  126. protected function _returnResultRow($sql, $class=null) {
  127. $this->_connect();
  128. if (!($query = mysql_query($sql, $this->_conn))) {
  129. error_log(mysql_error($this->_conn), 0);
  130. return false;
  131. }
  132. if (mysql_num_rows($query) <= 0) {
  133. return null;
  134. }
  135. $row = mysql_fetch_assoc($query);
  136. if (is_null($class)) {
  137. return $row;
  138. }
  139. mysql_free_result($query);
  140. return $this->_returnEntity($row, $class);
  141. }
  142. public function query($sql) {
  143. }
  144. public function lastInsertId() {
  145. return mysql_insert_id($this->_conn);
  146. }
  147. public function getAdapterError() {
  148. return mysql_error($this->_conn);
  149. }
  150. public function escape($value, $type=null) {
  151. $this->_connect();
  152. if ($type == 'binary') {
  153. $value = base64_encode($value);
  154. }
  155. return mysql_real_escape_string($value);
  156. }
  157. public function getError() {
  158. if (self::$_verbose) {
  159. return $this->getAdapterError();
  160. } else {
  161. return "There was an error saving to the database";
  162. }
  163. }
  164. protected function _whereRange($key, $values) {
  165. if (!is_array($values) && is_scalar($values)) {
  166. $values = array($values);
  167. }
  168. $where = "`{$key}` IN (".implode(",", $values).")";
  169. return $where;
  170. }
  171. protected function _processInsertQuery($class, $data) {
  172. $table = $this->_getMapper()->getTable($class);
  173. $sql = "INSERT INTO ".$this->_quoteIdentifier($table)." (`".implode('`,`',array_keys($data))."`) VALUES (".implode(',',$data).")";
  174. return $sql;
  175. }
  176. public function startTransaction() {
  177. return;
  178. }
  179. public function commitTransaction() {
  180. return;
  181. }
  182. public function rollbackTransaction() {
  183. return;
  184. }
  185. protected function _quoteIdentifier($column) {
  186. $parts = explode('.', $column);
  187. if (count($parts) > 0) {
  188. $column = implode('`.`', $parts);
  189. }
  190. return "`$column`";
  191. }
  192. public function execute($sql) {
  193. $this->_connect();
  194. $result = mysql_query($sql, $this->_conn);
  195. if ($result === false) {
  196. error_log(mysql_error($this->_conn));
  197. return false;
  198. }
  199. if ($result === true) {
  200. return mysql_affected_rows($this->_conn);
  201. }
  202. return $result;
  203. }
  204. protected function _queryToString(SimDAL_Query $query) {
  205. $sql = 'SELECT * FROM ' . $query->getFrom();
  206. foreach ($query->getJoins() as $join) {
  207. $sql .= $join->getJoinType() . ' ' . $join->getTable() . ' ON ';
  208. foreach ($join->getWheres() as $where) {
  209. $method = '_process' . $where->getProcessMethod();
  210. $sql = $this->$method($where);
  211. }
  212. }
  213. $wheres = array();
  214. foreach ($query->getWheres() as $where) {
  215. $method = '_process' . $where->getProcessMethod();
  216. $wheres[] = $this->$method($where);
  217. }
  218. if (count($wheres) > 0) {
  219. $sql .= ' WHERE ' . implode(' AND ', $wheres);
  220. }
  221. return $sql;
  222. }
  223. protected function _processWhereJoinDescendant($where) {
  224. return $where->getLeftValue()->getTable() . '.' . $where->getLeftValue()->getColumn() . '=' . $where->getRightValue()->getTable() . '.' . $where->getRightValue()->getColumn();
  225. }
  226. protected function _processWhereId(SimDAL_Query_Where_Id $where) {
  227. $primary_key_column = $where->getLeftValue();
  228. $output = $primary_key_column->getTable() . '.' . $primary_key_column->getColumn();
  229. $output .= ' = ' . $where->getRightValue();
  230. return $output;
  231. }
  232. }