connection.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 callback wrapped in a database transaction.
  77. *
  78. * @param Closure $callback
  79. * @return void
  80. */
  81. public function transaction($callback)
  82. {
  83. $this->pdo->beginTransaction();
  84. // After beginning the database transaction, we will call the Closure
  85. // so that it can do its database work. If an exception occurs we'll
  86. // rollback the transaction and re-throw back to the developer.
  87. try
  88. {
  89. call_user_func($callback);
  90. }
  91. catch (\Exception $e)
  92. {
  93. $this->pdo->rollBack();
  94. throw $e;
  95. }
  96. $this->pdo->commit();
  97. }
  98. /**
  99. * Execute a SQL query against the connection and return a single column result.
  100. *
  101. * <code>
  102. * // Get the total number of rows on a table
  103. * $count = DB::connection()->only('select count(*) from users');
  104. *
  105. * // Get the sum of payment amounts from a table
  106. * $sum = DB::connection()->only('select sum(amount) from payments')
  107. * </code>
  108. *
  109. * @param string $sql
  110. * @param array $bindings
  111. * @return mixed
  112. */
  113. public function only($sql, $bindings = array())
  114. {
  115. $results = (array) $this->first($sql, $bindings);
  116. return reset($results);
  117. }
  118. /**
  119. * Execute a SQL query against the connection and return the first result.
  120. *
  121. * <code>
  122. * // Execute a query against the database connection
  123. * $user = DB::connection()->first('select * from users');
  124. *
  125. * // Execute a query with bound parameters
  126. * $user = DB::connection()->first('select * from users where id = ?', array($id));
  127. * </code>
  128. *
  129. * @param string $sql
  130. * @param array $bindings
  131. * @return object
  132. */
  133. public function first($sql, $bindings = array())
  134. {
  135. if (count($results = $this->query($sql, $bindings)) > 0)
  136. {
  137. return $results[0];
  138. }
  139. }
  140. /**
  141. * Execute a SQL query and return an array of StdClass objects.
  142. *
  143. * @param string $sql
  144. * @param array $bindings
  145. * @return array
  146. */
  147. public function query($sql, $bindings = array())
  148. {
  149. list($statement, $result) = $this->execute($sql, $bindings);
  150. // The result we return depends on the type of query executed against the
  151. // database. On SELECT clauses, we will return the result set, for update
  152. // and deletes we will return the affected row count.
  153. if (stripos($sql, 'select') === 0)
  154. {
  155. return $this->fetch($statement, Config::get('database.fetch'));
  156. }
  157. elseif (stripos($sql, 'update') === 0 or stripos($sql, 'delete') === 0)
  158. {
  159. return $statement->rowCount();
  160. }
  161. else
  162. {
  163. return $result;
  164. }
  165. }
  166. /**
  167. * Execute a SQL query against the connection.
  168. *
  169. * The PDO statement and boolean result will be return in an array.
  170. *
  171. * @param string $sql
  172. * @param array $bindings
  173. * @return array
  174. */
  175. protected function execute($sql, $bindings = array())
  176. {
  177. $bindings = (array) $bindings;
  178. // Since expressions are injected into the query as strings, we need to
  179. // remove them from the array of bindings. After we have removed them,
  180. // we'll reset the array so there are not gaps within the keys.
  181. $bindings = array_filter($bindings, function($binding)
  182. {
  183. return ! $binding instanceof Expression;
  184. });
  185. $bindings = array_values($bindings);
  186. $sql = $this->grammar()->shortcut($sql, $bindings);
  187. // Next we need to translate all DateTime bindings to their date-time
  188. // strings that are compatible with the database. Each grammar may
  189. // define it's own date-time format according to its needs.
  190. $datetime = $this->grammar()->datetime;
  191. for ($i = 0; $i < count($bindings); $i++)
  192. {
  193. if ($bindings[$i] instanceof \DateTime)
  194. {
  195. $bindings[$i] = $bindings[$i]->format($datetime);
  196. }
  197. }
  198. // Each database operation is wrapped in a try / catch so we can wrap
  199. // any database exceptions in our custom exception class, which will
  200. // set the message to include the SQL and query bindings.
  201. try
  202. {
  203. $statement = $this->pdo->prepare($sql);
  204. $start = microtime(true);
  205. $result = $statement->execute($bindings);
  206. }
  207. // If an exception occurs, we'll pass it into our custom exception
  208. // and set the message to include the SQL and query bindings so
  209. // debugging is much easier on the developer.
  210. catch (\Exception $exception)
  211. {
  212. $exception = new Exception($sql, $bindings, $exception);
  213. throw $exception;
  214. }
  215. // Once we have execute the query, we log the SQL, bindings, and
  216. // execution time in a static array that is accessed by all of
  217. // the connections actively being used by the application.
  218. if (Config::get('database.profile'))
  219. {
  220. $this->log($sql, $bindings, $start);
  221. }
  222. return array($statement, $result);
  223. }
  224. /**
  225. * Fetch all of the rows for a given statement.
  226. *
  227. * @param PDOStatement $statement
  228. * @param int $style
  229. * @return array
  230. */
  231. protected function fetch($statement, $style)
  232. {
  233. // If the fetch style is "class", we'll hydrate an array of PHP
  234. // stdClass objects as generic containers for the query rows,
  235. // otherwise we'll just use the fetch styel value.
  236. if ($style === PDO::FETCH_CLASS)
  237. {
  238. return $statement->fetchAll(PDO::FETCH_CLASS, 'stdClass');
  239. }
  240. else
  241. {
  242. return $statement->fetchAll($style);
  243. }
  244. }
  245. /**
  246. * Log the query and fire the core query event.
  247. *
  248. * @param string $sql
  249. * @param array $bindings
  250. * @param int $start
  251. * @return void
  252. */
  253. protected function log($sql, $bindings, $start)
  254. {
  255. $time = number_format((microtime(true) - $start) * 1000, 2);
  256. Event::fire('laravel.query', array($sql, $bindings, $time));
  257. static::$queries[] = compact('sql', 'bindings', 'time');
  258. }
  259. /**
  260. * Get the driver name for the database connection.
  261. *
  262. * @return string
  263. */
  264. public function driver()
  265. {
  266. return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
  267. }
  268. /**
  269. * Magic Method for dynamically beginning queries on database tables.
  270. */
  271. public function __call($method, $parameters)
  272. {
  273. return $this->table($method);
  274. }
  275. }