refactoring for dependency injection and testability.

This commit is contained in:
Taylor Otwell
2011-08-25 22:53:05 -05:00
parent 0b86c94551
commit 1e7850d9ba
75 changed files with 1441 additions and 1461 deletions

View File

@@ -0,0 +1,170 @@
<?php namespace Laravel\Database;
class Connection {
/**
* The connection name.
*
* @var string
*/
public $name;
/**
* The connection configuration.
*
* @var array
*/
public $config;
/**
* The PDO connection.
*
* @var PDO
*/
public $pdo;
/**
* All of the queries that have been executed on the connection.
*
* @var array
*/
public $queries = array();
/**
* The database connector instance.
*
* @var Connector
*/
private $connector;
/**
* Create a new Connection instance.
*
* @param string $name
* @param array $config
* @param Connector $connector
* @return void
*/
public function __construct($name, $config, Connector $connector)
{
$this->name = $name;
$this->config = $config;
$this->connector = $connector;
}
/**
* Establish the PDO connection for the connection instance.
*
* @return void
*/
public function connect()
{
$this->pdo = $this->connector->connect($this->config);
}
/**
* Determine if a PDO connection has been established for the connection.
*
* @return bool
*/
public function connected()
{
return ! is_null($this->pdo);
}
/**
* Execute a SQL query against the connection and return a scalar result.
*
* @param string $sql
* @param array $bindings
* @return mixed
*/
public function scalar($sql, $bindings = array())
{
$result = (array) $this->first($sql, $bindings);
return (strpos(strtolower($sql), 'select count') === 0) ? (int) reset($result) : (float) reset($result);
}
/**
* Execute a SQL query against the connection and return the first result.
*
* @param string $sql
* @param array $bindings
* @return object
*/
public function first($sql, $bindings = array())
{
return (count($results = $this->query($sql, $bindings)) > 0) ? $results[0] : null;
}
/**
* Execute a SQL query against the connection.
*
* The method returns the following based on query type:
*
* SELECT -> Array of stdClasses
* UPDATE -> Number of rows affected.
* DELETE -> Number of Rows affected.
* ELSE -> Boolean true / false depending on success.
*
* @param string $sql
* @param array $bindings
* @return mixed
*/
public function query($sql, $bindings = array())
{
if ( ! $this->connected()) $this->connect();
$this->queries[] = compact('sql', 'bindings');
return $this->execute($this->pdo->prepare(trim($sql)), $bindings);
}
/**
* Execute a prepared PDO statement and return the appropriate results.
*
* @param PDOStatement $statement
* @param array $results
* @return mixed
*/
private function execute(\PDOStatement $statement, $bindings)
{
$result = $statement->execute($bindings);
if (strpos(strtoupper($statement->queryString), 'SELECT') === 0)
{
return $statement->fetchAll(\PDO::FETCH_CLASS, 'stdClass');
}
elseif (strpos(strtoupper($statement->queryString), 'INSERT') === 0)
{
return $result;
}
return $statement->rowCount();
}
/**
* Begin a fluent query against a table.
*
* @param string $table
* @return Query
*/
public function table($table)
{
return Query\Factory::make($table, $this, Query\Compiler\Factory::make($this));
}
/**
* Get the driver name for the database connection.
*
* @return string
*/
public function driver()
{
if ( ! $this->connected()) $this->connect();
return $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
}

View File

@@ -0,0 +1,28 @@
<?php namespace Laravel\Database;
use PDO;
abstract class Connector {
/**
* The PDO connection options.
*
* @var array
*/
public $options = array(
PDO::ATTR_CASE => PDO::CASE_LOWER,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
);
/**
* Establish a PDO database connection.
*
* @param array $config
* @return PDO
*/
abstract public function connect($config);
}

View File

@@ -0,0 +1,18 @@
<?php namespace Laravel\DB\Connector;
use Laravel\DB\Connector;
class Callback extends Connector {
/**
* Establish a PDO database connection.
*
* @param array $config
* @return PDO
*/
public function connect($config)
{
return call_user_func($config['connector']);
}
}

View File

@@ -0,0 +1,30 @@
<?php namespace Laravel\DB\Connector;
class Factory {
/**
* Create a new database connector instance for a given driver.
*
* @param array $config
* @return Connector
*/
public static function make($config)
{
if (isset($config['connector'])) return new Callback;
switch ($config['driver'])
{
case 'sqlite':
return new SQLite;
case 'mysql':
return new MySQL;
case 'pgsql':
return new Postgres;
}
throw new \Exception("Database configuration is invalid. Please verify your configuration.");
}
}

View File

@@ -0,0 +1,37 @@
<?php namespace Laravel\DB\Connector;
use Laravel\DB\Connector;
class MySQL extends Connector {
/**
* Establish a PDO database connection.
*
* @param array $config
* @return PDO
*/
public function connect($config)
{
$dsn = $config['driver'].':host='.$config['host'].';dbname='.$config['database'];
if (isset($config['port']))
{
$dsn .= ';port='.$config['port'];
}
if (isset($config['socket']))
{
$dsn .= ';unix_socket='.$config['socket'];
}
$connection = new \PDO($dsn, $config['username'], $config['password'], $this->options);
if (isset($config['charset']))
{
$connection->prepare("SET NAMES '".$config['charset']."'")->execute();
}
return $connection;
}
}

View File

@@ -0,0 +1,32 @@
<?php namespace Laravel\DB\Connector;
use Laravel\DB\Connector;
class Postgres extends Connector {
/**
* Establish a PDO database connection.
*
* @param array $config
* @return PDO
*/
public function connect($config)
{
$dsn = $config['driver'].':host='.$config['host'].';dbname='.$config['database'];
if (isset($config['port']))
{
$dsn .= ';port='.$config['port'];
}
$connection = new \PDO($dsn, $config['username'], $config['password'], $this->options);
if (isset($config['charset']))
{
$connection->prepare("SET NAMES '".$config['charset']."'")->execute();
}
return $connection;
}
}

View File

@@ -0,0 +1,31 @@
<?php namespace Laravel\DB\Connector;
use Laravel\DB\Connector;
class SQLite extends Connector {
/**
* Establish a PDO database connection.
*
* @param array $config
* @return PDO
*/
public function connect($config)
{
if ($config['database'] == ':memory:')
{
return new \PDO('sqlite::memory:', null, null, $this->options);
}
elseif (file_exists($path = DATABASE_PATH.$config['database'].'.sqlite'))
{
return new \PDO('sqlite:'.$path, null, null, $this->options);
}
elseif (file_exists($config['database']))
{
return new \PDO('sqlite:'.$config['database'], null, null, $this->options);
}
throw new \Exception("SQLite database [".$config['database']."] could not be found.");
}
}

View File

@@ -0,0 +1,212 @@
<?php namespace Laravel\Database\Eloquent;
class Hydrator {
/**
* Load the array of hydrated models and their eager relationships.
*
* @param Model $eloquent
* @return array
*/
public static function hydrate($eloquent)
{
$results = static::base(get_class($eloquent), $eloquent->query->get());
if (count($results) > 0)
{
foreach ($eloquent->includes as $include)
{
if ( ! method_exists($eloquent, $include))
{
throw new \Exception("Attempting to eager load [$include], but the relationship is not defined.");
}
static::eagerly($eloquent, $results, $include);
}
}
return $results;
}
/**
* Hydrate the base models for a query.
*
* The resulting model array is keyed by the primary keys of the models.
* This allows the models to easily be matched to their children.
*
* @param string $class
* @param array $results
* @return array
*/
private static function base($class, $results)
{
$models = array();
foreach ($results as $result)
{
$model = new $class;
$model->attributes = (array) $result;
$model->exists = true;
if (isset($model->attributes['id']))
{
$models[$model->id] = $model;
}
else
{
$models[] = $model;
}
}
return $models;
}
/**
* Eagerly load a relationship.
*
* @param object $eloquent
* @param array $parents
* @param string $include
* @return void
*/
private static function eagerly($eloquent, &$parents, $include)
{
// We temporarily spoof the query attributes to allow the query to be fetched without
// any problems, since the belongs_to method actually gets the related attribute.
$first = reset($parents);
$eloquent->attributes = $first->attributes;
$relationship = $eloquent->$include();
$eloquent->attributes = array();
// Reset the WHERE clause and bindings on the query. We'll add our own WHERE clause soon.
// This will allow us to load a range of related models instead of only one.
$relationship->query->reset_where();
// Initialize the relationship attribute on the parents. As expected, "many" relationships
// are initialized to an array and "one" relationships are initialized to null.
foreach ($parents as &$parent)
{
$parent->ignore[$include] = (in_array($eloquent->relating, array('has_many', 'has_and_belongs_to_many'))) ? array() : null;
}
if (in_array($relating = $eloquent->relating, array('has_one', 'has_many', 'belongs_to')))
{
return static::$relating($relationship, $parents, $eloquent->relating_key, $include);
}
else
{
static::has_and_belongs_to_many($relationship, $parents, $eloquent->relating_key, $eloquent->relating_table, $include);
}
}
/**
* Eagerly load a 1:1 relationship.
*
* @param object $relationship
* @param array $parents
* @param string $relating_key
* @param string $relating
* @param string $include
* @return void
*/
private static function has_one($relationship, &$parents, $relating_key, $include)
{
foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child)
{
$parents[$child->$relating_key]->ignore[$include] = $child;
}
}
/**
* Eagerly load a 1:* relationship.
*
* @param object $relationship
* @param array $parents
* @param string $relating_key
* @param string $relating
* @param string $include
* @return void
*/
private static function has_many($relationship, &$parents, $relating_key, $include)
{
foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child)
{
$parents[$child->$relating_key]->ignore[$include][$child->id] = $child;
}
}
/**
* Eagerly load a 1:1 belonging relationship.
*
* @param object $relationship
* @param array $parents
* @param string $relating_key
* @param string $include
* @return void
*/
private static function belongs_to($relationship, &$parents, $relating_key, $include)
{
$keys = array();
foreach ($parents as &$parent)
{
$keys[] = $parent->$relating_key;
}
$children = $relationship->where_in('id', array_unique($keys))->get();
foreach ($parents as &$parent)
{
if (array_key_exists($parent->$relating_key, $children))
{
$parent->ignore[$include] = $children[$parent->$relating_key];
}
}
}
/**
* Eagerly load a many-to-many relationship.
*
* @param object $relationship
* @param array $parents
* @param string $relating_key
* @param string $relating_table
* @param string $include
*
* @return void
*/
private static function has_and_belongs_to_many($relationship, &$parents, $relating_key, $relating_table, $include)
{
// The model "has and belongs to many" method sets the SELECT clause; however, we need
// to clear it here since we will be adding the foreign key to the select.
$relationship->query->select = null;
$relationship->query->where_in($relating_table.'.'.$relating_key, array_keys($parents));
// The foreign key is added to the select to allow us to easily match the models back to their parents.
// Otherwise, there would be no apparent connection between the models to allow us to match them.
$children = $relationship->query->get(array(Model::table(get_class($relationship)).'.*', $relating_table.'.'.$relating_key));
$class = get_class($relationship);
foreach ($children as $child)
{
$related = new $class;
$related->attributes = (array) $child;
$related->exists = true;
// Remove the foreign key since it was only added to the query to help match the models.
unset($related->attributes[$relating_key]);
$parents[$child->$relating_key]->ignore[$include][$child->id] = $related;
}
}
}

