SqliteTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\Driver;
  17. use Cake\Core\Configure;
  18. use Cake\Database\Connection;
  19. use Cake\Database\Driver\Sqlite;
  20. use Cake\Database\DriverFeatureEnum;
  21. use Cake\Datasource\ConnectionManager;
  22. use Cake\TestSuite\TestCase;
  23. use Mockery;
  24. use PDO;
  25. use PHPUnit\Framework\Attributes\DataProvider;
  26. /**
  27. * Tests Sqlite driver
  28. */
  29. class SqliteTest extends TestCase
  30. {
  31. public function tearDown(): void
  32. {
  33. parent::tearDown();
  34. ConnectionManager::drop('test_shared_cache');
  35. ConnectionManager::drop('test_shared_cache2');
  36. }
  37. /**
  38. * Test connecting to Sqlite with default configuration
  39. */
  40. public function testConnectionConfigDefault(): void
  41. {
  42. $driver = $this->getMockBuilder(Sqlite::class)
  43. ->onlyMethods(['createPdo'])
  44. ->getMock();
  45. $dsn = 'sqlite::memory:';
  46. $expected = [
  47. 'persistent' => false,
  48. 'database' => ':memory:',
  49. 'encoding' => 'utf8',
  50. 'cache' => null,
  51. 'mode' => null,
  52. 'username' => null,
  53. 'password' => null,
  54. 'flags' => [],
  55. 'init' => [],
  56. 'mask' => 420,
  57. 'log' => false,
  58. ];
  59. $expected['flags'] += [
  60. PDO::ATTR_PERSISTENT => false,
  61. PDO::ATTR_EMULATE_PREPARES => false,
  62. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  63. ];
  64. $driver->expects($this->once())->method('createPdo')
  65. ->with($dsn, $expected);
  66. $driver->connect();
  67. }
  68. /**
  69. * Test connecting to Sqlite with custom configuration
  70. */
  71. public function testConnectionConfigCustom(): void
  72. {
  73. $config = [
  74. 'persistent' => true,
  75. 'host' => 'foo',
  76. 'database' => 'bar.db',
  77. 'flags' => [1 => true, 2 => false],
  78. 'encoding' => 'a-language',
  79. 'init' => ['Execute this', 'this too'],
  80. 'mask' => 0666,
  81. ];
  82. $driver = $this->getMockBuilder(Sqlite::class)
  83. ->onlyMethods(['createPdo'])
  84. ->setConstructorArgs([$config])
  85. ->getMock();
  86. $dsn = 'sqlite:bar.db';
  87. $expected = $config;
  88. $expected += ['username' => null, 'password' => null, 'cache' => null, 'mode' => null, 'log' => false];
  89. $expected['flags'] += [
  90. PDO::ATTR_PERSISTENT => true,
  91. PDO::ATTR_EMULATE_PREPARES => false,
  92. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  93. ];
  94. $connection = $this->getMockBuilder('PDO')
  95. ->disableOriginalConstructor()
  96. ->onlyMethods(['exec'])
  97. ->getMock();
  98. $connection->expects($this->exactly(2))
  99. ->method('exec')
  100. ->with(
  101. ...self::withConsecutive(['Execute this'], ['this too'])
  102. );
  103. $driver->expects($this->once())->method('createPdo')
  104. ->with($dsn, $expected)
  105. ->willReturn($connection);
  106. $driver->connect();
  107. }
  108. /**
  109. * Tests creating multiple connections to same db.
  110. */
  111. public function testConnectionSharedCached(): void
  112. {
  113. $this->skipIf(!extension_loaded('pdo_sqlite'), 'Skipping as SQLite extension is missing');
  114. ConnectionManager::setConfig('test_shared_cache', [
  115. 'className' => Connection::class,
  116. 'driver' => Sqlite::class,
  117. 'database' => ':memory:',
  118. 'cache' => 'shared',
  119. ]);
  120. $connection = ConnectionManager::get('test_shared_cache');
  121. $this->assertSame([], $connection->getSchemaCollection()->listTables());
  122. $connection->execute('CREATE TABLE test (test int);');
  123. $this->assertSame(['test'], $connection->getSchemaCollection()->listTables());
  124. ConnectionManager::setConfig('test_shared_cache2', [
  125. 'className' => Connection::class,
  126. 'driver' => Sqlite::class,
  127. 'database' => ':memory:',
  128. 'cache' => 'shared',
  129. ]);
  130. $connection = ConnectionManager::get('test_shared_cache2');
  131. $this->assertSame(['test'], $connection->getSchemaCollection()->listTables());
  132. $this->assertFileDoesNotExist('file::memory:?cache=shared');
  133. }
  134. /**
  135. * Data provider for schemaValue()
  136. *
  137. * @return array
  138. */
  139. public static function schemaValueProvider(): array
  140. {
  141. return [
  142. [null, 'NULL'],
  143. [false, 'FALSE'],
  144. [true, 'TRUE'],
  145. [3.14159, '3.14159'],
  146. ['33', '33'],
  147. [66, 66],
  148. [0, 0],
  149. [10e5, '1000000'],
  150. ['farts', '"farts"'],
  151. ];
  152. }
  153. /**
  154. * Test the schemaValue method on Driver.
  155. *
  156. * @param mixed $input
  157. * @param mixed $expected
  158. */
  159. #[DataProvider('schemaValueProvider')]
  160. public function testSchemaValue($input, $expected): void
  161. {
  162. $mock = Mockery::mock(PDO::class)
  163. ->shouldAllowMockingMethod('quoteIdentifier')
  164. ->makePartial();
  165. $mock->shouldReceive('quote')
  166. ->andReturnUsing(function ($value) {
  167. return '"' . $value . '"';
  168. });
  169. $driver = $this->getMockBuilder(Sqlite::class)
  170. ->onlyMethods(['createPdo'])
  171. ->getMock();
  172. $driver->expects($this->any())
  173. ->method('createPdo')
  174. ->willReturn($mock);
  175. $this->assertEquals($expected, $driver->schemaValue($input));
  176. }
  177. /**
  178. * Tests driver-specific feature support check.
  179. */
  180. public function testSupports(): void
  181. {
  182. $driver = ConnectionManager::get('test')->getDriver();
  183. $this->skipIf(!$driver instanceof Sqlite);
  184. $featureVersions = [
  185. 'cte' => '3.8.3',
  186. 'window' => '3.28.0',
  187. ];
  188. foreach ($featureVersions as $feature => $version) {
  189. $this->assertSame(
  190. version_compare($driver->version(), $version, '>='),
  191. $driver->supports(DriverFeatureEnum::from($feature))
  192. );
  193. }
  194. $this->assertTrue($driver->supports(DriverFeatureEnum::DISABLE_CONSTRAINT_WITHOUT_TRANSACTION));
  195. $this->assertTrue($driver->supports(DriverFeatureEnum::SAVEPOINT));
  196. $this->assertTrue($driver->supports(DriverFeatureEnum::TRUNCATE_WITH_CONSTRAINTS));
  197. $this->assertTrue($driver->supports(DriverFeatureEnum::INTERSECT));
  198. $this->assertFalse($driver->supports(DriverFeatureEnum::INTERSECT_ALL));
  199. $this->assertFalse($driver->supports(DriverFeatureEnum::JSON));
  200. $this->assertFalse($driver->supports(DriverFeatureEnum::SET_OPERATIONS_ORDER_BY));
  201. }
  202. /**
  203. * Test of Inconsistency for JSON type field between mysql and sqlite
  204. *
  205. * @return void
  206. */
  207. public function testJSON(): void
  208. {
  209. Configure::write('ORM.mapJsonTypeForSqlite', true);
  210. $connection = ConnectionManager::get('test');
  211. $this->skipIf(!($connection->getDriver() instanceof Sqlite));
  212. assert($connection instanceof Connection);
  213. $connection->execute('CREATE TABLE json_test (id INTEGER PRIMARY KEY, data JSON_TEXT);');
  214. $table = $this->getTableLocator()->get('json_test');
  215. $data = ['foo' => 'bar', 'baz' => 1, 'qux' => ['a', 'b', 'c' => true]];
  216. $entity = $table->newEntity(['data' => $data]);
  217. $table->save($entity);
  218. $result = $table->find()->first();
  219. $this->assertEquals($data, $result->data);
  220. Configure::write('ORM.mapJsonTypeForSqlite', false);
  221. }
  222. /**
  223. * Tests identifier quoting
  224. */
  225. public function testQuoteIdentifier(): void
  226. {
  227. $driver = new Sqlite();
  228. $result = $driver->quoteIdentifier('name');
  229. $expected = '"name"';
  230. $this->assertEquals($expected, $result);
  231. $result = $driver->quoteIdentifier('Model.*');
  232. $expected = '"Model".*';
  233. $this->assertEquals($expected, $result);
  234. $result = $driver->quoteIdentifier('Items.No_ 2');
  235. $expected = '"Items"."No_ 2"';
  236. $this->assertEquals($expected, $result);
  237. $result = $driver->quoteIdentifier('Items.No_ 2 thing');
  238. $expected = '"Items"."No_ 2 thing"';
  239. $this->assertEquals($expected, $result);
  240. $result = $driver->quoteIdentifier('Items.No_ 2 thing AS thing');
  241. $expected = '"Items"."No_ 2 thing" AS "thing"';
  242. $this->assertEquals($expected, $result);
  243. $result = $driver->quoteIdentifier('Items.Item Category Code = :c1');
  244. $expected = '"Items"."Item Category Code" = :c1';
  245. $this->assertEquals($expected, $result);
  246. $result = $driver->quoteIdentifier('MTD()');
  247. $expected = 'MTD()';
  248. $this->assertEquals($expected, $result);
  249. $result = $driver->quoteIdentifier('(sm)');
  250. $expected = '(sm)';
  251. $this->assertEquals($expected, $result);
  252. $result = $driver->quoteIdentifier('name AS x');
  253. $expected = '"name" AS "x"';
  254. $this->assertEquals($expected, $result);
  255. $result = $driver->quoteIdentifier('Model.name AS x');
  256. $expected = '"Model"."name" AS "x"';
  257. $this->assertEquals($expected, $result);
  258. $result = $driver->quoteIdentifier('Function(Something.foo)');
  259. $expected = 'Function("Something"."foo")';
  260. $this->assertEquals($expected, $result);
  261. $result = $driver->quoteIdentifier('Function(SubFunction(Something.foo))');
  262. $expected = 'Function(SubFunction("Something"."foo"))';
  263. $this->assertEquals($expected, $result);
  264. $result = $driver->quoteIdentifier('Function(Something.foo) AS x');
  265. $expected = 'Function("Something"."foo") AS "x"';
  266. $this->assertEquals($expected, $result);
  267. $result = $driver->quoteIdentifier('name-with-minus');
  268. $expected = '"name-with-minus"';
  269. $this->assertEquals($expected, $result);
  270. $result = $driver->quoteIdentifier('my-name');
  271. $expected = '"my-name"';
  272. $this->assertEquals($expected, $result);
  273. $result = $driver->quoteIdentifier('Foo-Model.*');
  274. $expected = '"Foo-Model".*';
  275. $this->assertEquals($expected, $result);
  276. $result = $driver->quoteIdentifier('Team.P%');
  277. $expected = '"Team"."P%"';
  278. $this->assertEquals($expected, $result);
  279. $result = $driver->quoteIdentifier('Team.G/G');
  280. $expected = '"Team"."G/G"';
  281. $this->assertEquals($expected, $result);
  282. $result = $driver->quoteIdentifier('Model.name as y');
  283. $expected = '"Model"."name" AS "y"';
  284. $this->assertEquals($expected, $result);
  285. $result = $driver->quoteIdentifier('nämé');
  286. $expected = '"nämé"';
  287. $this->assertEquals($expected, $result);
  288. $result = $driver->quoteIdentifier('aßa.nämé');
  289. $expected = '"aßa"."nämé"';
  290. $this->assertEquals($expected, $result);
  291. $result = $driver->quoteIdentifier('aßa.*');
  292. $expected = '"aßa".*';
  293. $this->assertEquals($expected, $result);
  294. $result = $driver->quoteIdentifier('Modeß.nämé as y');
  295. $expected = '"Modeß"."nämé" AS "y"';
  296. $this->assertEquals($expected, $result);
  297. $result = $driver->quoteIdentifier('Model.näme Datum as y');
  298. $expected = '"Model"."näme Datum" AS "y"';
  299. $this->assertEquals($expected, $result);
  300. }
  301. }