| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 3.0.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\Database;
- use Cake\Collection\Collection;
- use Cake\Database\Connection;
- use Cake\Database\Driver\Mysql;
- use Cake\Database\Exception\MissingConnectionException;
- use Cake\Database\Exception\NestedTransactionRollbackException;
- use Cake\Database\Log\LoggingStatement;
- use Cake\Database\Log\QueryLogger;
- use Cake\Database\StatementInterface;
- use Cake\Database\Statement\BufferedStatement;
- use Cake\Datasource\ConnectionManager;
- use Cake\Log\Log;
- use Cake\TestSuite\TestCase;
- use Exception;
- use ReflectionMethod;
- use ReflectionProperty;
- /**
- * Tests Connection class
- */
- class ConnectionTest extends TestCase
- {
- public $fixtures = ['core.Things'];
- /**
- * Where the NestedTransactionRollbackException was created.
- *
- * @var int
- */
- protected $rollbackSourceLine = -1;
- /**
- * Internal states of nested transaction.
- *
- * @var array
- */
- protected $nestedTransactionStates = [];
- public function setUp()
- {
- parent::setUp();
- $this->connection = ConnectionManager::get('test');
- static::setAppNamespace();
- }
- public function tearDown()
- {
- Log::reset();
- $this->connection->disableSavePoints();
- $this->connection->setLogger(null);
- unset($this->connection);
- parent::tearDown();
- }
- /**
- * Auxiliary method to build a mock for a driver so it can be injected into
- * the connection object
- *
- * @return \Cake\Database\Driver|\PHPUnit_Framework_MockObject_MockObject
- */
- public function getMockFormDriver()
- {
- $driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
- $driver->expects($this->once())
- ->method('enabled')
- ->will($this->returnValue(true));
- return $driver;
- }
- /**
- * Tests connecting to database
- *
- * @return void
- */
- public function testConnect()
- {
- $this->assertTrue($this->connection->connect());
- $this->assertTrue($this->connection->isConnected());
- }
- /**
- * Tests creating a connection using no driver throws an exception
- *
- * @return void
- */
- public function testNoDriver()
- {
- $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
- $this->expectExceptionMessage('Database driver could not be found.');
- $connection = new Connection([]);
- }
- /**
- * Tests creating a connection using an invalid driver throws an exception
- *
- * @return void
- */
- public function testEmptyDriver()
- {
- $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
- $this->expectExceptionMessage('Database driver could not be found.');
- $connection = new Connection(['driver' => false]);
- }
- /**
- * Tests creating a connection using an invalid driver throws an exception
- *
- * @return void
- */
- public function testMissingDriver()
- {
- $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
- $this->expectExceptionMessage('Database driver \Foo\InvalidDriver could not be found.');
- $connection = new Connection(['driver' => '\Foo\InvalidDriver']);
- }
- /**
- * Tests trying to use a disabled driver throws an exception
- *
- * @return void
- */
- public function testDisabledDriver()
- {
- $this->expectException(\Cake\Database\Exception\MissingExtensionException::class);
- $this->expectExceptionMessage('Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency');
- $mock = $this->getMockBuilder(Mysql::class)
- ->setMethods(['enabled'])
- ->setMockClassName('DriverMock')
- ->getMock();
- $connection = new Connection(['driver' => $mock]);
- }
- /**
- * Tests that the `driver` option supports the short classname/plugin syntax.
- *
- * @return void
- */
- public function testDriverOptionClassNameSupport()
- {
- $connection = new Connection(['driver' => 'TestDriver']);
- $this->assertInstanceOf('\TestApp\Database\Driver\TestDriver', $connection->getDriver());
- $connection = new Connection(['driver' => 'TestPlugin.TestDriver']);
- $this->assertInstanceOf('\TestPlugin\Database\Driver\TestDriver', $connection->getDriver());
- list(, $name) = namespaceSplit(get_class($this->connection->getDriver()));
- $connection = new Connection(['driver' => $name]);
- $this->assertInstanceOf(get_class($this->connection->getDriver()), $connection->getDriver());
- }
- /**
- * Tests that connecting with invalid credentials or database name throws an exception
- *
- * @return void
- */
- public function testWrongCredentials()
- {
- $config = ConnectionManager::getConfig('test');
- $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
- $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
- $e = null;
- try {
- $connection->connect();
- } catch (MissingConnectionException $e) {
- }
- $this->assertNotNull($e);
- $this->assertStringStartsWith('Connection to database could not be established:', $e->getMessage());
- $this->assertInstanceOf('PDOException', $e->getPrevious());
- }
- /**
- * Tests creation of prepared statements
- *
- * @return void
- */
- public function testPrepare()
- {
- $sql = 'SELECT 1 + 1';
- $result = $this->connection->prepare($sql);
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertEquals($sql, $result->queryString);
- $query = $this->connection->newQuery()->select('1 + 1');
- $result = $this->connection->prepare($query);
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $sql = '#SELECT [`"\[]?1 \+ 1[`"\]]?#';
- $this->assertRegExp($sql, $result->queryString);
- }
- /**
- * Tests executing a simple query using bound values
- *
- * @return void
- */
- public function testExecuteWithArguments()
- {
- $sql = 'SELECT 1 + ?';
- $statement = $this->connection->execute($sql, [1], ['integer']);
- $this->assertCount(1, $statement);
- $result = $statement->fetch();
- $this->assertEquals([2], $result);
- $statement->closeCursor();
- $sql = 'SELECT 1 + ? + ? AS total';
- $statement = $this->connection->execute($sql, [2, 3], ['integer', 'integer']);
- $this->assertCount(1, $statement);
- $result = $statement->fetch('assoc');
- $this->assertEquals(['total' => 6], $result);
- $statement->closeCursor();
- $sql = 'SELECT 1 + :one + :two AS total';
- $statement = $this->connection->execute($sql, ['one' => 2, 'two' => 3], ['one' => 'integer', 'two' => 'integer']);
- $this->assertCount(1, $statement);
- $result = $statement->fetch('assoc');
- $statement->closeCursor();
- $this->assertEquals(['total' => 6], $result);
- }
- /**
- * Tests executing a query with params and associated types
- *
- * @return void
- */
- public function testExecuteWithArgumentsAndTypes()
- {
- $sql = "SELECT '2012-01-01' = ?";
- $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['date']);
- $result = $statement->fetch();
- $statement->closeCursor();
- $this->assertTrue((bool)$result[0]);
- }
- /**
- * test executing a buffered query interacts with Collection well.
- *
- * @return void
- */
- public function testBufferedStatementCollectionWrappingStatement()
- {
- $this->skipIf(
- !($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite),
- 'Only required for SQLite driver which does not support buffered results natively'
- );
- $this->loadFixtures('Things');
- $statement = $this->connection->query('SELECT * FROM things LIMIT 3');
- $collection = new Collection($statement);
- $result = $collection->extract('id')->toArray();
- $this->assertSame(['1', '2'], $result);
- // Check iteration after extraction
- $result = [];
- foreach ($collection as $v) {
- $result[] = $v['id'];
- }
- $this->assertSame(['1', '2'], $result);
- }
- /**
- * Tests that passing a unknown value to a query throws an exception
- *
- * @return void
- */
- public function testExecuteWithMissingType()
- {
- $this->expectException(\InvalidArgumentException::class);
- $sql = 'SELECT ?';
- $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['bar']);
- }
- /**
- * Tests executing a query with no params also works
- *
- * @return void
- */
- public function testExecuteWithNoParams()
- {
- $sql = 'SELECT 1';
- $statement = $this->connection->execute($sql);
- $result = $statement->fetch();
- $this->assertCount(1, $result);
- $this->assertEquals([1], $result);
- $statement->closeCursor();
- }
- /**
- * Tests it is possible to insert data into a table using matching types by key name
- *
- * @return void
- */
- public function testInsertWithMatchingTypes()
- {
- $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
- $result = $this->connection->insert(
- 'things',
- $data,
- ['id' => 'integer', 'title' => 'string', 'body' => 'string']
- );
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $result->closeCursor();
- $result = $this->connection->execute('SELECT * from things where id = 3');
- $this->assertCount(1, $result);
- $row = $result->fetch('assoc');
- $result->closeCursor();
- $this->assertEquals($data, $row);
- }
- /**
- * Tests it is possible to insert data into a table using matching types by array position
- *
- * @return void
- */
- public function testInsertWithPositionalTypes()
- {
- $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
- $result = $this->connection->insert(
- 'things',
- $data,
- ['integer', 'string', 'string']
- );
- $result->closeCursor();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $result = $this->connection->execute('SELECT * from things where id = 3');
- $this->assertCount(1, $result);
- $row = $result->fetch('assoc');
- $result->closeCursor();
- $this->assertEquals($data, $row);
- }
- /**
- * Tests an statement class can be reused for multiple executions
- *
- * @return void
- */
- public function testStatementReusing()
- {
- $total = $this->connection->execute('SELECT COUNT(*) AS total FROM things');
- $result = $total->fetch('assoc');
- $this->assertEquals(2, $result['total']);
- $total->closeCursor();
- $total->execute();
- $result = $total->fetch('assoc');
- $this->assertEquals(2, $result['total']);
- $total->closeCursor();
- $result = $this->connection->execute('SELECT title, body FROM things');
- $row = $result->fetch('assoc');
- $this->assertEquals('a title', $row['title']);
- $this->assertEquals('a body', $row['body']);
- $row = $result->fetch('assoc');
- $result->closeCursor();
- $this->assertEquals('another title', $row['title']);
- $this->assertEquals('another body', $row['body']);
- $result->execute();
- $row = $result->fetch('assoc');
- $result->closeCursor();
- $this->assertEquals('a title', $row['title']);
- }
- /**
- * Tests that it is possible to pass PDO constants to the underlying statement
- * object for using alternate fetch types
- *
- * @return void
- */
- public function testStatementFetchObject()
- {
- $result = $this->connection->execute('SELECT title, body FROM things');
- $row = $result->fetch(\PDO::FETCH_OBJ);
- $this->assertEquals('a title', $row->title);
- $this->assertEquals('a body', $row->body);
- }
- /**
- * Tests rows can be updated without specifying any conditions nor types
- *
- * @return void
- */
- public function testUpdateWithoutConditionsNorTypes()
- {
- $title = 'changed the title!';
- $body = 'changed the body!';
- $this->connection->update('things', ['title' => $title, 'body' => $body]);
- $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
- $this->assertCount(2, $result);
- $result->closeCursor();
- }
- /**
- * Tests it is possible to use key => value conditions for update
- *
- * @return void
- */
- public function testUpdateWithConditionsNoTypes()
- {
- $title = 'changed the title!';
- $body = 'changed the body!';
- $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
- $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Tests it is possible to use key => value and string conditions for update
- *
- * @return void
- */
- public function testUpdateWithConditionsCombinedNoTypes()
- {
- $title = 'changed the title!';
- $body = 'changed the body!';
- $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
- $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Tests you can bind types to update values
- *
- * @return void
- */
- public function testUpdateWithTypes()
- {
- $title = 'changed the title!';
- $body = new \DateTime('2012-01-01');
- $values = compact('title', 'body');
- $this->connection->update('things', $values, [], ['body' => 'date']);
- $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
- $this->assertCount(2, $result);
- $row = $result->fetch('assoc');
- $this->assertEquals('2012-01-01', $row['body']);
- $row = $result->fetch('assoc');
- $this->assertEquals('2012-01-01', $row['body']);
- $result->closeCursor();
- }
- /**
- * Tests you can bind types to update values
- *
- * @return void
- */
- public function testUpdateWithConditionsAndTypes()
- {
- $title = 'changed the title!';
- $body = new \DateTime('2012-01-01');
- $values = compact('title', 'body');
- $this->connection->update('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']);
- $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
- $this->assertCount(1, $result);
- $row = $result->fetch('assoc');
- $this->assertEquals('2012-01-01', $row['body']);
- $result->closeCursor();
- }
- /**
- * Tests delete from table with no conditions
- *
- * @return void
- */
- public function testDeleteNoConditions()
- {
- $this->connection->delete('things');
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests delete from table with conditions
- * @return void
- */
- public function testDeleteWithConditions()
- {
- $this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $result->closeCursor();
- $this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $result->closeCursor();
- $this->connection->delete('things', ['id' => '2'], ['id' => 'integer']);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to use simple database transactions
- *
- * @return void
- */
- public function testSimpleTransactions()
- {
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(2, $result);
- $result->closeCursor();
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $this->connection->commit();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- }
- /**
- * Tests that the destructor of Connection generates a warning log
- * when transaction is not closed
- *
- * @return void
- */
- public function testDestructorWithUncommittedTransaction()
- {
- $driver = $this->getMockFormDriver();
- $connection = new Connection(['driver' => $driver]);
- $connection->begin();
- $this->assertTrue($connection->inTransaction());
- $logger = $this->createMock('Psr\Log\AbstractLogger');
- $logger->expects($this->once())
- ->method('log')
- ->with('warning', $this->stringContains('The connection is going to be closed'));
- Log::setConfig('error', $logger);
- // Destroy the connection
- unset($connection);
- }
- /**
- * Tests that it is possible to use virtualized nested transaction
- * with early rollback algorithm
- *
- * @return void
- */
- public function testVirtualNestedTransaction()
- {
- //starting 3 virtual transaction
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->commit();
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(2, $result);
- }
- /**
- * Tests that it is possible to use virtualized nested transaction
- * with early rollback algorithm
- *
- * @return void
- */
- public function testVirtualNestedTransaction2()
- {
- //starting 3 virtual transaction
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(2, $result);
- }
- /**
- * Tests that it is possible to use virtualized nested transaction
- * with early rollback algorithm
- *
- * @return void
- */
- public function testVirtualNestedTransaction3()
- {
- //starting 3 virtual transaction
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->commit();
- $this->connection->commit();
- $this->connection->commit();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- }
- /**
- * Tests that it is possible to real use nested transactions
- *
- * @return void
- */
- public function testSavePoints()
- {
- $this->skipIf(!$this->connection->enableSavePoints(true));
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 2]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(0, $result);
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(2, $result);
- }
- /**
- * Tests that it is possible to real use nested transactions
- *
- * @return void
- */
- public function testSavePoints2()
- {
- $this->skipIf(!$this->connection->enableSavePoints(true));
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 1]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->begin();
- $this->connection->delete('things', ['id' => 2]);
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(0, $result);
- $this->connection->rollback();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- $this->connection->commit();
- $result = $this->connection->execute('SELECT * FROM things');
- $this->assertCount(1, $result);
- }
- /**
- * Tests inTransaction()
- *
- * @return void
- */
- public function testInTransaction()
- {
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->commit();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->commit();
- $this->assertFalse($this->connection->inTransaction());
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->begin();
- $this->connection->rollback();
- $this->assertFalse($this->connection->inTransaction());
- }
- /**
- * Tests inTransaction() with save points
- *
- * @return void
- */
- public function testInTransactionWithSavePoints()
- {
- $this->skipIf(
- $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver,
- 'SQLServer fails when this test is included.'
- );
- $this->skipIf(!$this->connection->enableSavePoints(true));
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->commit();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->commit();
- $this->assertFalse($this->connection->inTransaction());
- $this->connection->begin();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->begin();
- $this->connection->rollback();
- $this->assertTrue($this->connection->inTransaction());
- $this->connection->rollback();
- $this->assertFalse($this->connection->inTransaction());
- }
- /**
- * Tests connection can quote values to be safely used in query strings
- *
- * @return void
- */
- public function testQuote()
- {
- $this->skipIf(!$this->connection->supportsQuoting());
- $expected = "'2012-01-01'";
- $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
- $this->assertEquals($expected, $result);
- $expected = "'1'";
- $result = $this->connection->quote(1, 'string');
- $this->assertEquals($expected, $result);
- $expected = "'hello'";
- $result = $this->connection->quote('hello', 'string');
- $this->assertEquals($expected, $result);
- }
- /**
- * Tests identifier quoting
- *
- * @return void
- */
- public function testQuoteIdentifier()
- {
- $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
- ->setMethods(['enabled'])
- ->getMock();
- $driver->expects($this->once())
- ->method('enabled')
- ->will($this->returnValue(true));
- $connection = new Connection(['driver' => $driver]);
- $result = $connection->quoteIdentifier('name');
- $expected = '"name"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Model.*');
- $expected = '"Model".*';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Items.No_ 2');
- $expected = '"Items"."No_ 2"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Items.No_ 2 thing');
- $expected = '"Items"."No_ 2 thing"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Items.No_ 2 thing AS thing');
- $expected = '"Items"."No_ 2 thing" AS "thing"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Items.Item Category Code = :c1');
- $expected = '"Items"."Item Category Code" = :c1';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('MTD()');
- $expected = 'MTD()';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('(sm)');
- $expected = '(sm)';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('name AS x');
- $expected = '"name" AS "x"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Model.name AS x');
- $expected = '"Model"."name" AS "x"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Function(Something.foo)');
- $expected = 'Function("Something"."foo")';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
- $expected = 'Function(SubFunction("Something"."foo"))';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
- $expected = 'Function("Something"."foo") AS "x"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('name-with-minus');
- $expected = '"name-with-minus"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('my-name');
- $expected = '"my-name"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Foo-Model.*');
- $expected = '"Foo-Model".*';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Team.P%');
- $expected = '"Team"."P%"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Team.G/G');
- $expected = '"Team"."G/G"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Model.name as y');
- $expected = '"Model"."name" AS "y"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('nämé');
- $expected = '"nämé"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('aßa.nämé');
- $expected = '"aßa"."nämé"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('aßa.*');
- $expected = '"aßa".*';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Modeß.nämé as y');
- $expected = '"Modeß"."nämé" AS "y"';
- $this->assertEquals($expected, $result);
- $result = $connection->quoteIdentifier('Model.näme Datum as y');
- $expected = '"Model"."näme Datum" AS "y"';
- $this->assertEquals($expected, $result);
- }
- /**
- * Tests default return vale for logger() function
- *
- * @return void
- */
- public function testGetLoggerDefault()
- {
- $logger = $this->connection->getLogger();
- $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
- $this->assertSame($logger, $this->connection->getLogger());
- }
- /**
- * Tests that a custom logger object can be set
- *
- * @group deprecated
- * @return void
- */
- public function testSetLogger()
- {
- $this->deprecated(function () {
- $logger = new QueryLogger();
- $this->connection->logger($logger);
- $this->assertSame($logger, $this->connection->logger());
- });
- }
- /**
- * Tests setting and getting the logger object
- *
- * @return void
- */
- public function testGetAndSetLogger()
- {
- $logger = new QueryLogger();
- $this->connection->setLogger($logger);
- $this->assertSame($logger, $this->connection->getLogger());
- }
- /**
- * Tests that statements are decorated with a logger when logQueries is set to true
- *
- * @return void
- */
- public function testLoggerDecorator()
- {
- $logger = new QueryLogger();
- $this->connection->enableQueryLogging(true);
- $this->connection->setLogger($logger);
- $st = $this->connection->prepare('SELECT 1');
- $this->assertInstanceOf(LoggingStatement::class, $st);
- $this->assertSame($logger, $st->getLogger());
- $this->connection->enableQueryLogging(false);
- $st = $this->connection->prepare('SELECT 1');
- $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
- }
- /**
- * test logQueries method
- *
- * @deprecated
- * @return void
- */
- public function testLogQueries()
- {
- $this->deprecated(function () {
- $this->connection->logQueries(true);
- $this->assertTrue($this->connection->logQueries());
- $this->connection->logQueries(false);
- $this->assertFalse($this->connection->logQueries());
- });
- }
- /**
- * test enableQueryLogging method
- *
- * @return void
- */
- public function testEnableQueryLogging()
- {
- $this->connection->enableQueryLogging(true);
- $this->assertTrue($this->connection->isQueryLoggingEnabled());
- $this->connection->disableQueryLogging();
- $this->assertFalse($this->connection->isQueryLoggingEnabled());
- }
- /**
- * Tests that log() function logs to the configured query logger
- *
- * @return void
- */
- public function testLogFunction()
- {
- $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
- $this->connection->setLogger($logger);
- $logger->expects($this->once())->method('log')
- ->with($this->logicalAnd(
- $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
- $this->attributeEqualTo('query', 'SELECT 1')
- ));
- $this->connection->log('SELECT 1');
- }
- /**
- * Tests that begin and rollback are also logged
- *
- * @return void
- */
- public function testLogBeginRollbackTransaction()
- {
- $connection = $this
- ->getMockBuilder(Connection::class)
- ->setMethods(['connect'])
- ->disableOriginalConstructor()
- ->getMock();
- $connection->enableQueryLogging(true);
- $driver = $this->getMockFormDriver();
- $connection->setDriver($driver);
- $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
- $connection->setLogger($logger);
- $logger->expects($this->at(0))->method('log')
- ->with($this->logicalAnd(
- $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
- $this->attributeEqualTo('query', 'BEGIN')
- ));
- $logger->expects($this->at(1))->method('log')
- ->with($this->logicalAnd(
- $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
- $this->attributeEqualTo('query', 'ROLLBACK')
- ));
- $connection->begin();
- $connection->begin(); //This one will not be logged
- $connection->rollback();
- }
- /**
- * Tests that commits are logged
- *
- * @return void
- */
- public function testLogCommitTransaction()
- {
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
- $connection->setLogger($logger);
- $logger->expects($this->at(1))->method('log')
- ->with($this->logicalAnd(
- $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
- $this->attributeEqualTo('query', 'COMMIT')
- ));
- $connection->enableQueryLogging(true);
- $connection->begin();
- $connection->commit();
- }
- /**
- * Tests that the transactional method will start and commit a transaction
- * around some arbitrary function passed as argument
- *
- * @return void
- */
- public function testTransactionalSuccess()
- {
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect', 'commit', 'begin'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $connection->expects($this->at(0))->method('begin');
- $connection->expects($this->at(1))->method('commit');
- $result = $connection->transactional(function ($conn) use ($connection) {
- $this->assertSame($connection, $conn);
- return 'thing';
- });
- $this->assertEquals('thing', $result);
- }
- /**
- * Tests that the transactional method will rollback the transaction if false
- * is returned from the callback
- *
- * @return void
- */
- public function testTransactionalFail()
- {
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect', 'commit', 'begin', 'rollback'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $connection->expects($this->at(0))->method('begin');
- $connection->expects($this->at(1))->method('rollback');
- $connection->expects($this->never())->method('commit');
- $result = $connection->transactional(function ($conn) use ($connection) {
- $this->assertSame($connection, $conn);
- return false;
- });
- $this->assertFalse($result);
- }
- /**
- * Tests that the transactional method will rollback the transaction
- * and throw the same exception if the callback raises one
- *
- * @return void
- * @throws \InvalidArgumentException
- */
- public function testTransactionalWithException()
- {
- $this->expectException(\InvalidArgumentException::class);
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect', 'commit', 'begin', 'rollback'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $connection->expects($this->at(0))->method('begin');
- $connection->expects($this->at(1))->method('rollback');
- $connection->expects($this->never())->method('commit');
- $connection->transactional(function ($conn) use ($connection) {
- $this->assertSame($connection, $conn);
- throw new \InvalidArgumentException();
- });
- }
- /**
- * Tests it is possible to set a schema collection object
- *
- * @return void
- */
- public function testSetSchemaCollection()
- {
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $schema = $connection->getSchemaCollection();
- $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
- $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
- ->setConstructorArgs([$connection])
- ->getMock();
- $connection->setSchemaCollection($schema);
- $this->assertSame($schema, $connection->getSchemaCollection());
- }
- /**
- * Tests it is possible to set a schema collection object
- *
- * @group deprecated
- * @return void
- */
- public function testSchemaCollection()
- {
- $this->deprecated(function () {
- $driver = $this->getMockFormDriver();
- $connection = $this->getMockBuilder(Connection::class)
- ->setMethods(['connect'])
- ->setConstructorArgs([['driver' => $driver]])
- ->getMock();
- $schema = $connection->schemaCollection();
- $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
- $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
- ->setConstructorArgs([$connection])
- ->getMock();
- $connection->schemaCollection($schema);
- $this->assertSame($schema, $connection->schemaCollection());
- });
- }
- /**
- * Tests that allowed nesting of commit/rollback operations doesn't
- * throw any exceptions.
- *
- * @return void
- */
- public function testNestedTransactionRollbackExceptionNotThrown()
- {
- $this->connection->transactional(function () {
- $this->connection->transactional(function () {
- return true;
- });
- return true;
- });
- $this->assertFalse($this->connection->inTransaction());
- $this->connection->transactional(function () {
- $this->connection->transactional(function () {
- return true;
- });
- return false;
- });
- $this->assertFalse($this->connection->inTransaction());
- $this->connection->transactional(function () {
- $this->connection->transactional(function () {
- return false;
- });
- return false;
- });
- $this->assertFalse($this->connection->inTransaction());
- }
- /**
- * Tests that not allowed nesting of commit/rollback operations throws
- * a NestedTransactionRollbackException.
- *
- * @return void
- */
- public function testNestedTransactionRollbackExceptionThrown()
- {
- $this->rollbackSourceLine = -1;
- $e = null;
- try {
- $this->connection->transactional(function () {
- $this->connection->transactional(function () {
- return false;
- });
- $this->rollbackSourceLine = __LINE__ - 1;
- return true;
- });
- $this->fail('NestedTransactionRollbackException should be thrown');
- } catch (NestedTransactionRollbackException $e) {
- }
- $trace = $e->getTrace();
- $this->assertEquals(__FILE__, $trace[1]['file']);
- $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
- }
- /**
- * Tests more detail about that not allowed nesting of rollback/commit
- * operations throws a NestedTransactionRollbackException.
- *
- * @return void
- */
- public function testNestedTransactionStates()
- {
- $this->rollbackSourceLine = -1;
- $this->nestedTransactionStates = [];
- $e = null;
- try {
- $this->connection->transactional(function () {
- $this->pushNestedTransactionState();
- $this->connection->transactional(function () {
- return true;
- });
- $this->connection->transactional(function () {
- $this->pushNestedTransactionState();
- $this->connection->transactional(function () {
- return false;
- });
- $this->rollbackSourceLine = __LINE__ - 1;
- $this->pushNestedTransactionState();
- return true;
- });
- $this->connection->transactional(function () {
- return false;
- });
- $this->pushNestedTransactionState();
- return true;
- });
- $this->fail('NestedTransactionRollbackException should be thrown');
- } catch (NestedTransactionRollbackException $e) {
- }
- $this->pushNestedTransactionState();
- $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
- $this->assertFalse($this->connection->inTransaction());
- $trace = $e->getTrace();
- $this->assertEquals(__FILE__, $trace[1]['file']);
- $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
- }
- /**
- * Helper method to trace nested transaction states.
- *
- * @return void
- */
- public function pushNestedTransactionState()
- {
- $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
- $method->setAccessible(true);
- $this->nestedTransactionStates[] = $method->invoke($this->connection);
- }
- /**
- * Tests that the connection is restablished whenever it is interrupted
- * after having used the connection at least once.
- *
- * @return void
- */
- public function testAutomaticReconnect()
- {
- $conn = clone $this->connection;
- $statement = $conn->query('SELECT 1');
- $statement->execute();
- $statement->closeCursor();
- $prop = new ReflectionProperty($conn, '_driver');
- $prop->setAccessible(true);
- $oldDriver = $prop->getValue($conn);
- $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
- $prop->setValue($conn, $newDriver);
- $newDriver->expects($this->at(0))
- ->method('prepare')
- ->will($this->throwException(new Exception('server gone away')));
- $newDriver->expects($this->at(1))->method('disconnect');
- $newDriver->expects($this->at(2))->method('connect');
- $newDriver->expects($this->at(3))
- ->method('prepare')
- ->will($this->returnValue($statement));
- $res = $conn->query('SELECT 1');
- $this->assertInstanceOf(StatementInterface::class, $res);
- }
- /**
- * Tests that the connection is not restablished whenever it is interrupted
- * inside a transaction.
- *
- * @return void
- */
- public function testNoAutomaticReconnect()
- {
- $conn = clone $this->connection;
- $statement = $conn->query('SELECT 1');
- $statement->execute();
- $statement->closeCursor();
- $conn->begin();
- $prop = new ReflectionProperty($conn, '_driver');
- $prop->setAccessible(true);
- $oldDriver = $prop->getValue($conn);
- $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
- $prop->setValue($conn, $newDriver);
- $newDriver->expects($this->once())
- ->method('prepare')
- ->will($this->throwException(new Exception('server gone away')));
- $this->expectException(Exception::class);
- $conn->query('SELECT 1');
- }
- }
|