DboSourceTest.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. <?php
  2. /**
  3. * DboSourceTest file
  4. *
  5. * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
  14. * @package Cake.Test.Case.Model.Datasource
  15. * @since CakePHP(tm) v 1.2.0.4206
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Model', 'Model');
  19. App::uses('AppModel', 'Model');
  20. App::uses('DataSource', 'Model/Datasource');
  21. App::uses('DboSource', 'Model/Datasource');
  22. App::uses('DboTestSource', 'Model/Datasource');
  23. App::uses('DboSecondTestSource', 'Model/Datasource');
  24. App::uses('MockDataSource', 'Model/Datasource');
  25. require_once dirname(dirname(__FILE__)) . DS . 'models.php';
  26. /**
  27. * Class MockPDO
  28. *
  29. * @package Cake.Test.Case.Model.Datasource
  30. */
  31. class MockPDO extends PDO {
  32. /**
  33. * Constructor.
  34. */
  35. public function __construct() {
  36. }
  37. }
  38. /**
  39. * Class MockDataSource
  40. *
  41. * @package Cake.Test.Case.Model.Datasource
  42. */
  43. class MockDataSource extends DataSource {
  44. }
  45. /**
  46. * Class DboTestSource
  47. *
  48. * @package Cake.Test.Case.Model.Datasource
  49. */
  50. class DboTestSource extends DboSource {
  51. public $nestedSupport = false;
  52. public function connect($config = array()) {
  53. $this->connected = true;
  54. }
  55. public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  56. return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin);
  57. }
  58. public function setConfig($config = array()) {
  59. $this->config = $config;
  60. }
  61. public function setConnection($conn) {
  62. $this->_connection = $conn;
  63. }
  64. public function nestedTransactionSupported() {
  65. return $this->useNestedTransactions && $this->nestedSupport;
  66. }
  67. }
  68. /**
  69. * Class DboSecondTestSource
  70. *
  71. * @package Cake.Test.Case.Model.Datasource
  72. */
  73. class DboSecondTestSource extends DboSource {
  74. public $startQuote = '_';
  75. public $endQuote = '_';
  76. public function connect($config = array()) {
  77. $this->connected = true;
  78. }
  79. public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  80. return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin);
  81. }
  82. public function setConfig($config = array()) {
  83. $this->config = $config;
  84. }
  85. public function setConnection($conn) {
  86. $this->_connection = $conn;
  87. }
  88. }
  89. /**
  90. * DboSourceTest class
  91. *
  92. * @package Cake.Test.Case.Model.Datasource
  93. */
  94. class DboSourceTest extends CakeTestCase {
  95. /**
  96. * autoFixtures property
  97. *
  98. * @var bool
  99. */
  100. public $autoFixtures = false;
  101. /**
  102. * fixtures property
  103. *
  104. * @var array
  105. */
  106. public $fixtures = array(
  107. 'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment',
  108. 'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test'
  109. );
  110. /**
  111. * setUp method
  112. *
  113. * @return void
  114. */
  115. public function setUp() {
  116. parent::setUp();
  117. $this->testDb = new DboTestSource();
  118. $this->testDb->cacheSources = false;
  119. $this->testDb->startQuote = '`';
  120. $this->testDb->endQuote = '`';
  121. $this->Model = new TestModel();
  122. }
  123. /**
  124. * tearDown method
  125. *
  126. * @return void
  127. */
  128. public function tearDown() {
  129. parent::tearDown();
  130. unset($this->Model);
  131. }
  132. /**
  133. * test that booleans and null make logical condition strings.
  134. *
  135. * @return void
  136. */
  137. public function testBooleanNullConditionsParsing() {
  138. $result = $this->testDb->conditions(true);
  139. $this->assertEquals(' WHERE 1 = 1', $result, 'true conditions failed %s');
  140. $result = $this->testDb->conditions(false);
  141. $this->assertEquals(' WHERE 0 = 1', $result, 'false conditions failed %s');
  142. $result = $this->testDb->conditions(null);
  143. $this->assertEquals(' WHERE 1 = 1', $result, 'null conditions failed %s');
  144. $result = $this->testDb->conditions(array());
  145. $this->assertEquals(' WHERE 1 = 1', $result, 'array() conditions failed %s');
  146. $result = $this->testDb->conditions('');
  147. $this->assertEquals(' WHERE 1 = 1', $result, '"" conditions failed %s');
  148. $result = $this->testDb->conditions(' ', '" " conditions failed %s');
  149. $this->assertEquals(' WHERE 1 = 1', $result);
  150. }
  151. /**
  152. * test that booleans work on empty set.
  153. *
  154. * @return void
  155. */
  156. public function testBooleanEmptyConditionsParsing() {
  157. $result = $this->testDb->conditions(array('OR' => array()));
  158. $this->assertEquals(' WHERE 1 = 1', $result, 'empty conditions failed');
  159. $result = $this->testDb->conditions(array('OR' => array('OR' => array())));
  160. $this->assertEquals(' WHERE 1 = 1', $result, 'nested empty conditions failed');
  161. }
  162. /**
  163. * test that order() will accept objects made from DboSource::expression
  164. *
  165. * @return void
  166. */
  167. public function testOrderWithExpression() {
  168. $expression = $this->testDb->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col");
  169. $result = $this->testDb->order($expression);
  170. $expected = " ORDER BY CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col";
  171. $this->assertEquals($expected, $result);
  172. }
  173. /**
  174. * testMergeAssociations method
  175. *
  176. * @return void
  177. */
  178. public function testMergeAssociations() {
  179. $data = array('Article2' => array(
  180. 'id' => '1', 'user_id' => '1', 'title' => 'First Article',
  181. 'body' => 'First Article Body', 'published' => 'Y',
  182. 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  183. ));
  184. $merge = array('Topic' => array(array(
  185. 'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23',
  186. 'updated' => '2007-03-17 01:18:31'
  187. )));
  188. $expected = array(
  189. 'Article2' => array(
  190. 'id' => '1', 'user_id' => '1', 'title' => 'First Article',
  191. 'body' => 'First Article Body', 'published' => 'Y',
  192. 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  193. ),
  194. 'Topic' => array(
  195. 'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23',
  196. 'updated' => '2007-03-17 01:18:31'
  197. )
  198. );
  199. $this->testDb->mergeAssociation($data, $merge, 'Topic', 'hasOne');
  200. $this->assertEquals($expected, $data);
  201. $data = array('Article2' => array(
  202. 'id' => '1', 'user_id' => '1', 'title' => 'First Article',
  203. 'body' => 'First Article Body', 'published' => 'Y',
  204. 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  205. ));
  206. $merge = array('User2' => array(array(
  207. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99',
  208. 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  209. )));
  210. $expected = array(
  211. 'Article2' => array(
  212. 'id' => '1', 'user_id' => '1', 'title' => 'First Article',
  213. 'body' => 'First Article Body', 'published' => 'Y',
  214. 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  215. ),
  216. 'User2' => array(
  217. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  218. )
  219. );
  220. $this->testDb->mergeAssociation($data, $merge, 'User2', 'belongsTo');
  221. $this->assertEquals($expected, $data);
  222. $data = array(
  223. 'Article2' => array(
  224. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  225. )
  226. );
  227. $merge = array(array('Comment' => false));
  228. $expected = array(
  229. 'Article2' => array(
  230. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  231. ),
  232. 'Comment' => array()
  233. );
  234. $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
  235. $this->assertEquals($expected, $data);
  236. $data = array(
  237. 'Article' => array(
  238. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  239. )
  240. );
  241. $merge = array(
  242. array(
  243. 'Comment' => array(
  244. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  245. )
  246. ),
  247. array(
  248. 'Comment' => array(
  249. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  250. )
  251. )
  252. );
  253. $expected = array(
  254. 'Article' => array(
  255. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  256. ),
  257. 'Comment' => array(
  258. array(
  259. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  260. ),
  261. array(
  262. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  263. )
  264. )
  265. );
  266. $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
  267. $this->assertEquals($expected, $data);
  268. $data = array(
  269. 'Article' => array(
  270. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  271. )
  272. );
  273. $merge = array(
  274. array(
  275. 'Comment' => array(
  276. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  277. ),
  278. 'User2' => array(
  279. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  280. )
  281. ),
  282. array(
  283. 'Comment' => array(
  284. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  285. ),
  286. 'User2' => array(
  287. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  288. )
  289. )
  290. );
  291. $expected = array(
  292. 'Article' => array(
  293. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  294. ),
  295. 'Comment' => array(
  296. array(
  297. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
  298. 'User2' => array(
  299. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  300. )
  301. ),
  302. array(
  303. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
  304. 'User2' => array(
  305. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  306. )
  307. )
  308. )
  309. );
  310. $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
  311. $this->assertEquals($expected, $data);
  312. $data = array(
  313. 'Article' => array(
  314. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  315. )
  316. );
  317. $merge = array(
  318. array(
  319. 'Comment' => array(
  320. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  321. ),
  322. 'User2' => array(
  323. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  324. ),
  325. 'Tag' => array(
  326. array('id' => 1, 'tag' => 'Tag 1'),
  327. array('id' => 2, 'tag' => 'Tag 2')
  328. )
  329. ),
  330. array(
  331. 'Comment' => array(
  332. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  333. ),
  334. 'User2' => array(
  335. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  336. ),
  337. 'Tag' => array()
  338. )
  339. );
  340. $expected = array(
  341. 'Article' => array(
  342. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  343. ),
  344. 'Comment' => array(
  345. array(
  346. 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
  347. 'User2' => array(
  348. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  349. ),
  350. 'Tag' => array(
  351. array('id' => 1, 'tag' => 'Tag 1'),
  352. array('id' => 2, 'tag' => 'Tag 2')
  353. )
  354. ),
  355. array(
  356. 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
  357. 'User2' => array(
  358. 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  359. ),
  360. 'Tag' => array()
  361. )
  362. )
  363. );
  364. $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
  365. $this->assertEquals($expected, $data);
  366. $data = array(
  367. 'Article' => array(
  368. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  369. )
  370. );
  371. $merge = array(
  372. array(
  373. 'Tag' => array(
  374. 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  375. )
  376. ),
  377. array(
  378. 'Tag' => array(
  379. 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  380. )
  381. ),
  382. array(
  383. 'Tag' => array(
  384. 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  385. )
  386. )
  387. );
  388. $expected = array(
  389. 'Article' => array(
  390. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  391. ),
  392. 'Tag' => array(
  393. array(
  394. 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  395. ),
  396. array(
  397. 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  398. ),
  399. array(
  400. 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  401. )
  402. )
  403. );
  404. $this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasAndBelongsToMany');
  405. $this->assertEquals($expected, $data);
  406. $data = array(
  407. 'Article' => array(
  408. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  409. )
  410. );
  411. $merge = array(
  412. array(
  413. 'Tag' => array(
  414. 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  415. )
  416. ),
  417. array(
  418. 'Tag' => array(
  419. 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  420. )
  421. ),
  422. array(
  423. 'Tag' => array(
  424. 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
  425. )
  426. )
  427. );
  428. $expected = array(
  429. 'Article' => array(
  430. 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
  431. ),
  432. 'Tag' => array('id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31')
  433. );
  434. $this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasOne');
  435. $this->assertEquals($expected, $data);
  436. }
  437. /**
  438. * testMagicMethodQuerying method
  439. *
  440. * @return void
  441. */
  442. public function testMagicMethodQuerying() {
  443. $result = $this->db->query('findByFieldName', array('value'), $this->Model);
  444. $expected = array('first', array(
  445. 'conditions' => array('TestModel.field_name' => 'value'),
  446. 'fields' => null, 'order' => null, 'recursive' => null
  447. ));
  448. $this->assertEquals($expected, $result);
  449. $result = $this->db->query('findByFindBy', array('value'), $this->Model);
  450. $expected = array('first', array(
  451. 'conditions' => array('TestModel.find_by' => 'value'),
  452. 'fields' => null, 'order' => null, 'recursive' => null
  453. ));
  454. $this->assertEquals($expected, $result);
  455. $result = $this->db->query('findAllByFieldName', array('value'), $this->Model);
  456. $expected = array('all', array(
  457. 'conditions' => array('TestModel.field_name' => 'value'),
  458. 'fields' => null, 'order' => null, 'limit' => null,
  459. 'page' => null, 'recursive' => null
  460. ));
  461. $this->assertEquals($expected, $result);
  462. $result = $this->db->query('findAllById', array('a'), $this->Model);
  463. $expected = array('all', array(
  464. 'conditions' => array('TestModel.id' => 'a'),
  465. 'fields' => null, 'order' => null, 'limit' => null,
  466. 'page' => null, 'recursive' => null
  467. ));
  468. $this->assertEquals($expected, $result);
  469. $result = $this->db->query('findByFieldName', array(array('value1', 'value2', 'value3')), $this->Model);
  470. $expected = array('first', array(
  471. 'conditions' => array('TestModel.field_name' => array('value1', 'value2', 'value3')),
  472. 'fields' => null, 'order' => null, 'recursive' => null
  473. ));
  474. $this->assertEquals($expected, $result);
  475. $result = $this->db->query('findByFieldName', array(null), $this->Model);
  476. $expected = array('first', array(
  477. 'conditions' => array('TestModel.field_name' => null),
  478. 'fields' => null, 'order' => null, 'recursive' => null
  479. ));
  480. $this->assertEquals($expected, $result);
  481. $result = $this->db->query('findByFieldName', array('= a'), $this->Model);
  482. $expected = array('first', array(
  483. 'conditions' => array('TestModel.field_name' => '= a'),
  484. 'fields' => null, 'order' => null, 'recursive' => null
  485. ));
  486. $this->assertEquals($expected, $result);
  487. $result = $this->db->query('findByFieldName', array(), $this->Model);
  488. $expected = false;
  489. $this->assertEquals($expected, $result);
  490. }
  491. /**
  492. * @expectedException PDOException
  493. * @return void
  494. */
  495. public function testDirectCallThrowsException() {
  496. $this->db->query('directCall', array(), $this->Model);
  497. }
  498. /**
  499. * testValue method
  500. *
  501. * @return void
  502. */
  503. public function testValue() {
  504. if ($this->db instanceof Sqlserver) {
  505. $this->markTestSkipped('Cannot run this test with SqlServer');
  506. }
  507. $result = $this->db->value('{$__cakeForeignKey__$}');
  508. $this->assertEquals('{$__cakeForeignKey__$}', $result);
  509. $result = $this->db->value(array('first', 2, 'third'));
  510. $expected = array('\'first\'', 2, '\'third\'');
  511. $this->assertEquals($expected, $result);
  512. }
  513. /**
  514. * Tests if the connection can be re-established and that the new (optional) config is set.
  515. *
  516. * @return void
  517. */
  518. public function testReconnect() {
  519. $this->testDb->reconnect(array('prefix' => 'foo'));
  520. $this->assertTrue($this->testDb->connected);
  521. $this->assertEquals('foo', $this->testDb->config['prefix']);
  522. }
  523. /**
  524. * testName method
  525. *
  526. * @return void
  527. */
  528. public function testName() {
  529. $result = $this->testDb->name('name');
  530. $expected = '`name`';
  531. $this->assertEquals($expected, $result);
  532. $result = $this->testDb->name(array('name', 'Model.*'));
  533. $expected = array('`name`', '`Model`.*');
  534. $this->assertEquals($expected, $result);
  535. $result = $this->testDb->name('MTD()');
  536. $expected = 'MTD()';
  537. $this->assertEquals($expected, $result);
  538. $result = $this->testDb->name('(sm)');
  539. $expected = '(sm)';
  540. $this->assertEquals($expected, $result);
  541. $result = $this->testDb->name('name AS x');
  542. $expected = '`name` AS `x`';
  543. $this->assertEquals($expected, $result);
  544. $result = $this->testDb->name('Model.name AS x');
  545. $expected = '`Model`.`name` AS `x`';
  546. $this->assertEquals($expected, $result);
  547. $result = $this->testDb->name('Function(Something.foo)');
  548. $expected = 'Function(`Something`.`foo`)';
  549. $this->assertEquals($expected, $result);
  550. $result = $this->testDb->name('Function(SubFunction(Something.foo))');
  551. $expected = 'Function(SubFunction(`Something`.`foo`))';
  552. $this->assertEquals($expected, $result);
  553. $result = $this->testDb->name('Function(Something.foo) AS x');
  554. $expected = 'Function(`Something`.`foo`) AS `x`';
  555. $this->assertEquals($expected, $result);
  556. $result = $this->testDb->name('I18n__title__pt-br.locale');
  557. $expected = '`I18n__title__pt-br`.`locale`';
  558. $this->assertEquals($expected, $result);
  559. $result = $this->testDb->name('name-with-minus');
  560. $expected = '`name-with-minus`';
  561. $this->assertEquals($expected, $result);
  562. $result = $this->testDb->name(array('my-name', 'Foo-Model.*'));
  563. $expected = array('`my-name`', '`Foo-Model`.*');
  564. $this->assertEquals($expected, $result);
  565. $result = $this->testDb->name(array('Team.P%', 'Team.G/G'));
  566. $expected = array('`Team`.`P%`', '`Team`.`G/G`');
  567. $this->assertEquals($expected, $result);
  568. $result = $this->testDb->name('Model.name as y');
  569. $expected = '`Model`.`name` AS `y`';
  570. $this->assertEquals($expected, $result);
  571. }
  572. /**
  573. * test that cacheMethod works as expected
  574. *
  575. * @return void
  576. */
  577. public function testCacheMethod() {
  578. $this->testDb->cacheMethods = true;
  579. $result = $this->testDb->cacheMethod('name', 'some-key', 'stuff');
  580. $this->assertEquals('stuff', $result);
  581. $result = $this->testDb->cacheMethod('name', 'some-key');
  582. $this->assertEquals('stuff', $result);
  583. $result = $this->testDb->cacheMethod('conditions', 'some-key');
  584. $this->assertNull($result);
  585. $result = $this->testDb->cacheMethod('name', 'other-key');
  586. $this->assertNull($result);
  587. $this->testDb->cacheMethods = false;
  588. $result = $this->testDb->cacheMethod('name', 'some-key', 'stuff');
  589. $this->assertEquals('stuff', $result);
  590. $result = $this->testDb->cacheMethod('name', 'some-key');
  591. $this->assertNull($result);
  592. }
  593. /**
  594. * Test that rare collisions do not happen with method caching
  595. *
  596. * @return void
  597. */
  598. public function testNameMethodCacheCollisions() {
  599. $this->testDb->cacheMethods = true;
  600. $this->testDb->flushMethodCache();
  601. $this->testDb->name('Model.fieldlbqndkezcoapfgirmjsh');
  602. $result = $this->testDb->name('Model.fieldkhdfjmelarbqnzsogcpi');
  603. $expected = '`Model`.`fieldkhdfjmelarbqnzsogcpi`';
  604. $this->assertEquals($expected, $result);
  605. }
  606. /**
  607. * Test that flushMethodCache works as expected
  608. *
  609. * @return void
  610. */
  611. public function testFlushMethodCache() {
  612. $this->testDb->cacheMethods = true;
  613. $this->testDb->cacheMethod('name', 'some-key', 'stuff');
  614. Cache::write('method_cache', DboTestSource::$methodCache, '_cake_core_');
  615. $this->testDb->flushMethodCache();
  616. $result = $this->testDb->cacheMethod('name', 'some-key');
  617. $this->assertNull($result);
  618. }
  619. /**
  620. * testLog method
  621. *
  622. * @outputBuffering enabled
  623. * @return void
  624. */
  625. public function testLog() {
  626. $this->testDb->logQuery('Query 1');
  627. $this->testDb->logQuery('Query 2');
  628. $log = $this->testDb->getLog(false, false);
  629. $result = Hash::extract($log['log'], '{n}.query');
  630. $expected = array('Query 1', 'Query 2');
  631. $this->assertEquals($expected, $result);
  632. $oldDebug = Configure::read('debug');
  633. Configure::write('debug', 2);
  634. ob_start();
  635. $this->testDb->showLog();
  636. $contents = ob_get_clean();
  637. $this->assertRegExp('/Query 1/s', $contents);
  638. $this->assertRegExp('/Query 2/s', $contents);
  639. ob_start();
  640. $this->testDb->showLog(true);
  641. $contents = ob_get_clean();
  642. $this->assertRegExp('/Query 1/s', $contents);
  643. $this->assertRegExp('/Query 2/s', $contents);
  644. Configure::write('debug', $oldDebug);
  645. }
  646. /**
  647. * test getting the query log as an array.
  648. *
  649. * @return void
  650. */
  651. public function testGetLog() {
  652. $this->testDb->logQuery('Query 1');
  653. $this->testDb->logQuery('Query 2');
  654. $log = $this->testDb->getLog();
  655. $expected = array('query' => 'Query 1', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  656. $this->assertEquals($expected, $log['log'][0]);
  657. $expected = array('query' => 'Query 2', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  658. $this->assertEquals($expected, $log['log'][1]);
  659. $expected = array('query' => 'Error 1', 'affected' => '', 'numRows' => '', 'took' => '');
  660. }
  661. /**
  662. * test getting the query log as an array, setting bind params.
  663. *
  664. * @return void
  665. */
  666. public function testGetLogParams() {
  667. $this->testDb->logQuery('Query 1', array(1, 2, 'abc'));
  668. $this->testDb->logQuery('Query 2', array('field1' => 1, 'field2' => 'abc'));
  669. $log = $this->testDb->getLog();
  670. $expected = array('query' => 'Query 1', 'params' => array(1, 2, 'abc'), 'affected' => '', 'numRows' => '', 'took' => '');
  671. $this->assertEquals($expected, $log['log'][0]);
  672. $expected = array('query' => 'Query 2', 'params' => array('field1' => 1, 'field2' => 'abc'), 'affected' => '', 'numRows' => '', 'took' => '');
  673. $this->assertEquals($expected, $log['log'][1]);
  674. }
  675. /**
  676. * test that query() returns boolean values from operations like CREATE TABLE
  677. *
  678. * @return void
  679. */
  680. public function testFetchAllBooleanReturns() {
  681. $name = $this->db->fullTableName('test_query');
  682. $query = "CREATE TABLE {$name} (name varchar(10));";
  683. $result = $this->db->query($query);
  684. $this->assertTrue($result, 'Query did not return a boolean');
  685. $query = "DROP TABLE {$name};";
  686. $result = $this->db->query($query);
  687. $this->assertTrue($result, 'Query did not return a boolean');
  688. }
  689. /**
  690. * test order to generate query order clause for virtual fields
  691. *
  692. * @return void
  693. */
  694. public function testVirtualFieldsInOrder() {
  695. $Article = ClassRegistry::init('Article');
  696. $Article->virtualFields = array(
  697. 'this_moment' => 'NOW()',
  698. 'two' => '1 + 1',
  699. );
  700. $order = array('two', 'this_moment');
  701. $result = $this->db->order($order, 'ASC', $Article);
  702. $expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC';
  703. $this->assertEquals($expected, $result);
  704. $order = array('Article.two', 'Article.this_moment');
  705. $result = $this->db->order($order, 'ASC', $Article);
  706. $expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC';
  707. $this->assertEquals($expected, $result);
  708. }
  709. /**
  710. * test the permutations of fullTableName()
  711. *
  712. * @return void
  713. */
  714. public function testFullTablePermutations() {
  715. $Article = ClassRegistry::init('Article');
  716. $result = $this->testDb->fullTableName($Article, false, false);
  717. $this->assertEquals('articles', $result);
  718. $Article->tablePrefix = 'tbl_';
  719. $result = $this->testDb->fullTableName($Article, false, false);
  720. $this->assertEquals('tbl_articles', $result);
  721. $Article->useTable = $Article->table = 'with spaces';
  722. $Article->tablePrefix = '';
  723. $result = $this->testDb->fullTableName($Article, true, false);
  724. $this->assertEquals('`with spaces`', $result);
  725. $this->loadFixtures('Article');
  726. $Article->useTable = $Article->table = 'articles';
  727. $Article->setDataSource('test');
  728. $testdb = $Article->getDataSource();
  729. $result = $testdb->fullTableName($Article, false, true);
  730. $this->assertEquals($testdb->getSchemaName() . '.articles', $result);
  731. // tests for empty schemaName
  732. $noschema = ConnectionManager::create('noschema', array(
  733. 'datasource' => 'DboTestSource'
  734. ));
  735. $Article->setDataSource('noschema');
  736. $Article->schemaName = null;
  737. $result = $noschema->fullTableName($Article, false, true);
  738. $this->assertEquals('articles', $result);
  739. $this->testDb->config['prefix'] = 't_';
  740. $result = $this->testDb->fullTableName('post_tag', false, false);
  741. $this->assertEquals('t_post_tag', $result);
  742. }
  743. /**
  744. * test that read() only calls queryAssociation on db objects when the method is defined.
  745. *
  746. * @return void
  747. */
  748. public function testReadOnlyCallingQueryAssociationWhenDefined() {
  749. $this->loadFixtures('Article', 'User', 'ArticlesTag', 'Tag');
  750. ConnectionManager::create('test_no_queryAssociation', array(
  751. 'datasource' => 'MockDataSource'
  752. ));
  753. $Article = ClassRegistry::init('Article');
  754. $Article->Comment->useDbConfig = 'test_no_queryAssociation';
  755. $result = $Article->find('all');
  756. $this->assertTrue(is_array($result));
  757. }
  758. /**
  759. * test that queryAssociation() reuse already joined data for 'belongsTo' and 'hasOne' associations
  760. * instead of running unneeded queries for each record
  761. *
  762. * @return void
  763. */
  764. public function testQueryAssociationUnneededQueries() {
  765. $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag');
  766. $Comment = ClassRegistry::init('Comment');
  767. $fullDebug = $this->db->fullDebug;
  768. $this->db->fullDebug = true;
  769. $Comment->find('all', array('recursive' => 2)); // ensure Model descriptions are saved
  770. $this->db->getLog();
  771. // case: Comment belongsTo User and Article
  772. $Comment->unbindModel(array(
  773. 'hasOne' => array('Attachment')
  774. ));
  775. $Comment->Article->unbindModel(array(
  776. 'belongsTo' => array('User'),
  777. 'hasMany' => array('Comment'),
  778. 'hasAndBelongsToMany' => array('Tag')
  779. ));
  780. $Comment->find('all', array('recursive' => 2));
  781. $log = $this->db->getLog();
  782. $this->assertEquals(1, count($log['log']));
  783. // case: Comment belongsTo Article, Article belongsTo User
  784. $Comment->unbindModel(array(
  785. 'belongsTo' => array('User'),
  786. 'hasOne' => array('Attachment')
  787. ));
  788. $Comment->Article->unbindModel(array(
  789. 'hasMany' => array('Comment'),
  790. 'hasAndBelongsToMany' => array('Tag'),
  791. ));
  792. $Comment->find('all', array('recursive' => 2));
  793. $log = $this->db->getLog();
  794. $this->assertEquals(7, count($log['log']));
  795. // case: Comment hasOne Attachment
  796. $Comment->unbindModel(array(
  797. 'belongsTo' => array('Article', 'User'),
  798. ));
  799. $Comment->Attachment->unbindModel(array(
  800. 'belongsTo' => array('Comment'),
  801. ));
  802. $Comment->find('all', array('recursive' => 2));
  803. $log = $this->db->getLog();
  804. $this->assertEquals(1, count($log['log']));
  805. $this->db->fullDebug = $fullDebug;
  806. }
  807. /**
  808. * Tests that generation association queries without LinkModel still works.
  809. * Mainly BC.
  810. *
  811. * @return void
  812. */
  813. public function testGenerateAssociationQuery() {
  814. $this->loadFixtures('Article');
  815. $Article = ClassRegistry::init('Article');
  816. $queryData = array(
  817. 'conditions' => array(
  818. 'Article.id' => 1
  819. ),
  820. 'fields' => array(
  821. 'Article.id',
  822. 'Article.title',
  823. ),
  824. 'joins' => array(),
  825. 'limit' => 2,
  826. 'offset' => 2,
  827. 'order' => array('title'),
  828. 'page' => 2,
  829. 'group' => null,
  830. 'callbacks' => 1
  831. );
  832. $result = $this->db->generateAssociationQuery($Article, null, null, null, null, $queryData, false);
  833. $this->assertContains('SELECT', $result);
  834. $this->assertContains('FROM', $result);
  835. $this->assertContains('WHERE', $result);
  836. $this->assertContains('ORDER', $result);
  837. }
  838. /**
  839. * test that fields() is using methodCache()
  840. *
  841. * @return void
  842. */
  843. public function testFieldsUsingMethodCache() {
  844. $this->testDb->cacheMethods = false;
  845. DboTestSource::$methodCache = array();
  846. $Article = ClassRegistry::init('Article');
  847. $this->testDb->fields($Article, null, array('title', 'body', 'published'));
  848. $this->assertTrue(empty(DboTestSource::$methodCache['fields']), 'Cache not empty');
  849. }
  850. /**
  851. * test that fields() method cache detects datasource changes
  852. *
  853. * @return void
  854. */
  855. public function testFieldsCacheKeyWithDatasourceChange() {
  856. ConnectionManager::create('firstschema', array(
  857. 'datasource' => 'DboTestSource'
  858. ));
  859. ConnectionManager::create('secondschema', array(
  860. 'datasource' => 'DboSecondTestSource'
  861. ));
  862. Cache::delete('method_cache', '_cake_core_');
  863. DboTestSource::$methodCache = array();
  864. $Article = ClassRegistry::init('Article');
  865. $Article->setDataSource('firstschema');
  866. $ds = $Article->getDataSource();
  867. $ds->cacheMethods = true;
  868. $first = $ds->fields($Article, null, array('title', 'body', 'published'));
  869. $Article->setDataSource('secondschema');
  870. $ds = $Article->getDataSource();
  871. $ds->cacheMethods = true;
  872. $second = $ds->fields($Article, null, array('title', 'body', 'published'));
  873. $this->assertNotEquals($first, $second);
  874. $this->assertEquals(2, count(DboTestSource::$methodCache['fields']));
  875. }
  876. /**
  877. * test that fields() method cache detects schema name changes
  878. *
  879. * @return void
  880. */
  881. public function testFieldsCacheKeyWithSchemanameChange() {
  882. if ($this->db instanceof Postgres || $this->db instanceof Sqlserver) {
  883. $this->markTestSkipped('Cannot run this test with SqlServer or Postgres');
  884. }
  885. Cache::delete('method_cache', '_cake_core_');
  886. DboSource::$methodCache = array();
  887. $Article = ClassRegistry::init('Article');
  888. $ds = $Article->getDataSource();
  889. $ds->cacheMethods = true;
  890. $first = $ds->fields($Article);
  891. $Article->schemaName = 'secondSchema';
  892. $ds = $Article->getDataSource();
  893. $ds->cacheMethods = true;
  894. $second = $ds->fields($Article);
  895. $this->assertEquals(2, count(DboSource::$methodCache['fields']));
  896. }
  897. /**
  898. * Test that group works without a model
  899. *
  900. * @return void
  901. */
  902. public function testGroupNoModel() {
  903. $result = $this->db->group('created');
  904. $this->assertEquals(' GROUP BY created', $result);
  905. }
  906. /**
  907. * Test getting the last error.
  908. *
  909. * @return void
  910. */
  911. public function testLastError() {
  912. $stmt = $this->getMock('PDOStatement');
  913. $stmt->expects($this->any())
  914. ->method('errorInfo')
  915. ->will($this->returnValue(array('', 'something', 'bad')));
  916. $result = $this->db->lastError($stmt);
  917. $expected = 'something: bad';
  918. $this->assertEquals($expected, $result);
  919. }
  920. /**
  921. * Tests that transaction commands are logged
  922. *
  923. * @return void
  924. */
  925. public function testTransactionLogging() {
  926. $conn = $this->getMock('MockPDO');
  927. $db = new DboTestSource();
  928. $db->setConnection($conn);
  929. $conn->expects($this->exactly(2))->method('beginTransaction')
  930. ->will($this->returnValue(true));
  931. $conn->expects($this->once())->method('commit')->will($this->returnValue(true));
  932. $conn->expects($this->once())->method('rollback')->will($this->returnValue(true));
  933. $db->begin();
  934. $log = $db->getLog();
  935. $expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  936. $this->assertEquals($expected, $log['log'][0]);
  937. $db->commit();
  938. $expected = array('query' => 'COMMIT', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  939. $log = $db->getLog();
  940. $this->assertEquals($expected, $log['log'][0]);
  941. $db->begin();
  942. $expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  943. $log = $db->getLog();
  944. $this->assertEquals($expected, $log['log'][0]);
  945. $db->rollback();
  946. $expected = array('query' => 'ROLLBACK', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
  947. $log = $db->getLog();
  948. $this->assertEquals($expected, $log['log'][0]);
  949. }
  950. /**
  951. * Test nested transaction calls
  952. *
  953. * @return void
  954. */
  955. public function testTransactionNested() {
  956. $conn = $this->getMock('MockPDO');
  957. $db = new DboTestSource();
  958. $db->setConnection($conn);
  959. $db->useNestedTransactions = true;
  960. $db->nestedSupport = true;
  961. $conn->expects($this->at(0))->method('beginTransaction')->will($this->returnValue(true));
  962. $conn->expects($this->at(1))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true));
  963. $conn->expects($this->at(2))->method('exec')->with($this->equalTo('RELEASE SAVEPOINT LEVEL1'))->will($this->returnValue(true));
  964. $conn->expects($this->at(3))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true));
  965. $conn->expects($this->at(4))->method('exec')->with($this->equalTo('ROLLBACK TO SAVEPOINT LEVEL1'))->will($this->returnValue(true));
  966. $conn->expects($this->at(5))->method('commit')->will($this->returnValue(true));
  967. $this->_runTransactions($db);
  968. }
  969. /**
  970. * Test nested transaction calls without support
  971. *
  972. * @return void
  973. */
  974. public function testTransactionNestedWithoutSupport() {
  975. $conn = $this->getMock('MockPDO');
  976. $db = new DboTestSource();
  977. $db->setConnection($conn);
  978. $db->useNestedTransactions = true;
  979. $db->nestedSupport = false;
  980. $conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true));
  981. $conn->expects($this->never())->method('exec');
  982. $conn->expects($this->once())->method('commit')->will($this->returnValue(true));
  983. $this->_runTransactions($db);
  984. }
  985. /**
  986. * Test nested transaction disabled
  987. *
  988. * @return void
  989. */
  990. public function testTransactionNestedDisabled() {
  991. $conn = $this->getMock('MockPDO');
  992. $db = new DboTestSource();
  993. $db->setConnection($conn);
  994. $db->useNestedTransactions = false;
  995. $db->nestedSupport = true;
  996. $conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true));
  997. $conn->expects($this->never())->method('exec');
  998. $conn->expects($this->once())->method('commit')->will($this->returnValue(true));
  999. $this->_runTransactions($db);
  1000. }
  1001. /**
  1002. * Nested transaction calls
  1003. *
  1004. * @param DboTestSource $db
  1005. * @return void
  1006. */
  1007. protected function _runTransactions($db) {
  1008. $db->begin();
  1009. $db->begin();
  1010. $db->commit();
  1011. $db->begin();
  1012. $db->rollback();
  1013. $db->commit();
  1014. }
  1015. /**
  1016. * Test build statement with some fields missing
  1017. *
  1018. * @return void
  1019. */
  1020. public function testBuildStatementDefaults() {
  1021. $conn = $this->getMock('MockPDO', array('quote'));
  1022. $conn->expects($this->at(0))
  1023. ->method('quote')
  1024. ->will($this->returnValue('foo bar'));
  1025. $db = new DboTestSource();
  1026. $db->setConnection($conn);
  1027. $subQuery = $db->buildStatement(
  1028. array(
  1029. 'fields' => array('DISTINCT(AssetsTag.asset_id)'),
  1030. 'table' => "assets_tags",
  1031. 'alias' => "AssetsTag",
  1032. 'conditions' => array("Tag.name" => 'foo bar'),
  1033. 'limit' => null,
  1034. 'group' => "AssetsTag.asset_id"
  1035. ),
  1036. $this->Model
  1037. );
  1038. $expected = 'SELECT DISTINCT(AssetsTag.asset_id) FROM assets_tags AS AssetsTag WHERE Tag.name = foo bar GROUP BY AssetsTag.asset_id';
  1039. $this->assertEquals($expected, $subQuery);
  1040. }
  1041. /**
  1042. * data provider for testBuildJoinStatement
  1043. *
  1044. * @return array
  1045. */
  1046. public static function joinStatements() {
  1047. return array(
  1048. array(array(
  1049. 'type' => 'CROSS',
  1050. 'alias' => 'PostsTag',
  1051. 'table' => 'posts_tags',
  1052. 'conditions' => array('1 = 1')
  1053. ), 'CROSS JOIN cakephp.posts_tags AS PostsTag'),
  1054. array(array(
  1055. 'type' => 'LEFT',
  1056. 'alias' => 'PostsTag',
  1057. 'table' => 'posts_tags',
  1058. 'conditions' => array('PostsTag.post_id = Post.id')
  1059. ), 'LEFT JOIN cakephp.posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
  1060. array(array(
  1061. 'type' => 'LEFT',
  1062. 'alias' => 'Stock',
  1063. 'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
  1064. 'conditions' => 'Stock.article_id = Article.id'
  1065. ), 'LEFT JOIN (SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id) AS Stock ON (Stock.article_id = Article.id)')
  1066. );
  1067. }
  1068. /**
  1069. * Test buildJoinStatement()
  1070. * ensure that schemaName is not added when table value is a subquery
  1071. *
  1072. * @dataProvider joinStatements
  1073. * @return void
  1074. */
  1075. public function testBuildJoinStatement($join, $expected) {
  1076. $db = $this->getMock('DboTestSource', array('getSchemaName'));
  1077. $db->expects($this->any())
  1078. ->method('getSchemaName')
  1079. ->will($this->returnValue('cakephp'));
  1080. $result = $db->buildJoinStatement($join);
  1081. $this->assertEquals($expected, $result);
  1082. }
  1083. /**
  1084. * data provider for testBuildJoinStatementWithTablePrefix
  1085. *
  1086. * @return array
  1087. */
  1088. public static function joinStatementsWithPrefix($schema) {
  1089. return array(
  1090. array(array(
  1091. 'type' => 'LEFT',
  1092. 'alias' => 'PostsTag',
  1093. 'table' => 'posts_tags',
  1094. 'conditions' => array('PostsTag.post_id = Post.id')
  1095. ), 'LEFT JOIN pre_posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
  1096. array(array(
  1097. 'type' => 'LEFT',
  1098. 'alias' => 'Stock',
  1099. 'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
  1100. 'conditions' => 'Stock.article_id = Article.id'
  1101. ), 'LEFT JOIN (SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id) AS Stock ON (Stock.article_id = Article.id)')
  1102. );
  1103. }
  1104. /**
  1105. * Test buildJoinStatement()
  1106. * ensure that prefix is not added when table value is a subquery
  1107. *
  1108. * @dataProvider joinStatementsWithPrefix
  1109. * @return void
  1110. */
  1111. public function testBuildJoinStatementWithTablePrefix($join, $expected) {
  1112. $db = new DboTestSource();
  1113. $db->config['prefix'] = 'pre_';
  1114. $result = $db->buildJoinStatement($join);
  1115. $this->assertEquals($expected, $result);
  1116. }
  1117. /**
  1118. * Test conditionKeysToString()
  1119. *
  1120. * @return void
  1121. */
  1122. public function testConditionKeysToString() {
  1123. $Article = ClassRegistry::init('Article');
  1124. $conn = $this->getMock('MockPDO', array('quote'));
  1125. $db = new DboTestSource();
  1126. $db->setConnection($conn);
  1127. $conn->expects($this->at(0))
  1128. ->method('quote')
  1129. ->will($this->returnValue('just text'));
  1130. $conditions = array('Article.name' => 'just text');
  1131. $result = $db->conditionKeysToString($conditions, true, $Article);
  1132. $expected = "Article.name = just text";
  1133. $this->assertEquals($expected, $result[0]);
  1134. $conn->expects($this->at(0))
  1135. ->method('quote')
  1136. ->will($this->returnValue('just text'));
  1137. $conn->expects($this->at(1))
  1138. ->method('quote')
  1139. ->will($this->returnValue('other text'));
  1140. $conditions = array('Article.name' => array('just text', 'other text'));
  1141. $result = $db->conditionKeysToString($conditions, true, $Article);
  1142. $expected = "Article.name IN (just text, other text)";
  1143. $this->assertEquals($expected, $result[0]);
  1144. }
  1145. /**
  1146. * Test conditionKeysToString() with virtual field
  1147. *
  1148. * @return void
  1149. */
  1150. public function testConditionKeysToStringVirtualField() {
  1151. $Article = ClassRegistry::init('Article');
  1152. $Article->virtualFields = array(
  1153. 'extra' => 'something virtual'
  1154. );
  1155. $conn = $this->getMock('MockPDO', array('quote'));
  1156. $db = new DboTestSource();
  1157. $db->setConnection($conn);
  1158. $conn->expects($this->at(0))
  1159. ->method('quote')
  1160. ->will($this->returnValue('just text'));
  1161. $conditions = array('Article.extra' => 'just text');
  1162. $result = $db->conditionKeysToString($conditions, true, $Article);
  1163. $expected = "(" . $Article->virtualFields['extra'] . ") = just text";
  1164. $this->assertEquals($expected, $result[0]);
  1165. $conn->expects($this->at(0))
  1166. ->method('quote')
  1167. ->will($this->returnValue('just text'));
  1168. $conn->expects($this->at(1))
  1169. ->method('quote')
  1170. ->will($this->returnValue('other text'));
  1171. $conditions = array('Article.extra' => array('just text', 'other text'));
  1172. $result = $db->conditionKeysToString($conditions, true, $Article);
  1173. $expected = "(" . $Article->virtualFields['extra'] . ") IN (just text, other text)";
  1174. $this->assertEquals($expected, $result[0]);
  1175. }
  1176. /**
  1177. * Test the limit function.
  1178. *
  1179. * @return void
  1180. */
  1181. public function testLimit() {
  1182. $db = new DboTestSource();
  1183. $result = $db->limit('0');
  1184. $this->assertNull($result);
  1185. $result = $db->limit('10');
  1186. $this->assertEquals(' LIMIT 10', $result);
  1187. $result = $db->limit('FARTS', 'BOOGERS');
  1188. $this->assertEquals(' LIMIT 0, 0', $result);
  1189. $result = $db->limit(20, 10);
  1190. $this->assertEquals(' LIMIT 10, 20', $result);
  1191. $result = $db->limit(10, 300000000000000000000000000000);
  1192. $scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
  1193. $this->assertNotContains($scientificNotation, $result);
  1194. }
  1195. /**
  1196. * Test insertMulti with id position.
  1197. *
  1198. * @return void
  1199. */
  1200. public function testInsertMultiId() {
  1201. $this->loadFixtures('Article');
  1202. $Article = ClassRegistry::init('Article');
  1203. $db = $Article->getDatasource();
  1204. $datetime = date('Y-m-d H:i:s');
  1205. $data = array(
  1206. array(
  1207. 'user_id' => 1,
  1208. 'title' => 'test',
  1209. 'body' => 'test',
  1210. 'published' => 'N',
  1211. 'created' => $datetime,
  1212. 'updated' => $datetime,
  1213. 'id' => 100,
  1214. ),
  1215. array(
  1216. 'user_id' => 1,
  1217. 'title' => 'test 101',
  1218. 'body' => 'test 101',
  1219. 'published' => 'N',
  1220. 'created' => $datetime,
  1221. 'updated' => $datetime,
  1222. 'id' => 101,
  1223. )
  1224. );
  1225. $result = $db->insertMulti('articles', array_keys($data[0]), $data);
  1226. $this->assertTrue($result, 'Data was saved');
  1227. $data = array(
  1228. array(
  1229. 'id' => 102,
  1230. 'user_id' => 1,
  1231. 'title' => 'test',
  1232. 'body' => 'test',
  1233. 'published' => 'N',
  1234. 'created' => $datetime,
  1235. 'updated' => $datetime,
  1236. ),
  1237. array(
  1238. 'id' => 103,
  1239. 'user_id' => 1,
  1240. 'title' => 'test 101',
  1241. 'body' => 'test 101',
  1242. 'published' => 'N',
  1243. 'created' => $datetime,
  1244. 'updated' => $datetime,
  1245. )
  1246. );
  1247. $result = $db->insertMulti('articles', array_keys($data[0]), $data);
  1248. $this->assertTrue($result, 'Data was saved');
  1249. }
  1250. /**
  1251. * Test defaultConditions()
  1252. *
  1253. * @return void
  1254. */
  1255. public function testDefaultConditions() {
  1256. $this->loadFixtures('Article');
  1257. $Article = ClassRegistry::init('Article');
  1258. $db = $Article->getDataSource();
  1259. // Creates a default set of conditions from the model if $conditions is null/empty.
  1260. $Article->id = 1;
  1261. $result = $db->defaultConditions($Article, null);
  1262. $this->assertEquals(array('Article.id' => 1), $result);
  1263. // $useAlias == false
  1264. $Article->id = 1;
  1265. $result = $db->defaultConditions($Article, null, false);
  1266. $this->assertEquals(array($db->fullTableName($Article, false) . '.id' => 1), $result);
  1267. // If conditions are supplied then they will be returned.
  1268. $Article->id = 1;
  1269. $result = $db->defaultConditions($Article, array('Article.title' => 'First article'));
  1270. $this->assertEquals(array('Article.title' => 'First article'), $result);
  1271. // If a model doesn't exist and no conditions were provided either null or false will be returned based on what was input.
  1272. $Article->id = 1000000;
  1273. $result = $db->defaultConditions($Article, null);
  1274. $this->assertNull($result);
  1275. $Article->id = 1000000;
  1276. $result = $db->defaultConditions($Article, false);
  1277. $this->assertFalse($result);
  1278. // Safe update mode
  1279. $Article->id = 1000000;
  1280. $Article->__safeUpdateMode = true;
  1281. $result = $db->defaultConditions($Article, null);
  1282. $this->assertFalse($result);
  1283. }
  1284. /**
  1285. * Test that count how many times is afterFind called
  1286. *
  1287. * @return void
  1288. */
  1289. public function testCountAfterFindCalls() {
  1290. $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag');
  1291. // Use alias to make testing "primary = true" easy
  1292. $Primary = $this->getMock('Comment', array('afterFind'), array(array('alias' => 'Primary')), '', true);
  1293. $Primary->expects($this->any())->method('afterFind')->will($this->returnArgument(0));
  1294. $Article = $this->getMock('Article', array('afterFind'), array(), '', true);
  1295. $User = $this->getMock('User', array('afterFind'), array(), '', true);
  1296. $Comment = $this->getMock('Comment', array('afterFind'), array(), '', true);
  1297. $Tag = $this->getMock('Tag', array('afterFind'), array(), '', true);
  1298. $Attachment = $this->getMock('Attachment', array('afterFind'), array(), '', true);
  1299. $Primary->Article = $Article;
  1300. $Primary->Article->User = $User;
  1301. $Primary->Article->Tag = $Tag;
  1302. $Primary->Article->Comment = $Comment;
  1303. $Primary->Attachment = $Attachment;
  1304. $Primary->Attachment->Comment = $Comment;
  1305. $Primary->User = $User;
  1306. // primary = true
  1307. $Primary->expects($this->once())
  1308. ->method('afterFind')->with($this->anything(), $this->isTrue())->will($this->returnArgument(0));
  1309. // primary = false
  1310. $Article->expects($this->once()) // Primary belongs to 1 Article
  1311. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1312. $User->expects($this->exactly(2)) // Article belongs to 1 User and Primary belongs to 1 User
  1313. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1314. $Tag->expects($this->exactly(2)) // Article has 2 Tags
  1315. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1316. $Comment->expects($this->exactly(3)) // Article has 2 Comments and Attachment belongs to 1 Comment
  1317. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1318. $Attachment->expects($this->once()) // Primary has 1 Attachment
  1319. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1320. $result = $Primary->find('first', array('conditions' => array('Primary.id' => 5), 'recursive' => 2));
  1321. $this->assertCount(2, $result['Article']['Tag']);
  1322. $this->assertCount(2, $result['Article']['Comment']);
  1323. }
  1324. }