30 const DELAYED_QUERY =
'q';
31 const DELAYED_HANDLER =
'h';
36 private $table_prefix;
41 private $connections = [];
46 private $query_count = 0;
62 protected $delayed_queries = [];
79 $this->query_cache = $query_cache;
82 $this->resetConnections($db_config);
93 $this->closeConnections();
97 $this->query_cache->enable();
98 $this->query_cache->clear();
110 foreach ($this->connections as $connection) {
111 $connection->close();
114 $this->connections = [];
125 if (isset($this->connections[$type])) {
126 return $this->connections[
$type];
127 }
else if (isset($this->connections[
'readwrite'])) {
128 return $this->connections[
'readwrite'];
131 $this->setupConnections();
133 return $this->getConnection($type);
145 if ($this->db_config->isDatabaseSplit()) {
146 $this->connect(
'read');
147 $this->connect(
'write');
149 $this->connect(
'readwrite');
164 $conf = $this->db_config->getConnectionConfig(
$type);
167 'dbname' => $conf[
'database'],
168 'user' => $conf[
'user'],
169 'password' => $conf[
'password'],
170 'host' => $conf[
'host'],
171 'port' => $conf[
'port'],
172 'charset' => $conf[
'encoding'],
173 'driver' =>
'pdo_mysql',
177 $this->connections[
$type] = DriverManager::getConnection(
$params);
180 $sub_query =
"SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')";
181 $this->connections[
$type]->executeStatement(
"SET SESSION sql_mode=($sub_query);");
182 }
catch (\Exception $e) {
184 $this->
log(LogLevel::ERROR, $e);
186 if ($e->getCode() == 1102 || $e->getCode() == 1049) {
187 $msg =
"Elgg couldn't select the database '{$conf['database']}'. Please check that the database is created and you have access to it.";
189 $msg =
"Elgg couldn't connect to the database using the given credentials. Check the settings file.";
212 return $this->getResults($query, $callback,
false);
228 return $this->getResults($query, $callback,
true);
242 $params = $query->getParameters();
243 $sql = $query->getSQL();
245 $this->
getLogger()->info(
"DB insert query {$sql} (params: " . print_r(
$params,
true) .
')');
247 $this->query_cache->clear();
249 $this->executeQuery($query);
250 return (
int) $query->getConnection()->lastInsertId();
264 $params = $query->getParameters();
265 $sql = $query->getSQL();
267 $this->
getLogger()->info(
"DB update query {$sql} (params: " . print_r(
$params,
true) .
')');
269 $this->query_cache->clear();
271 $result = $this->executeQuery($query);
272 if (!$get_num_rows) {
289 $params = $query->getParameters();
290 $sql = $query->getSQL();
292 $this->
getLogger()->info(
"DB delete query {$sql} (params: " . print_r(
$params,
true) .
')');
294 $this->query_cache->clear();
296 $result = $this->executeQuery($query);
312 if (is_string($callback)) {
316 if (is_object($callback)) {
317 return spl_object_hash($callback) .
'::__invoke';
320 if (is_array($callback)) {
321 if (is_string($callback[0])) {
322 return "{$callback[0]}::{$callback[1]}";
325 return spl_object_hash($callback[0]) .
"::{$callback[1]}";
344 protected function getResults(QueryBuilder
$query, $callback = null,
bool $single =
false) {
345 $params = $query->getParameters();
346 $sql = $query->getSQL();
351 $extras = (int) $single .
'|';
353 if (!is_callable($callback)) {
357 $extras .= $this->fingerprintCallback($callback);
360 $hash = $this->query_cache->getHash($sql,
$params, $extras);
362 $cached_results = $this->query_cache->get($hash);
363 if (isset($cached_results)) {
364 return $cached_results;
367 $this->
getLogger()->info(
"DB select query {$sql} (params: " . print_r(
$params,
true) .
')');
371 $stmt = $this->executeQuery($query);
373 while ($row = $stmt->fetchAssociative()) {
374 $row_obj = (object) $row;
376 $row_obj = call_user_func($callback, $row_obj);
383 $return[] = $row_obj;
388 $this->query_cache->set($hash, $return);
407 $result = $this->trackQuery($query,
function() use ($query) {
409 return $query->executeQuery();
411 return $query->executeStatement();
414 }
catch (\Exception $e) {
417 $ex->setQuery($query->getSQL());
435 $params = $query->getParameters();
436 $sql = $query->getSQL();
438 $this->query_count++;
440 $timer_key = preg_replace(
'~\\s+~',
' ',
trim($sql .
'|' . serialize(
$params)));
443 $stop_timer =
function() use ($timer_key) {
444 $this->
endTimer([
'SQL', $timer_key]);
449 }
catch (\Exception $e) {
472 if (Application::isCli() && !$this->config->testing_mode) {
477 $stmt = $this->executeQuery($query);
479 if (is_callable($callback)) {
480 call_user_func($callback, $stmt);
482 }
catch (\Throwable $t) {
490 $this->delayed_queries[] = [
491 self::DELAYED_QUERY =>
$query,
492 self::DELAYED_HANDLER => $callback,
504 foreach ($this->delayed_queries as $set) {
505 $query = $set[self::DELAYED_QUERY];
506 $handler = $set[self::DELAYED_HANDLER];
509 $stmt = $this->executeQuery(
$query);
514 }
catch (\Throwable $t) {
520 $this->delayed_queries = [];
531 $this->query_cache->enable();
543 $this->query_cache->disable();
552 return $this->query_count;
563 $driver = $this->getConnection(
$type)->getWrappedConnection();
564 if ($driver instanceof ServerInfoAwareConnection) {
565 $version = $driver->getServerVersion();
567 if ($this->isMariaDB(
$type)) {
568 if (str_starts_with(
$version,
'5.5.5-')) {
587 $driver = $this->getConnection(
$type)->getWrappedConnection();
588 if ($driver instanceof ServerInfoAwareConnection) {
589 $version = $driver->getServerVersion();
591 return stristr(
$version,
'mariadb') !==
false;
606 if (
$name ===
'prefix') {
607 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
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.
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.
__construct(DbConfig $db_config, QueryCache $query_cache, Config $config)
Constructor.
endTimer(array $keys)
Ends the timer (when enabled)