connection.php 7.99 KB
Newer Older
1 2 3
<?php namespace Laravel\Database;

use PDO, PDOStatement, Laravel\Config, Laravel\Event;
4

Taylor Otwell committed
5 6 7
class Connection {

	/**
Taylor Otwell committed
8
	 * The raw PDO connection instance.
9
	 *
Taylor Otwell committed
10
	 * @var PDO
11
	 */
Taylor Otwell committed
12
	public $pdo;
13 14

	/**
Taylor Otwell committed
15
	 * The connection configuration array.
Taylor Otwell committed
16
	 *
Taylor Otwell committed
17
	 * @var array
Taylor Otwell committed
18
	 */
19
	public $config;
Taylor Otwell committed
20 21

	/**
Taylor Otwell committed
22
	 * The query grammar instance for the connection.
23
	 *
Taylor Otwell committed
24
	 * @var Grammars\Grammar
25
	 */
Taylor Otwell committed
26
	protected $grammar;
27 28

	/**
29 30 31 32 33 34 35
	 * All of the queries that have been executed on all connections.
	 *
	 * @var array
	 */
	public static $queries = array();

	/**
36
	 * Create a new database connection instance.
Taylor Otwell committed
37
	 *
38 39
	 * @param  PDO    $pdo
	 * @param  array  $config
Taylor Otwell committed
40 41
	 * @return void
	 */
42
	public function __construct(PDO $pdo, $config)
Taylor Otwell committed
43 44
	{
		$this->pdo = $pdo;
45
		$this->config = $config;
Taylor Otwell committed
46
	}
Taylor Otwell committed
47 48

	/**
49 50
	 * Begin a fluent query against a table.
	 *
51 52 53 54 55 56 57 58
	 * <code>
	 *		// Start a fluent query against the "users" table
	 *		$query = DB::connection()->table('users');
	 *
	 *		// Start a fluent query against the "users" table and get all the users
	 *		$users = DB::connection()->table('users')->get();
	 * </code>
	 *
59 60 61 62 63 64 65 66 67 68 69
	 * @param  string  $table
	 * @return Query
	 */
	public function table($table)
	{
		return new Query($this, $this->grammar(), $table);
	}

	/**
	 * Create a new query grammar for the connection.
	 *
70
	 * @return Query\Grammars\Grammar
71 72 73 74 75
	 */
	protected function grammar()
	{
		if (isset($this->grammar)) return $this->grammar;

76 77 78 79 80 81
		if (isset(\Laravel\Database::$registrar[$this->driver()]))
		{
			\Laravel\Database::$registrar[$this->driver()]['query']();
		}

		switch ($this->driver())
82 83
		{
			case 'mysql':
84
				return $this->grammar = new Query\Grammars\MySQL($this);
85

Taylor Otwell committed
86 87 88
			case 'sqlite':
				return $this->grammar = new Query\Grammars\SQLite($this);

89
			case 'sqlsrv':
90
				return $this->grammar = new Query\Grammars\SQLServer($this);
91

92 93 94
			case 'pgsql':
				return $this->grammar = new Query\Grammars\Postgres($this);

95
			default:
96
				return $this->grammar = new Query\Grammars\Grammar($this);
97 98 99 100
		}
	}

	/**
101 102
	 * Execute a callback wrapped in a database transaction.
	 *
103
	 * @param  callback  $callback
104 105 106 107 108 109
	 * @return void
	 */
	public function transaction($callback)
	{
		$this->pdo->beginTransaction();

110
		// After beginning the database transaction, we will call the callback
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
		// so that it can do its database work. If an exception occurs we'll
		// rollback the transaction and re-throw back to the developer.
		try
		{
			call_user_func($callback);
		}
		catch (\Exception $e)
		{
			$this->pdo->rollBack();

			throw $e;
		}

		$this->pdo->commit();
	}

	/**
128
	 * Execute a SQL query against the connection and return a single column result.
Taylor Otwell committed
129
	 *
Taylor Otwell committed
130 131
	 * <code>
	 *		// Get the total number of rows on a table
132
	 *		$count = DB::connection()->only('select count(*) from users');
Taylor Otwell committed
133 134
	 *
	 *		// Get the sum of payment amounts from a table
135
	 *		$sum = DB::connection()->only('select sum(amount) from payments')
Taylor Otwell committed
136 137 138 139
	 * </code>
	 *
	 * @param  string  $sql
	 * @param  array   $bindings
140
	 * @return mixed
Taylor Otwell committed
141
	 */
142
	public function only($sql, $bindings = array())
Taylor Otwell committed
143
	{
144
		$results = (array) $this->first($sql, $bindings);
Taylor Otwell committed
145

146
		return reset($results);
Taylor Otwell committed
147 148 149 150 151
	}

	/**
	 * Execute a SQL query against the connection and return the first result.
	 *
Taylor Otwell committed
152 153 154 155 156 157 158 159
	 * <code>
	 *		// Execute a query against the database connection
	 *		$user = DB::connection()->first('select * from users');
	 *
	 *		// Execute a query with bound parameters
	 *		$user = DB::connection()->first('select * from users where id = ?', array($id));
	 * </code>
	 *
Taylor Otwell committed
160 161 162 163 164 165
	 * @param  string  $sql
	 * @param  array   $bindings
	 * @return object
	 */
	public function first($sql, $bindings = array())
	{
Taylor Otwell committed
166 167 168 169
		if (count($results = $this->query($sql, $bindings)) > 0)
		{
			return $results[0];
		}
Taylor Otwell committed
170 171 172
	}

