PageRenderTime 59ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/laravel/database/connection.php

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