Class Kohana_Database_Query_Builder_Join

Kohana_Database_Query_Builder_Join

extends Database_Query_Builder
extends Kohana_Database_Query_Builder
extends Database_Query
extends Kohana_Database_Query

Database query builder for JOIN statements. See Query Builder for usage and examples.

package
Kohana/Database
category
Query
author
Kohana Team
copyright
(c) Kohana Team
license
https://koseven.ga/LICENSE.md


Properties

protected $_as_object

Default value:
bool FALSE

protected $_force_execute

Default value:
bool FALSE

protected $_lifetime

Default value:
NULL

protected $_object_params

Default value:
array(0) 

protected $_on

Default value:
array(0) 

protected $_parameters

Default value:
array(0) 

protected $_sql

Default value:
NULL

protected $_table

Default value:
NULL

protected $_type

Default value:
NULL

protected $_using

Default value:
array(0) 

Methods

public __construct(mixed $table [, string $type = NULL ] ) (defined in Kohana_Database_Query_Builder_Join)

Creates a new JOIN statement for a table. Optionally, the type of JOIN can be specified as the second parameter.

Parameters

  • mixed $table required - Column name or array($column, $alias) or object
  • string $type = NULL - Type of JOIN: INNER, RIGHT, LEFT, etc

Return Values

  • void

Source Code

public function __construct($table, $type = NULL)
{
	// Set the table to JOIN on
	$this->_table = $table;

	if ($type !== NULL)
	{
		// Set the JOIN type
		$this->_type = (string) $type;
	}
}

public compile([ mixed $db = NULL ] ) (defined in Kohana_Database_Query_Builder_Join)

Compile the SQL partial for a JOIN statement and return it.

Parameters

  • mixed $db = NULL - Database instance or name of instance

Return Values

  • string

Source Code

public function compile($db = NULL)
{
	if ( ! is_object($db))
	{
		// Get the database instance
		$db = Database::instance($db);
	}

	if ($this->_type)
	{
		$sql = strtoupper($this->_type).' JOIN';
	}
	else
	{
		$sql = 'JOIN';
	}

	// Quote the table name that is being joined
	$sql .= ' '.$db->quote_table($this->_table);

	if ( ! empty($this->_using))
	{
		// Quote and concat the columns
		$sql .= ' USING ('.implode(', ', array_map([$db, 'quote_column'], $this->_using)).')';
	}
	else
	{
		$conditions = [];
		foreach ($this->_on as $condition)
		{
			// Split the condition
			list($c1, $op, $c2) = $condition;

			if ($op)
			{
				// Make the operator uppercase and spaced
				$op = ' '.strtoupper($op);
			}

			// Quote each of the columns used for the condition
			$conditions[] = $db->quote_column($c1).$op.' '.$db->quote_column($c2);
		}

		// Concat the conditions "... AND ..."
		$sql .= ' ON ('.implode(' AND ', $conditions).')';
	}

	return $sql;
}

public on(mixed $c1 , string $op , mixed $c2 ) (defined in Kohana_Database_Query_Builder_Join)

Adds a new condition for joining.

Parameters

  • mixed $c1 required - Column name or array($column, $alias) or object
  • string $op required - Logic operator
  • mixed $c2 required - Column name or array($column, $alias) or object

Return Values

  • $this

Source Code

public function on($c1, $op, $c2)
{
	if ( ! empty($this->_using))
	{
		throw new Kohana_Exception('JOIN ... ON ... cannot be combined with JOIN ... USING ...');
	}

	$this->_on[] = [$c1, $op, $c2];

	return $this;
}

public reset() (defined in Kohana_Database_Query_Builder_Join)

Reset the current builder status.

Return Values

  • $this

Source Code

public function reset()
{
	$this->_type =
	$this->_table = NULL;

	$this->_on = [];
}

public using(string $columns ) (defined in Kohana_Database_Query_Builder_Join)

Adds a new condition for joining.

Parameters

  • string $columns required - Column name

Return Values

  • $this

Source Code

public function using($columns)
{
	if ( ! empty($this->_on))
	{
		throw new Kohana_Exception('JOIN ... ON ... cannot be combined with JOIN ... USING ...');
	}

	$columns = func_get_args();

	$this->_using = array_merge($this->_using, $columns);

	return $this;
}

public __toString() (defined in Kohana_Database_Query)

Return the SQL query string.

Return Values

  • string

Source Code

public function __toString()
{
	try
	{
		// Return the SQL string
		return $this->compile(Database::instance());
	}
	catch (Exception $e)
	{
		return Kohana_Exception::text($e);
	}
}

public as_assoc() (defined in Kohana_Database_Query)

Returns results as associative arrays

Return Values

  • $this

Source Code

public function as_assoc()
{
	$this->_as_object = FALSE;

	$this->_object_params = [];

	return $this;
}

public as_object([ string $class = bool TRUE , array $params = NULL ] ) (defined in Kohana_Database_Query)

Returns results as objects

