31 const DELAYED_QUERY =
'q';
32 const DELAYED_HANDLER =
'h';
42 protected array $connections = [];
47 protected int $query_count = 0;
56 protected array $delayed_queries = [];
71 $this->resetConnections($db_config);
82 $this->closeConnections();
86 $this->query_cache->enable();
87 $this->query_cache->clear();
99 foreach ($this->connections as $connection) {
100 $connection->close();
103 $this->connections = [];
114 if (isset($this->connections[$type])) {
116 return $this->connections[
$type];
117 }
elseif (isset($this->connections[
'readwrite'])) {
119 return $this->connections[
'readwrite'];
120 }
elseif (isset($this->connections[
'read'])) {
122 return $this->connections[
'read'];
125 $this->setupConnections();
127 return $this->getConnection($type);
139 if ($this->db_config->isDatabaseSplit()) {
140 $this->connect(
'read');
141 $this->connect(
'write');
143 $this->connect(
'readwrite');
158 $conf = $this->db_config->getConnectionConfig(
$type);
161 'dbname' => $conf[
'database'],
162 'user' => $conf[
'user'],
163 'password' => $conf[
'password'],
164 'host' => $conf[
'host'],
165 'port' => $conf[
'port'],
166 'charset' => $conf[
'encoding'],
167 'driver' =>
'pdo_mysql',
171 $this->connections[
$type] = DriverManager::getConnection(
$params);
174 $sub_query =
"SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')";
175 $this->connections[
$type]->executeStatement(
"SET SESSION sql_mode=($sub_query);");
176 }
catch (\Exception $e) {
178 $this->
log(LogLevel::ERROR, $e);
180 if ($e->getCode() == 1102 || $e->getCode() == 1049) {
181 $msg =
"Elgg couldn't select the database '{$conf['database']}'. Please check that the database is created and you have access to it.";
183 $msg =
"Elgg couldn't connect to the database using the given credentials. Check the settings file.";
206 return $this->getResults($query, $callback,
false);
222 return $this->getResults($query, $callback,
true);
236 $params = $query->getParameters();
237 $sql = $query->getSQL();
239 $this->
getLogger()->info(
"DB insert query {$sql} (params: " . print_r(
$params,
true) .
')');
241 $this->query_cache->clear();
243 $this->executeQuery($query);
247 }
catch (DriverException $e) {
248 if ($e->getPrevious() instanceof NoIdentityValue) {
267 $params = $query->getParameters();
268 $sql = $query->getSQL();
270 $this->
getLogger()->info(
"DB update query {$sql} (params: " . print_r(
$params,
true) .
')');
272 $this->query_cache->clear();
274 $result = $this->executeQuery($query);
275 if (!$get_num_rows) {
292 $params = $query->getParameters();
293 $sql = $query->getSQL();
295 $this->
getLogger()->info(
"DB delete query {$sql} (params: " . print_r(
$params,
true) .
')');
297 $this->query_cache->clear();
299 $result = $this->executeQuery($query);
315 if (is_string($callback)) {
319 if (is_object($callback)) {
320 return spl_object_hash($callback) .
'::__invoke';
323 if (is_array($callback)) {
324 if (is_string($callback[0])) {
325 return "{$callback[0]}::{$callback[1]}";
328 return spl_object_hash($callback[0]) .
"::{$callback[1]}";
348 $params = $query->getParameters();
349 $sql = $query->getSQL();
354 $extras = (int) $single .
'|';
356 if (!is_callable($callback)) {
360 $extras .= $this->fingerprintCallback($callback);
363 $hash = $this->getCacheHash($sql,
$params, $extras);
365 $cached_results = $this->query_cache->load($hash);
366 if (isset($cached_results)) {
367 return $cached_results;
370 $this->
getLogger()->info(
"DB select query {$sql} (params: " . print_r(
$params,
true) .
')');
374 $stmt = $this->executeQuery($query);
376 while ($row = $stmt->fetchAssociative()) {
377 $row_obj = (object) $row;
379 $row_obj = call_user_func($callback, $row_obj);
386 $return[] = $row_obj;
390 $this->query_cache->save($hash, $return);
409 $result = $this->trackQuery($query,
function() use ($query) {
411 return $query->executeQuery();
413 return $query->executeStatement();
416 }
catch (\Exception $e) {
419 $ex->setQuery($query->getSQL());
438 $query_id = $sql .
'|';
440 $query_id .= serialize(
$params) .
'|';
443 $query_id .= $extras;
446 return md5($query_id);
459 $params = $query->getParameters();
460 $sql = $query->getSQL();
462 $this->query_count++;
464 $timer_key = preg_replace(
'~\\s+~',
' ',
trim($sql .
'|' . serialize(
$params)));
467 $stop_timer =
function() use ($timer_key) {
468 $this->
endTimer([
'SQL', $timer_key]);
473 }
catch (\Exception $e) {
496 if (Application::isCli() && !$this->config->testing_mode) {
501 $stmt = $this->executeQuery($query);
503 if (is_callable($callback)) {
504 call_user_func($callback, $stmt);
506 }
catch (\Throwable $t) {
514 $this->delayed_queries[] = [
515 self::DELAYED_QUERY =>
$query,
516 self::DELAYED_HANDLER => $callback,
528 foreach ($this->delayed_queries as $set) {
529 $query = $set[self::DELAYED_QUERY];
530 $handler = $set[self::DELAYED_HANDLER];
533 $stmt = $this->executeQuery(
$query);
538 }
catch (\Throwable $t) {
544 $this->delayed_queries = [];
553 return $this->query_count;
564 return $this->getConnection(
$type)->getServerVersion();
575 return $this->getConnection(
$type)->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MariaDBPlatform;
588 return $this->getConnection(
$type)->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MySQLPlatform;
600 if (
$name ===
'prefix') {
601 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.
if(!$user||!$user->canDelete()) $name
updateData(QueryBuilder $query, bool $get_num_rows=false)
Update the database.
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
Database abstraction query builder.
getConnection()
Returns the connection.
isMySQL(string $type=DbConfig::READ_WRITE)
Is the database MySQL.
deleteData(QueryBuilder $query)
Delete data from the database.
getData(QueryBuilder $query, $callback=null)
Retrieve rows from the database.
insertData(QueryBuilder $query)
Insert a row into the database.
resetConnections(DbConfig $config)
Reset the connections with new credentials.
if($item instanceof\ElggEntity) elseif($item instanceof\ElggRiverItem) elseif($item instanceof\ElggRelationship) elseif(is_callable([$item, 'getType']))
registerDelayedQuery(QueryBuilder $query, $callback=null)
Queue a query for execution upon shutdown.
$config
Advanced site settings, debugging section.
setParameters(array $params)
Set query parameters.
trait Loggable
Enables adding a logger.
__set($name, $value)
Handle magic property writes.
executeQuery(QueryBuilder $query)
Execute a query.
trackQuery(QueryBuilder $query, callable $callback)
Tracks the query count and timers for a given query.
__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.
getResults(QueryBuilder $query, $callback=null, bool $single=false)
Handles queries that return results, running the results through a an optional callback function...
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.
__construct(DbConfig $db_config, protected QueryCache $query_cache, protected Config $config)
Constructor.
beginTimer(array $keys)
Start the timer (when enabled)
getDataRow(QueryBuilder $query, $callback=null)
Retrieve a single row from the database.
getCacheHash(string $sql, array $params=[], string $extras= '')
Returns a hashed key for storage in the cache.
_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.
connect(string $type= 'readwrite')
Establish a connection to the database server.
endTimer(array $keys)
Ends the timer (when enabled)