Commit badc8a60 authored by Taylor Otwell's avatar Taylor Otwell

database refactoring.

parent 829088f3
...@@ -26,8 +26,8 @@ return array( ...@@ -26,8 +26,8 @@ return array(
'Cookie' => 'System\\Cookie', 'Cookie' => 'System\\Cookie',
'Crypt' => 'System\\Crypt', 'Crypt' => 'System\\Crypt',
'Date' => 'System\\Date', 'Date' => 'System\\Date',
'DB' => 'System\\DB', 'DB' => 'System\\DB\\Manager',
'Eloquent' => 'System\\DB\\Eloquent', 'Eloquent' => 'System\\DB\\Eloquent\\Model',
'File' => 'System\\File', 'File' => 'System\\File',
'Form' => 'System\\Form', 'Form' => 'System\\Form',
'Hash' => 'System\\Hash', 'Hash' => 'System\\Hash',
......
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
* @link http://laravel.com * @link http://laravel.com
*/ */
$t = microtime(true);
// -------------------------------------------------------------- // --------------------------------------------------------------
// The path to the application directory. // The path to the application directory.
// -------------------------------------------------------------- // --------------------------------------------------------------
...@@ -135,6 +137,16 @@ if (System\Config::get('session.driver') != '') ...@@ -135,6 +137,16 @@ if (System\Config::get('session.driver') != '')
System\Session::load(System\Cookie::get('laravel_session')); System\Session::load(System\Cookie::get('laravel_session'));
} }
// --------------------------------------------------------------
// Load all of the core routing classes.
// --------------------------------------------------------------
require SYS_PATH.'request'.EXT;
require SYS_PATH.'response'.EXT;
require SYS_PATH.'routing/route'.EXT;
require SYS_PATH.'routing/router'.EXT;
require SYS_PATH.'routing/loader'.EXT;
require SYS_PATH.'routing/filter'.EXT;
// -------------------------------------------------------------- // --------------------------------------------------------------
// Register the route filters. // Register the route filters.
// -------------------------------------------------------------- // --------------------------------------------------------------
...@@ -150,7 +162,7 @@ $response = System\Routing\Filter::call('before', array(), true); ...@@ -150,7 +162,7 @@ $response = System\Routing\Filter::call('before', array(), true);
// ---------------------------------------------------------- // ----------------------------------------------------------
if (is_null($response)) if (is_null($response))
{ {
$route = System\Routing\Router::make(Request::method(), Request::uri(), new System\Routing\Loader)->route(); $route = System\Routing\Router::make(System\Request::method(), System\Request::uri(), new System\Routing\Loader(APP_PATH))->route();
$response = (is_null($route)) ? System\Response::error('404') : $route->call(); $response = (is_null($route)) ? System\Response::error('404') : $route->call();
} }
......
<?php namespace System; <?php namespace System\DB;
class DB { class Connection {
/** /**
* The established database connections. * The connection name.
*
* @var string
*/
public $name;
/**
* The connection configuration.
* *
* @var array * @var array
*/ */
public static $connections = array(); public $config;
/** /**
* Get a database connection. If no database name is specified, the default * The Connector instance.
* connection will be returned as defined in the db configuration file.
* *
* Note: Database connections are managed as singletons. * @var Connector
*/
public $connector;
/**
* The PDO connection.
* *
* @param string $connection * @var PDO
* @return PDO
*/ */
public static function connection($connection = null) public $pdo;
{
if (is_null($connection))
{
$connection = Config::get('db.default');
}
if ( ! array_key_exists($connection, static::$connections)) /**
* Create a new Connection instance.
*
* @param string $name
* @param object $config
* @param Conector $connector
* @return void
*/
public function __construct($name, $config, $connector)
{ {
static::$connections[$connection] = DB\Connector::connect($connection); $this->name = $name;
} $this->config = $config;
$this->connector = $connector;
return static::$connections[$connection]; $this->pdo = $this->connector->connect($this->config);
} }
/** /**
...@@ -38,12 +51,11 @@ class DB { ...@@ -38,12 +51,11 @@ class DB {
* *
* @param string $sql * @param string $sql
* @param array $bindings * @param array $bindings
* @param string $connection
* @return object * @return object
*/ */
public static function first($sql, $bindings = array(), $connection = null) public function first($sql, $bindings = array())
{ {
return (count($results = static::query($sql, $bindings, $connection)) > 0) ? $results[0] : null; return (count($results = $this->query($sql, $bindings)) > 0) ? $results[0] : null;
} }
/** /**
...@@ -58,12 +70,11 @@ class DB { ...@@ -58,12 +70,11 @@ class DB {
* *
* @param string $sql * @param string $sql
* @param array $bindings * @param array $bindings
* @param string $connection
* @return array * @return array
*/ */
public static function query($sql, $bindings = array(), $connection = null) public function query($sql, $bindings = array())
{ {
$query = static::connection($connection)->prepare($sql); $query = $this->pdo->prepare($sql);
$result = $query->execute($bindings); $result = $query->execute($bindings);
...@@ -84,44 +95,44 @@ class DB { ...@@ -84,44 +95,44 @@ class DB {
/** /**
* Begin a fluent query against a table. * Begin a fluent query against a table.
* *
* This method is simply a convenient shortcut into Query::table.
*
* @param string $table * @param string $table
* @param string $connection
* @return Query * @return Query
*/ */
public static function table($table, $connection = null) public function table($table)
{ {
return new DB\Query($table, $connection); return new Query($table, $this);
} }
/** /**
* Get the driver name for a database connection. * Get the keyword identifier wrapper for the connection.
* *
* @param string $connection
* @return string * @return string
*/ */
public static function driver($connection = null) public function wrapper()
{ {
return static::connection($connection)->getAttribute(\PDO::ATTR_DRIVER_NAME); if (array_key_exists('wrap', $this->config) and $this->config['wrap'] === false) return '';
return ($this->driver() == 'mysql') ? '`' : '"';
} }
/** /**
* Get the table prefix for a database connection. * Get the driver name for the database connection.
* *
* @param string $connection
* @return string * @return string
*/ */
public static function prefix($connection = null) public function driver()
{
$connections = Config::get('db.connections');
if (is_null($connection))
{ {
$connection = Config::get('db.default'); return $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
} }
return (array_key_exists('prefix', $connections[$connection])) ? $connections[$connection]['prefix'] : ''; /**
* Get the table prefix for the database connection.
*
* @return string
*/
public function prefix()
{
return (array_key_exists('prefix', $this->config)) ? $this->config['prefix'] : '';
} }
} }
\ No newline at end of file
...@@ -9,7 +9,7 @@ class Connector { ...@@ -9,7 +9,7 @@ class Connector {
* *
* @var array * @var array
*/ */
public static $options = array( public $options = array(
\PDO::ATTR_CASE => \PDO::CASE_LOWER, \PDO::ATTR_CASE => \PDO::CASE_LOWER,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL, \PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL,
...@@ -20,24 +20,22 @@ class Connector { ...@@ -20,24 +20,22 @@ class Connector {
/** /**
* Establish a PDO database connection. * Establish a PDO database connection.
* *
* @param string $connection * @param object $connection
* @return PDO * @return PDO
*/ */
public static function connect($connection) public function connect($config)
{ {
$config = static::configuration($connection);
switch ($config->driver) switch ($config->driver)
{ {
case 'sqlite': case 'sqlite':
return static::connect_to_sqlite($config); return $this->connect_to_sqlite($config);
case 'mysql': case 'mysql':
case 'pgsql': case 'pgsql':
return static::connect_to_server($config); return $this->connect_to_server($config);
default: default:
return static::connect_to_generic($config); return $this->connect_to_generic($config);
} }
throw new \Exception('Database driver '.$config->driver.' is not supported.'); throw new \Exception('Database driver '.$config->driver.' is not supported.');
...@@ -47,20 +45,25 @@ class Connector { ...@@ -47,20 +45,25 @@ class Connector {
* Establish a PDO connection to a SQLite database. * Establish a PDO connection to a SQLite database.
* *
* SQLite database paths can be specified either relative to the application/db * SQLite database paths can be specified either relative to the application/db
* directory, or as an absolute path to any location on the file system. * directory, or as an absolute path to any location on the file system. In-memory
* databases are also supported.
* *
* @param object $config * @param object $config
* @return PDO * @return PDO
*/ */
private static function connect_to_sqlite($config) private function connect_to_sqlite($config)
{
if ($config->database == ':memory:')
{ {
if (file_exists($path = DATABASE_PATH.$config->database.'.sqlite')) 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, static::$options); return new \PDO('sqlite:'.$path, null, null, $this->options);
} }
elseif (file_exists($config->database)) elseif (file_exists($config->database))
{ {
return new \PDO('sqlite:'.$config->database, null, null, static::$options); return new \PDO('sqlite:'.$config->database, null, null, $this->options);
} }
else else
{ {
...@@ -74,7 +77,7 @@ class Connector { ...@@ -74,7 +77,7 @@ class Connector {
* @param object $config * @param object $config
* @return PDO * @return PDO
*/ */
private static function connect_to_server($config) private function connect_to_server($config)
{ {
$dsn = $config->driver.':host='.$config->host.';dbname='.$config->database; $dsn = $config->driver.':host='.$config->host.';dbname='.$config->database;
...@@ -83,7 +86,7 @@ class Connector { ...@@ -83,7 +86,7 @@ class Connector {
$dsn .= ';port='.$config->port; $dsn .= ';port='.$config->port;
} }
$connection = new \PDO($dsn, $config->username, $config->password, static::$options); $connection = new \PDO($dsn, $config->username, $config->password, $this->options);
if (isset($config->charset)) if (isset($config->charset))
{ {
...@@ -99,27 +102,9 @@ class Connector { ...@@ -99,27 +102,9 @@ class Connector {
* @param object $config * @param object $config
* @return PDO * @return PDO
*/ */
private static function connect_to_generic($config) private function connect_to_generic($config)
{ {
return new \PDO($config->driver.':'.$config->dsn, $config->username, $config->password, static::$options); return new \PDO($config->driver.':'.$config->dsn, $config->username, $config->password, $this->options);
}
/**
* Get the configuration options for a database connection.
*
* @param string $connection
* @return object
*/
private static function configuration($connection)
{
$config = Config::get('db.connections');
if ( ! array_key_exists($connection, $config))
{
throw new \Exception("Database connection [$connection] is not defined.");
}
return (object) $config[$connection];
} }
} }
\ No newline at end of file
<?php namespace System\DB\Eloquent; <?php namespace System\DB\Eloquent;
use System\DB\Eloquent;
class Hydrator { class Hydrator {
/** /**
* Load the array of hydrated models and their eager relationships. * Load the array of hydrated models and their eager relationships.
* *
* @param object $eloquent * @param Model $eloquent
* @return array * @return array
*/ */
public static function hydrate($eloquent) public static function hydrate($eloquent)
...@@ -68,8 +66,6 @@ class Hydrator { ...@@ -68,8 +66,6 @@ class Hydrator {
*/ */
private static function eagerly($eloquent, &$parents, $include) private static function eagerly($eloquent, &$parents, $include)
{ {
// Get the relationship Eloquent model.
//
// We temporarily spoof the belongs_to key to allow the query to be fetched without // We temporarily spoof the belongs_to key to allow the query to be fetched without
// any problems, since the belongs_to method actually gets the attribute. // any problems, since the belongs_to method actually gets the attribute.
$eloquent->attributes[$spoof = $include.'_id'] = 0; $eloquent->attributes[$spoof = $include.'_id'] = 0;
...@@ -79,9 +75,7 @@ class Hydrator { ...@@ -79,9 +75,7 @@ class Hydrator {
unset($eloquent->attributes[$spoof]); unset($eloquent->attributes[$spoof]);
// Reset the WHERE clause and bindings on the query. We'll add our own WHERE clause soon. // Reset the WHERE clause and bindings on the query. We'll add our own WHERE clause soon.
$relationship->query->where = 'WHERE 1 = 1'; $relationship->query->reset_where();
$relationship->query->bindings = array();
// Initialize the relationship attribute on the parents. As expected, "many" relationships // Initialize the relationship attribute on the parents. As expected, "many" relationships
// are initialized to an array and "one" relationships are initialized to null. // are initialized to an array and "one" relationships are initialized to null.
...@@ -90,21 +84,13 @@ class Hydrator { ...@@ -90,21 +84,13 @@ class Hydrator {
$parent->ignore[$include] = (in_array($eloquent->relating, array('has_many', 'has_and_belongs_to_many'))) ? array() : null; $parent->ignore[$include] = (in_array($eloquent->relating, array('has_many', 'has_and_belongs_to_many'))) ? array() : null;
} }
if ($eloquent->relating == 'has_one') if (in_array($relating = $eloquent->relating, array('has_one', 'has_many', 'belongs_to')))
{
static::eagerly_load_one($relationship, $parents, $eloquent->relating_key, $include);
}
elseif ($eloquent->relating == 'has_many')
{
static::eagerly_load_many($relationship, $parents, $eloquent->relating_key, $include);
}
elseif ($eloquent->relating == 'belongs_to')
{ {
static::eagerly_load_belonging($relationship, $parents, $eloquent->relating_key, $include); return static::$relating($relationship, $parents, $eloquent->relating_key, $include);
} }
else else
{ {
static::eagerly_load_many_to_many($relationship, $parents, $eloquent->relating_key, $eloquent->relating_table, $include); static::has_and_belongs_to_many($relationship, $parents, $eloquent->relating_key, $eloquent->relating_table, $include);
} }
} }
...@@ -118,7 +104,7 @@ class Hydrator { ...@@ -118,7 +104,7 @@ class Hydrator {
* @param string $include * @param string $include
* @return void * @return void
*/ */
private static function eagerly_load_one($relationship, &$parents, $relating_key, $include) private static function has_one($relationship, &$parents, $relating_key, $include)
{ {
foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child) foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child)
{ {
...@@ -136,7 +122,7 @@ class Hydrator { ...@@ -136,7 +122,7 @@ class Hydrator {
* @param string $include * @param string $include
* @return void * @return void
*/ */
private static function eagerly_load_many($relationship, &$parents, $relating_key, $include) private static function has_many($relationship, &$parents, $relating_key, $include)
{ {
foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child) foreach ($relationship->where_in($relating_key, array_keys($parents))->get() as $key => $child)
{ {
...@@ -153,7 +139,7 @@ class Hydrator { ...@@ -153,7 +139,7 @@ class Hydrator {
* @param string $include * @param string $include
* @return void * @return void
*/ */
private static function eagerly_load_belonging($relationship, &$parents, $relating_key, $include) private static function belongs_to($relationship, &$parents, $relating_key, $include)
{ {
$keys = array(); $keys = array();
...@@ -184,14 +170,17 @@ class Hydrator { ...@@ -184,14 +170,17 @@ class Hydrator {
* *
* @return void * @return void
*/ */
private static function eagerly_load_many_to_many($relationship, &$parents, $relating_key, $relating_table, $include) 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->select = null;
$relationship->query->where_in($relating_table.'.'.$relating_key, array_keys($parents)); $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. // The foreign key is added to the select to allow us to easily match the models back to their parents.
$children = $relationship->query->get(array(Eloquent::table(get_class($relationship)).'.*', $relating_table.'.'.$relating_key)); // 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); $class = get_class($relationship);
......
<?php namespace System\DB;
use System\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.
*
* @param string $connection
* @return Connection
*/
public static function connection($connection = null)
{
if (is_null($connection))
{
$connection = Config::get('db.default');
}
if ( ! array_key_exists($connection, static::$connections))
{
$config = Config::get('db.connections');
if ( ! array_key_exists($connection, $config))
{
throw new \Exception("Database connection [$connection] is not defined.");
}
static::$connections[$connection] = new Connection($connection, (object) $config[$connection], new Connector);
}
return static::$connections[$connection];
}
/**
* Begin a fluent query against a table.
*
* @param string $table
* @param string $connection
* @return Query
*/
public static function table($table, $connection = null)
{
return static::connection($connection)->table($table);
}
/**
* Magic Method for calling methods on the default database connection.
*/
public static function __callStatic($method, $parameters)
{
return call_user_func_array(array(static::connection(), $method), $parameters);
}
}
\ No newline at end of file
This diff is collapsed.
<?php namespace System\DB\Query;
class Compiler {
/**
* Build a SQL SELECT statement.
*
* @param Query $query
* @return string
*/
public static function select($query)
{
$sql = $query->select.' '.$query->from.' '.$query->where;
if (count($query->orderings) > 0)
{
$sql .= ' ORDER BY '.implode(', ', $query->orderings);
}
if ( ! is_null($query->limit))
{
$sql .= ' LIMIT '.$query->limit;
}
if ( ! is_null($query->offset))
{
$sql .= ' OFFSET '.$query->offset;
}
return $sql;
}
/**
* Build a SQL INSERT statement.
*
* @param Query $query
* @param array $values
* @return string
*/
public static function insert($query, $values)
{
$sql = 'INSERT INTO '.$query->wrap($query->table);
$columns = array();
foreach (array_keys($values) as $column)
{
$columns[] = $query->wrap($column);
}
return $sql .= ' ('.implode(', ', $columns).') VALUES ('.$query->parameterize($values).')';
}
/**
* Build a SQL UPDATE statement.
*
* @param Query $query
* @param array $values
* @return string
*/
public static function update($query, $values)
{
$sql = 'UPDATE '.$query->wrap($query->table).' SET ';
$sets = array();
foreach (array_keys($values) as $column)
{
$sets[] = $query->wrap($column).' = ?';
}
return $sql .= implode(', ', $sets).' '.$query->where;
}
/**
* Build a SQL DELETE statement.
*
* @param Query $query
* @return string
*/
public static function delete($query)
{
return 'DELETE FROM '.$query->wrap($query->table).' '.$query->where;
}
}
\ No newline at end of file
<?php namespace System\DB\Query;
use System\Str;
class Dynamic {
/**
* Add conditions to a query from a dynamic method call.
*
* @param string $method
* @param array $parameters
* @param Query $query
* @return Query
*/
public static function build($method, $parameters, $query)
{
// 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_')
{
if ( ! array_key_exists($index, $parameters))
{
throw new \Exception("Wrong number of parameters for dynamic finder [$method].");
}
$query->where($segment, '=', $parameters[$index], $connector);
$index++;
}
else
{
$connector = trim(strtoupper($segment), '_');
}
}
return $query;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment