connection.php 7.5 KB

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