code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function getColumns() { return array_keys($this->assignments ?? []); }
Retrieves the list of columns updated @return array
getColumns
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLAssignmentRow.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php
BSD-3-Clause
public static function create($table = null, $assignment = [], $where = []) { return Injector::inst()->createWithArgs(__CLASS__, func_get_args()); }
Construct a new SQLUpdate object @param string $table Table name to update (ANSI quoted) @param array $assignment List of column assignments @param array $where List of where clauses @return static
create
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLUpdate.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLUpdate.php
BSD-3-Clause
function __construct($table = null, $assignment = [], $where = []) { parent::__construct(null, $where); $this->assignment = new SQLAssignmentRow(); $this->setTable($table); $this->setAssignments($assignment); }
Construct a new SQLUpdate object @param string $table Table name to update (ANSI quoted) @param array $assignment List of column assignments @param array $where List of where clauses
__construct
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLUpdate.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLUpdate.php
BSD-3-Clause
public function clear() { $this->assignment->clear(); return $this; }
Clears all currently set assignment values @return $this The self reference to this query
clear
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLUpdate.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLUpdate.php
BSD-3-Clause
public static function create($from = [], $where = [], $delete = []) { return Injector::inst()->createWithArgs(__CLASS__, func_get_args()); }
Construct a new SQLDelete. @param array|string $from An array of Tables (FROM clauses). The first one should be just the table name. Each should be ANSI quoted. @param array $where An array of WHERE clauses. @param array|string $delete The table(s) to delete, if multiple tables are queried from @return static
create
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLDelete.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLDelete.php
BSD-3-Clause
function __construct($from = [], $where = [], $delete = []) { parent::__construct($from, $where); $this->setDelete($delete); }
Construct a new SQLDelete. @param array|string $from An array of Tables (FROM clauses). The first one should be just the table name. Each should be ANSI quoted. @param array $where An array of WHERE clauses. @param array|string $delete The table(s) to delete, if multiple tables are queried from
__construct
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLDelete.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLDelete.php
BSD-3-Clause
public function getDelete() { return $this->delete; }
List of tables to limit the delete to, if multiple tables are specified in the condition clause @return array
getDelete
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLDelete.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLDelete.php
BSD-3-Clause
public function setDelete($tables) { $this->delete = []; return $this->addDelete($tables); }
Sets the list of tables to limit the delete to, if multiple tables are specified in the condition clause @param string|array $tables Escaped SQL statement, usually an unquoted table name @return $this Self reference
setDelete
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLDelete.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLDelete.php
BSD-3-Clause
function __construct($from = [], $where = []) { $this->setFrom($from); $this->setWhere($where); }
Construct a new SQLInteractExpression. @param array|string $from An array of Tables (FROM clauses). The first one should be just the table name. @param array $where An array of WHERE clauses.
__construct
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function setFrom($from) { $this->from = []; return $this->addFrom($from); }
Sets the list of tables to query from or update @example $query->setFrom('"MyTable"'); // SELECT * FROM "MyTable" @param string|array $from Single, or list of, ANSI quoted table names @return $this
setFrom
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function addFrom($from) { if (is_array($from)) { $this->from = array_merge($this->from, $from); } elseif (!empty($from)) { // Check if the from clause looks like a regular table name // Table name most be an uninterrupted string, with no spaces. // It may be padded with spaces. e.g. ` TableName ` will be // treated as Table Name, but not ` Table Name `. if (preg_match('/^\s*[^\s]+\s*$/', $from)) { // Add an alias for the table name, stripping any quotes $this->from[str_replace(['"','`'], '', $from)] = $from; } else { // Add from clause without an alias - this is probably a full // sub-select with its own explicit alias. $this->from[] = $from; } } return $this; }
Add a table to include in the query or update @example $query->addFrom('"MyTable"'); // SELECT * FROM "MyTable" @param string|array $from Single, or list of, ANSI quoted table names @return $this Self reference
addFrom
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function useDisjunction() { $this->setConnective('OR'); }
Use the disjunctive operator 'OR' to join filter expressions in the WHERE clause.
useDisjunction
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function useConjunction() { $this->setConnective('AND'); }
Use the conjunctive operator 'AND' to join filter expressions in the WHERE clause.
useConjunction
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function addLeftJoin($table, $onPredicate, $tableAlias = '', $order = 20, $parameters = []) { return $this->addJoin($table, 'LEFT', $onPredicate, $tableAlias, $order, $parameters); }
Add a LEFT JOIN criteria to the tables list. @param string $table Unquoted table name @param string $onPredicate The "ON" SQL fragment in a "LEFT JOIN ... AS ... ON ..." statement, Needs to be valid (quoted) SQL. @param string $tableAlias Optional alias which makes it easier to identify and replace joins later on @param int $order A numerical index to control the order that joins are added to the query; lower order values will cause the query to appear first. The default is 20, and joins created automatically by the ORM have a value of 10. @param array $parameters Any additional parameters if the join is a parameterized subquery @return $this Self reference
addLeftJoin
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function addRightJoin($table, $onPredicate, $tableAlias = '', $order = 20, $parameters = []) { return $this->addJoin($table, 'RIGHT', $onPredicate, $tableAlias, $order, $parameters); }
Add a RIGHT JOIN criteria to the tables list. @param string $table Unquoted table name @param string $onPredicate The "ON" SQL fragment in a "RIGHT JOIN ... AS ... ON ..." statement, Needs to be valid (quoted) SQL. @param string $tableAlias Optional alias which makes it easier to identify and replace joins later on @param int $order A numerical index to control the order that joins are added to the query; lower order values will cause the query to appear first. The default is 20, and joins created automatically by the ORM have a value of 10. @param array $parameters Any additional parameters if the join is a parameterized subquery @return $this Self reference
addRightJoin
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function addInnerJoin($table, $onPredicate, $tableAlias = null, $order = 20, $parameters = []) { return $this->addJoin($table, 'INNER', $onPredicate, $tableAlias, $order, $parameters); }
Add an INNER JOIN criteria @param string $table Unquoted table name @param string $onPredicate The "ON" SQL fragment in an "INNER JOIN ... AS ... ON ..." statement. Needs to be valid (quoted) SQL. @param string $tableAlias Optional alias which makes it easier to identify and replace joins later on @param int $order A numerical index to control the order that joins are added to the query; lower order values will cause the query to appear first. The default is 20, and joins created automatically by the ORM have a value of 10. @param array $parameters Any additional parameters if the join is a parameterized subquery @return $this Self reference
addInnerJoin
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function addFilterToJoin($table, $filter) { $this->from[$table]['filter'][] = $filter; return $this; }
Add an additional filter (part of the ON clause) on a join. @param string $table Table to join on from the original join (unquoted) @param string $filter The "ON" SQL fragment (escaped) @return $this Self reference
addFilterToJoin
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function setJoinFilter($table, $filter) { $this->from[$table]['filter'] = [$filter]; return $this; }
Set the filter (part of the ON clause) on a join. @param string $table Table to join on from the original join (unquoted) @param string $filter The "ON" SQL fragment (escaped) @return $this Self reference
setJoinFilter
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function isJoinedTo($tableAlias) { return isset($this->from[$tableAlias]); }
Returns true if we are already joining to the given table alias @param string $tableAlias Table name @return boolean
isJoinedTo
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
protected function getOrderedJoins($from) { if (count($from ?? []) <= 1) { return $from; } // Remove the regular FROM tables out so we only deal with the JOINs $regularTables = []; foreach ($from as $alias => $tableClause) { if (is_string($tableClause) && !preg_match(SQLConditionalExpression::getJoinRegex(), $tableClause)) { $regularTables[$alias] = $tableClause; unset($from[$alias]); } } // Sort the joins $this->mergesort($from, function ($firstJoin, $secondJoin) { if (!is_array($firstJoin) || !is_array($secondJoin) || $firstJoin['order'] == $secondJoin['order'] ) { return 0; } else { return ($firstJoin['order'] < $secondJoin['order']) ? -1 : 1; } }); // Put the regular FROM tables back into the results $regularTables = array_reverse($regularTables, true); foreach ($regularTables as $alias => $tableName) { if (!empty($alias) && !is_numeric($alias)) { $from = array_merge([$alias => $tableName], $from); } else { array_unshift($from, $tableName); } } return $from; }
Ensure that framework "auto-generated" table JOINs are first in the finalised SQL query. This prevents issues where developer-initiated JOINs attempt to JOIN using relations that haven't actually yet been scaffolded by the framework. Demonstrated by PostGres in errors like: "...ERROR: missing FROM-clause..." @param $from array - in the format of $this->from @return array - and reorderded list of selects
getOrderedJoins
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
protected function mergesort(&$array, $cmpFunction = 'strcmp') { // Arrays of size < 2 require no action. if (count($array ?? []) < 2) { return; } // Split the array in half $halfway = floor(count($array ?? []) / 2); $array1 = array_slice($array ?? [], 0, $halfway); $array2 = array_slice($array ?? [], $halfway ?? 0); // Recurse to sort the two halves $this->mergesort($array1, $cmpFunction); $this->mergesort($array2, $cmpFunction); // If all of $array1 is <= all of $array2, just append them. if (call_user_func($cmpFunction, end($array1), reset($array2)) < 1) { $array = array_merge($array1, $array2); return; } // Merge the two sorted arrays into a single sorted array $array = []; $val1 = reset($array1); $val2 = reset($array2); do { if (call_user_func($cmpFunction, $val1, $val2) < 1) { $array[key($array1)] = $val1; $val1 = next($array1); } else { $array[key($array2)] = $val2; $val2 = next($array2); } } while ($val1 && $val2); // Merge the remainder while ($val1) { $array[key($array1)] = $val1; $val1 = next($array1); } while ($val2) { $array[key($array2)] = $val2; $val2 = next($array2); } return; }
Since uasort don't preserve the order of an array if the comparison is equal we have to resort to a merge sort. It's quick and stable: O(n*log(n)). @see http://stackoverflow.com/q/4353739/139301 @param array $array The array to sort (by reference) @param callable|string $cmpFunction The function to use for comparison
mergesort
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function getWhereParameterised(&$parameters) { $this->splitQueryParameters($this->where, $predicates, $parameters); return $predicates; }
Return a list of WHERE clauses used internally. @param array $parameters Out variable for parameters required for this query @return array
getWhereParameterised
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function filtersOnID() { $regexp = '/^(.*\.)?("|`)?ID("|`)?\s?(=|IN)/'; foreach ($this->getWhereParameterised($parameters) as $predicate) { if (preg_match($regexp ?? '', $predicate ?? '')) { return true; } } return false; }
Checks whether this query is for a specific ID in a table @return boolean
filtersOnID
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function filtersOnFK() { $regexp = '/^(.*\.)?("|`)?[a-zA-Z]+ID("|`)?\s?(=|IN)/'; foreach ($this->getWhereParameterised($parameters) as $predicate) { if (preg_match($regexp ?? '', $predicate ?? '')) { return true; } } return false; }
Checks whether this query is filtering on a foreign key, ie finding a has_many relationship @return boolean
filtersOnFK
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function toDelete() { $delete = new SQLDelete(); $this->copyTo($delete); return $delete; }
Generates an SQLDelete object using the currently specified parameters @return SQLDelete
toDelete
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function toSelect() { $select = new SQLSelect(); $this->copyTo($select); return $select; }
Generates an SQLSelect object using the currently specified parameters. @return SQLSelect
toSelect
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function toUpdate() { $update = new SQLUpdate(); $this->copyTo($update); return $update; }
Generates an SQLUpdate object using the currently specified parameters. No fields will have any assigned values for the newly generated SQLUpdate object. @return SQLUpdate
toUpdate
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLConditionalExpression.php
BSD-3-Clause
public function replaceText($old, $new) { $this->replacementsOld[] = $old; $this->replacementsNew[] = $new; }
Swap some text in the SQL query with another. Note that values in parameters will not be replaced @param string $old The old text (escaped) @param string $new The new text (escaped)
replaceText
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLExpression.php
BSD-3-Clause
public function __toString() { try { $sql = $this->sql($parameters); if (!empty($parameters)) { $sql .= " <" . var_export($parameters, true) . ">"; } return $sql; } catch (Exception $e) { return "<sql query>"; } }
Return the generated SQL string for this query @return string
__toString
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLExpression.php
BSD-3-Clause
public function renameTable($old, $new) { $this->replaceText("`$old`", "`$new`"); $this->replaceText("\"$old\"", "\"$new\""); $this->replaceText(Convert::symbol2sql($old), Convert::symbol2sql($new)); }
Swap the use of one table with another. @param string $old Name of the old table (unquoted, escaped) @param string $new Name of the new table (unquoted, escaped)
renameTable
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLExpression.php
BSD-3-Clause
public function sql(&$parameters = []) { // Build each component as needed $sql = DB::build_sql($this, $parameters); if (empty($sql)) { return null; } if ($this->replacementsOld) { $sql = str_replace($this->replacementsOld ?? '', $this->replacementsNew ?? '', $sql ?? ''); } return $sql; }
Generate the SQL statement for this query. @param array $parameters Out variable for parameters required for this query @return string The completed SQL query
sql
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLExpression.php
BSD-3-Clause
protected function copyTo(SQLExpression $object) { $target = array_keys(get_object_vars($object)); foreach (get_object_vars($this) as $variable => $value) { if (in_array($variable, $target ?? [])) { $object->$variable = $value; } } }
Copies the query parameters contained in this object to another SQLExpression @param SQLExpression $object The object to copy properties to
copyTo
php
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLExpression.php
BSD-3-Clause
public function column($column = null) { $result = []; foreach ($this as $record) { if ($column) { $result[] = $record[$column]; } else { $result[] = $record[key($record)]; } } return $result; }
Return an array containing all the values from a specific column. If no column is set, then the first will be returned @param string $column @return array
column
php
silverstripe/silverstripe-framework
src/ORM/Connect/Query.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Query.php
BSD-3-Clause
public function record() { return $this->getIterator()->current(); }
Returns the first record in the result @return array
record
php
silverstripe/silverstripe-framework
src/ORM/Connect/Query.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Query.php
BSD-3-Clause
public function value() { $record = $this->record(); if ($record) { return $record[key($record)]; } return null; }
Returns the first column of the first record. @return string
value
php
silverstripe/silverstripe-framework
src/ORM/Connect/Query.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Query.php
BSD-3-Clause
public function setConnector(DBConnector $connector) { $this->connector = $connector; }
Injector injection point for connector dependency @param DBConnector $connector
setConnector
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getSchemaManager() { return $this->schemaManager; }
Returns the current schema manager @return DBSchemaManager
getSchemaManager
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function setSchemaManager(DBSchemaManager $schemaManager) { $this->schemaManager = $schemaManager; if ($this->schemaManager) { $this->schemaManager->setDatabase($this); } }
Injector injection point for schema manager @param DBSchemaManager $schemaManager
setSchemaManager
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getQueryBuilder() { return $this->queryBuilder; }
Returns the current query builder @return DBQueryBuilder
getQueryBuilder
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function setQueryBuilder(DBQueryBuilder $queryBuilder) { $this->queryBuilder = $queryBuilder; }
Injector injection point for schema manager @param DBQueryBuilder $queryBuilder
setQueryBuilder
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
protected function previewWrite($sql) { // Only preview if previewWrite is set, we are in dev mode, and // the query is mutable if (isset($_REQUEST['previewwrite']) && Director::isDev() && $this->connector->isQueryMutable($sql) ) { // output preview message Debug::message("Will execute: $sql"); return true; } else { return false; } }
Determines if the query should be previewed, and thus interrupted silently. If so, this function also displays the query via the debugging system. Subclasess should respect the results of this call for each query, and not execute any queries that generate a true response. @param string $sql The query to be executed @return boolean Flag indicating that the query was previewed
previewWrite
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
protected function benchmarkQuery($sql, $callback, $parameters = []) { if (isset($_REQUEST['showqueries']) && Director::isDev()) { $displaySql = true; $this->queryCount++; $starttime = microtime(true); $result = $callback($sql); $endtime = round(microtime(true) - $starttime, 4); // replace parameters as closely as possible to what we'd expect the DB to put in if (in_array(strtolower($_REQUEST['showqueries'] ?? ''), ['inline', 'backtrace'])) { $sql = DB::inline_parameters($sql, $parameters); } elseif (strtolower($_REQUEST['showqueries'] ?? '') === 'whitelist') { $displaySql = false; foreach (Database::$whitelist_array as $query => $searchType) { $fullQuery = ($searchType === Database::FULL_QUERY && $query === $sql); $partialQuery = ($searchType === Database::PARTIAL_QUERY && mb_strpos($sql ?? '', $query ?? '') !== false); if (!$fullQuery && !$partialQuery) { continue; } $sql = DB::inline_parameters($sql, $parameters); $this->displayQuery($sql, $endtime); } } if ($displaySql) { $this->displayQuery($sql, $endtime); } // Show a backtrace if ?showqueries=backtrace if ($_REQUEST['showqueries'] === 'backtrace') { Backtrace::backtrace(); } return $result; } return $callback($sql); }
Allows the display and benchmarking of queries as they are being run @param string $sql Query to run, and single parameter to callback @param callable $callback Callback to execute code @param array $parameters Parameters for any parameterised query @return mixed Result of query
benchmarkQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public static function setWhitelistQueryArray($whitelistArray) { Database::$whitelist_array = $whitelistArray; }
Add the sql queries that need to be partially or fully matched @param array $whitelistArray
setWhitelistQueryArray
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public static function getWhitelistQueryArray() { return Database::$whitelist_array; }
Get the sql queries that need to be partially or fully matched @return array
getWhitelistQueryArray
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getGeneratedID($table) { return $this->connector->getGeneratedID($table); }
Get the autogenerated ID from the previous INSERT query. @param string $table The name of the table to get the generated ID for @return integer the most recently generated ID for the specified table
getGeneratedID
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function isActive() { return $this->connector->isActive(); }
Determines if we are connected to a server AND have a valid database selected. @return boolean Flag indicating that a valid database is connected
isActive
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function escapeString($value) { return $this->connector->escapeString($value); }
Returns an escaped string. This string won't be quoted, so would be suitable for appending to other quoted strings. @param mixed $value Value to be prepared for database query @return string Prepared string
escapeString
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function quoteString($value) { return $this->connector->quoteString($value); }
Wrap a string into DB-specific quotes. @param mixed $value Value to be prepared for database query @return string Prepared string
quoteString
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function escapeIdentifier($value, $separator = '.') { // Split string into components if (!is_array($value)) { $value = explode($separator ?? '', $value ?? ''); } // Implode quoted column return '"' . implode('"' . $separator . '"', $value) . '"'; }
Escapes an identifier (table / database name). Typically the value is simply double quoted. Don't pass in already escaped identifiers in, as this will double escape the value! @param string|array $value The identifier to escape or list of split components @param string $separator Splitter for each component @return string
escapeIdentifier
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function quiet() { $this->schemaManager->quiet(); }
Enable suppression of database messages.
quiet
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function clearTable($table) { $this->query("TRUNCATE \"$table\""); }
Clear all data in a given table @param string $table Name of table
clearTable
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function nullCheckClause($field, $isNull) { $clause = $isNull ? "%s IS NULL" : "%s IS NOT NULL"; return sprintf($clause ?? '', $field); }
Generates a WHERE clause for null comparison check @param string $field Quoted field name @param bool $isNull Whether to check for NULL or NOT NULL @return string Non-parameterised null comparison clause
nullCheckClause
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function concatOperator() { return ' || '; }
String operator for concatenation of strings @return string
concatOperator
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getVersion() { return $this->connector->getVersion(); }
Query for the version of the currently connected database @return string Version of this database
getVersion
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function affectedRows() { return $this->connector->affectedRows(); }
Return the number of rows affected by the previous operation. @return int
affectedRows
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function supportsSavepoints() { return false; }
Does this database support savepoints in transactions By default it is assumed that they don't unless they are explicitly enabled. @return boolean Flag indicating support for savepoints in transactions
supportsSavepoints
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function withTransaction( $callback, $errorCallback = null, $transactionMode = false, $errorIfTransactionsUnsupported = false ) { $supported = $this->supportsTransactions(); if (!$supported && $errorIfTransactionsUnsupported) { throw new BadMethodCallException("Transactions not supported by this database."); } if ($supported) { $this->transactionStart($transactionMode); } try { call_user_func($callback); } catch (Exception $ex) { if ($supported) { $this->transactionRollback(); } if ($errorCallback) { call_user_func($errorCallback); } throw $ex; } if ($supported) { $this->transactionEnd(); } }
Invoke $callback within a transaction @param callable $callback Callback to run @param callable $errorCallback Optional callback to run after rolling back transaction. @param bool|string $transactionMode Optional transaction mode to use @param bool $errorIfTransactionsUnsupported If true, this method will fail if transactions are unsupported. Otherwise, the $callback will potentially be invoked outside of a transaction. @throws Exception
withTransaction
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function transactionDepth() { // Placeholder error for transactional DBs that don't expose depth if ($this->supportsTransactions()) { user_error(get_class($this) . " does not support transactionDepth", E_USER_WARNING); } return 0; }
Return depth of current transaction @return int Nesting level, or 0 if not in a transaction
transactionDepth
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function supportsLocks() { return false; }
Determines if the used database supports application-level locks, which is different from table- or row-level locking. See {@link getLock()} for details. @return bool Flag indicating that locking is available
supportsLocks
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function canLock($name) { return false; }
Returns if the lock is available. See {@link supportsLocks()} to check if locking is generally supported. @param string $name Name of the lock @return bool
canLock
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getLock($name, $timeout = 5) { return false; }
Sets an application-level lock so that no two processes can run at the same time, also called a "cooperative advisory lock". Return FALSE if acquiring the lock fails; otherwise return TRUE, if lock was acquired successfully. Lock is automatically released if connection to the database is broken (either normally or abnormally), making it less prone to deadlocks than session- or file-based locks. Should be accompanied by a {@link releaseLock()} call after the logic requiring the lock has completed. Can be called multiple times, in which case locks "stack" (PostgreSQL, SQL Server), or auto-releases the previous lock (MySQL). Note that this might trigger the database to wait for the lock to be released, delaying further execution. @param string $name Name of lock @param integer $timeout Timeout in seconds @return bool
getLock
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function releaseLock($name) { return false; }
Remove an application-level lock file to allow another process to run (if the execution aborts (e.g. due to an error) all locks are automatically released). @param string $name Name of the lock @return bool Flag indicating whether the lock was successfully released
releaseLock
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function connect($parameters) { // Notify connector of parameters $this->connector->connect($parameters); // SS_Database subclass maintains responsibility for selecting database // once connected in order to correctly handle schema queries about // existence of database, error handling at the correct level, etc if (!empty($parameters['database'])) { $this->selectDatabase($parameters['database'], false, false); } }
Instruct the database to generate a live connection @param array $parameters An map of parameters, which should include: - server: The server, eg, localhost - username: The username to log on with - password: The password to log on with - database: The database to connect to - charset: The character set to use. Defaults to utf8 - timezone: (optional) The timezone offset. For example: +12:00, "Pacific/Auckland", or "SYSTEM" - driver: (optional) Driver name
connect
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function databaseExists($name) { return $this->schemaManager->databaseExists($name); }
Determine if the database with the specified name exists @param string $name Name of the database to check for @return bool Flag indicating whether this database exists
databaseExists
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function databaseList() { return $this->schemaManager->databaseList(); }
Retrieves the list of all databases the user has access to @return array List of database names
databaseList
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) { // In case our live environment is locked down, we can bypass a SHOW DATABASE check $canConnect = Config::inst()->get(static::class, 'optimistic_connect') || $this->schemaManager->databaseExists($name); if ($canConnect) { return $this->connector->selectDatabase($name); } // Check DB creation permission if (!$create) { if ($errorLevel !== false) { user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel ?? 0); } // Unselect database $this->connector->unloadDatabase(); return false; } $this->schemaManager->createDatabase($name); return $this->connector->selectDatabase($name); }
Change the connection to the specified database, optionally creating the database if it doesn't exist in the current schema. @param string $name Name of the database @param bool $create Flag indicating whether the database should be created if it doesn't exist. If $create is false and the database doesn't exist then an error will be raised @param int|bool $errorLevel The level of error reporting to enable for the query, or false if no error should be raised @return bool Flag indicating success
selectDatabase
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function dropSelectedDatabase() { $databaseName = $this->connector->getSelectedDatabase(); if ($databaseName) { $this->connector->unloadDatabase(); $this->schemaManager->dropDatabase($databaseName); } }
Drop the database that this object is currently connected to. Use with caution.
dropSelectedDatabase
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getSelectedDatabase() { return $this->connector->getSelectedDatabase(); }
Returns the name of the currently selected database @return string|null Name of the selected database, or null if none selected
getSelectedDatabase
php
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/Database.php
BSD-3-Clause
public function getSeparator() { return "\n "; }
Determines the line separator to use. @return string Non-empty whitespace character
getSeparator
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
protected function buildSelectQuery(SQLSelect $query, array &$parameters) { $needsParenthisis = count($query->getUnions()) > 0; $nl = $this->getSeparator(); $sql = ''; if ($needsParenthisis) { $sql .= "({$nl}"; } $sql .= $this->buildWithFragment($query, $parameters); $sql .= $this->buildSelectFragment($query, $parameters); $sql .= $this->buildFromFragment($query, $parameters); $sql .= $this->buildWhereFragment($query, $parameters); $sql .= $this->buildGroupByFragment($query, $parameters); $sql .= $this->buildHavingFragment($query, $parameters); $sql .= $this->buildOrderByFragment($query, $parameters); $sql .= $this->buildLimitFragment($query, $parameters); if ($needsParenthisis) { $sql .= "{$nl})"; } $sql .= $this->buildUnionFragment($query, $parameters); return $sql; }
Builds a query from a SQLSelect expression @param SQLSelect $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed SQL string
buildSelectQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
protected function buildDeleteQuery(SQLDelete $query, array &$parameters) { $sql = $this->buildDeleteFragment($query, $parameters); $sql .= $this->buildFromFragment($query, $parameters); $sql .= $this->buildWhereFragment($query, $parameters); return $sql; }
Builds a query from a SQLDelete expression @param SQLDelete $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed SQL string
buildDeleteQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
protected function buildUpdateQuery(SQLUpdate $query, array &$parameters) { $sql = $this->buildUpdateFragment($query, $parameters); $sql .= $this->buildWhereFragment($query, $parameters); return $sql; }
Builds a query from a SQLUpdate expression @param SQLUpdate $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed SQL string
buildUpdateQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
protected function buildSelectFragment(SQLSelect $query, array &$parameters) { $distinct = $query->getDistinct(); $select = $query->getSelect(); $clauses = []; foreach ($select as $alias => $field) { // Don't include redundant aliases. $fieldAlias = "\"{$alias}\""; if ($alias === $field || substr($field ?? '', -strlen($fieldAlias ?? '')) === $fieldAlias) { $clauses[] = $field; } else { $clauses[] = "$field AS $fieldAlias"; } } $text = 'SELECT '; if ($distinct) { $text .= 'DISTINCT '; } return $text . implode(', ', $clauses); }
Returns the SELECT clauses ready for inserting into a query. @param SQLSelect $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed select part of statement
buildSelectFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildDeleteFragment(SQLDelete $query, array &$parameters) { $text = 'DELETE'; // If doing a multiple table delete then list the target deletion tables here // Note that some schemas don't support multiple table deletion $delete = $query->getDelete(); if (!empty($delete)) { $text .= ' ' . implode(', ', $delete); } return $text; }
Return the DELETE clause ready for inserting into a query. @param SQLDelete $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed delete part of statement
buildDeleteFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildUpdateFragment(SQLUpdate $query, array &$parameters) { $nl = $this->getSeparator(); $text = "{$nl}UPDATE " . $this->getTableWithJoins($query, $parameters); // Join SET components together, considering parameters $parts = []; foreach ($query->getAssignments() as $column => $assignment) { // Assignment is a single item array, expand with a loop here foreach ($assignment as $assignmentSQL => $assignmentParameters) { $parts[] = "$column = $assignmentSQL"; $parameters = array_merge($parameters, $assignmentParameters); break; } } $nl = $this->getSeparator(); $text .= "{$nl}SET " . implode(', ', $parts); return $text; }
Return the UPDATE clause ready for inserting into a query. @param SQLUpdate $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed from part of statement
buildUpdateFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildFromFragment(SQLConditionalExpression $query, array &$parameters) { $from = $this->getTableWithJoins($query, $parameters, true); if ($from === '') { return ''; } $nl = $this->getSeparator(); return "{$nl}FROM " . $from; }
Return the FROM clause ready for inserting into a query. @param SQLConditionalExpression $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed from part of statement
buildFromFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildWhereFragment(SQLConditionalExpression $query, array &$parameters) { // Get parameterised elements $where = $query->getWhereParameterised($whereParameters); if (empty($where)) { return ''; } // Join conditions $connective = $query->getConnective(); $parameters = array_merge($parameters, $whereParameters); $nl = $this->getSeparator(); return "{$nl}WHERE (" . implode("){$nl}{$connective} (", $where) . ")"; }
Returns the WHERE clauses ready for inserting into a query. @param SQLConditionalExpression $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed where condition
buildWhereFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildGroupByFragment(SQLSelect $query, array &$parameters) { $groupBy = $query->getGroupBy(); if (empty($groupBy)) { return ''; } $nl = $this->getSeparator(); return "{$nl}GROUP BY " . implode(', ', $groupBy); }
Returns the GROUP BY clauses ready for inserting into a query. @param SQLSelect $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string Completed group part of statement
buildGroupByFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildHavingFragment(SQLSelect $query, array &$parameters) { $having = $query->getHavingParameterised($havingParameters); if (empty($having)) { return ''; } // Generate having, considering parameters present $connective = $query->getConnective(); $parameters = array_merge($parameters, $havingParameters); $nl = $this->getSeparator(); return "{$nl}HAVING (" . implode("){$nl}{$connective} (", $having) . ")"; }
Returns the HAVING clauses ready for inserting into a query. @param SQLSelect $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string
buildHavingFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function buildLimitFragment(SQLSelect $query, array &$parameters) { $nl = $this->getSeparator(); // Ensure limit is given $limit = $query->getLimit(); if (empty($limit)) { return ''; } // For literal values return this as the limit SQL if (!is_array($limit)) { return "{$nl}LIMIT $limit"; } // Assert that the array version provides the 'limit' key if (!isset($limit['limit']) || !is_numeric($limit['limit'])) { throw new InvalidArgumentException( 'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: ' . var_export($limit, true) ); } // Format the array limit, given an optional start key $clause = "{$nl}LIMIT {$limit['limit']}"; if (isset($limit['start']) && is_numeric($limit['start']) && $limit['start'] !== 0) { $clause .= " OFFSET {$limit['start']}"; } return $clause; }
Return the LIMIT clause ready for inserting into a query. @param SQLSelect $query The expression object to build from @param array $parameters Out parameter for the resulting query parameters @return string The finalised limit SQL fragment
buildLimitFragment
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBQueryBuilder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBQueryBuilder.php
BSD-3-Clause
public function getSQL() { return $this->sql; }
Returns the SQL that generated this error @return string
getSQL
php
silverstripe/silverstripe-framework
src/ORM/Connect/DatabaseException.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DatabaseException.php
BSD-3-Clause
public function __construct($message = '', $code = 0, $previous = null, $sql = null, $parameters = []) { parent::__construct($message, $code, $previous); $this->sql = $sql; $this->parameters = $parameters; }
Constructs the database exception @param string $message The Exception message to throw. @param integer $code The Exception code. @param Exception $previous The previous exception used for the exception chaining. @param string $sql The SQL executed for this query @param array $parameters The parameters given for this query, if any
__construct
php
silverstripe/silverstripe-framework
src/ORM/Connect/DatabaseException.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DatabaseException.php
BSD-3-Clause
public function __construct( string $message = '', ?string $keyName = null, ?string $duplicatedValue = null, ?string $sql = null, array $parameters = [] ) { parent::__construct($message, sql: $sql, parameters: $parameters); $this->keyName = $keyName; $this->duplicatedValue = $duplicatedValue; }
Constructs the database exception @param string $message The Exception message to throw. @param string|null $keyName The name of the key which the error is for (e.g. index name) @param string|null $duplicatedValue The value which was duplicated (e.g. combined value of multiple columns in index) @param string|null $sql The SQL executed for this query @param array $parameters The parameters given for this query, if any
__construct
php
silverstripe/silverstripe-framework
src/ORM/Connect/DuplicateEntryException.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DuplicateEntryException.php
BSD-3-Clause
public function setDatabase(Database $database) { $this->database = $database; }
Injector injection point for database controller @param Database $database
setDatabase
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function query($sql, $errorLevel = E_USER_ERROR) { return $this->database->query($sql, $errorLevel); }
Execute the given SQL query. This abstract function must be defined by subclasses as part of the actual implementation. It should return a subclass of SS_Query as the result. @param string $sql The SQL query to execute @param int $errorLevel The level of error reporting to enable for the query @return Query
query
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function cancelSchemaUpdate() { $this->schemaUpdateTransaction = null; $this->schemaIsUpdating = false; }
Cancels the schema updates requested during (but not after) schemaUpdate() call.
cancelSchemaUpdate
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
function isSchemaUpdating() { return $this->schemaIsUpdating; }
Returns true if we are during a schema update. @return boolean
isSchemaUpdating
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function doesSchemaNeedUpdating() { return (bool) $this->schemaUpdateTransaction; }
Returns true if schema modifications were requested during (but not after) schemaUpdate() call. @return boolean
doesSchemaNeedUpdating
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transCreateTable($table, $options = null, $advanced_options = null) { $this->schemaUpdateTransaction[$table] = [ 'command' => 'create', 'newFields' => [], 'newIndexes' => [], 'options' => $options, 'advancedOptions' => $advanced_options ]; }
Instruct the schema manager to record a table creation to later execute @param string $table Name of the table @param array $options Create table options (ENGINE, etc.) @param array $advanced_options Advanced table creation options
transCreateTable
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transAlterTable($table, $options, $advanced_options) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredOptions'] = $options; $this->schemaUpdateTransaction[$table]['advancedOptions'] = $advanced_options; }
Instruct the schema manager to record a table alteration to later execute @param string $table Name of the table @param array $options Create table options (ENGINE, etc.) @param array $advanced_options Advanced table creation options
transAlterTable
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transCreateField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newFields'][$field] = $schema; }
Instruct the schema manager to record a field to be later created @param string $table Name of the table to hold this field @param string $field Name of the field to create @param string $schema Field specification as a string
transCreateField
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transCreateIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newIndexes'][$index] = $schema; }
Instruct the schema manager to record an index to be later created @param string $table Name of the table to hold this index @param string $index Name of the index to create @param array $schema Already parsed index specification
transCreateIndex
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transAlterField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredFields'][$field] = $schema; }
Instruct the schema manager to record a field to be later updated @param string $table Name of the table to hold this field @param string $field Name of the field to update @param string $schema Field specification as a string
transAlterField
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function transAlterIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredIndexes'][$index] = $schema; }
Instruct the schema manager to record an index to be later updated @param string $table Name of the table to hold this index @param string $index Name of the index to update @param array $schema Already parsed index specification
transAlterIndex
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
protected function transInitTable($table) { if (!isset($this->schemaUpdateTransaction[$table])) { $this->schemaUpdateTransaction[$table] = [ 'command' => 'alter', 'newFields' => [], 'newIndexes' => [], 'alteredFields' => [], 'alteredIndexes' => [], 'alteredOptions' => '' ]; } }
Handler for the other transXXX methods - mark the given table as being altered if it doesn't already exist @param string $table Name of the table to initialise
transInitTable
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
protected function explodeColumnString($spec) { // Remove any leading/trailing brackets and outlying modifiers // E.g. 'unique (Title, "QuotedColumn");' => 'Title, "QuotedColumn"' $containedSpec = preg_replace('/(.*\(\s*)|(\s*\).*)/', '', $spec ?? ''); // Split potentially quoted modifiers // E.g. 'Title, "QuotedColumn"' => ['Title', 'QuotedColumn'] return preg_split('/"?\s*,\s*"?/', trim($containedSpec ?? '', '(") ')); }
Splits a spec string safely, considering quoted columns, whitespace, and cleaning brackets @param string $spec The input index specification string @return array List of columns in the spec
explodeColumnString
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
protected function implodeColumnList($columns) { if (empty($columns)) { return ''; } return '"' . implode('","', $columns) . '"'; }
Builds a properly quoted column list from an array @param array $columns List of columns to implode @return string A properly quoted list of column names
implodeColumnList
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
protected function quoteColumnSpecString($spec) { $bits = $this->explodeColumnString($spec); return $this->implodeColumnList($bits); }
Given an index specification in the form of a string ensure that each column name is property quoted, stripping brackets and modifiers. This index may also be in the form of a "CREATE INDEX..." sql fragment @param string $spec The input specification or query. E.g. 'unique (Column1, Column2)' @return string The properly quoted column list. E.g. '"Column1", "Column2"'
quoteColumnSpecString
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
protected function convertIndexSpec($indexSpec) { // Return already converted spec if (!is_array($indexSpec) || !array_key_exists('type', $indexSpec ?? []) || !array_key_exists('columns', $indexSpec ?? []) || !is_array($indexSpec['columns']) || array_key_exists('value', $indexSpec ?? []) ) { throw new \InvalidArgumentException( sprintf( 'argument to convertIndexSpec must be correct indexSpec, %s given', var_export($indexSpec, true) ) ); } // Combine elements into standard string format return sprintf('%s (%s)', $indexSpec['type'], $this->implodeColumnList($indexSpec['columns'])); }
This takes the index spec which has been provided by a class (ie static $indexes = blah blah) and turns it into a proper string. Some indexes may be arrays, such as fulltext and unique indexes, and this allows database-specific arrays to be created. See {@link requireTable()} for details on the index format. @see http://dev.mysql.com/doc/refman/5.0/en/create-index.html @see parseIndexSpec() for approximate inverse @param string|array $indexSpec @return string
convertIndexSpec
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function hasField($tableName, $fieldName) { if (!$this->hasTable($tableName)) { return false; } $fields = $this->fieldList($tableName); return array_key_exists($fieldName, $fields ?? []); }
Return true if the table exists and already has a the field specified @param string $tableName - The table to check @param string $fieldName - The field to check @return bool - True if the table exists and the field exists on the table
hasField
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause