31 const DELAYED_QUERY =
'q';
32 const DELAYED_HANDLER =
'h';
42 protected array $connections = [];
47 protected int $query_count = 0;
56 protected $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])) {
115 return $this->connections[
$type];
116 }
else if (isset($this->connections[
'readwrite'])) {
117 return $this->connections[
'readwrite'];
120 $this->setupConnections();
122 return $this->getConnection($type);
134 if ($this->db_config->isDatabaseSplit()) {
135 $this->connect(
'read');
136 $this->connect(
'write');
138 $this->connect(
'readwrite');
153 $conf = $this->db_config->getConnectionConfig(
$type);
156 'dbname' => $conf[
'database'],
157 'user' => $conf[
'user'],
158 'password' => $conf[
'password'],
159 'host' => $conf[
'host'],
160 'port' => $conf[
'port'],
161 'charset' => $conf[
'encoding'],
162 'driver' =>
'pdo_mysql',
166 $this->connections[
$type] = DriverManager::getConnection(
$params);
169 $sub_query =
"SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')";
170 $this->connections[
$type]->executeStatement(
"SET SESSION sql_mode=($sub_query);");
171 }
catch (\Exception $e) {
173 $this->
log(LogLevel::ERROR, $e);
175 if ($e->getCode() == 1102 || $e->getCode() == 1049) {
176 $msg =
"Elgg couldn't select the database '{$conf['database']}'. Please check that the database is created and you have access to it.";
178 $msg =
"Elgg couldn't connect to the database using the given credentials. Check the settings file.";
201 return $this->getResults($query, $callback,
false);
217 return $this->getResults($query, $callback,
true);
231 $params = $query->getParameters();
232 $sql = $query->getSQL();
234 $this->
getLogger()->info(
"DB insert query {$sql} (params: " . print_r(
$params,
true) .
')');
236 $this->query_cache->clear();
238 $this->executeQuery($query);
242 }
catch (DriverException $e) {
243 if ($e->getPrevious() instanceof NoIdentityValue) {
262 $params = $query->getParameters();
263 $sql = $query->getSQL();
265 $this->
getLogger()->info(
"DB update query {$sql} (params: " . print_r(
$params,
true) .
')');
267 $this->query_cache->clear();
269 $result = $this->executeQuery($query);
270 if (!$get_num_rows) {
287 $params = $query->getParameters();
288 $sql = $query->getSQL();
290 $this->
getLogger()->info(
"DB delete query {$sql} (params: " . print_r(
$params,
true) .
')');
292 $this->query_cache->clear();
294 $result = $this->executeQuery($query);
310 if (is_string($callback)) {
314 if (is_object($callback)) {
315 return spl_object_hash($callback) .
'::__invoke';
318 if (is_array($callback)) {
319 if (is_string($callback[0])) {
320 return "{$callback[0]}::{$callback[1]}";
323 return spl_object_hash($callback[0]) .
"::{$callback[1]}";
343 $params = $query->getParameters();
344 $sql = $query->getSQL();
349 $extras = (int) $single .
'|';
351 if (!is_callable($callback)) {
355 $extras .= $this->fingerprintCallback($callback);
358 $hash = $this->query_cache->getHash($sql,
$params, $extras);
360 $cached_results = $this->query_cache->get($hash);
361 if (isset($cached_results)) {
362 return $cached_results;
365 $this->
getLogger()->info(
"DB select query {$sql} (params: " . print_r(
$params,
true) .
')');
369 $stmt = $this->executeQuery($query);
371 while ($row = $stmt->fetchAssociative()) {
372 $row_obj = (object) $row;
374 $row_obj = call_user_func($callback, $row_obj);
381 $return[] = $row_obj;
386 $this->query_cache->set($hash, $return);
405 $result = $this->trackQuery($query,
function() use ($query) {
407 return $query->executeQuery();
409 return $query->executeStatement();
412 }
catch (\Exception $e) {
415 $ex->setQuery($query->getSQL());
433 $params = $query->getParameters();
434 $sql = $query->getSQL();
436 $this->query_count++;
438 $timer_key = preg_replace(
'~\\s+~',
' ',
trim($sql .
'|' . serialize(
$params)));
441 $stop_timer =
function() use ($timer_key) {
442 $this->
endTimer([
'SQL', $timer_key]);
447 }
catch (\Exception $e) {
470 if (Application::isCli() && !$this->config->testing_mode) {
475 $stmt = $this->executeQuery($query);
477 if (is_callable($callback)) {
478 call_user_func($callback, $stmt);
480 }
catch (\Throwable $t) {
488 $this->delayed_queries[] = [
489 self::DELAYED_QUERY =>
$query,
490 self::DELAYED_HANDLER => $callback,
502 foreach ($this->delayed_queries as $set) {
503 $query = $set[self::DELAYED_QUERY];
504 $handler = $set[self::DELAYED_HANDLER];
507 $stmt = $this->executeQuery(
$query);
512 }
catch (\Throwable $t) {
518 $this->delayed_queries = [];
529 $this->query_cache->enable();
541 $this->query_cache->disable();
550 return $this->query_count;
561 return $this->getConnection(
$type)->getServerVersion();
572 return $this->getConnection(
$type)->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MariaDBPlatform;
585 return $this->getConnection(
$type)->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MySQLPlatform;
597 if (
$name ===
'prefix') {
598 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.
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.
disableQueryCache()
Disable the query cache.
beginTimer(array $keys)
Start the timer (when enabled)
getDataRow(QueryBuilder $query, $callback=null)
Retrieve a single row from the database.
enableQueryCache()
Enable the query 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.
Query builder for fetching data from the database.
endTimer(array $keys)
Ends the timer (when enabled)