Piwik\
Contains SQL related helper functions for Matomo (formerly Piwik)'s MySQL database.
Plugins should always use this class to execute SQL against the database.
$rows = Db::fetchAll("SELECT col1, col2 FROM mytable WHERE thing = ?", array('thingvalue'));
foreach ($rows as $row) {
doSomething($row['col1'], $row['col2']);
}
$value = Db::fetchOne("SELECT MAX(col1) FROM mytable");
doSomethingElse($value);
Db::query("DELETE FROM mytable WHERE id < ?", array(23));
This class defines the following properties:
$lockPrivilegeGranted
— Cached result of isLockprivilegeGranted function.$lockPrivilegeGranted
Cached result of isLockprivilegeGranted function.
Public so tests can simulate the situation where the lock tables privilege isn't granted.
bool
value.The class defines the following methods:
get()
— Returns the database connection and creates it if it hasn't been already.getReader()
— Returns the database connection and creates it if it hasn't been already.getDatabaseConfig()
— Returns an array with the Database connection information.createDatabaseObject()
— Connects to the database.createReaderDatabaseObject()
— Connects to the reader database.destroyDatabaseObject()
— Disconnects and destroys the database connection.exec()
— Executes an unprepared SQL query.query()
ash; Executes an SQL query and returns the Zend_Db_Statement for the query.fetchAll()
— Executes an SQL SELECT
statement and returns all fetched rows from the result set.fetchRow()
— Executes an SQL SELECT
statement and returns the first row of the result set.fetchOne()
— Executes an SQL SELECT
statement and returns the first column value of the first row in the result set.fetchAssoc()
— Executes an SQL SELECT
statement and returns the entire result set indexed by the first selected field.deleteAllRows()
— Deletes all desired rows in a table, while using a limit.optimizeTables()
— Runs an OPTIMIZE TABLE
query on the supplied table or tables.dropTables()
— Drops the supplied table or tables.dropAllTables()
— Drops all tableslockTables()
— Locks the supplied table or tables.unlockAllTables()
— Releases all table locks.segmentedFetchFirst()
— Performs a SELECT
statement on a table one chunk at a time and returns the first successfully fetched value.segmentedFetchOne()
— Performs a SELECT
on a table one chunk at a time and returns an array of every fetched value.segmentedFetchAll()
— Performs a SELECT on a table one chunk at a time and returns an array of every fetched row.segmentedQuery()
— Performs a UPDATE
or DELETE
statement on a table one chunk at a time.getDbLock()
— Attempts to get a named lock.releaseDbLock()
— Releases a named lock.isLockPrivilegeGranted()
— Checks whether the database user is allowed to lock tables.enableQueryLog()
isQueryLogEnabled()
isOptimizeInnoDBSupported()
get()
Returns the database connection and creates it if it hasn't been already.
Piwik\Tracker\Db
|Piwik\Db\AdapterInterface
|Db
—getReader()
Since Matomo Matomo
Returns the database connection and creates it if it hasn't been already. Make sure to not write any data on the reader and only use the connection to read data.
Piwik\Tracker\Db
|Piwik\Db\AdapterInterface
|Db
—getDatabaseConfig()
Returns an array with the Database connection information.
It accepts the following parameter(s):
$dbConfig
(array
|null
) —It returns a array
value.
createDatabaseObject()
Connects to the database.
Shouldn't be called directly, use get() instead.
$dbConfig
(array
|null
) —
Connection parameters in an array. Defaults to the [database]
INI config section.createReaderDatabaseObject()
Since Matomo Matomo
Connects to the reader database.
Shouldn't be called directly, use get() instead.
$dbConfig
(array
|null
) —
Connection parameters in an array. Defaults to the [database]
INI config section.destroyDatabaseObject()
Disconnects and destroys the database connection.
For tests.
exec()
Executes an unprepared SQL query. Recommended for DDL statements like CREATE
,
DROP
and ALTER
. The return value is DBMS-specific. For MySQLI, it returns the
number of rows affected. For PDO, it returns a
Zend_Db_Statement object.
It accepts the following parameter(s):
$sql
(string
) —
The SQL query.Returns: integer
|Zend_Db_Statement
—
It throws one of the following exceptions:
Exception
— If there is an error in the SQL.query()
Executes an SQL query and returns the Zend_Db_Statement for the query.
This method is meant for non-query SQL statements like INSERT
and `UPDATE. If you want to fetch
data from the DB you should use one of the fetch... functions.
$sql
(string
) —
The SQL query.$parameters
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
.Zend_Db_Statement
value.Exception
— If there is a problem with the SQL or bind parameters.fetchAll()
Executes an SQL SELECT
statement and returns all fetched rows from the result set.
It accepts the following parameter(s):
$sql
(string
) —
The SQL query.$parameters
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
.Returns: array
—
The fetched rows, each element is an associative array mapping column names
with column values.
Exception
— If there is a problem with the SQL or bind parameters.fetchRow()
Executes an SQL SELECT
statement and returns the first row of the result set.
It accepts the following parameter(s):
$sql
(string
) —
The SQL query.$parameters
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
.Returns: array
—
The fetched row, each element is an associative array mapping column names
with column values.
Exception
— If there is a problem with the SQL or bind parameters.fetchOne()
Executes an SQL SELECT
statement and returns the first column value of the first
row in the result set.
$sql
(string
) —
The SQL query.$parameters
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
.string
value.Exception
— If there is a problem with the SQL or bind parameters.fetchAssoc()
Executes an SQL SELECT
statement and returns the entire result set indexed by the first
selected field.
It accepts the following parameter(s):
$sql
(string
) —
The SQL query.$parameters
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
.Returns: array
—
eg,
array('col1value1' => array('col2' => '...', 'col3' => ...),
'col1value2' => array('col2' => '...', 'col3' => ...))
Exception
— If there is a problem with the SQL or bind parameters.deleteAllRows()
Deletes all desired rows in a table, while using a limit. This function will execute many DELETE queries until there are no more rows to delete.
Use this function when you need to delete many thousands of rows from a table without locking the table for too long.
Example
// delete all visit rows whose ID is less than a certain value, 100000 rows at a time
$idVisit = // ...
Db::deleteAllRows(Common::prefixTable('log_visit'), "WHERE idvisit <= ?", "idvisit ASC", 100000, array($idVisit));
It accepts the following parameter(s):
$table
(string
) —
The name of the table to delete from. Must be prefixed (see Common::prefixTable()).$where
(string
) —
The where clause of the query. Must include the WHERE keyword.$orderBy
(string
) —
The column to order by and the order by direction, eg, idvisit ASC
.$maxRowsPerQuery
(int
) —
The maximum number of rows to delete per DELETE
query.$parameters
(array
) —
Parameters to bind for each query.Returns: int
—
The total number of rows deleted.
optimizeTables()
Runs an OPTIMIZE TABLE
query on the supplied table or tables.
Tables will only be optimized if the [General] enable_sql_optimize_queries
INI config option is
set to 1.
$tables
(string
|array
) —
The name of the table to optimize or an array of tables to optimize. Table names must be prefixed (see Common::prefixTable()).$force
(bool
) —
If true, the OPTIMIZE TABLE
query will be run even if InnoDB tables are being used.bool
value.dropTables()
Drops the supplied table or tables.
$tables
(string
|array
) —
The name of the table to drop or an array of table names to drop. Table names must be prefixed (see Common::prefixTable()).Zend_Db_Statement
value.dropAllTables()
Drops all tables
lockTables()
Locks the supplied table or tables.
NOTE: Matomo does not require the LOCK TABLES
privilege to be available. Matomo
should still work if it has not been granted.
$tablesToRead
(string
|array
) —
The table or tables to obtain 'read' locks on. Table names must be prefixed (see Common::prefixTable()).$tablesToWrite
(string
|array
) —
The table or tables to obtain 'write' locks on. Table names must be prefixed (see Common::prefixTable()).Zend_Db_Statement
value.unlockAllTables()
Releases all table locks.
NOTE: Matomo does not require the LOCK TABLES
privilege to be available. Matomo
should still work if it has not been granted.
Zend_Db_Statement
value.segmentedFetchFirst()
Performs a SELECT
statement on a table one chunk at a time and returns the first
successfully fetched value.
This function will execute a query on one set of rows in a table. If nothing is fetched, it will execute the query on the next set of rows and so on until the query returns a value.
This function will break up a SELECT into several smaller
SELECTs and
should be used when performing a
SELECTthat can take a long time to finish.
Using several smaller
SELECT`s will ensure that the table will not be locked
for too long.
Example
// find the most recent visit that is older than a certain date
$dateStart = // ...
$sql = "SELECT idvisit
FROM $logVisit
WHERE '$dateStart' > visit_last_action_time
AND idvisit <= ?
AND idvisit > ?
ORDER BY idvisit DESC
LIMIT 1";
// since visits
return Db::segmentedFetchFirst($sql, $maxIdVisit, 0, -self::$selectSegmentSize);
$sql
(string
) —
The SQL to perform. The last two conditions of the WHERE
expression must be as follows: 'id >= ? AND id < ?'
where id is the int id of the table.$first
(int
) —
The minimum ID to loop from.$last
(int
) —
The maximum ID to loop to.$step
(int
) —
The maximum number of rows to scan in one query.$params
(array
) —
Parameters to bind in the query, eg, array(param1 => value1, param2 => value2)
string
value.segmentedFetchOne()
Performs a SELECT
on a table one chunk at a time and returns an array
of every fetched value.
This function will break up a SELECT
query into several smaller queries by
using only a limited number of rows at a time. It will accumulate the results
of each smaller query and return the result.
This function should be used when performing a SELECT
that can
take a long time to finish. Using several smaller queries will ensure that
the table will not be locked for too long.
It accepts the following parameter(s):
$sql
(string
) —
The SQL to perform. The last two conditions of the WHERE
expression must be as follows: 'id >= ? AND id < ?'
where id is the int id of the table.$first
(int
) —
The minimum ID to loop from.$last
(int
) —
The maximum ID to loop to.$step
(int
) —
The maximum number of rows to scan in one query.$params
(array
) —
Parameters to bind in the query, array(param1 => value1, param2 => value2)
Returns: array
—
An array of primitive values.
segmentedFetchAll()
Performs a SELECT on a table one chunk at a time and returns an array of every fetched row.
This function will break up a SELECT
query into several smaller queries by
using only a limited number of rows at a time. It will accumulate the results
of each smaller query and return the result.
This function should be used when performing a SELECT
that can
take a long time to finish. Using several smaller queries will ensure that
the table will not be locked for too long.
It accepts the following parameter(s):
$sql
(string
) —
The SQL to perform. The last two conditions of the WHERE
expression must be as follows: 'id >= ? AND id < ?'
where id is the int id of the table.$first
(int
) —
The minimum ID to loop from.$last
(int
) —
The maximum ID to loop to.$step
(int
) —
The maximum number of rows to scan in one query.$params
(array
) —
Parameters to bind in the query, array( param1 => value1, param2 => value2)Returns: array
—
An array of rows that includes the result set of every smaller
query.
segmentedQuery()
Performs a UPDATE
or DELETE
statement on a table one chunk at a time.
This function will break up a query into several smaller queries by using only a limited number of rows at a time.
This function should be used when executing a non-query statement will take a long time to finish. Using several smaller queries will ensure that the table will not be locked for too long.
$sql
(string
) —
The SQL to perform. The last two conditions of the WHERE
expression must be as follows: 'id >= ? AND id < ?'
where id is the int id of the table.$first
(int
) —
The minimum ID to loop from.$last
(int
) —
The maximum ID to loop to.$step
(int
) —
The maximum number of rows to scan in one query.$params
(array
) —
Parameters to bind in the query, array(param1 => value1, param2 => value2)
getDbLock()
Attempts to get a named lock. This function uses a timeout of 1s, but will retry a set number of times.
It accepts the following parameter(s):
$lockName
(string
) —
The lock name.$maxRetries
(int
) —
The max number of times to retry.Returns: bool
—
true
if the lock was obtained, false
if otherwise.
Exception
— if Lock name is too longreleaseDbLock()
Releases a named lock.
It accepts the following parameter(s):
$lockName
(string
) —
The lock name.Returns: bool
—
true
if the lock was released, false
if otherwise.
isLockPrivilegeGranted()
Checks whether the database user is allowed to lock tables.
bool
value.enableQueryLog()
It accepts the following parameter(s):
$enable
(bool
) —It does not return anything or a mixed result.
isQueryLogEnabled()
boolean
value.isOptimizeInnoDBSupported()
It accepts the following parameter(s):
$version
It does not return anything or a mixed result.