connection.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php namespace Laravel\Database; use PDO, PDOStatement;
  2. class Connection {
  3. /**
  4. * The raw PDO connection instance.
  5. *
  6. * @var PDO
  7. */
  8. public $pdo;
  9. /**
  10. * All of the queries that have been executed on the connection.
  11. *
  12. * @var array
  13. */
  14. public $queries = array();
  15. /**
  16. * The connection configuration array.
  17. *
  18. * @var array
  19. */
  20. protected $config;
  21. /**
  22. * The query grammar instance for the connection.
  23. *
  24. * @var Grammars\Grammar
  25. */
  26. protected $grammar;
  27. /**
  28. * Create a new database connection instance.
  29. *
  30. * @param PDO $pdo
  31. * @param array $config
  32. * @return void
  33. */
  34. public function __construct(PDO $pdo, $config)
  35. {
  36. $this->pdo = $pdo;
  37. $this->config = $config;
  38. }
  39. /**
  40. * Begin a fluent query against a table.
  41. *
  42. * @param string $table
  43. * @return Query
  44. */
  45. public function table($table)
  46. {
  47. return new Query($this, $this->grammar(), $table);
  48. }
  49. /**
  50. * Create a new query grammar for the connection.
  51. *
  52. * Query grammars allow support for new database systems to be added quickly
  53. * and easily. Since the responsibility of the query generation is delegated
  54. * to the grammar classes, it is simple to override only the methods with
  55. * SQL syntax that differs from the default implementation.
  56. *
  57. * @return Grammars\Grammar
  58. */
  59. protected function grammar()
  60. {
  61. if (isset($this->grammar)) return $this->grammar;
  62. // We allow the developer to hard-code a grammar for the connection. This really
  63. // has no use yet; however, if database systems that can use multiple grammars
  64. // like ODBC are added in the future, this will be needed.
  65. switch (isset($this->config['grammar']) ? $this->config['grammar'] : $this->driver())
  66. {
  67. case 'mysql':
  68. return $this->grammar = new Grammars\MySQL;
  69. default:
  70. return $this->grammar = new Grammars\Grammar;
  71. }
  72. }
  73. /**
  74. * Execute a SQL query against the connection and return a single column result.
  75. *
  76. * <code>
  77. * // Get the total number of rows on a table
  78. * $count = DB::connection()->only('select count(*) from users');
  79. *
  80. * // Get the sum of payment amounts from a table
  81. * $sum = DB::connection()->only('select sum(amount) from payments')
  82. * </code>
  83. *
  84. * @param string $sql
  85. * @param array $bindings
  86. * @return mixed
  87. */
  88. public function only($sql, $bindings = array())
  89. {
  90. $result = (array) $this->first($sql, $bindings);
  91. return reset($result);
  92. }
  93. /**
  94. * Execute a SQL query against the connection and return the first result.
  95. *
  96. * <code>
  97. * // Execute a query against the database connection
  98. * $user = DB::connection()->first('select * from users');
  99. *
  100. * // Execute a query with bound parameters
  101. * $user = DB::connection()->first('select * from users where id = ?', array($id));
  102. * </code>
  103. *
  104. * @param string $sql
  105. * @param array $bindings
  106. * @return object
  107. */
  108. public function first($sql, $bindings = array())
  109. {
  110. if (count($results = $this->query($sql, $bindings)) > 0)
  111. {
  112. return $results[0];
  113. }
  114. }
  115. /**
  116. * Execute a SQL query against the connection.
  117. *
  118. * The method returns the following based on query type:
  119. *
  120. * SELECT -> Array of stdClasses
  121. * UPDATE -> Number of rows affected.
  122. * DELETE -> Number of Rows affected.
  123. * ELSE -> Boolean true / false depending on success.
  124. *
  125. * <code>
  126. * // Execute a query against the database connection
  127. * $users = DB::connection()->query('select * from users');
  128. *
  129. * // Execute a query with bound parameters
  130. * $user = DB::connection()->query('select * from users where id = ?', array($id));
  131. * </code>
  132. *
  133. * @param string $sql
  134. * @param array $bindings
  135. * @return mixed
  136. */
  137. public function query($sql, $bindings = array())
  138. {
  139. // Since expressions are injected into the query as raw strings, we need
  140. // to remove them from the array of bindings. They are not truly bound
  141. // to the PDO statement as named parameters.
  142. foreach ($bindings as $key => $value)
  143. {
  144. if ($value instanceof Expression) unset($bindings[$key]);
  145. }
  146. $sql = $this->transform($sql, $bindings);
  147. $this->queries[] = compact('sql', 'bindings');
  148. return $this->execute($this->pdo->prepare($sql), $bindings);
  149. }
  150. /**
  151. * Transform an SQL query into an executable query.
  152. *
  153. * Laravel provides a convenient short-cut when writing raw queries for
  154. * handling cumbersome "where in" statements. This method will transform
  155. * those segments into their full SQL counterparts.
  156. *
  157. * @param string $sql
  158. * @param array $bindings
  159. * @return string
  160. */
  161. protected function transform($sql, $bindings)
  162. {
  163. if (strpos($sql, '(...)') !== false)
  164. {
  165. for ($i = 0; $i < count($bindings); $i++)
  166. {
  167. // If the binding is an array, we can assume it is being used to fill
  168. // a "where in" condition, so we will replace the next place-holder
  169. // in the query with the correct number of parameters based on the
  170. // number of elements in this binding.
  171. if (is_array($bindings[$i]))
  172. {
  173. $parameters = implode(', ', array_fill(0, count($bindings[$i]), '?'));
  174. $sql = preg_replace('~\(\.\.\.\)~', "({$parameters})", $sql, 1);
  175. }
  176. }
  177. }
  178. return trim($sql);
  179. }
  180. /**
  181. * Execute a prepared PDO statement and return the appropriate results.
  182. *
  183. * @param PDOStatement $statement
  184. * @param array $results
  185. * @return mixed
  186. */
  187. protected function execute(PDOStatement $statement, $bindings)
  188. {
  189. $result = $statement->execute($bindings);
  190. $sql = strtoupper($statement->queryString);
  191. if (strpos($sql, 'SELECT') === 0)
  192. {
  193. return $statement->fetchAll(PDO::FETCH_CLASS, 'stdClass');
  194. }
  195. elseif (strpos($sql, 'UPDATE') === 0 or strpos($sql, 'DELETE') === 0)
  196. {
  197. return $statement->rowCount();
  198. }
  199. else
  200. {
  201. return $result;
  202. }
  203. }
  204. /**
  205. * Get the driver name for the database connection.
  206. *
  207. * @return string
  208. */
  209. public function driver()
  210. {
  211. return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
  212. }
  213. /**
  214. * Magic Method for dynamically beginning queries on database tables.
  215. */
  216. public function __call($method, $parameters)
  217. {
  218. return $this->table($method);
  219. }
  220. }