Parameters

  • string $class = bool TRUE - Classname or TRUE for stdClass
  • array $params = NULL - $params

Return Values

  • $this

Source Code

public function as_object($class = TRUE, array $params = NULL)
{
	$this->_as_object = $class;

	if ($params)
	{
		// Add object parameters
		$this->_object_params = $params;
	}

	return $this;
}

public bind(string $param , mixed & $var ) (defined in Kohana_Database_Query)

Bind a variable to a parameter in the query.

Parameters

  • string $param required - Parameter key to replace
  • byref mixed $var required - Variable to use

Return Values

  • $this

Source Code

public function bind($param, & $var)
{
	// Bind a value to a variable
	$this->_parameters[$param] =& $var;

	return $this;
}

public cached([ integer $lifetime = NULL , boolean $force = bool FALSE ] ) (defined in Kohana_Database_Query)

Enables the query to be cached for a specified amount of time.

Parameters

  • integer $lifetime = NULL - Number of seconds to cache, 0 deletes it from the cache
  • boolean $force = bool FALSE - Whether or not to execute the query during a cache hit

Tags

Return Values

  • $this

Source Code

public function cached($lifetime = NULL, $force = FALSE)
{
	if ($lifetime === NULL)
	{
		// Use the global setting
		$lifetime = Kohana::$cache_life;
	}

	$this->_force_execute = $force;
	$this->_lifetime = $lifetime;

	return $this;
}

public execute([ mixed $db = NULL , string $as_object = NULL , array $object_params = NULL ] ) (defined in Kohana_Database_Query)

Execute the current query on the given database.

Parameters

  • mixed $db = NULL - Database instance or name of instance
  • string $as_object = NULL - Result object classname, TRUE for stdClass or FALSE for array
  • array $object_params = NULL - Result object constructor arguments

Return Values

  • object - Database_Result for SELECT queries
  • mixed - The insert id for INSERT queries
  • integer - Number of affected rows for all other queries

Source Code

public function execute($db = NULL, $as_object = NULL, $object_params = NULL)
{
	if ( ! is_object($db))
	{
		// Get the database instance
		$db = Database::instance($db);
	}

	if ($as_object === NULL)
	{
		$as_object = $this->_as_object;
	}

	if ($object_params === NULL)
	{
		$object_params = $this->_object_params;
	}

	// Compile the SQL query
	$sql = $this->compile($db);

	if ($this->_lifetime !== NULL AND $this->_type === Database::SELECT)
	{
		// Set the cache key based on the database instance name and SQL
		$cache_key = 'Database::query("'.$db.'", "'.$sql.'")';

		// Read the cache first to delete a possible hit with lifetime <= 0
		if (($result = Kohana::cache($cache_key, NULL, $this->_lifetime)) !== NULL
			AND ! $this->_force_execute)
		{
			// Return a cached result
			return new Database_Result_Cached($result, $sql, $as_object, $object_params);
		}
	}

	// Execute the query
	$result = $db->query($this->_type, $sql, $as_object, $object_params);

	if (isset($cache_key) AND $this->_lifetime > 0)
	{
		// Cache the result array
		Kohana::cache($cache_key, $result->as_array(), $this->_lifetime);
	}

	return $result;
}

public param(string $param , mixed $value ) (defined in Kohana_Database_Query)

Set the value of a parameter in the query.

Parameters

  • string $param required - Parameter key to replace
  • mixed $value required - Value to use

Return Values

  • $this

Source Code

public function param($param, $value)
{
	// Add or overload a new parameter
	$this->_parameters[$param] = $value;

	return $this;
}

public parameters(array $params ) (defined in Kohana_Database_Query)

Add multiple parameters to the query.

Parameters

  • array $params required - List of parameters

Return Values

  • $this

Source Code

public function parameters(array $params)
{
	// Merge the new parameters in
	$this->_parameters = $params + $this->_parameters;

	return $this;
}

public type() (defined in Kohana_Database_Query)

Get the type of the query.

Return Values

  • integer

Source Code

public function type()
{
	return $this->_type;
}

protected _compile_conditions(object $db , array $conditions ) (defined in Kohana_Database_Query_Builder)

Compiles an array of conditions into an SQL partial. Used for WHERE and HAVING.

Parameters

  • object $db required - Database instance
  • array $conditions required - Condition statements

Return Values

  • string

Source Code

