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 = [];
76 $this->query_cache = $query_cache;
78 $this->resetConnections($config);
89 $this->closeConnections();
93 $this->query_cache->enable();
94 $this->query_cache->clear();
106 foreach ($this->connections as $connection) {
107 $connection->close();
110 $this->connections = [];
121 if (isset($this->connections[$type])) {
122 return $this->connections[
$type];
123 }
else if (isset($this->connections[
'readwrite'])) {
124 return $this->connections[
'readwrite'];
127 $this->setupConnections();
129 return $this->getConnection($type);
141 if ($this->config->isDatabaseSplit()) {
142 $this->connect(
'read');
143 $this->connect(
'write');
145 $this->connect(
'readwrite');
160 $conf = $this->config->getConnectionConfig(
$type);
163 'dbname' => $conf[
'database'],
164 'user' => $conf[
'user'],
165 'password' => $conf[
'password'],
166 'host' => $conf[
'host'],
167 'port' => $conf[
'port'],
168 'charset' => $conf[
'encoding'],
169 'driver' =>
'pdo_mysql',
173 $this->connections[
$type] = DriverManager::getConnection(
$params);
176 $sub_query =
"SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')";
177 $this->connections[
$type]->executeStatement(
"SET SESSION sql_mode=($sub_query);");
180 $this->
log(LogLevel::ERROR, $e);
182 if ($e->getCode() == 1102 || $e->getCode() == 1049) {
183 $msg =
"Elgg couldn't select the database '{$conf['database']}'. Please check that the database is created and you have access to it.";
185 $msg =
"Elgg couldn't connect to the database using the given credentials. Check the settings file.";
208 return $this->getResults($query, $callback,
false);
224 return $this->getResults($query, $callback,
true);
238 $params = $query->getParameters();
239 $sql = $query->getSQL();
241 $this->
getLogger()->info(
"DB insert query {$sql} (params: " . print_r(
$params,
true) .
')');
243 $this->query_cache->clear();
245 $this->executeQuery($query);
246 return (
int) $query->getConnection()->lastInsertId();
260 $params = $query->getParameters();
261 $sql = $query->getSQL();
263 $this->
getLogger()->info(
"DB update query {$sql} (params: " . print_r(
$params,
true) .
')');
265 $this->query_cache->clear();
267 $result = $this->executeQuery($query);
268 if (!$get_num_rows) {
285 $params = $query->getParameters();
286 $sql = $query->getSQL();
288 $this->
getLogger()->info(
"DB delete query {$sql} (params: " . print_r(
$params,
true) .
')');
290 $this->query_cache->clear();
292 $result = $this->executeQuery($query);
308 if (is_string($callback)) {
312 if (is_object($callback)) {
313 return spl_object_hash($callback) .
'::__invoke';
316 if (is_array($callback)) {
317 if (is_string($callback[0])) {
318 return "{$callback[0]}::{$callback[1]}";
321 return spl_object_hash($callback[0]) .
"::{$callback[1]}";
340 protected function getResults(QueryBuilder
$query, $callback = null,
bool $single =
false) {
341 $params = $query->getParameters();
342 $sql = $query->getSQL();
347 $extras = (int) $single .
'|';
349 if (!is_callable($callback)) {
353 $extras .= $this->fingerprintCallback($callback);
356 $hash = $this->query_cache->getHash($sql,
$params, $extras);
358 $cached_results = $this->query_cache->get($hash);
359 if (isset($cached_results)) {
360 return $cached_results;
363 $this->
getLogger()->info(
"DB select query {$sql} (params: " . print_r(
$params,
true) .
')');
367 $stmt = $this->executeQuery($query);
369 while ($row = $stmt->fetchAssociative()) {
370 $row_obj = (object) $row;
372 $row_obj = call_user_func($callback, $row_obj);
379 $return[] = $row_obj;
384 $this->query_cache->set($hash, $return);
403 $result = $this->trackQuery($query,
function() use ($query) {
405 return $query->executeQuery();
407 return $query->executeStatement();
413 $ex->setQuery($query->getSQL());
431 $params = $query->getParameters();
432 $sql = $query->getSQL();
434 $this->query_count++;
436 $timer_key = preg_replace(
'~\\s+~',
' ',
trim($sql .
'|' . serialize(
$params)));
439 $stop_timer =
function() use ($timer_key) {
440 $this->
endTimer([
'SQL', $timer_key]);
468 $this->delayed_queries[] = [
469 self::DELAYED_QUERY =>
$query,
470 self::DELAYED_HANDLER => $callback,
482 foreach ($this->delayed_queries as $set) {
483 $query = $set[self::DELAYED_QUERY];
484 $handler = $set[self::DELAYED_HANDLER];
487 $stmt = $this->executeQuery(
$query);
498 $this->delayed_queries = [];
509 $this->query_cache->enable();
521 $this->query_cache->disable();
530 return $this->query_count;
541 $driver = $this->getConnection(
$type)->getWrappedConnection();
542 if ($driver instanceof ServerInfoAwareConnection) {
543 $version = $driver->getServerVersion();
545 if ($this->isMariaDB(
$type)) {
546 if (str_starts_with(
$version,
'5.5.5-')) {
565 $driver = $this->getConnection(
$type)->getWrappedConnection();
566 if ($driver instanceof ServerInfoAwareConnection) {
567 $version = $driver->getServerVersion();
569 return stristr(
$version,
'mariadb') !==
false;
584 if (
$name ===
'prefix') {
585 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
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.
endTimer(array $keys)
Ends the timer (when enabled)