View File

@@ -0,0 +1,500 @@
<?php namespace Laravel\Database\Eloquent;
use Laravel\IoC;
use Laravel\Str;
use Laravel\Config;
use Laravel\Inflector;
use Laravel\Database\Manager;
abstract class Model {
/**
* The connection that should be used for the model.
*
* @var string
*/
public static $connection;
/**
* The model query instance.
*
* @var Query
*/
public $query;
/**
* Indicates if the model exists in the database.
*
* @var bool
*/
public $exists = false;
/**
* The model's attributes.
*
* Typically, a model has an attribute for each column on the table.
*
* @var array
*/
public $attributes = array();
/**
* The model's dirty attributes.
*
* @var array
*/
public $dirty = array();
/**
* The model's ignored attributes.
*
* Ignored attributes will not be saved to the database, and are
* primarily used to hold relationships.
*
* @var array
*/
public $ignore = array();
/**
* The relationships that should be eagerly loaded.
*
* @var array
*/
public $includes = array();
/**
* The relationship type the model is currently resolving.
*
* @var string
*/
public $relating;
/**
* The foreign key of the "relating" relationship.
*
* @var string
*/
public $relating_key;
/**
* The table name of the model being resolved.
*
* This is used during many-to-many eager loading.
*
* @var string
*/
public $relating_table;
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct($attributes = array())
{
$this->fill($attributes);
}
/**
* Set the attributes of the model using an array.
*
* @param array $attributes
* @return Model
*/
public function fill($attributes)
{
foreach ($attributes as $key => $value)
{
$this->$key = $value;
}
return $this;
}
/**
* Set the eagerly loaded models on the queryable model.
*
* @return Model
*/
private function _with()
{
$this->includes = func_get_args();
return $this;
}
/**
* Factory for creating queryable Eloquent model instances.
*
* @param string $class
* @return object
*/
public static function query($class)
{
$model = new $class;
// Since this method is only used for instantiating models for querying
// purposes, we will go ahead and set the Query instance on the model.
$model->query = Manager::connection(static::$connection)->table(static::table($class));
return $model;
}
/**
* Get the table name for a model.
*
* @param string $class
* @return string
*/
public static function table($class)
{
if (property_exists($class, 'table')) return $class::$table;
return strtolower(Inflector::plural(static::model_name($class)));
}
/**
* Get an Eloquent model name without any namespaces.
*
* @param string|Model $model
* @return string
*/
public static function model_name($model)
{
$class = (is_object($model)) ? get_class($model) : $model;
$segments = array_reverse(explode('\\', $class));
return $segments[0];
}
/**
* Get all of the models from the database.
*
* @return array
*/
public static function all()
{
return Hydrator::hydrate(static::query(get_called_class()));
}
/**
* Get a model by the primary key.
*
* @param int $id
* @return mixed
*/
public static function find($id)
{
return static::query(get_called_class())->where('id', '=', $id)->first();
}
/**
* Get the first model result
*
* @return mixed
*/
private function _first()
{
return (count($results = $this->take(1)->_get()) > 0) ? reset($results) : null;
}
/**
* Get an array of models from the database.
*
* @return array
*/
private function _get()
{
return Hydrator::hydrate($this);
}
/**
* Retrieve the query for a 1:1 relationship.
*
* @param string $model
* @param string $foreign_key
* @return mixed
*/
public function has_one($model, $foreign_key = null)
{
$this->relating = __FUNCTION__;
return $this->has_one_or_many($model, $foreign_key);
}
/**
* Retrieve the query for a 1:* relationship.
*
* @param string $model
* @param string $foreign_key
* @return mixed
*/
public function has_many($model, $foreign_key = null)
{
$this->relating = __FUNCTION__;
return $this->has_one_or_many($model, $foreign_key);
}
/**
* Retrieve the query for a 1:1 or 1:* relationship.
*
* The default foreign key for has one and has many relationships is the name
* of the model with an appended _id. For example, the foreign key for a
* User model would be user_id. Photo would be photo_id, etc.
*
* @param string $model
* @param string $foreign_key
* @return mixed
*/
private function has_one_or_many($model, $foreign_key)
{
$this->relating_key = (is_null($foreign_key)) ? strtolower(static::model_name($this)).'_id' : $foreign_key;
return static::query($model)->where($this->relating_key, '=', $this->id);
}
/**
* Retrieve the query for a 1:1 belonging relationship.
*
* The default foreign key for belonging relationships is the name of the
* relationship method name with _id. So, if a model has a "manager" method
* returning a belongs_to relationship, the key would be manager_id.
*
* @param string $model
* @param string $foreign_key
* @return mixed
*/
public function belongs_to($model, $foreign_key = null)
{
$this->relating = __FUNCTION__;
if ( ! is_null($foreign_key))
{
$this->relating_key = $foreign_key;
}
else
{
list(, $caller) = debug_backtrace(false);
$this->relating_key = $caller['function'].'_id';
}
return static::query($model)->where('id', '=', $this->attributes[$this->relating_key]);
}
/**
* Retrieve the query for a *:* relationship.
*
* The default foreign key for many-to-many relations is the name of the model
* with an appended _id. This is the same convention as has_one and has_many.
*
* @param string $model
* @param string $table
* @param string $foreign_key
* @param string $associated_key
* @return mixed
*/
public function has_and_belongs_to_many($model, $table = null, $foreign_key = null, $associated_key = null)
{
$this->relating = __FUNCTION__;
$this->relating_table = (is_null($table)) ? $this->intermediate_table($model) : $table;
// Allowing the overriding of the foreign and associated keys provides the flexibility for
// self-referential many-to-many relationships, such as a "buddy list".
$this->relating_key = (is_null($foreign_key)) ? strtolower(static::model_name($this)).'_id' : $foreign_key;
// The associated key is the foreign key name of the related model. So, if the related model
// is "Role", the associated key on the intermediate table would be "role_id".
$associated_key = (is_null($associated_key)) ? strtolower(static::model_name($model)).'_id' : $associated_key;
return static::query($model)
->select(array(static::table($model).'.*'))
->join($this->relating_table, static::table($model).'.id', '=', $this->relating_table.'.'.$associated_key)
->where($this->relating_table.'.'.$this->relating_key, '=', $this->id);
}
/**
* Determine the intermediate table name for a given model.
*
* By default, the intermediate table name is the plural names of the models
* arranged alphabetically and concatenated with an underscore.
*
* @param string $model
* @return string
*/
private function intermediate_table($model)
{
$models = array(Inflector::plural(static::model_name($model)), Inflector::plural(static::model_name($this)));
sort($models);
return strtolower($models[0].'_'.$models[1]);
}
/**
* Save the model to the database.
*
* @return bool
*/
public function save()
{
// If the model does not have any dirty attributes, there is no reason
// to save it to the database.
if ($this->exists and count($this->dirty) == 0) return true;
$model = get_class($this);
// Since the model was instantiated using "new", a query instance has not been set.
// Only models being used for querying have their query instances set by default.
$this->query = Manager::connection(static::$connection)->table(static::table($model));
if (property_exists($model, 'timestamps') and $model::$timestamps)
{
$this->timestamp();
}
// If the model already exists in the database, we will just update it.
// Otherwise, we will insert the model and set the ID attribute.
if ($this->exists)
{
$success = ($this->query->where_id($this->attributes['id'])->update($this->dirty) === 1);
}
else
{
$success = is_numeric($this->attributes['id'] = $this->query->insert_get_id($this->attributes));
}
($this->exists = true) and $this->dirty = array();
return $success;
}
/**
* Set the creation and update timestamps on the model.
*
* @return void
*/
private function timestamp()
{
$this->updated_at = date('Y-m-d H:i:s');
if ( ! $this->exists) $this->created_at = $this->updated_at;
}
/**
* Delete a model from the database.
*
* @param int $id
* @return int
*/
public function delete($id = null)
{
// If the delete method is being called on an existing model, we only want to delete
// that model. If it is being called from an Eloquent query model, it is probably
// the developer's intention to delete more than one model, so we will pass the
// delete statement to the query instance.
if ( ! $this->exists) return $this->query->delete();
return Manager::connection(static::$connection)->table(static::table(get_class($this)))->delete($this->id);
}
/**
* Magic method for retrieving model attributes.
*/
public function __get($key)
{
if (array_key_exists($key, $this->attributes))
{
return $this->attributes[$key];
}
// Is the requested item a model relationship that has already been loaded?
// All of the loaded relationships are stored in the "ignore" array.
elseif (array_key_exists($key, $this->ignore))
{
return $this->ignore[$key];
}
// Is the requested item a model relationship? If it is, we will dynamically
// load it and return the results of the relationship query.
elseif (method_exists($this, $key))
{
$query = $this->$key();
return $this->ignore[$key] = (in_array($this->relating, array('has_one', 'belongs_to'))) ? $query->first() : $query->get();
}
}
/**
* Magic Method for setting model attributes.
*/
public function __set($key, $value)
{
// If the key is a relationship, add it to the ignored attributes.
// Ignored attributes are not stored in the database.
if (method_exists($this, $key))
{
$this->ignore[$key] = $value;
}
else
{
$this->attributes[$key] = $value;
$this->dirty[$key] = $value;
}
}
/**
* Magic Method for determining if a model attribute is set.
*/
public function __isset($key)
{
return (array_key_exists($key, $this->attributes) or array_key_exists($key, $this->ignore));
}
/**
* Magic Method for unsetting model attributes.
*/
public function __unset($key)
{
unset($this->attributes[$key], $this->ignore[$key], $this->dirty[$key]);
}
/**
* Magic Method for handling dynamic method calls.
*/
public function __call($method, $parameters)
{
// To allow the "with", "get", "first", and "paginate" methods to be called both
// staticly and on an instance, we need to have private, underscored versions
// of the methods and handle them dynamically.
if (in_array($method, array('with', 'get', 'first')))
{
return call_user_func_array(array($this, '_'.$method), $parameters);
}
// All of the aggregate and persistance functions can be passed directly to the query
// instance. For these functions, we can simply return the response of the query.
if (in_array($method, array('insert', 'update', 'count', 'sum', 'min', 'max', 'avg')))
{
return call_user_func_array(array($this->query, $method), $parameters);
}
// Pass the method to the query instance. This allows the chaining of methods
// from the query builder, providing the same convenient query API as the
// query builder itself.
call_user_func_array(array($this->query, $method), $parameters);
return $this;
}
/**
* Magic Method for handling dynamic static method calls.
*/
public static function __callStatic($method, $parameters)
{
// Just pass the method to a model instance and let the __call method take care of it.
return call_user_func_array(array(static::query(get_called_class()), $method), $parameters);
}
}

