Database_PDO
Kohana_Database_PDO
Database
Kohana_Database

Class Contents

Class declared in MODPATH/database/classes/database/pdo.php on line 3.

Constants

SELECT
integer 1
INSERT
integer 2
UPDATE
integer 3
DELETE
integer 4

Properties

public static $default
string(7) "default"
public static $instances
array(0) 
public $last_query

Methods

protected __construct( )
Kohana_Database_PDO

Source Code
protected function __construct($name, array $config)
{
	parent::__construct($name, $config);

	if (isset($this->_config['identifier']))
	{
		// Allow the identifier to be overloaded per-connection
		$this->_identifier = (string) $this->_config['identifier'];
	}
}

public connect( )
Kohana_Database_PDO

Source Code
public function connect()
{
	if ($this->_connection)
		return;

	// Extract the connection parameters, adding required variabels
	extract($this->_config['connection'] + array(
		'dsn'        => '',
		'username'   => NULL,
		'password'   => NULL,
		'persistent' => FALSE,
	));

	// Clear the connection parameters for security
	unset($this->_config['connection']);

	// Force PDO to use exceptions for all errors
	$attrs = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

	if ( ! empty($persistent))
	{
		// Make the connection persistent
		$attrs[PDO::ATTR_PERSISTENT] = TRUE;
	}

	try
	{
		// Create a new PDO connection
		$this->_connection = new PDO($dsn, $username, $password, $attrs);
	}
	catch (PDOException $e)
	{
		throw new Database_Exception(':error', array(
				':error' => $e->getMessage(),
			),
			$e->getCode(),
			$e);
	}

	if ( ! empty($this->_config['charset']))
	{
		// Set the character set
		$this->set_charset($this->_config['charset']);
	}
}

public disconnect( )
Kohana_Database_PDO

Source Code
public function disconnect()
{
	// Destroy the PDO object
	$this->_connection = NULL;

	return TRUE;
}

public escape( )
Kohana_Database_PDO

Source Code
public function escape($value)
{
	// Make sure the database is connected
	$this->_connection or $this->connect();

	return $this->_connection->quote($value);
}

public list_columns( )
Kohana_Database_PDO

Source Code
public function list_columns($table, $like = NULL, $add_prefix = TRUE)
{
	throw new Kohana_Exception('Database method :method is not supported by :class',
		array(':method' => __FUNCTION__, ':class' => __CLASS__));
}

public list_tables( )
Kohana_Database_PDO

Source Code
public function list_tables($like = NULL)
{
	throw new Kohana_Exception('Database method :method is not supported by :class',
		array(':method' => __FUNCTION__, ':class' => __CLASS__));
}

public query( )
Kohana_Database_PDO

Source Code
public function query($type, $sql, $as_object = FALSE, array $params = NULL)
{
	// Make sure the database is connected
	$this->_connection or $this->connect();

	if ( ! empty($this->_config['profiling']))
	{
		// Benchmark this query for the current instance
		$benchmark = Profiler::start("Database ({$this->_instance})", $sql);
	}

	try
	{
		$result = $this->_connection->query($sql);
	}
	catch (Exception $e)
	{
		if (isset($benchmark))
		{
			// This benchmark is worthless
			Profiler::delete($benchmark);
		}

		// Convert the exception in a database exception
		throw new Database_Exception(':error [ :query ]', array(
				':error' => $e->getMessage(),
				':query' => $sql
			),
			$e->getCode(),
			$e);
	}

	if (isset($benchmark))
	{
		Profiler::stop($benchmark);
	}

	// Set the last query
	$this->last_query = $sql;

	if ($type === Database::SELECT)
	{
		// Convert the result into an array, as PDOStatement::rowCount is not reliable
		if ($as_object === FALSE)
		{
			$result->setFetchMode(PDO::FETCH_ASSOC);
		}
		elseif (is_string($as_object))
		{
			$result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params);
		}
		else
		{
			$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
		}

		$result = $result->fetchAll();

		// Return an iterator of results
		return new Database_Result_Cached($result, $sql, $as_object, $params);
	}
	elseif ($type === Database::INSERT)
	{
		// Return a list of insert id and rows created
		return array(
			$this->_connection->lastInsertId(),
			$result->rowCount(),
		);
	}
	else
	{
		// Return the number of rows affected
		return $result->rowCount();
	}
}

public set_charset( )
Kohana_Database_PDO

