LegacyDBTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace Test\DB;
  9. use OC_DB;
  10. /**
  11. * Class LegacyDBTest
  12. *
  13. * @group DB
  14. */
  15. class LegacyDBTest extends \Test\TestCase {
  16. protected $backupGlobals = FALSE;
  17. protected static $schema_file;
  18. protected $test_prefix;
  19. public static function setUpBeforeClass() {
  20. self::$schema_file = \OC::$server->getTempManager()->getTemporaryFile();
  21. }
  22. /**
  23. * @var string
  24. */
  25. private $table1;
  26. /**
  27. * @var string
  28. */
  29. private $table2;
  30. /**
  31. * @var string
  32. */
  33. private $table3;
  34. /**
  35. * @var string
  36. */
  37. private $table4;
  38. /**
  39. * @var string
  40. */
  41. private $table5;
  42. /**
  43. * @var string
  44. */
  45. private $text_table;
  46. protected function setUp() {
  47. parent::setUp();
  48. $dbFile = \OC::$SERVERROOT.'/tests/data/db_structure.xml';
  49. $r = $this->getUniqueID('_', 4).'_';
  50. $content = file_get_contents( $dbFile );
  51. $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content );
  52. file_put_contents( self::$schema_file, $content );
  53. OC_DB::createDbFromStructure(self::$schema_file);
  54. $this->test_prefix = $r;
  55. $this->table1 = $this->test_prefix.'cntcts_addrsbks';
  56. $this->table2 = $this->test_prefix.'cntcts_cards';
  57. $this->table3 = $this->test_prefix.'vcategory';
  58. $this->table4 = $this->test_prefix.'decimal';
  59. $this->table5 = $this->test_prefix.'uniconst';
  60. $this->text_table = $this->test_prefix.'text_table';
  61. }
  62. protected function tearDown() {
  63. OC_DB::removeDBStructure(self::$schema_file);
  64. unlink(self::$schema_file);
  65. parent::tearDown();
  66. }
  67. public function testQuotes() {
  68. $query = OC_DB::prepare('SELECT `fullname` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  69. $result = $query->execute(array('uri_1'));
  70. $this->assertTrue((bool)$result);
  71. $row = $result->fetchRow();
  72. $this->assertFalse($row);
  73. $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)');
  74. $result = $query->execute(array('fullname test', 'uri_1'));
  75. $this->assertEquals(1, $result);
  76. $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  77. $result = $query->execute(array('uri_1'));
  78. $this->assertTrue((bool)$result);
  79. $row = $result->fetchRow();
  80. $this->assertArrayHasKey('fullname', $row);
  81. $this->assertEquals($row['fullname'], 'fullname test');
  82. $row = $result->fetchRow();
  83. $this->assertFalse((bool)$row); //PDO returns false, MDB2 returns null
  84. }
  85. /**
  86. * @medium
  87. */
  88. public function testNOW() {
  89. $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (NOW(),?)');
  90. $result = $query->execute(array('uri_2'));
  91. $this->assertEquals(1, $result);
  92. $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  93. $result = $query->execute(array('uri_2'));
  94. $this->assertTrue((bool)$result);
  95. }
  96. public function testUNIX_TIMESTAMP() {
  97. $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (UNIX_TIMESTAMP(),?)');
  98. $result = $query->execute(array('uri_3'));
  99. $this->assertEquals(1, $result);
  100. $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  101. $result = $query->execute(array('uri_3'));
  102. $this->assertTrue((bool)$result);
  103. }
  104. public function testLastInsertId() {
  105. $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)');
  106. $result1 = OC_DB::executeAudited($query, array('insertid 1','uri_1'));
  107. $id1 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2);
  108. // we don't know the id we should expect, so insert another row
  109. $result2 = OC_DB::executeAudited($query, array('insertid 2','uri_2'));
  110. $id2 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2);
  111. // now we can check if the two ids are in correct order
  112. $this->assertGreaterThan($id1, $id2);
  113. }
  114. public function testinsertIfNotExist() {
  115. $categoryEntries = array(
  116. array('user' => 'test', 'type' => 'contact', 'category' => 'Family', 'expectedResult' => 1),
  117. array('user' => 'test', 'type' => 'contact', 'category' => 'Friends', 'expectedResult' => 1),
  118. array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 1),
  119. array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 0),
  120. array('user' => 'test', 'type' => 'contact', 'category' => 'School', 'expectedResult' => 1),
  121. );
  122. foreach($categoryEntries as $entry) {
  123. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table3,
  124. array(
  125. 'uid' => $entry['user'],
  126. 'type' => $entry['type'],
  127. 'category' => $entry['category'],
  128. ));
  129. $this->assertEquals($entry['expectedResult'], $result);
  130. }
  131. $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table3.'`');
  132. $result = $query->execute();
  133. $this->assertTrue((bool)$result);
  134. $this->assertEquals(4, count($result->fetchAll()));
  135. }
  136. public function testInsertIfNotExistNull() {
  137. $categoryEntries = array(
  138. array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 1),
  139. array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 0),
  140. array('addressbookid' => 123, 'fullname' => 'test', 'expectedResult' => 1),
  141. );
  142. foreach($categoryEntries as $entry) {
  143. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2,
  144. array(
  145. 'addressbookid' => $entry['addressbookid'],
  146. 'fullname' => $entry['fullname'],
  147. ));
  148. $this->assertEquals($entry['expectedResult'], $result);
  149. }
  150. $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table2.'`');
  151. $result = $query->execute();
  152. $this->assertTrue((bool)$result);
  153. $this->assertEquals(2, count($result->fetchAll()));
  154. }
  155. public function testInsertIfNotExistDonTOverwrite() {
  156. $fullName = 'fullname test';
  157. $uri = 'uri_1';
  158. $carddata = 'This is a vCard';
  159. // Normal test to have same known data inserted.
  160. $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)');
  161. $result = $query->execute(array($fullName, $uri, $carddata));
  162. $this->assertEquals(1, $result);
  163. $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  164. $result = $query->execute(array($uri));
  165. $this->assertTrue((bool)$result);
  166. $rowset = $result->fetchAll();
  167. $this->assertEquals(1, count($rowset));
  168. $this->assertArrayHasKey('carddata', $rowset[0]);
  169. $this->assertEquals($carddata, $rowset[0]['carddata']);
  170. // Try to insert a new row
  171. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2,
  172. array(
  173. 'fullname' => $fullName,
  174. 'uri' => $uri,
  175. ));
  176. $this->assertEquals(0, $result);
  177. $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?');
  178. $result = $query->execute(array($uri));
  179. $this->assertTrue((bool)$result);
  180. // Test that previously inserted data isn't overwritten
  181. // And that a new row hasn't been inserted.
  182. $rowset = $result->fetchAll();
  183. $this->assertEquals(1, count($rowset));
  184. $this->assertArrayHasKey('carddata', $rowset[0]);
  185. $this->assertEquals($carddata, $rowset[0]['carddata']);
  186. }
  187. public function testInsertIfNotExistsViolating() {
  188. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5,
  189. array(
  190. 'storage' => 1,
  191. 'path_hash' => md5('welcome.txt'),
  192. 'etag' => $this->getUniqueID()
  193. ));
  194. $this->assertEquals(1, $result);
  195. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5,
  196. array(
  197. 'storage' => 1,
  198. 'path_hash' => md5('welcome.txt'),
  199. 'etag' => $this->getUniqueID()
  200. ),['storage', 'path_hash']);
  201. $this->assertEquals(0, $result);
  202. }
  203. public function insertIfNotExistsViolatingThrows() {
  204. return [
  205. [null],
  206. [['etag']],
  207. ];
  208. }
  209. /**
  210. * @dataProvider insertIfNotExistsViolatingThrows
  211. * @expectedException \Doctrine\DBAL\Exception\UniqueConstraintViolationException
  212. *
  213. * @param array $compareKeys
  214. */
  215. public function testInsertIfNotExistsViolatingThrows($compareKeys) {
  216. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5,
  217. array(
  218. 'storage' => 1,
  219. 'path_hash' => md5('welcome.txt'),
  220. 'etag' => $this->getUniqueID()
  221. ));
  222. $this->assertEquals(1, $result);
  223. $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5,
  224. array(
  225. 'storage' => 1,
  226. 'path_hash' => md5('welcome.txt'),
  227. 'etag' => $this->getUniqueID()
  228. ), $compareKeys);
  229. $this->assertEquals(0, $result);
  230. }
  231. public function testUtf8Data() {
  232. $table = "*PREFIX*{$this->table2}";
  233. $expected = "Ћö雙喜\xE2\x80\xA2";
  234. $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)");
  235. $result = $query->execute(array($expected, 'uri_1', 'This is a vCard'));
  236. $this->assertEquals(1, $result);
  237. $actual = OC_DB::prepare("SELECT `fullname` FROM `$table`")->execute()->fetchOne();
  238. $this->assertSame($expected, $actual);
  239. }
  240. /**
  241. * Insert, select and delete decimal(12,2) values
  242. * @dataProvider decimalData
  243. */
  244. public function testDecimal($insert, $expect) {
  245. $table = "*PREFIX*" . $this->table4;
  246. $rowname = 'decimaltest';
  247. $query = OC_DB::prepare('INSERT INTO `' . $table . '` (`' . $rowname . '`) VALUES (?)');
  248. $result = $query->execute(array($insert));
  249. $this->assertEquals(1, $result);
  250. $query = OC_DB::prepare('SELECT `' . $rowname . '` FROM `' . $table . '`');
  251. $result = $query->execute();
  252. $this->assertTrue((bool)$result);
  253. $row = $result->fetchRow();
  254. $this->assertArrayHasKey($rowname, $row);
  255. $this->assertEquals($expect, $row[$rowname]);
  256. $query = OC_DB::prepare('DELETE FROM `' . $table . '`');
  257. $result = $query->execute();
  258. $this->assertTrue((bool)$result);
  259. }
  260. public function decimalData() {
  261. return [
  262. ['1337133713.37', '1337133713.37'],
  263. ['1234567890', '1234567890.00'],
  264. ];
  265. }
  266. public function testUpdateAffectedRowsNoMatch() {
  267. $this->insertCardData('fullname1', 'uri1');
  268. // The WHERE clause does not match any rows
  269. $this->assertSame(0, $this->updateCardData('fullname3', 'uri2'));
  270. }
  271. public function testUpdateAffectedRowsDifferent() {
  272. $this->insertCardData('fullname1', 'uri1');
  273. // The WHERE clause matches a single row and the value we are updating
  274. // is different from the one already present.
  275. $this->assertSame(1, $this->updateCardData('fullname1', 'uri2'));
  276. }
  277. public function testUpdateAffectedRowsSame() {
  278. $this->insertCardData('fullname1', 'uri1');
  279. // The WHERE clause matches a single row and the value we are updating
  280. // to is the same as the one already present. MySQL reports 0 here when
  281. // the PDO::MYSQL_ATTR_FOUND_ROWS flag is not specified.
  282. $this->assertSame(1, $this->updateCardData('fullname1', 'uri1'));
  283. }
  284. public function testUpdateAffectedRowsMultiple() {
  285. $this->insertCardData('fullname1', 'uri1');
  286. $this->insertCardData('fullname2', 'uri2');
  287. // The WHERE clause matches two rows. One row contains a value that
  288. // needs to be updated, the other one already contains the value we are
  289. // updating to. MySQL reports 1 here when the PDO::MYSQL_ATTR_FOUND_ROWS
  290. // flag is not specified.
  291. $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ?");
  292. $this->assertSame(2, $query->execute(array('uri1')));
  293. }
  294. protected function insertCardData($fullname, $uri) {
  295. $query = OC_DB::prepare("INSERT INTO `*PREFIX*{$this->table2}` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)");
  296. $this->assertSame(1, $query->execute(array($fullname, $uri, $this->getUniqueID())));
  297. }
  298. protected function updateCardData($fullname, $uri) {
  299. $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ? WHERE `fullname` = ?");
  300. return $query->execute(array($uri, $fullname));
  301. }
  302. public function testILIKE() {
  303. $table = "*PREFIX*{$this->table2}";
  304. $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)");
  305. $query->execute(array('fooBAR', 'foo', 'bar'));
  306. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?");
  307. $result = $query->execute(array('foobar'));
  308. $this->assertCount(0, $result->fetchAll());
  309. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?");
  310. $result = $query->execute(array('foobar'));
  311. $this->assertCount(1, $result->fetchAll());
  312. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?");
  313. $result = $query->execute(array('foo'));
  314. $this->assertCount(0, $result->fetchAll());
  315. }
  316. public function testILIKEWildcard() {
  317. $table = "*PREFIX*{$this->table2}";
  318. $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)");
  319. $query->execute(array('FooBAR', 'foo', 'bar'));
  320. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?");
  321. $result = $query->execute(array('%bar'));
  322. $this->assertCount(0, $result->fetchAll());
  323. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?");
  324. $result = $query->execute(array('foo%'));
  325. $this->assertCount(0, $result->fetchAll());
  326. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?");
  327. $result = $query->execute(array('%ba%'));
  328. $this->assertCount(0, $result->fetchAll());
  329. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?");
  330. $result = $query->execute(array('%bar'));
  331. $this->assertCount(1, $result->fetchAll());
  332. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?");
  333. $result = $query->execute(array('foo%'));
  334. $this->assertCount(1, $result->fetchAll());
  335. $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?");
  336. $result = $query->execute(array('%ba%'));
  337. $this->assertCount(1, $result->fetchAll());
  338. }
  339. /**
  340. * @dataProvider insertAndSelectDataProvider
  341. */
  342. public function testInsertAndSelectData($expected, $throwsOnMysqlWithoutUTF8MB4) {
  343. $table = "*PREFIX*{$this->text_table}";
  344. $config = \OC::$server->getConfig();
  345. $query = OC_DB::prepare("INSERT INTO `$table` (`textfield`) VALUES (?)");
  346. if ($throwsOnMysqlWithoutUTF8MB4 && $config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false) === false) {
  347. $this->markTestSkipped('MySQL requires UTF8mb4 to store value: ' . $expected);
  348. }
  349. $result = $query->execute(array($expected));
  350. $this->assertEquals(1, $result);
  351. $actual = OC_DB::prepare("SELECT `textfield` FROM `$table`")->execute()->fetchOne();
  352. $this->assertSame($expected, $actual);
  353. }
  354. public function insertAndSelectDataProvider() {
  355. return [
  356. ['abcdefghijklmnopqrstuvwxyzABCDEFGHIKLMNOPQRSTUVWXYZ', false],
  357. ['0123456789', false],
  358. ['äöüÄÖÜß!"§$%&/()=?#\'+*~°^`´', false],
  359. ['²³¼½¬{[]}\\', false],
  360. ['♡⚗', false],
  361. ['💩', true], # :hankey: on github
  362. ];
  363. }
  364. }