View File

@@ -0,0 +1,93 @@
<?php namespace Laravel\Database;
use Laravel\Config;
class Manager {
/**
* The established database connections.
*
* @var array
*/
public static $connections = array();
/**
* Get a database connection. If no database name is specified, the default
* connection will be returned as defined in the db configuration file.
*
* Note: Database connections are managed as singletons.
*
* <code>
* // Get the default database connection
* $connection = DB::connection();
*
* // Get a specific database connection
* $connection = DB::connection('mysql');
* </code>
*
* @param string $connection
* @return Database\Connection
*/
public static function connection($connection = null)
{
if (is_null($connection)) $connection = Config::get('database.default');
if ( ! array_key_exists($connection, static::$connections))
{
if (is_null($config = Config::get('database.connections.'.$connection)))
{
throw new \Exception("Database connection [$connection] is not defined.");
}
$connector = Connector\Factory::make($config);
static::$connections[$connection] = new Connection($connection, $config, $connector);
}
return static::$connections[$connection];
}
/**
* Begin a fluent query against a table.
*
* This method primarily serves as a short-cut to the $connection->table() method.
*
* <code>
* // Begin a fluent query against the "users" table
* $query = DB::table('users');
*
* // Equivalent call using the connection table method.
* $query = DB::connection()->table('users');
*
* // Begin a fluent query against the "users" table for a specific connection
* $query = DB::table('users', 'mysql');
* </code>
*
* @param string $table
* @param string $connection
* @return Database\Query
*/
public static function table($table, $connection = null)
{
return static::connection($connection)->table($table);
}
/**
* Magic Method for calling methods on the default database connection.
*
* This provides a convenient API for querying or examining the default database connection.
*
* <code>
* // Run a query against the default database connection
* $results = DB::query('select * from users');
*
* // Equivalent call using the connection instance
* $results = DB::connection()->query('select * from users');
* </code>
*/
public static function __callStatic($method, $parameters)
{
return call_user_func_array(array(static::connection(), $method), $parameters);
}
}