Source Code
public function set_charset($charset)
{
	// Make sure the database is connected
	$this->_connection or $this->connect();

	// Execute a raw SET NAMES query
	$this->_connection->exec('SET NAMES '.$this->quote($charset));
}

final public __destruct( )
Kohana_Database

Source Code
final public function __destruct()
{
	$this->disconnect();
}

final public __toString( )
Kohana_Database

Source Code
final public function __toString()
{
	return $this->_instance;
}

protected _parse_type( )
Kohana_Database

Source Code
protected function _parse_type($type)
{
	if (($open = strpos($type, '(')) === FALSE)
	{
		// No length specified
		return array($type, NULL);
	}

	// Closing parenthesis
	$close = strpos($type, ')', $open);

	// Length without parentheses
	$length = substr($type, $open + 1, $close - 1 - $open);

	// Type without the length
	$type = substr($type, 0, $open).substr($type, $close + 1);

	return array($type, $length);
}

public count_last_query( )
Kohana_Database

Source Code
public function count_last_query()
{
	if ($sql = $this->last_query)
	{
		$sql = trim($sql);
		if (stripos($sql, 'SELECT') !== 0)
		{
			return FALSE;
		}

		if (stripos($sql, 'LIMIT') !== FALSE)
		{
			// Remove LIMIT from the SQL
			$sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql);
		}

		if (stripos($sql, 'OFFSET') !== FALSE)
		{
			// Remove OFFSET from the SQL
			$sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql);
		}

		// Get the total rows from the last query executed
		$result = $this->query
		(
			Database::SELECT,
			'SELECT COUNT(*) AS '.$this->quote_identifier('total_rows').' '
			.'FROM ('.$sql.') AS '.$this->quote_table('counted_results'),
			TRUE
		);

		// Return the total number of rows from the query
		return (int) $result->current()->total_rows;
	}

	return FALSE;
}

public count_records( )
Kohana_Database

Source Code
public function count_records($table)
{
	// Quote the table name
	$table = $this->quote_identifier($table);

	return $this->query(Database::SELECT, 'SELECT COUNT(*) AS total_row_count FROM '.$table, FALSE)
		->get('total_row_count');
}

public datatype( )
Kohana_Database

Source Code
public function datatype($type)
{
	static $types = array
	(
		// SQL-92
		'bit'                           => array('type' => 'string', 'exact' => TRUE),
		'bit varying'                   => array('type' => 'string'),
		'char'                          => array('type' => 'string', 'exact' => TRUE),
		'char varying'                  => array('type' => 'string'),
		'character'                     => array('type' => 'string', 'exact' => TRUE),
		'character varying'             => array('type' => 'string'),
		'date'                          => array('type' => 'string'),
		'dec'                           => array('type' => 'float', 'exact' => TRUE),
		'decimal'                       => array('type' => 'float', 'exact' => TRUE),
		'double precision'              => array('type' => 'float'),
		'float'                         => array('type' => 'float'),
		'int'                           => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'),
		'integer'                       => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'),
		'interval'                      => array('type' => 'string'),
		'national char'                 => array('type' => 'string', 'exact' => TRUE),
		'national char varying'         => array('type' => 'string'),
		'national character'            => array('type' => 'string', 'exact' => TRUE),
		'national character varying'    => array('type' => 'string'),
		'nchar'                         => array('type' => 'string', 'exact' => TRUE),
		'nchar varying'                 => array('type' => 'string'),
		'numeric'                       => array('type' => 'float', 'exact' => TRUE),
		'real'                          => array('type' => 'float'),
		'smallint'                      => array('type' => 'int', 'min' => '-32768', 'max' => '32767'),
		'time'                          => array('type' => 'string'),
		'time with time zone'           => array('type' => 'string'),
		'timestamp'                     => array('type' => 'string'),
		'timestamp with time zone'      => array('type' => 'string'),
		'varchar'                       => array('type' => 'string'),

		// SQL:1999
		'binary large object'               => array('type' => 'string', 'binary' => TRUE),
		'blob'                              => array('type' => 'string', 'binary' => TRUE),
		'boolean'                           => array('type' => 'bool'),
		'char large object'                 => array('type' => 'string'),
		'character large object'            => array('type' => 'string'),
		'clob'                              => array('type' => 'string'),
		'national character large object'   => array('type' => 'string'),
		'nchar large object'                => array('type' => 'string'),
		'nclob'                             => array('type' => 'string'),
		'time without time zone'            => array('type' => 'string'),
		'timestamp without time zone'       => array('type' => 'string'),

		// SQL:2003
		'bigint'    => array('type' => 'int', 'min' => '-9223372036854775808', 'max' => '9223372036854775807'),

		// SQL:2008
		'binary'            => array('type' => 'string', 'binary' => TRUE, 'exact' => TRUE),
		'binary varying'    => array('type' => 'string', 'binary' => TRUE),
		'varbinary'         => array('type' => 'string', 'binary' => TRUE),
	);

	if (isset($types[$type]))
		return $types[$type];

	return array();
}

