connection.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php namespace Laravel\Database; use PDO, PDOStatement, Laravel\Config, Laravel\Event;
  2. class Connection {
  3. /**
  4. * The raw PDO connection instance.
  5. *
  6. * @var PDO
  7. */
  8. public $pdo;
  9. /**
  10. * The connection configuration array.
  11. *
  12. * @var array
  13. */
  14. public $config;
  15. /**
  16. * The query grammar instance for the connection.
  17. *
  18. * @var Grammars\Grammar
  19. */
  20. protected $grammar;
  21. /**
  22. * All of the queries that have been executed on all connections.
  23. *
  24. * @var array
  25. */
  26. public static $queries = array();
  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. * <code>
  43. * // Start a fluent query against the "users" table
  44. * $query = DB::connection()->table('users');
  45. *
  46. * // Start a fluent query against the "users" table and get all the users
  47. * $users = DB::connection()->table('users')->get();
  48. * </code>
  49. *
  50. * @param string $table
  51. * @return Query
  52. */
  53. public function table($table)
  54. {
  55. return new Query($this, $this->grammar(), $table);
  56. }
  57. /**
  58. * Create a new query grammar for the connection.
  59. *
  60. * @return Query\Grammars\Grammar
  61. */
  62. protected function grammar()
  63. {
  64. if (isset($this->grammar)) return $this->grammar;
  65. switch (isset($this->config['grammar']) ? $this->config['grammar'] : $this->driver())
  66. {
  67. case 'mysql':
  68. return $this->grammar = new Query\Grammars\MySQL($this);
  69. case 'sqlsrv':
  70. return $this->grammar = new Query\Grammars\SQLServer($this);
  71. default:
  72. return $this->grammar = new Query\Grammars\Grammar($this);
  73. }
  74. }
  75. /**
  76. * Execute a SQL query against the connection and return a single column result.
  77. *
  78. * <code>
  79. * // Get the total number of rows on a table
  80. * $count = DB::connection()->only('select count(*) from users');
  81. *
  82. * // Get the sum of payment amounts from a table
  83. * $sum = DB::connection()->only('select sum(amount) from payments')
  84. * </code>
  85. *
  86. * @param string $sql
  87. * @param array $bindings
  88. * @return mixed
  89. */
  90. public function only($sql, $bindings = array())
  91. {
  92. $results = (array) $this->first($sql, $bindings);
  93. return reset($results);
  94. }
  95. /**
  96. * Execute a SQL query against the connection and return the first result.
  97. *
  98. * <code>
  99. * // Execute a query against the database connection
  100. * $user = DB::connection()->first('select * from users');
  101. *
  102. * // Execute a query with bound parameters
  103. * $user = DB::connection()->first('select * from users where id = ?', array($id));
  104. * </code>
  105. *
  106. * @param string $sql
  107. * @param array $bindings
  108. * @return object
  109. */
  110. public function first($sql, $bindings = array())
  111. {
  112. if (count($results = $this->query($sql, $bindings)) > 0)
  113. {
  114. return $results[0];
  115. }
  116. }
  117. /**
  118. * Execute a SQL query and return an array of StdClass objects.
  119. *
  120. * @param string $sql
  121. * @param array $bindings
  122. * @return array
  123. */
  124. public function query($sql, $bindings = array())
  125. {
  126. list($statement, $result) = $this->execute($sql, $bindings);
  127. // The result we return depends on the type of query executed against the
  128. // database. On SELECT clauses, we will return the result set, for update
  129. // and deletes we will return the affected row count.
  130. if (stripos($sql, 'select') === 0)
  131. {
  132. return $this->fetch($statement, Config::get('database.fetch'));
  133. }
  134. elseif (stripos($sql, 'update') === 0 or stripos($sql, 'delete') === 0)
  135. {
  136. return $statement->rowCount();
  137. }
  138. else
  139. {
  140. return $result;
  141. }
  142. }
  143. /**
  144. * Execute a SQL query against the connection.
  145. *
  146. * The PDO statement and boolean result will be return in an array.
  147. *
  148. * @param string $sql
  149. * @param array $bindings
  150. * @return array
  151. */
  152. protected function execute($sql, $bindings = array())
  153. {
  154. $bindings = (array) $bindings;
  155. // Since expressions are injected into the query as strings, we need to
  156. // remove them from the array of bindings. After we have removed them,
  157. // we'll reset the array so there aren't gaps in the keys.
  158. $bindings = array_values(array_filter($bindings, function($binding)
  159. {
  160. return ! $binding instanceof Expression;
  161. }));
  162. $sql = $this->grammar()->shortcut($sql, $bindings);
  163. // Each database operation is wrapped in a try / catch so we can wrap
  164. // any database exceptions in our custom exception class, which will
  165. // set the message to include the SQL and query bindings.
  166. try
  167. {
  168. $statement = $this->pdo->prepare($sql);
  169. $start = microtime(true);
  170. $result = $statement->execute($bindings);
  171. }
  172. // If an exception occurs, we'll pass it into our custom exception
  173. // and set the message to include the SQL and query bindings so
  174. // debugging is much easier on the developer.
  175. catch (\Exception $exception)
  176. {
  177. $exception = new Exception($sql, $bindings, $exception);
  178. throw $exception;
  179. }
  180. // Once we have execute the query, we log the SQL, bindings, and
  181. // execution time in a static array that is accessed by all of
  182. // the connections actively being used by the application.
  183. if (Config::get('database.profile'))
  184. {
  185. $this->log($sql, $bindings, $start);
  186. }
  187. return array($statement, $result);
  188. }
  189. /**
  190. * Fetch all of the rows for a given statement.
  191. *
  192. * @param PDOStatement $statement
  193. * @param int $style
  194. * @return array
  195. */
  196. protected function fetch($statement, $style)
  197. {
  198. // If the fetch style is "class", we'll hydrate an array of PHP
  199. // stdClass objects as generic containers for the query rows,
  200. // otherwise we'll just use the fetch styel value.
  201. if ($style === PDO::FETCH_CLASS)
  202. {
  203. return $statement->fetchAll(PDO::FETCH_CLASS, 'stdClass');
  204. }
  205. else
  206. {
  207. return $statement->fetchAll($style);
  208. }
  209. }
  210. /**
  211. * Log the query and fire the core query event.
  212. *
  213. * @param string $sql
  214. * @param array $bindings
  215. * @param int $start
  216. * @return void
  217. */
  218. protected function log($sql, $bindings, $start)
  219. {
  220. $time = number_format((microtime(true) - $start) * 1000, 2);
  221. Event::fire('laravel.query', array($sql, $bindings, $time));
  222. static::$queries[] = compact('sql', 'bindings', 'time');
  223. }
  224. /**
  225. * Get the driver name for the database connection.
  226. *
  227. * @return string
  228. */
  229. public function driver()
  230. {
  231. return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
  232. }
  233. /**
  234. * Magic Method for dynamically beginning queries on database tables.
  235. */
  236. public function __call($method, $parameters)
  237. {
  238. return $this->table($method);
  239. }
  240. }