712
laravel/database/query.php Normal file
View File

@@ -0,0 +1,712 @@
<?php namespace Laravel\Database;
use Laravel\IoC;
use Laravel\Str;
use Laravel\Config;
use Laravel\Request;
class Query {
/**
* The database connection.
*
* @var Connection
*/
public $connection;
/**
* The query compiler instance.
*
* @var Compiler
*/
public $compiler;
/**
* The SELECT clause.
*
* @var array
*/
public $select;
/**
* If the query is performing an aggregate function, this will contain the column
* and and function to use when aggregating.
*
* @var array
*/
public $aggregate;
/**
* Indicates if the query should return distinct results.
*
* @var bool
*/
public $distinct = false;
/**
* The table name.
*
* @var string
*/
public $table;
/**
* The table joins.
*
* @var array
*/
public $joins;
/**
* The WHERE clauses.
*
* @var array
*/
public $wheres;
/**
* The ORDER BY clauses.
*
* @var array
*/
public $orderings;
/**
* The LIMIT value.
*
* @var int
*/
public $limit;
/**
* The OFFSET value.
*
* @var int
*/
public $offset;
/**
* The query value bindings.
*
* @var array
*/
public $bindings = array();
/**
* Create a new query instance.
*
* @param string $table
* @param Connection $connection
* @param Compiler $compiler
* @return void
*/
public function __construct($table, Connection $connection, Query\Compiler $compiler)
{
$this->table = $table;
$this->compiler = $compiler;
$this->connection = $connection;
}
/**
* Force the query to return distinct results.
*
* @return Query
*/
public function distinct()
{
$this->distinct = true;
return $this;
}
/**
* Add an array of columns to the SELECT clause.
*
* <code>
* $query->select(array('id', 'email'));
* </code>
*
* @param array $columns
* @return Query
*/
public function select($columns = array('*'))
{
$this->select = $columns;
return $this;
}
/**
* Add a join clause to the query.
*
* <code>
* $query->join('users', 'users.id', '=', 'posts.user_id');
* </code>
*
* @param string $table
* @param string $column1
* @param string $operator
* @param string $column2
* @param string $type
* @return Query
*/
public function join($table, $column1, $operator, $column2, $type = 'INNER')
{
$this->joins[] = compact('table', 'column1', 'operator', 'column2', 'type');
return $this;
}
/**
* Add a left join to the query.
*
* <code>
* $query->left_join('users', 'users.id', '=', 'posts.user_id');
* </code>
*
* @param string $table
* @param string $column1
* @param string $operator
* @param string $column2
* @return Query
*/
public function left_join($table, $column1, $operator, $column2)
{
return $this->join($table, $column1, $operator, $column2, 'LEFT');
}
/**
* Reset the where clause to its initial state. All bindings will be cleared.
*
* @return void
*/
public function reset_where()
{
$this->wheres = array();
$this->bindings = array();
}
/**
* Add a raw where condition to the query.
*
* <code>
* $query->raw_where('user_id = ? and password = ?', array(1, 'secret'));
* </code>
*
* @param string $where
* @param array $bindings
* @param string $connector
* @return Query
*/
public function raw_where($where, $bindings = array(), $connector = 'AND')
{
$this->wheres[] = ' '.$connector.' '.$where;
$this->bindings = array_merge($this->bindings, $bindings);
return $this;
}
/**
* Add a raw or where condition to the query.
*
* <code>
* $query->raw_or_where('user_id = ? and password = ?', array(1, 'secret'));
* </code>
*
* @param string $where
* @param array $bindings
* @return Query
*/
public function raw_or_where($where, $bindings = array())
{
return $this->raw_where($where, $bindings, 'OR');
}
/**
* Add a where condition to the query.
*
* <code>
* $query->where('id', '=', 1);
* </code>
*
* @param string $column
* @param string $operator
* @param mixed $value
* @param string $connector
* @return Query
*/
public function where($column, $operator, $value, $connector = 'AND')
{
$this->wheres[] = array_merge(array('type' => 'where'), compact('column', 'operator', 'value', 'connector'));
$this->bindings[] = $value;
return $this;
}
/**
* Add an or where condition to the query.
*
* <code>
* $query->or_where('id', '=', 1);
* </code>
*
* @param string $column
* @param string $operator
* @param mixed $value
* @return Query
*/
public function or_where($column, $operator, $value)
{
return $this->where($column, $operator, $value, 'OR');
}
/**
* Add a where condition for the primary key to the query.
*
* <code>
* $query->where_id(1);
* </code>
*
* @param mixed $value
* @return Query
*/
public function where_id($value)
{
return $this->where('id', '=', $value);
}
/**
* Add an or where condition for the primary key to the query.
*
* <code>
* $query->or_where_id(1);
* </code>
*
* @param mixed $value
* @return Query
*/
public function or_where_id($value)
{
return $this->or_where('id', '=', $value);
}
/**
* Add a where in condition to the query.
*
* <code>
* $query->where_in('id', array(1, 2, 3));
* </code>
*
* @param string $column
* @param array $values
* @param string $connector
* @param bool $not
* @return Query
*/
public function where_in($column, $values, $connector = 'AND', $not = false)
{
$this->wheres[] = array_merge(array('type' => 'where_in'), compact('column', 'values', 'connector', 'not'));
$this->bindings = array_merge($this->bindings, $values);
return $this;
}
/**
* Add an or where in condition to the query.
*
* <code>
* $query->or_where_in('id', array(1, 2, 3));
* </code>
*
* @param string $column
* @param array $values
* @return Query
*/
public function or_where_in($column, $values)
{
return $this->where_in($column, $values, 'OR');
}
/**
* Add a where not in condition to the query.
*
* <code>
* $query->where_not_in('id', array(1, 2, 3));
* </code>
*
* @param string $column
* @param array $values
* @param string $connector
* @return Query
*/
public function where_not_in($column, $values, $connector = 'AND')
{
return $this->where_in($column, $values, $connector, true);
}
/**
* Add an or where not in condition to the query.
*
* <code>
* $query->or_where_not_in('id', array(1, 2, 3));
* </code>
*
* @param string $column
* @param array $values
* @return Query
*/
public function or_where_not_in($column, $values)
{
return $this->where_not_in($column, $values, 'OR');
}
/**
* Add a where null condition to the query.
*
* @param string $column
* @param string $connector
* @param bool $not
* @return Query
*/
public function where_null($column, $connector = 'AND', $not = false)
{
$this->wheres[] = array_merge(array('type' => 'where_null'), compact('column', 'connector', 'not'));
return $this;
}
/**
* Add an or where null condition to the query.
*
* @param string $column
* @return Query
*/
public function or_where_null($column)
{
return $this->where_null($column, 'OR');
}
/**
* Add a where not null condition to the query.
*
* @param string $column
* @param string $connector
* @return Query
*/
public function where_not_null($column, $connector = 'AND')
{
return $this->where_null($column, $connector, true);
}
/**
* Add an or where not null condition to the query.
*
* @param string $column
* @return Query
*/
public function or_where_not_null($column)
{
return $this->where_not_null($column, 'OR');
}
/**
* Add dynamic where conditions to the query.
*
* Dynamic queries are caught by the __call magic method and are parsed here.
* They provide a convenient, expressive API for building simple conditions.
*
* @param string $method
* @param array $parameters
* @return Query
*/
private function dynamic_where($method, $parameters)
{
// Strip the "where_" off of the method.
$finder = substr($method, 6);
// Split the column names from the connectors.
$segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
// The connector variable will determine which connector will be used for the condition.
// We'll change it as we come across new connectors in the dynamic method string.
//
// The index variable helps us get the correct parameter value for the where condition.
// We increment it each time we add a condition.
$connector = 'AND';
$index = 0;
foreach ($segments as $segment)
{
if ($segment != '_and_' and $segment != '_or_')
{
$this->where($segment, '=', $parameters[$index], $connector);
$index++;
}
else
{
$connector = trim(strtoupper($segment), '_');
}
}
return $this;
}
/**
* Add an ordering to the query.
*
* <code>
* // Set an ascending sort on the query
* $query->order_by('votes', 'asc');
*
* // Set a descending sort on the query
* $query->order_by('votes', 'desc');
* </code>
*
* @param string $column
* @param string $direction
* @return Query
*/
public function order_by($column, $direction = 'asc')
{
$this->orderings[] = compact('column', 'direction');
return $this;
}
/**
* Set the query offset.
*
* @param int $value
* @return Query
*/
public function skip($value)
{
$this->offset = $value;
return $this;
}
/**
* Set the query limit.
*
* @param int $value
* @return Query
*/
public function take($value)
{
$this->limit = $value;
return $this;
}
/**
* Set the query limit and offset for a given page and item per page count.
*
* If the given page is not an integer or is less than zero, one will be used.
*
* <code>
* // Get the the 15 users that should be displayed for page 1
* $results = DB::table('users')->for_page(1, 15);
* </code>
*
* @param int $page
* @param int $per_page
* @return Query
*/
public function for_page($page, $per_page = 15)
{
if ($page < 1 or filter_var($page, FILTER_VALIDATE_INT) === false) $page = 1;
return $this->skip(($page - 1) * $per_page)->take($per_page)
}
/**
* Calculate and set the limit and offset values for a given page.
*
* @param int $page
* @param int $per_page
* @return Query
*/
public function for_page($page, $per_page)
{
return $this->skip(($page - 1) * $per_page)->take($per_page);
}
/**
* Find a record by the primary key.
*
* <code>
* // Get the user having an ID of 1
* $user = DB::table('users')->find(1);
* </code>
*
* @param int $id
* @param array $columns
* @return object
*/
public function find($id, $columns = array('*'))
{
return $this->where('id', '=', $id)->first($columns);
}
/**
* Get an aggregate value.
*
* @param string $aggregate
* @param string $column
* @return mixed
*/
private function aggregate($aggregator, $column)
{
$this->aggregate = compact('aggregator', 'column');
$result = $this->connection->scalar($this->compiler->select($this), $this->bindings);
// Reset the SELECT clause so more queries can be performed using the same instance.
// This is helpful for getting aggregates and then getting actual results.
$this->select = null;
return $result;
}
/**
* Execute the query as a SELECT statement and return the first result.
*
* @param array $columns
* @return stdClass
*/
public function first($columns = array('*'))
{
return (count($results = $this->take(1)->get($columns)) > 0) ? $results[0] : null;
}
/**
* Execute the query as a SELECT statement.
*
* @param array $columns
* @return array
*/
public function get($columns = array('*'))
{
if (is_null($this->select)) $this->select($columns);
$results = $this->connection->query($this->compiler->select($this), $this->bindings);
// Reset the SELECT clause so more queries can be performed using the same instance.
// This is helpful for getting aggregates and then getting actual results.
$this->select = null;
return $results;
}
/**
* Insert an array of values into the database table.
*
* <code>
* // Insert into the "users" table
* $success = DB::table('users')->insert(array('id' => 1, 'email' => 'example@gmail.com'));
* </code>
*
* @param array $values
* @return bool
*/
public function insert($values)
{
return $this->connection->query($this->compiler->insert($this, $values), array_values($values));
}
/**
* Insert an array of values into the database table and return the value of the ID column.
*
* <code>
* // Insert into the "users" table and get the auto-incrementing ID
* $id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com'));
* </code>
*
* @param array $values
* @return int
*/
public function insert_get_id($values)
{
$this->connection->query($this->compiler->insert($this, $values), array_values($values));
return (int) $this->connection->pdo->lastInsertId();
}
/**
* Update an array of values in the database table.
*
* <code>
* // Update a user's e-mail address
* $affected = DB::table('users')->where_id(1)->update(array('email' => 'new_email@example.com'));
* </code>
*
* @param array $values
* @return int
*/
public function update($values)
{
return $this->connection->query($this->compiler->update($this, $values), array_merge(array_values($values), $this->bindings));
}
/**
* Execute the query as a DELETE statement.
*
* Optionally, an ID may be passed to the method do delete a specific row.
*
* <code>
* // Delete everything from the "users" table
* $affected = DB::table('users')->delete();
*
* // Delete a specific user from the table
* $affected = DB::table('users')->delete(1);
*
* // Execute a delete statement with where conditions
* $affected = DB::table('users')->where_email($email)->delete();
* </code>
*
* @param int $id
* @return int
*/
public function delete($id = null)
{
if ( ! is_null($id)) $this->where('id', '=', $id);
return $this->connection->query($this->compiler->delete($this), $this->bindings);
}
/**
* Magic Method for handling dynamic functions.
*
* This method handles all calls to aggregate functions as well as the construction of dynamic where clauses.
*
* <code>
* // Get the total number of rows on the "users" table
* $count = DB::table('users')->count();
*
* // Get a user using a dynamic where clause
* $user = DB::table('users')->where_email('example@gmail.com')->first();
* </code>
*/
public function __call($method, $parameters)
{
if (strpos($method, 'where_') === 0)
{
return $this->dynamic_where($method, $parameters, $this);
}
if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
{
return ($method == 'count') ? $this->aggregate(strtoupper($method), '*') : $this->aggregate(strtoupper($method), $parameters[0]);
}
throw new \Exception("Method [$method] is not defined on the Query class.");
}
}

