Database query builder for INSERT statements. See Query Builder for usage and examples.
Class declared in MODPATH/database/classes/Database/Query/Builder/Insert.php on line 3.
$_as_objectbool FALSE
$_columnsarray(0)
$_force_executebool FALSE
$_lifetimeNULL
$_object_paramsarray(0)
$_parametersarray(0)
$_sqlNULL
$_tableNULL
$_typeNULL
$_valuesarray(0)
Set the table and columns for an insert.
mixed
$table
= NULL - Table name or [$table, $alias] or object array
$columns
= NULL - Column names void
public function __construct($table = null, array $columns = null)
{
if ($table) {
// Set the inital table name
$this->table($table);
}
if ($columns) {
// Set the column names
$this->_columns = $columns;
}
// Start the query with no SQL
return parent::__construct(Database::INSERT, '');
}
Set the columns that will be inserted.
array
$columns
required - Column names $this
public function columns(array $columns)
{
$this->_columns = $columns;
return $this;
}
Compile the SQL query and return it.
mixed
$db
= NULL - Database instance or name of instance string
public function compile($db = null)
{
if (!is_object($db)) {
// Get the database instance
$db = Database::instance($db);
}
// Start an insertion query
$query = 'INSERT INTO ' . $db->quote_table($this->_table);
// Add the column names
$query .= ' (' . implode(', ', array_map([$db, 'quote_column'], $this->_columns)) . ') ';
if (is_array($this->_values)) {
// Callback for quoting values
$quote = [$db, 'quote'];
$groups = [];
foreach ($this->_values as $group) {
foreach ($group as $offset => $value) {
if ((is_string($value) AND array_key_exists($value, $this->_parameters)) === false) {
// Quote the value, it is not a parameter
$group[$offset] = $db->quote($value);
}
}
$groups[] = '(' . implode(', ', $group) . ')';
}
// Add the values
$query .= 'VALUES ' . implode(', ', $groups);
} else {
// Add the sub-query
$query .= (string) $this->_values;
}
$this->_sql = $query;
return parent::compile($db);
;
}
Reset the current builder status.
$this
public function reset()
{
$this->_table = null;
$this->_columns = $this->_values = [];
$this->_parameters = [];
$this->_sql = null;
return $this;
}
Use a sub-query to for the inserted values.
object
$query
required - Database_Query of SELECT type $this
public function select(Database_Query $query)
{
if ($query->type() !== Database::SELECT) {
throw new Kohana_Exception('Only SELECT queries can be combined with INSERT queries');
}
$this->_values = $query;
return $this;
}
Sets the table to insert into.
string
$table
required - Table name $this
public function table($table)
{
if (!is_string($table))
throw new Kohana_Exception('INSERT INTO syntax does not allow table aliasing');
$this->_table = $table;
return $this;
}
Adds or overwrites values. Multiple value sets can be added.
array
$values
required - Values list $this
public function values(array $values)
{
if (!is_array($this->_values)) {
throw new Kohana_Exception('INSERT INTO ... SELECT statements cannot be combined with INSERT INTO ... VALUES');
}
// Get all of the passed values
$values = func_get_args();
foreach ($values as $value) {
$this->_values[] = $value;
}
return $this;
}
Return the SQL query string.
string
public function __toString()
{
try {
// Return the SQL string
return $this->compile(Database::instance());
} catch (Exception $e) {
return Kohana_Exception::text($e);
}
}
Returns results as associative arrays
$this
public function as_assoc()
{
$this->_as_object = false;
$this->_object_params = [];
return $this;
}
Returns results as objects
string
$class
= bool TRUE - Classname or true for stdClass array
$params
= NULL - $params $this
public function as_object($class = true, array $params = null)
{
$this->_as_object = $class;
if ($params) {
// Add object parameters
$this->_object_params = $params;
}
return $this;
}
Bind a variable to a parameter in the query.
string
$param
required - Parameter key to replace byref mixed
$var
required - Variable to use $this
public function bind($param, & $var)
{
// Bind a value to a variable
$this->_parameters[$param] = & $var;
return $this;
}
Enables the query to be cached for a specified amount of time.
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 $this
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;
}
Execute the current query on the given database.
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 object
- Database_Result for SELECT queriesmixed
- The insert id for INSERT queriesinteger
- Number of affected rows for all other queriespublic 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;
}
Set the value of a parameter in the query.
string
$param
required - Parameter key to replace mixed
$value
required - Value to use $this
public function param($param, $value)
{
// Add or overload a new parameter
$this->_parameters[$param] = $value;
return $this;
}
Add multiple parameters to the query.
array
$params
required - List of parameters $this
public function parameters(array $params)
{
// Merge the new parameters in
$this->_parameters = $params + $this->_parameters;
return $this;
}
Get the type of the query.
integer
public function type()
{
return $this->_type;
}
Compiles an array of conditions into an SQL partial. Used for WHERE and HAVING.
object
$db
required - Database instance array
$conditions
required - Condition statements string
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 ((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;
}
Compiles an array of GROUP BY columns into an SQL partial.
object
$db
required - Database instance array
$columns
required - $columns string
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);
}
Compiles an array of JOIN statements into an SQL partial.
object
$db
required - Database instance array
$joins
required - Join statements string
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);
}
Compiles an array of ORDER BY statements into an SQL partial.
object
$db
required - Database instance array
$columns
required - Sorting columns string
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);
if (!in_array($direction, ['ASC', 'DESC'])) {
throw new Database_Exception('Order direction must be "ASC" or "DESC".');
}
$direction = ' ' . $direction;
}
$sort[] = $column . $direction;
}
return 'ORDER BY ' . implode(', ', $sort);
}
Compiles an array of set values into an SQL partial. Used for UPDATE.
object
$db
required - Database instance array
$values
required - Updated values string
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);
}