File size: 10,429 Bytes
bf8c0ce | 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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | <?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Tests\Integration;
use Exception;
use Piwik\Common;
use Piwik\Config;
use Piwik\DataAccess\TableMetadata;
use Piwik\Db;
use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
/**
* @group Core
*/
class DbTest extends IntegrationTestCase
{
private $dbReaderConfigBackup;
public function setUp(): void
{
parent::setUp();
$this->dbReaderConfigBackup = Config::getInstance()->database_reader;
}
public function tearDown(): void
{
Db::destroyDatabaseObject();
Config::getInstance()->database_reader = $this->dbReaderConfigBackup;
parent::tearDown();
}
// this test is for PDO which will fail if execute() is called w/ a null param value
public function testInsertWithNull()
{
$GLOBALS['abc'] = 1;
$table = Common::prefixTable('testtable');
Db::exec("CREATE TABLE `$table` (
testid BIGINT NOT NULL AUTO_INCREMENT,
testvalue BIGINT NULL,
PRIMARY KEY (testid)
)");
Db::query("INSERT INTO `$table` (testvalue) VALUES (?)", [4]);
Db::query("INSERT INTO `$table` (testvalue) VALUES (?)", [null]);
$values = Db::fetchAll("SELECT testid, testvalue FROM `$table`");
$expected = [
['testid' => 1, 'testvalue' => 4],
['testid' => 2, 'testvalue' => null],
];
$this->assertEquals($expected, $values);
}
public function testGetColumnNamesFromTable()
{
$this->assertColumnNames('access', array('idaccess', 'login', 'idsite', 'access'));
$this->assertColumnNames('option', array('option_name', 'option_value', 'autoload'));
}
public function testGetDb()
{
$db = Db::get();
$this->assertNotEmpty($db);
$this->assertTrue($db instanceof Db\AdapterInterface);
}
public function testHasReaderDatabaseObjectByDefaultNotInUse()
{
$this->assertFalse(Db::hasReaderDatabaseObject());
}
public function testHasReaderConfiguredByDefaultNotConfigured()
{
$this->assertFalse(Db::hasReaderConfigured());
}
public function testGetReaderWhenNotConfiguredStillReturnsRegularDbConnection()
{
$this->assertFalse(Db::hasReaderConfigured());// ensure no reader is configured
$db = Db::getReader();
$this->assertNotEmpty($db);
$this->assertTrue($db instanceof Db\AdapterInterface);
}
public function testWithReader()
{
Config::getInstance()->database_reader = Config::getInstance()->database;
$this->assertFalse(Db::hasReaderDatabaseObject());
$this->assertTrue(Db::hasReaderConfigured());
$db = Db::getReader();
$this->assertNotEmpty($db);
$this->assertTrue($db instanceof Db\AdapterInterface);
$this->assertTrue(Db::hasReaderDatabaseObject());
Db::destroyDatabaseObject();
$this->assertFalse(Db::hasReaderDatabaseObject());
}
public function testWithReaderCreatesDifferentConnectionForDb()
{
Config::getInstance()->database_reader = Config::getInstance()->database;
$db = Db::getReader();
$this->assertNotSame($db->getConnection(), Db::get()->getConnection());
}
public function testWithoutReaderUsesSameDbConnection()
{
$this->assertFalse(Db::hasReaderConfigured());
$this->assertFalse(Db::hasReaderDatabaseObject());
$db = Db::getReader();
$this->assertSame($db->getConnection(), Db::get()->getConnection());
}
public function testWithReaderCanReconnectToWriterIfServerHasGoneAway(): void
{
Config::getInstance()->database_reader = Config::getInstance()->database;
$connectionId = $this->setUpMySQLHasGoneAwayConnection();
$reconnectionId = Db::executeWithDatabaseWriterReconnectionAttempt(function () {
return Db::query('SELECT CONNECTION_ID()')->fetchColumn();
});
self::assertNotSame($connectionId, $reconnectionId);
}
public function testWithReaderDoesNotInterceptNonGoneAwayErrors(): void
{
Config::getInstance()->database_reader = Config::getInstance()->database;
$expectedConnectionId = Db::query('SELECT CONNECTION_ID()')->fetchColumn();
$dbException = null;
try {
Db::executeWithDatabaseWriterReconnectionAttempt(function () {
Db::query('SHOW SYNTAX ERROR');
});
} catch (Exception $e) {
$dbException = $e;
}
self::assertNotNull($dbException, 'Expected database exception was not thrown');
self::assertTrue(
Db::get()->isErrNo(
$dbException,
\Piwik\Updater\Migration\Db::ERROR_CODE_SYNTAX_ERROR
)
);
// verify the connection has not been replaced
$connectionId = Db::query('SELECT CONNECTION_ID()')->fetchColumn();
self::assertSame($expectedConnectionId, $connectionId);
}
public function testWithoutReaderDoesNotReconnectIfServerHasGoneAway(): void
{
$this->setUpMySQLHasGoneAwayConnection();
$dbException = null;
try {
Db::executeWithDatabaseWriterReconnectionAttempt(function () {
Db::query('SELECT 1');
});
} catch (Exception $e) {
$dbException = $e;
}
self::assertNotNull($dbException, 'Expected database exception was not thrown');
self::assertTrue(
Db::get()->isErrNo(
$dbException,
\Piwik\Updater\Migration\Db::ERROR_CODE_MYSQL_SERVER_HAS_GONE_AWAY
)
|| false !== stripos($dbException->getMessage(), 'server has gone away')
);
}
private function assertColumnNames($tableName, $expectedColumnNames)
{
$tableMetadataAccess = new TableMetadata();
$colmuns = $tableMetadataAccess->getColumns(Common::prefixTable($tableName));
$this->assertEquals($expectedColumnNames, $colmuns);
}
/**
* @dataProvider getDbAdapter
*/
public function testSqlModeIsSetPDO($adapter, $expectedClass)
{
Db::destroyDatabaseObject();
Config::getInstance()->database['adapter'] = $adapter;
$db = Db::get();
// make sure test is useful and setting adapter works
$this->assertInstanceOf($expectedClass, $db);
$result = $db->fetchOne('SELECT @@SESSION.sql_mode');
$expected = 'NO_AUTO_VALUE_ON_ZERO';
$this->assertSame($expected, $result);
}
public function testGetDbLockShouldThrowAnExceptionIfDbLockNameIsTooLong()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('name has to be 64 characters or less');
Db::getDbLock(str_pad('test', 65, '1'));
}
public function testGetDbLockShouldGetLock()
{
$db = Db::get();
$this->assertTrue(Db::getDbLock('MyLock'));
// same session still has lock
$this->assertTrue(Db::getDbLock('MyLock'));
Db::setDatabaseObject(null);
// different session, should not be able to acquire lock
$this->assertFalse(Db::getDbLock('MyLock', 1));
// different session cannot release lock
$this->assertFalse(Db::releaseDbLock('MyLock'));
Db::destroyDatabaseObject();
// release lock again by using previous session
Db::setDatabaseObject($db);
$this->assertTrue(Db::releaseDbLock('MyLock'));
Db::destroyDatabaseObject();
}
/**
* @dataProvider getDbAdapter
*/
public function testGetRowCount($adapter, $expectedClass)
{
Db::destroyDatabaseObject();
Config::getInstance()->database['adapter'] = $adapter;
$db = Db::get();
// make sure test is useful and setting adapter works
$this->assertInstanceOf($expectedClass, $db);
$result = $db->query('select 21');
$this->assertEquals(1, $db->rowCount($result));
}
/**
* @dataProvider getDbAdapter
*/
public function testConnectionCollationDefault(string $adapter, string $expectedClass): void
{
Db::destroyDatabaseObject();
$config = Config::getInstance();
$config->database['adapter'] = $adapter;
$config->database['collation'] = null;
$db = Db::get();
self::assertInstanceOf($expectedClass, $db);
// exact value depends on database used
$currentCollation = $db->fetchOne('SELECT @@collation_connection');
self::assertStringStartsWith('utf8', $currentCollation);
}
/**
* @dataProvider getDbAdapter
*/
public function testConnectionCollationSetInConfig(string $adapter, string $expectedClass): void
{
Db::destroyDatabaseObject();
$config = Config::getInstance();
$config->database['adapter'] = $adapter;
$config->database['collation'] = $config->database['charset'] . '_swedish_ci';
$db = Db::get();
self::assertInstanceOf($expectedClass, $db);
$currentCollation = $db->fetchOne('SELECT @@collation_connection');
self::assertSame($config->database['collation'], $currentCollation);
}
public function getDbAdapter()
{
return array(
array('Mysqli', 'Piwik\Db\Adapter\Mysqli'),
array('PDO\MYSQL', 'Piwik\Db\Adapter\Pdo\Mysql'),
);
}
/**
* Forces Db::get() to return a database connection that
* will throw "server has gone away" when running a query.
*
* @return string The MySQL connection id of the killed connection
*/
private function setUpMySQLHasGoneAwayConnection(): string
{
// get extra connection to kill database connection
// circumvents "query execution was interrupted" errors
$db = Db::get();
Db::setDatabaseObject(null);
// connect and kill connection
$connectionId = Db::query('SELECT CONNECTION_ID()')->fetchColumn();
$db->exec('KILL ' . $connectionId);
// clean up extra connection
$db->closeConnection();
unset($db);
return (string) $connectionId;
}
}
|