protected function _compile_conditions(Database $db, array $conditions)
{
	$last_condition = NULL;

	$sql = '';
	foreach ($conditions as $group)
	{
		// Process groups of conditions
		foreach ($group as $logic => $condition)
		{
			if ($condition === '(')
			{
				if ( ! empty($sql) AND $last_condition !== '(')
				{
					// Include logic operator
					$sql .= ' '.$logic.' ';
				}

				$sql .= '(';
			}
			elseif ($condition === ')')
			{
				$sql .= ')';
			}
			else
			{
				if ( ! empty($sql) AND $last_condition !== '(')
				{
					// Add the logic operator
					$sql .= ' '.$logic.' ';
				}

				// Split the condition
				list($column, $op, $value) = $condition;

				if ($value === NULL)
				{
					if ($op === '=')
					{
						// Convert "val = NULL" to "val IS NULL"
						$op = 'IS';
					}
					elseif ($op === '!=' OR $op === '<>')
					{
						// Convert "val != NULL" to "valu IS NOT NULL"
						$op = 'IS NOT';
					}
				}

				// Database operators are always uppercase
				$op = strtoupper($op);

				if ($op === 'BETWEEN' AND is_array($value))
				{
					// BETWEEN always has exactly two arguments
					list($min, $max) = $value;

					if ((is_string($min) AND array_key_exists($min, $this->_parameters)) === FALSE)
					{
						// Quote the value, it is not a parameter
						$min = $db->quote($min);
					}

					if ((is_string($max) AND array_key_exists($max, $this->_parameters)) === FALSE)
					{
						// Quote the value, it is not a parameter
						$max = $db->quote($max);
					}

					// Quote the min and max value
					$value = $min.' AND '.$max;
				}
				elseif ($op === 'IN' AND is_array($value) AND count($value) === 0)
				{
					$value = '(NULL)';
				}
				elseif ((is_string($value) AND array_key_exists($value, $this->_parameters)) === FALSE)
				{
					// Quote the value, it is not a parameter
					$value = $db->quote($value);
				}

				if ($column)
				{
					if (is_array($column))
					{
						// Use the column name
						$column = $db->quote_identifier(reset($column));
					}
					else
					{
						// Apply proper quoting to the column
						$column = $db->quote_column($column);
					}
				}

				// Append the statement to the query
				$sql .= trim($column.' '.$op.' '.$value);
			}

			$last_condition = $condition;
		}
	}

	return $sql;
}

protected _compile_group_by(object $db , array $columns ) (defined in Kohana_Database_Query_Builder)

Compiles an array of GROUP BY columns into an SQL partial.

Parameters

  • object $db required - Database instance
  • array $columns required - $columns

Return Values

  • string

Source Code

protected function _compile_group_by(Database $db, array $columns)
{
	$group = [];

	foreach ($columns as $column)
	{
		if (is_array($column))
		{
			// Use the column alias
			$column = $db->quote_identifier(end($column));
		}
		else
		{
			// Apply proper quoting to the column
			$column = $db->quote_column($column);
		}

		$group[] = $column;
	}

	return 'GROUP BY '.implode(', ', $group);
}

protected _compile_join(object $db , array $joins ) (defined in Kohana_Database_Query_Builder)

Compiles an array of JOIN statements into an SQL partial.

Parameters

  • object $db required - Database instance
  • array $joins required - Join statements

Return Values

  • string

Source Code

protected function _compile_join(Database $db, array $joins)
{
	$statements = [];

	foreach ($joins as $join)
	{
		// Compile each of the join statements
		$statements[] = $join->compile($db);
	}

	return implode(' ', $statements);
}

protected _compile_order_by(Database $db , array $columns ) (defined in Kohana_Database_Query_Builder)

Compiles an array of ORDER BY statements into an SQL partial.

Parameters

  • Database $db required - Database instance
  • array $columns required - Sorting columns

Tags

Return Values

  • string

Source Code

protected function _compile_order_by(Database $db, array $columns)
{
	$sort = [];
	foreach ($columns as $group)
	{
		list ($column, $direction) = $group;

		if (is_array($column))
		{
			// Use the column alias
			$column = $db->quote_identifier(end($column));
		}
		else
		{
			// Apply proper quoting to the column
			$column = $db->quote_column($column);
		}

		if ($direction)
		{
			// Make the direction uppercase
			$direction = ' '.strtoupper($direction);

			// Make sure direction is either ASC or DESC to prevent injections
			if ( ! in_array($direction, [' ASC', ' DESC'])) {
				throw new Database_Exception('Invalid sorting direction: ' . $direction);
			}
		}

		$sort[] = $column.$direction;
	}

	return 'ORDER BY '.implode(', ', $sort);
}

protected _compile_set(object $db , array $values ) (defined in Kohana_Database_Query_Builder)

Compiles an array of set values into an SQL partial. Used for UPDATE.

Parameters

  • object $db required - Database instance
  • array $values required - Updated values

Return Values

  • string

Source Code

protected function _compile_set(Database $db, array $values)
{
	$set = [];
	foreach ($values as $group)
	{
		// Split the set
		list ($column, $value) = $group;

		// Quote the column name
		$column = $db->quote_column($column);

		if ((is_string($value) AND array_key_exists($value, $this->_parameters)) === FALSE)
		{
			// Quote the value, it is not a parameter
			$value = $db->quote($value);
		}

		$set[$column] = $column.' = '.$value;
	}

	return implode(', ', $set);
}

Do you want to contribute to Koseven?

We need YOUR help!

This project is open source. What does this mean? YOU can help:
  • Found a bug? Report it on Github
  • Need a feature? Add it Here
  • Want to help? Join the Forum
Go to Github