connection.php 7.6 KB

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