View File

@@ -0,0 +1,314 @@
<?php namespace Laravel\Database\Query;
use Laravel\Database\Query;
class Compiler {
/**
* Compile a SQL SELECT statment from a Query instance.
*
* This query instance will be examined and the proper SQL syntax will be returned as a string.
* This class may be overridden to accommodate syntax differences between various database systems.
*
* @param Query $query
* @return string
*/
public function select(Query $query)
{
if ( ! is_null($query->aggregate))
{
$sql[] = $this->compile_aggregate($query->aggregate['aggregator'], $query->aggregate['column']);
}
else
{
$sql[] = $this->compile_select($query);
}
$sql[] = $this->compile_from($query->table);
foreach (array('joins', 'wheres', 'orderings', 'limit', 'offset') as $clause)
{
if ( ! is_null($query->$clause)) $sql[] = call_user_func(array($this, 'compile_'.$clause), $query->$clause);
}
return implode(' ', array_filter($sql, function($value) { return ! is_null($value) and (string) $value !== ''; }));
}
/**
* Compile the query SELECT clause.
*
* For convenience, the entire query object is passed to the method. This to account for
* database systems who put the LIMIT amount in the SELECT clause.
*
* @param Query $query
* @return string
*/
public function compile_select(Query $query)
{
return (($query->distinct) ? 'SELECT DISTINCT ' : 'SELECT ').$this->wrap_columns($query->select);
}
/**
* Wrap and comma-delimit a set of SELECT columns.
*
* @param array $columns
* @return string
*/
public function wrap_columns($columns)
{
return implode(', ', array_map(array($this, 'wrap'), $columns));
}
/**
* Compile the query SELECT clause with an aggregate function.
*
* @param string $aggregator
* @param string $column
* @return string
*/
public function compile_aggregate($aggregator, $column)
{
return 'SELECT '.$aggregator.'('.$this->wrap($column).') AS '.$this->wrap('aggregate');
}
/**
* Compile the query FROM clause.
*
* Note: This method does not compile any JOIN clauses. Joins are compiled by the compile_joins method.
*
* @param string $table
* @return string
*/
public function compile_from($table)
{
return 'FROM '.$this->wrap($table);
}
/**
* Compile the query JOIN clauses.
*
* @param array $joins
* @return string
*/
public function compile_joins($joins)
{
foreach ($joins as $join)
{
extract($join);
$sql[] = $type.' JOIN '.$this->wrap($table).' ON '.$this->wrap($column1).' '.$operator.' '.$this->wrap($column2);
}
return implode(' ', $sql);
}
/**
* Compile the query WHERE clauses.
*
* @param array $wheres
* @return string
*/
public function compile_wheres($wheres)
{
$sql = array('WHERE 1 = 1');
foreach ($wheres as $where)
{
if (is_string($where))
{
$sql[] = $where;
}
elseif ($where['type'] === 'where')
{
$sql[] = $where['connector'].' '.$this->compile_where($where);
}
elseif ($where['type'] === 'where_in')
{
$sql[] = $where['connector'].' '.$this->compile_where_in($where);
}
elseif ($where['type'] === 'where_null')
{
$sql[] = $where['connector'].' '.$this->compile_where_null($where);
}
}
return implode(' ', $sql);
}
/**
* Compile a simple WHERE clause.
*
* @param array $where
* @return string
*/
public function compile_where($where)
{
return $this->wrap($where['column']).' '.$where['operator'].' ?';
}
/**
* Compile a WHERE IN clause.
*
* @param array $where
* @return string
*/
public function compile_where_in($where)
{
$operator = ($where['not']) ? 'NOT IN' : 'IN';
return $this->wrap($where['column']).' '.$operator.' ('.$this->parameterize($where['values']).')';
}
/**
* Compile a WHERE NULL clause.
*
* @param array $where
* @return string
*/
public function compile_where_null($where)
{
$operator = ($where['not']) ? 'NOT NULL' : 'NULL';
return $this->wrap($where['column']).' IS '.$operator;
}
/**
* Compile the query ORDER BY clause.
*
* @param array $orderings
* @return string
*/
public function compile_orderings($orderings)
{
foreach ($orderings as $ordering)
{
$sql[] = $this->wrap($ordering['column']).' '.strtoupper($ordering['direction']);
}
return 'ORDER BY '.implode(', ', $sql);
}
/**
* Compile the query LIMIT.
*
* @param int $limit
* @return string
*/
public function compile_limit($limit)
{
return 'LIMIT '.$limit;
}
/**
* Compile the query OFFSET.
*
* @param int $offset
* @return string
*/
public function compile_offset($offset)
{
return 'OFFSET '.$offset;
}
/**
* Compile a SQL INSERT statment from a Query instance.
*
* @param Query $query
* @param array $values
* @return string
*/
public function insert(Query $query, $values)
{
$columns = array_map(array($this, 'wrap'), array_keys($values));
return 'INSERT INTO '.$this->wrap($query->table).' ('.implode(', ', $columns).') VALUES ('.$this->parameterize($values).')';
}
/**
* Compile a SQL INSERT statment that returns an auto-incrementing ID from a Query instance.
*
* @param Query $query
* @param array $values
* @return string
*/
public function insert_get_id(Query $query, $values)
{
return $this->insert($query, $values);
}
/**
* Compile a SQL UPDATE statment from a Query instance.
*
* @param Query $query
* @param array $values
* @return string
*/
public function update(Query $query, $values)
{
foreach (array_keys($values) as $column) { $sets[] = $this->wrap($column).' = ?'; }
$sql = 'UPDATE '.$this->wrap($query->table).' SET '.implode(', ', $sets);
return (count($query->wheres) > 0) ? $sql.' '.$this->compile_wheres($query->wheres) : $sql;
}
/**
* Compile a SQL DELETE statment from a Query instance.
*
* @param Query $query
* @return string
*/
public function delete(Query $query)
{
$sql = 'DELETE FROM '.$this->wrap($query->table);
return (count($query->wheres) > 0) ? $sql.' '.$this->compile_wheres($query->wheres) : $sql;
}
/**
* Wrap a value in keyword identifiers.
*
* @param string $value
* @return string
*/
public function wrap($value)
{
if (strpos(strtolower($value), ' as ') !== false) return $this->wrap_alias($value);
foreach (explode('.', $value) as $segment)
{
$wrapped[] = ($segment != '*') ? $this->wrapper().$segment.$this->wrapper() : $segment;
}
return implode('.', $wrapped);
}
/**
* Wrap an alias in keyword identifiers.
*
* @param string $value
* @return string
*/
public function wrap_alias($value)
{
$segments = explode(' ', $value);
return $this->wrap($segments[0]).' AS '.$this->wrap($segments[2]);
}
/**
* Get the keyword identifier wrapper for the connection.
*
* @return string
*/
public function wrapper() { return '"'; }
/**
* Create query parameters from an array of values.
*
* @param array $values
* @return string
*/
public function parameterize($values) { return implode(', ', array_fill(0, count($values), '?')); }
}