public static instance( )
Kohana_Database

Source Code
public static function instance($name = NULL, array $config = NULL)
{
	if ($name === NULL)
	{
		// Use the default instance name
		$name = Database::$default;
	}

	if ( ! isset(Database::$instances[$name]))
	{
		if ($config === NULL)
		{
			// Load the configuration for this database
			$config = Kohana::config('database')->$name;
		}

		if ( ! isset($config['type']))
		{
			throw new Kohana_Exception('Database type not defined in :name configuration',
				array(':name' => $name));
		}

		// Set the driver class name
		$driver = 'Database_'.ucfirst($config['type']);

		// Create the database connection instance
		new $driver($name, $config);
	}

	return Database::$instances[$name];
}

public quote( )
Kohana_Database

Source Code
public function quote($value)
{
	if ($value === NULL)
	{
		return 'NULL';
	}
	elseif ($value === TRUE)
	{
		return "'1'";
	}
	elseif ($value === FALSE)
	{
		return "'0'";
	}
	elseif (is_object($value))
	{
		if ($value instanceof Database_Query)
		{
			// Create a sub-query
			return '('.$value->compile($this).')';
		}
		elseif ($value instanceof Database_Expression)
		{
			// Use a raw expression
			return $value->value();
		}
		else
		{
			// Convert the object to a string
			return $this->quote( (string) $value);
		}
	}
	elseif (is_array($value))
	{
		return '('.implode(', ', array_map(array($this, __FUNCTION__), $value)).')';
	}
	elseif (is_int($value))
	{
		return (int) $value;
	}
	elseif (is_float($value))
	{
		// Convert to non-locale aware float to prevent possible commas
		return sprintf('%F', $value);
	}

	return $this->escape($value);
}

public quote_identifier( )
Kohana_Database

Source Code
public function quote_identifier($value)
{
	if ($value === '*')
	{
		return $value;
	}
	elseif (is_object($value))
	{
		if ($value instanceof Database_Query)
		{
			// Create a sub-query
			return '('.$value->compile($this).')';
		}
		elseif ($value instanceof Database_Expression)
		{
			// Use a raw expression
			return $value->value();
		}
		else
		{
			// Convert the object to a string
			return $this->quote_identifier( (string) $value);
		}
	}
	elseif (is_array($value))
	{
		// Separate the column and alias
		list ($value, $alias) = $value;

		return $this->quote_identifier($value).' AS '.$this->quote_identifier($alias);
	}

	if (strpos($value, '"') !== FALSE)
	{
		// Quote the column in FUNC("ident") identifiers
		return preg_replace('/"(.+?)"/e', '$this->quote_identifier("$1")', $value);
	}
	elseif (strpos($value, '.') !== FALSE)
	{
		// Split the identifier into the individual parts
		$parts = explode('.', $value);

		if ($prefix = $this->table_prefix())
		{
			// Get the offset of the table name, 2nd-to-last part
			// This works for databases that can have 3 identifiers (Postgre)
			$offset = count($parts) - 2;

			// Add the table prefix to the table name
			$parts[$offset] = $prefix.$parts[$offset];
		}

		// Quote each of the parts
		return implode('.', array_map(array($this, __FUNCTION__), $parts));
	}
	else
	{
		return $this->_identifier.$value.$this->_identifier;
	}
}

public quote_table( )
Kohana_Database

Source Code
public function quote_table($value)
{
	// Assign the table by reference from the value
	if (is_array($value))
	{
		$table =& $value[0];

		// Attach table prefix to alias
		$value[1] = $this->table_prefix().$value[1];
	}
	else
	{
		$table =& $value;
	}

	if (is_string($table) AND strpos($table, '.') === FALSE)
	{
		// Add the table prefix for tables
		$table = $this->table_prefix().$table;
	}

	return $this->quote_identifier($value);
}

public table_prefix( )
Kohana_Database

Source Code
public function table_prefix()
{
	return $this->_config['table_prefix'];
}