Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Db.php « Tracker « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e5ec25f57fdaa4063dac665ec6c7527cbd00aed4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Tracker;

use Exception;
use PDOStatement;
use Piwik\Common;
use Piwik\Config;
use Piwik\Piwik;
use Piwik\Timer;
use Piwik\Tracker;
use Piwik\Tracker\Db\DbException;
use Piwik\Tracker\Db\Mysqli;
use Piwik\Tracker\Db\Pdo\Mysql;

/**
 * Simple database wrapper.
 * We can't afford to have a dependency with the Zend_Db module in Tracker.
 * We wrote this simple class
 *
 */
abstract class Db
{
    protected static $profiling = false;

    protected $queriesProfiling = array();

    protected $connection = null;

    /**
     * Enables the SQL profiling.
     * For each query, saves in the DB the time spent on this query.
     * Very useful to see the slow query under heavy load.
     * You can then use Piwik::displayDbTrackerProfile();
     * to display the SQLProfiling report and see which queries take time, etc.
     */
    public static function enableProfiling()
    {
        self::$profiling = true;
    }

    /**
     * Disables the SQL profiling logging.
     */
    public static function disableProfiling()
    {
        self::$profiling = false;
    }

    /**
     * Returns true if the SQL profiler is enabled
     * Only used by the unit test that tests that the profiler is off on a  production server
     *
     * @return bool
     */
    public static function isProfilingEnabled()
    {
        return self::$profiling;
    }

    /**
     * Initialize profiler
     *
     * @return Timer
     */
    protected function initProfiler()
    {
        return new Timer;
    }

    /**
     * Record query profile
     *
     * @param string $query
     * @param Timer $timer
     */
    protected function recordQueryProfile($query, $timer)
    {
        if (!isset($this->queriesProfiling[$query])) {
            $this->queriesProfiling[$query] = array('sum_time_ms' => 0, 'count' => 0);
        }

        $time  = $timer->getTimeMs(2);
        $time += $this->queriesProfiling[$query]['sum_time_ms'];
        $count = $this->queriesProfiling[$query]['count'] + 1;

        $this->queriesProfiling[$query] = array('sum_time_ms' => $time, 'count' => $count);
    }

    /**
     * When destroyed, if SQL profiled enabled, logs the SQL profiling information
     */
    public function recordProfiling()
    {
        if (is_null($this->connection)) {
            return;
        }

        // turn off the profiler so we don't profile the following queries
        self::$profiling = false;

        foreach ($this->queriesProfiling as $query => $info) {
            $time  = $info['sum_time_ms'];
            $time  = Common::forceDotAsSeparatorForDecimalPoint($time);
            $count = $info['count'];

            $queryProfiling = "INSERT INTO " . Common::prefixTable('log_profiling') . "
						(query,count,sum_time_ms) VALUES (?,$count,$time)
						ON DUPLICATE KEY UPDATE count=count+$count,sum_time_ms=sum_time_ms+$time";
            $this->query($queryProfiling, array($query));
        }

        // turn back on profiling
        self::$profiling = true;
    }

    /**
     * Connects to the DB
     *
     * @throws \Piwik\Tracker\Db\DbException if there was an error connecting the DB
     */
    abstract public function connect();

    /**
     * Disconnects from the server
     */
    public function disconnect()
    {
        $this->connection = null;
    }

    /**
     * Returns an array containing all the rows of a query result, using optional bound parameters.
     *
     * @param string $query Query
     * @param array $parameters Parameters to bind
     * @see query()
     * @throws \Piwik\Tracker\Db\DbException if an exception occurred
     */
    abstract public function fetchAll($query, $parameters = array());

    /**
     * Returns the first row of a query result, using optional bound parameters.
     *
     * @param string $query Query
     * @param array $parameters Parameters to bind
     * @see also query()
     *
     * @throws DbException if an exception occurred
     */
    abstract public function fetch($query, $parameters = array());

    /**
     * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db interface
     *
     * @see fetch()
     * @param string $query Query
     * @param array $parameters Parameters to bind
     * @return
     */
    public function fetchRow($query, $parameters = array())
    {
        return $this->fetch($query, $parameters);
    }

    /**
     * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db interface
     *
     * @see fetch()
     * @param string $query Query
     * @param array $parameters Parameters to bind
     * @return bool|mixed
     */
    public function fetchOne($query, $parameters = array())
    {
        $result = $this->fetch($query, $parameters);
        return is_array($result) && !empty($result) ? reset($result) : false;
    }

    /**
     * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db + PDO interface
     *
     * @see fetch()
     * @param string $query Query
     * @param array $parameters Parameters to bind
     * @return
     */
    public function exec($query, $parameters = array())
    {
        return $this->fetch($query, $parameters);
    }

    /**
     * Return number of affected rows in last query
     *
     * @param mixed $queryResult Result from query()
     * @return int
     */
    abstract public function rowCount($queryResult);

    /**
     * Executes a query, using optional bound parameters.
     *
     * @param string $query Query
     * @param array $parameters Parameters to bind array('idsite'=> 1)
     *
     * @return PDOStatement or false if failed
     * @throws DbException if an exception occurred
     */
    abstract public function query($query, $parameters = array());

    /**
     * Returns the last inserted ID in the DB
     * Wrapper of PDO::lastInsertId()
     *
     * @return int
     */
    abstract public function lastInsertId();

    /**
     * Test error number
     *
     * @param Exception $e
     * @param string $errno
     * @return bool  True if error number matches; false otherwise
     */
    abstract public function isErrNo($e, $errno);

    /**
     * Factory to create database objects
     *
     * @param array $configDb Database configuration
     * @throws Exception
     * @return \Piwik\Tracker\Db\Mysqli|\Piwik\Tracker\Db\Pdo\Mysql
     */
    public static function factory($configDb)
    {
        /**
         * Triggered before a connection to the database is established by the Tracker.
         *
         * This event can be used to change the database connection settings used by the Tracker.
         *
         * @param array $dbInfos Reference to an array containing database connection info,
         *                       including:
         *
         *                       - **host**: The host name or IP address to the MySQL database.
         *                       - **username**: The username to use when connecting to the
         *                                       database.
         *                       - **password**: The password to use when connecting to the
         *                                       database.
         *                       - **dbname**: The name of the Piwik MySQL database.
         *                       - **port**: The MySQL database port to use.
         *                       - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'`
         *                       - **type**: The MySQL engine to use, for instance 'InnoDB'
         */
        Piwik::postEvent('Tracker.getDatabaseConfig', array(&$configDb));

        switch ($configDb['adapter']) {
            case 'PDO\MYSQL':
            case 'PDO_MYSQL': // old format pre Piwik 2
                require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Pdo/Mysql.php';
                return new Mysql($configDb);

            case 'MYSQLI':
                require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Mysqli.php';
                return new Mysqli($configDb);
        }

        throw new Exception('Unsupported database adapter ' . $configDb['adapter']);
    }

    public static function connectPiwikTrackerDb()
    {
        $db = null;
        $configDb = Config::getInstance()->database;

        if (!isset($configDb['port'])) {
            // before 0.2.4 there is no port specified in config file
            $configDb['port'] = '3306';
        }

        $db = self::factory($configDb);
        $db->connect();

        return $db;
    }
}