View File

@@ -0,0 +1,35 @@
<?php namespace Laravel\Database\Query\Compiler;
use Laravel\Database\Connection;
use Laravel\Database\Query\Compiler;
class Factory {
/**
* Create a new query compiler for a given connection.
*
* Using driver-based compilers allows us to provide the proper syntax to different database
* systems using a common API. A core set of functions is provided through the base Compiler
* class, which can be extended and overridden for various database systems.
*
* @param Connection $connection
* @return Compiler
*/
public static function make(Connection $connection)
{
$compiler = (isset($connection->config['compiler'])) ? $connection->config['compiler'] : $connection->driver();
switch ($compiler)
{
case 'mysql':
return new MySQL;
case 'pgsql':
return new Postgres;
default:
return new Compiler;
}
}
}

View File

@@ -0,0 +1,14 @@
<?php namespace Laravel\Database\Query\Compiler;
use Laravel\Database\Query\Compiler;
class MySQL extends Compiler {
/**
* Get the keyword identifier wrapper for the connection.
*
* @return string
*/
public function wrapper() { return '`'; }
}

View File

@@ -0,0 +1,19 @@
<?php namespace Laravel\Database\Query\Compiler;
use Laravel\Database\Query\Compiler;
class Postgres extends Compiler {
/**
* Compile a SQL INSERT statment that returns an auto-incrementing ID from a Query instance.
*
* @param Query $query
* @param array $values
* @return string
*/
public function insert_get_id(Query $query, $values)
{
return $this->insert($query, $values).' RETURNING '.$this->wrap('id');
}
}

View File

@@ -0,0 +1,28 @@
<?php namespace Laravel\Database\Query;
use Laravel\Database\Query;
use Laravel\Database\Connection;
class Factory {
/**
* Create a new query instance based on the connection driver.
*
* @param string $table
* @param Connection $connection
* @param Compiler $compiler
* @return Query
*/
public static function make($table, Connection $connection, Compiler $compiler)
{
switch ($connection->driver())
{
case 'pgsql':
return new Postgres($table, $connection, $compiler);
default:
return new Query($table, $connection, $compiler);
}
}
}

View File

@@ -0,0 +1,27 @@
<?php namespace Laravel\Database\Query;
use Laravel\Database\Query;
class Postgres extends Query {
/**
* Insert an array of values into the database table and return the value of the ID column.
*
* <code>
* // Insert into the "users" table and get the auto-incrementing ID
* $id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com'));
* </code>
*
* @param array $values
* @return int
*/
public function insert_get_id($values)
{
$query = $this->connection->pdo->prepare($this->compiler->insert_get_id($this, $values));
$query->execute(array_values($values));
return (int) $query->fetch(\PDO::FETCH_CLASS, 'stdClass')->id;
}
}