	/**
173
	 * Execute a SQL query and return an array of StdClass objects.
Taylor Otwell committed
174
	 *
175 176 177 178 179 180
	 * @param  string  $sql
	 * @param  array   $bindings
	 * @return array
	 */
	public function query($sql, $bindings = array())
	{
181 182
		$sql = trim($sql);

183 184
		list($statement, $result) = $this->execute($sql, $bindings);

185 186
		// The result we return depends on the type of query executed against the
		// database. On SELECT clauses, we will return the result set, for update
Taylor Otwell committed
187
		// and deletes we will return the affected row count.
188 189
		if (stripos($sql, 'select') === 0)
		{
190
			return $this->fetch($statement, Config::get('database.fetch'));
191 192 193 194 195
		}
		elseif (stripos($sql, 'update') === 0 or stripos($sql, 'delete') === 0)
		{
			return $statement->rowCount();
		}
196
		// For insert statements that use the "returning" clause, which is allowed
SonicHedgehog committed
197
		// by database systems such as Postgres, we need to actually return the
198 199 200 201 202
		// real query result so the consumer can get the ID.
		elseif (stripos($sql, 'insert') === 0 and stripos($sql, 'returning') !== false)
		{
			return $this->fetch($statement, Config::get('database.fetch'));
		}
203 204 205 206
		else
		{
			return $result;
		}
207 208 209 210 211 212
	}

	/**
	 * Execute a SQL query against the connection.
	 *
	 * The PDO statement and boolean result will be return in an array.
Taylor Otwell committed
213
	 *
Taylor Otwell committed
214 215
	 * @param  string  $sql
	 * @param  array   $bindings
216
	 * @return array
Taylor Otwell committed
217
	 */
218
	protected function execute($sql, $bindings = array())
Taylor Otwell committed
219
	{
Taylor Otwell committed
220 221
		$bindings = (array) $bindings;

222 223
		// Since expressions are injected into the query as strings, we need to
		// remove them from the array of bindings. After we have removed them,
Taylor Otwell committed
224 225
		// we'll reset the array so there are not gaps within the keys.
		$bindings = array_filter($bindings, function($binding)
226
		{
227
			return ! $binding instanceof Expression;
Taylor Otwell committed
228 229 230
		});

		$bindings = array_values($bindings);
231

232
		$sql = $this->grammar()->shortcut($sql, $bindings);
233

234 235 236 237 238 239 240 241 242 243 244 245 246
		// Next we need to translate all DateTime bindings to their date-time
		// strings that are compatible with the database. Each grammar may
		// define it's own date-time format according to its needs.
		$datetime = $this->grammar()->datetime;

		for ($i = 0; $i < count($bindings); $i++)
		{
			if ($bindings[$i] instanceof \DateTime)
			{
				$bindings[$i] = $bindings[$i]->format($datetime);
			}
		}

247 248 249 250 251 252
		// Each database operation is wrapped in a try / catch so we can wrap
		// any database exceptions in our custom exception class, which will
		// set the message to include the SQL and query bindings.
		try
		{
			$statement = $this->pdo->prepare($sql);
253

254
			$start = microtime(true);
255

256 257 258 259 260 261 262 263
			$result = $statement->execute($bindings);
		}
		// If an exception occurs, we'll pass it into our custom exception
		// and set the message to include the SQL and query bindings so
		// debugging is much easier on the developer.
		catch (\Exception $exception)
		{
			$exception = new Exception($sql, $bindings, $exception);
264

265 266
			throw $exception;
		}
267 268 269

		// Once we have execute the query, we log the SQL, bindings, and
		// execution time in a static array that is accessed by all of
270
		// the connections actively being used by the application.
271 272
		if (Config::get('database.profile'))
		{
273
			$this->log($sql, $bindings, $start);
274
		}
275 276

		return array($statement, $result);
Taylor Otwell committed
277
	}
Taylor Otwell committed
278

Taylor Otwell committed
279
	/**
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	 * Fetch all of the rows for a given statement.
	 *
	 * @param  PDOStatement  $statement
	 * @param  int           $style
	 * @return array
	 */
	protected function fetch($statement, $style)
	{
		// If the fetch style is "class", we'll hydrate an array of PHP
		// stdClass objects as generic containers for the query rows,
		// otherwise we'll just use the fetch styel value.
		if ($style === PDO::FETCH_CLASS)
		{
			return $statement->fetchAll(PDO::FETCH_CLASS, 'stdClass');
		}
		else
		{
			return $statement->fetchAll($style);
		}
	}

	/**
302 303 304 305
	 * Log the query and fire the core query event.
	 *
	 * @param  string  $sql
	 * @param  array   $bindings
306
	 * @param  int     $start
307 308
	 * @return void
	 */
309
	protected function log($sql, $bindings, $start)
310
	{
311 312
		$time = number_format((microtime(true) - $start) * 1000, 2);

313
		Event::fire('laravel.query', array($sql, $bindings, $time));
314

Taylor Otwell committed
315
		static::$queries[] = compact('sql', 'bindings', 'time');
316 317 318
	}

	/**
Taylor Otwell committed
319 320 321 322 323 324
	 * Get the driver name for the database connection.
	 *
	 * @return string
	 */
	public function driver()
	{
325
		return $this->config['driver'];
Taylor Otwell committed
326 327
	}

328 329 330 331 332 333 334 335
	/**
	 * Magic Method for dynamically beginning queries on database tables.
	 */
	public function __call($method, $parameters)
	{
		return $this->table($method);
	}

336
}