DboSourceTest.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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. ), 'LEFT JOIN cakephp.posts_tags AS PostsTag'),
  1059. array(array(
  1060. 'type' => 'LEFT',
  1061. 'alias' => 'PostsTag',
  1062. 'table' => 'posts_tags',
  1063. 'conditions' => array('PostsTag.post_id = Post.id')
  1064. ), 'LEFT JOIN cakephp.posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
  1065. array(array(
  1066. 'type' => 'LEFT',
  1067. 'alias' => 'Stock',
  1068. 'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
  1069. 'conditions' => 'Stock.article_id = Article.id'
  1070. ), '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)')
  1071. );
  1072. }
  1073. /**
  1074. * Test buildJoinStatement()
  1075. * ensure that schemaName is not added when table value is a subquery
  1076. *
  1077. * @dataProvider joinStatements
  1078. * @return void
  1079. */
  1080. public function testBuildJoinStatement($join, $expected) {
  1081. $db = $this->getMock('DboTestSource', array('getSchemaName'));
  1082. $db->expects($this->any())
  1083. ->method('getSchemaName')
  1084. ->will($this->returnValue('cakephp'));
  1085. $result = $db->buildJoinStatement($join);
  1086. $this->assertEquals($expected, $result);
  1087. }
  1088. /**
  1089. * data provider for testBuildJoinStatementWithTablePrefix
  1090. *
  1091. * @return array
  1092. */
  1093. public static function joinStatementsWithPrefix($schema) {
  1094. return array(
  1095. array(array(
  1096. 'type' => 'LEFT',
  1097. 'alias' => 'PostsTag',
  1098. 'table' => 'posts_tags',
  1099. 'conditions' => array('PostsTag.post_id = Post.id')
  1100. ), 'LEFT JOIN pre_posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
  1101. array(array(
  1102. 'type' => 'LEFT',
  1103. 'alias' => 'Stock',
  1104. 'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
  1105. 'conditions' => 'Stock.article_id = Article.id'
  1106. ), '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)')
  1107. );
  1108. }
  1109. /**
  1110. * Test buildJoinStatement()
  1111. * ensure that prefix is not added when table value is a subquery
  1112. *
  1113. * @dataProvider joinStatementsWithPrefix
  1114. * @return void
  1115. */
  1116. public function testBuildJoinStatementWithTablePrefix($join, $expected) {
  1117. $db = new DboTestSource();
  1118. $db->config['prefix'] = 'pre_';
  1119. $result = $db->buildJoinStatement($join);
  1120. $this->assertEquals($expected, $result);
  1121. }
  1122. /**
  1123. * Test conditionKeysToString()
  1124. *
  1125. * @return void
  1126. */
  1127. public function testConditionKeysToString() {
  1128. $Article = ClassRegistry::init('Article');
  1129. $conn = $this->getMock('MockPDO', array('quote'));
  1130. $db = new DboTestSource();
  1131. $db->setConnection($conn);
  1132. $conn->expects($this->at(0))
  1133. ->method('quote')
  1134. ->will($this->returnValue('just text'));
  1135. $conditions = array('Article.name' => 'just text');
  1136. $result = $db->conditionKeysToString($conditions, true, $Article);
  1137. $expected = "Article.name = just text";
  1138. $this->assertEquals($expected, $result[0]);
  1139. $conn->expects($this->at(0))
  1140. ->method('quote')
  1141. ->will($this->returnValue('just text'));
  1142. $conn->expects($this->at(1))
  1143. ->method('quote')
  1144. ->will($this->returnValue('other text'));
  1145. $conditions = array('Article.name' => array('just text', 'other text'));
  1146. $result = $db->conditionKeysToString($conditions, true, $Article);
  1147. $expected = "Article.name IN (just text, other text)";
  1148. $this->assertEquals($expected, $result[0]);
  1149. }
  1150. /**
  1151. * Test conditionKeysToString() with virtual field
  1152. *
  1153. * @return void
  1154. */
  1155. public function testConditionKeysToStringVirtualField() {
  1156. $Article = ClassRegistry::init('Article');
  1157. $Article->virtualFields = array(
  1158. 'extra' => 'something virtual'
  1159. );
  1160. $conn = $this->getMock('MockPDO', array('quote'));
  1161. $db = new DboTestSource();
  1162. $db->setConnection($conn);
  1163. $conn->expects($this->at(0))
  1164. ->method('quote')
  1165. ->will($this->returnValue('just text'));
  1166. $conditions = array('Article.extra' => 'just text');
  1167. $result = $db->conditionKeysToString($conditions, true, $Article);
  1168. $expected = "(" . $Article->virtualFields['extra'] . ") = just text";
  1169. $this->assertEquals($expected, $result[0]);
  1170. $conn->expects($this->at(0))
  1171. ->method('quote')
  1172. ->will($this->returnValue('just text'));
  1173. $conn->expects($this->at(1))
  1174. ->method('quote')
  1175. ->will($this->returnValue('other text'));
  1176. $conditions = array('Article.extra' => array('just text', 'other text'));
  1177. $result = $db->conditionKeysToString($conditions, true, $Article);
  1178. $expected = "(" . $Article->virtualFields['extra'] . ") IN (just text, other text)";
  1179. $this->assertEquals($expected, $result[0]);
  1180. }
  1181. /**
  1182. * Test the limit function.
  1183. *
  1184. * @return void
  1185. */
  1186. public function testLimit() {
  1187. $db = new DboTestSource();
  1188. $result = $db->limit('0');
  1189. $this->assertNull($result);
  1190. $result = $db->limit('10');
  1191. $this->assertEquals(' LIMIT 10', $result);
  1192. $result = $db->limit('FARTS', 'BOOGERS');
  1193. $this->assertEquals(' LIMIT 0, 0', $result);
  1194. $result = $db->limit(20, 10);
  1195. $this->assertEquals(' LIMIT 10, 20', $result);
  1196. $result = $db->limit(10, 300000000000000000000000000000);
  1197. $scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
  1198. $this->assertNotContains($scientificNotation, $result);
  1199. }
  1200. /**
  1201. * Test insertMulti with id position.
  1202. *
  1203. * @return void
  1204. */
  1205. public function testInsertMultiId() {
  1206. $this->loadFixtures('Article');
  1207. $Article = ClassRegistry::init('Article');
  1208. $db = $Article->getDatasource();
  1209. $datetime = date('Y-m-d H:i:s');
  1210. $data = array(
  1211. array(
  1212. 'user_id' => 1,
  1213. 'title' => 'test',
  1214. 'body' => 'test',
  1215. 'published' => 'N',
  1216. 'created' => $datetime,
  1217. 'updated' => $datetime,
  1218. 'id' => 100,
  1219. ),
  1220. array(
  1221. 'user_id' => 1,
  1222. 'title' => 'test 101',
  1223. 'body' => 'test 101',
  1224. 'published' => 'N',
  1225. 'created' => $datetime,
  1226. 'updated' => $datetime,
  1227. 'id' => 101,
  1228. )
  1229. );
  1230. $result = $db->insertMulti('articles', array_keys($data[0]), $data);
  1231. $this->assertTrue($result, 'Data was saved');
  1232. $data = array(
  1233. array(
  1234. 'id' => 102,
  1235. 'user_id' => 1,
  1236. 'title' => 'test',
  1237. 'body' => 'test',
  1238. 'published' => 'N',
  1239. 'created' => $datetime,
  1240. 'updated' => $datetime,
  1241. ),
  1242. array(
  1243. 'id' => 103,
  1244. 'user_id' => 1,
  1245. 'title' => 'test 101',
  1246. 'body' => 'test 101',
  1247. 'published' => 'N',
  1248. 'created' => $datetime,
  1249. 'updated' => $datetime,
  1250. )
  1251. );
  1252. $result = $db->insertMulti('articles', array_keys($data[0]), $data);
  1253. $this->assertTrue($result, 'Data was saved');
  1254. }
  1255. /**
  1256. * Test defaultConditions()
  1257. *
  1258. * @return void
  1259. */
  1260. public function testDefaultConditions() {
  1261. $this->loadFixtures('Article');
  1262. $Article = ClassRegistry::init('Article');
  1263. $db = $Article->getDataSource();
  1264. // Creates a default set of conditions from the model if $conditions is null/empty.
  1265. $Article->id = 1;
  1266. $result = $db->defaultConditions($Article, null);
  1267. $this->assertEquals(array('Article.id' => 1), $result);
  1268. // $useAlias == false
  1269. $Article->id = 1;
  1270. $result = $db->defaultConditions($Article, null, false);
  1271. $this->assertEquals(array($db->fullTableName($Article, false) . '.id' => 1), $result);
  1272. // If conditions are supplied then they will be returned.
  1273. $Article->id = 1;
  1274. $result = $db->defaultConditions($Article, array('Article.title' => 'First article'));
  1275. $this->assertEquals(array('Article.title' => 'First article'), $result);
  1276. // If a model doesn't exist and no conditions were provided either null or false will be returned based on what was input.
  1277. $Article->id = 1000000;
  1278. $result = $db->defaultConditions($Article, null);
  1279. $this->assertNull($result);
  1280. $Article->id = 1000000;
  1281. $result = $db->defaultConditions($Article, false);
  1282. $this->assertFalse($result);
  1283. // Safe update mode
  1284. $Article->id = 1000000;
  1285. $Article->__safeUpdateMode = true;
  1286. $result = $db->defaultConditions($Article, null);
  1287. $this->assertFalse($result);
  1288. }
  1289. /**
  1290. * Test that count how many times is afterFind called
  1291. *
  1292. * @return void
  1293. */
  1294. public function testCountAfterFindCalls() {
  1295. $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag');
  1296. // Use alias to make testing "primary = true" easy
  1297. $Primary = $this->getMock('Comment', array('afterFind'), array(array('alias' => 'Primary')), '', true);
  1298. $Primary->expects($this->any())->method('afterFind')->will($this->returnArgument(0));
  1299. $Article = $this->getMock('Article', array('afterFind'), array(), '', true);
  1300. $User = $this->getMock('User', array('afterFind'), array(), '', true);
  1301. $Comment = $this->getMock('Comment', array('afterFind'), array(), '', true);
  1302. $Tag = $this->getMock('Tag', array('afterFind'), array(), '', true);
  1303. $Attachment = $this->getMock('Attachment', array('afterFind'), array(), '', true);
  1304. $Primary->Article = $Article;
  1305. $Primary->Article->User = $User;
  1306. $Primary->Article->Tag = $Tag;
  1307. $Primary->Article->Comment = $Comment;
  1308. $Primary->Attachment = $Attachment;
  1309. $Primary->Attachment->Comment = $Comment;
  1310. $Primary->User = $User;
  1311. // primary = true
  1312. $Primary->expects($this->once())
  1313. ->method('afterFind')->with($this->anything(), $this->isTrue())->will($this->returnArgument(0));
  1314. // primary = false
  1315. $Article->expects($this->once()) // Primary belongs to 1 Article
  1316. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1317. $User->expects($this->exactly(2)) // Article belongs to 1 User and Primary belongs to 1 User
  1318. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1319. $Tag->expects($this->exactly(2)) // Article has 2 Tags
  1320. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1321. $Comment->expects($this->exactly(3)) // Article has 2 Comments and Attachment belongs to 1 Comment
  1322. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1323. $Attachment->expects($this->once()) // Primary has 1 Attachment
  1324. ->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
  1325. $result = $Primary->find('first', array('conditions' => array('Primary.id' => 5), 'recursive' => 2));
  1326. $this->assertCount(2, $result['Article']['Tag']);
  1327. $this->assertCount(2, $result['Article']['Comment']);
  1328. }
  1329. }