30 const DELAYED_QUERY =
'q';
31 const DELAYED_TYPE =
't';
32 const DELAYED_HANDLER =
'h';
33 const DELAYED_PARAMS =
'p';
38 private $table_prefix;
43 private $connections = [];
48 private $query_count = 0;
64 protected $delayed_queries = [];
78 $this->query_cache = $query_cache;
80 $this->resetConnections($config);
91 $this->closeConnections();
95 $this->query_cache->enable();
96 $this->query_cache->clear();
108 foreach ($this->connections as $connection) {
109 $connection->close();
112 $this->connections = [];
123 if (isset($this->connections[$type])) {
124 return $this->connections[
$type];
125 }
else if (isset($this->connections[
'readwrite'])) {
126 return $this->connections[
'readwrite'];
129 $this->setupConnections();
131 return $this->getConnection($type);
143 if ($this->config->isDatabaseSplit()) {
144 $this->connect(
'read');
145 $this->connect(
'write');
147 $this->connect(
'readwrite');
162 $conf = $this->config->getConnectionConfig(
$type);
165 'dbname' => $conf[
'database'],
166 'user' => $conf[
'user'],
167 'password' => $conf[
'password'],
168 'host' => $conf[
'host'],
169 'port' => $conf[
'port'],
170 'charset' => $conf[
'encoding'],
171 'driver' =>
'pdo_mysql',
175 $this->connections[
$type] = DriverManager::getConnection(
$params);
178 $sub_query =
"SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')";
179 $this->connections[
$type]->executeStatement(
"SET SESSION sql_mode=($sub_query);");
182 $this->
log(LogLevel::ERROR, $e);
184 if ($e->getCode() == 1102 || $e->getCode() == 1049) {
185 $msg =
"Elgg couldn't select the database '{$conf['database']}'. " 186 .
"Please check that the database is created and you have access to it.";
188 $msg =
"Elgg couldn't connect to the database using the given credentials. Check the settings file.";
211 if (!
$query instanceof QueryBuilder) {
212 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
232 if (!
$query instanceof QueryBuilder) {
233 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
250 if (!
$query instanceof QueryBuilder) {
251 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
255 $connection = $this->getConnection(
'write');
256 if (
$query instanceof QueryBuilder) {
259 $connection =
$query->getConnection();
262 $this->
getLogger()->info(
"DB insert query {$sql} (params: " . print_r(
$params,
true) .
")");
264 $this->query_cache->clear();
267 return (
int) $connection->lastInsertId();
282 if (!
$query instanceof QueryBuilder) {
283 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
287 if (
$query instanceof QueryBuilder) {
292 $this->
getLogger()->info(
"DB update query {$sql} (params: " . print_r(
$params,
true) .
")");
294 $this->query_cache->clear();
297 if (!$get_num_rows) {
315 if (!
$query instanceof QueryBuilder) {
316 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
320 if (
$query instanceof QueryBuilder) {
325 $this->
getLogger()->info(
"DB delete query {$sql} (params: " . print_r(
$params,
true) .
")");
327 $this->query_cache->clear();
345 if (is_string($callback)) {
349 if (is_object($callback)) {
350 return spl_object_hash($callback) .
'::__invoke';
353 if (is_array($callback)) {
354 if (is_string($callback[0])) {
355 return "{$callback[0]}::{$callback[1]}";
358 return spl_object_hash($callback[0]) .
"::{$callback[1]}";
380 if (
$query instanceof QueryBuilder) {
390 $extras = (int) $single .
'|';
392 if (!is_callable($callback)) {
396 $extras .= $this->fingerprintCallback($callback);
399 $hash = $this->query_cache->getHash($sql,
$params, $extras);
401 $cached_results = $this->query_cache->get($hash);
402 if (isset($cached_results)) {
403 return $cached_results;
406 $this->
getLogger()->info(
"DB select query {$sql} (params: " . print_r(
$params,
true) .
")");
410 if (
$query instanceof QueryBuilder) {
411 $stmt = $this->executeQuery(
$query,
$query->getConnection());
413 $stmt = $this->executeQuery(
$query, $this->getConnection(
'read'),
$params);
416 while ($row = $stmt->fetchAssociative()) {
417 $row_obj = (object) $row;
419 $row_obj = call_user_func($callback, $row_obj);
426 $return[] = $row_obj;
431 $this->query_cache->set($hash, $return);
455 if (
$query instanceof QueryBuilder) {
461 if (
substr($param_key, 0, 1) !==
':') {
465 $this->
getLogger()->warning(
'Unsupported colon detected in named param: ' . $param_key);
473 if (
$query instanceof QueryBuilder) {
474 if (
$query->getType() === QueryBuilder::SELECT) {
475 return $query->executeQuery();
477 return $query->executeStatement();
480 return $connection->executeQuery($sql,
$params);
483 return $connection->executeQuery($sql);
509 if (
$query instanceof QueryBuilder) {
510 $params =
$query->getParameters();
514 $this->query_count++;
516 $timer_key = preg_replace(
'~\\s+~',
' ',
trim($sql .
'|' . serialize($params)));
519 $stop_timer =
function() use ($timer_key) {
520 $this->
endTimer([
'SQL', $timer_key]);
550 if (!
$query instanceof QueryBuilder) {
551 $this->
logDeprecatedMessage(
'The use of non ' . QueryBuilder::class .
' queries in ' . __METHOD__ .
' has been deprecated',
'4.0');
554 if ($type !==
'read' && $type !==
'write') {
558 $this->delayed_queries[] = [
559 self::DELAYED_QUERY =>
$query,
560 self::DELAYED_TYPE =>
$type,
561 self::DELAYED_HANDLER => $callback,
562 self::DELAYED_PARAMS =>
$params,
576 foreach ($this->delayed_queries as $set) {
577 $query = $set[self::DELAYED_QUERY];
578 $type = $set[self::DELAYED_TYPE];
579 $handler = $set[self::DELAYED_HANDLER];
580 $params = $set[self::DELAYED_PARAMS];
594 $this->delayed_queries = [];
605 $this->query_cache->enable();
617 $this->query_cache->disable();
626 return $this->query_count;
637 $driver = $this->getConnection(
$type)->getWrappedConnection();
638 if ($driver instanceof ServerInfoAwareConnection) {
639 $version = $driver->getServerVersion();
641 if ($this->isMariaDB(
$type)) {
661 $driver = $this->getConnection(
$type)->getWrappedConnection();
662 if ($driver instanceof ServerInfoAwareConnection) {
663 $version = $driver->getServerVersion();
665 return stristr(
$version,
'mariadb') !==
false;
680 if (
$name ===
'prefix') {
681 return $this->table_prefix;
trait Profilable
Make an object accept a timer.
getQueryCount()
Get the number of queries made to the database.
$params
Saves global plugin settings.
Exception thrown if an error which can only be found on runtime occurs.
Database configuration service.
getConnection(string $type)
Gets (if required, also creates) a DB connection.
__construct(DbConfig $config, QueryCache $query_cache)
Constructor.
if(!$user||!$user->canDelete()) $name
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is void
executeQuery($query, Connection $connection, array $params=[])
Execute a query.
resetConnections(DbConfig $config)
Reset the connections with new credentials.
$config
Advanced site settings, debugging section.
setParameters(array $params)
Set query parameters.
trait Loggable
Enables adding a logger.
getData($query, $callback=null, array $params=[])
Retrieve rows from the database.
__set($name, $value)
Handle magic property writes.
__get($name)
Handle magic property reads.
getTablePrefix()
Get the database table prefix.
isMariaDB(string $type=DbConfig::READ_WRITE)
Is the database MariaDB.
Volatile cache for select queries.
A generic parent class for database exceptions.
Result of a single BatchUpgrade run.
fingerprintCallback($callback)
Get a string that uniquely identifies a callback during the current request.
log($level, $message, array $context=[])
Log a message.
getLogger()
Returns logger.
deleteData($query, array $params=[])
Delete data from the database.
disableQueryCache()
Disable the query cache.
if($item instanceof\ElggEntity) elseif($item instanceof\ElggRiverItem) elseif($item instanceof ElggRelationship) elseif(is_callable([$item, 'getType']))
beginTimer(array $keys)
Start the timer (when enabled)
updateData($query, bool $get_num_rows=false, array $params=[])
Update the database.
enableQueryCache()
Enable the query cache.
getDataRow($query, $callback=null, array $params=[])
Retrieve a single row from the database.
_elgg_services()
Get the global service provider.
executeDelayedQueries()
Trigger all queries that were registered as "delayed" queries.
getServerVersion(string $type=DbConfig::READ_WRITE)
Get the server version number.
closeConnections()
Close all database connections.
setupConnections()
Establish database connections.
insertData($query, array $params=[])
Insert a row into the database.
connect(string $type= 'readwrite')
Establish a connection to the database server.
trackQuery($query, array $params, callable $callback)
Tracks the query count and timers for a given query.
getResults($query, $callback=null, bool $single=false, array $params=[])
Handles queries that return results, running the results through a an optional callback function...
endTimer(array $keys)
Ends the timer (when enabled)
registerDelayedQuery($query, string $type, $callback=null, array $params=[])
Queue a query for execution upon shutdown.
logDeprecatedMessage(string $message, string $version)
Sends a message about deprecated use of a function, view, etc.