MysqlTest.php 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623
  1. <?php
  2. /**
  3. * DboMysqlTest file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Test.Case.Model.Datasource.Database
  16. * @since CakePHP(tm) v 1.2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Model', 'Model');
  20. App::uses('AppModel', 'Model');
  21. App::uses('Mysql', 'Model/Datasource/Database');
  22. App::uses('CakeSchema', 'Model');
  23. require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
  24. /**
  25. * DboMysqlTest class
  26. *
  27. * @package Cake.Test.Case.Model.Datasource.Database
  28. */
  29. class MysqlTest extends CakeTestCase {
  30. /**
  31. * autoFixtures property
  32. *
  33. * @var bool false
  34. */
  35. public $autoFixtures = false;
  36. /**
  37. * fixtures property
  38. *
  39. * @var array
  40. */
  41. public $fixtures = array(
  42. 'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment',
  43. 'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test',
  44. 'core.binary_test', 'core.inno'
  45. );
  46. /**
  47. * The Dbo instance to be tested
  48. *
  49. * @var DboSource
  50. */
  51. public $Dbo = null;
  52. /**
  53. * Sets up a Dbo class instance for testing
  54. *
  55. */
  56. public function setUp() {
  57. $this->Dbo = ConnectionManager::getDataSource('test');
  58. if (!($this->Dbo instanceof Mysql)) {
  59. $this->markTestSkipped('The MySQL extension is not available.');
  60. }
  61. $this->_debug = Configure::read('debug');
  62. Configure::write('debug', 1);
  63. $this->model = ClassRegistry::init('MysqlTestModel');
  64. }
  65. /**
  66. * Sets up a Dbo class instance for testing
  67. *
  68. */
  69. public function tearDown() {
  70. unset($this->model);
  71. ClassRegistry::flush();
  72. Configure::write('debug', $this->_debug);
  73. }
  74. /**
  75. * Test Dbo value method
  76. *
  77. * @group quoting
  78. */
  79. public function testQuoting() {
  80. $result = $this->Dbo->fields($this->model);
  81. $expected = array(
  82. '`MysqlTestModel`.`id`',
  83. '`MysqlTestModel`.`client_id`',
  84. '`MysqlTestModel`.`name`',
  85. '`MysqlTestModel`.`login`',
  86. '`MysqlTestModel`.`passwd`',
  87. '`MysqlTestModel`.`addr_1`',
  88. '`MysqlTestModel`.`addr_2`',
  89. '`MysqlTestModel`.`zip_code`',
  90. '`MysqlTestModel`.`city`',
  91. '`MysqlTestModel`.`country`',
  92. '`MysqlTestModel`.`phone`',
  93. '`MysqlTestModel`.`fax`',
  94. '`MysqlTestModel`.`url`',
  95. '`MysqlTestModel`.`email`',
  96. '`MysqlTestModel`.`comments`',
  97. '`MysqlTestModel`.`last_login`',
  98. '`MysqlTestModel`.`created`',
  99. '`MysqlTestModel`.`updated`'
  100. );
  101. $this->assertEquals($expected, $result);
  102. $expected = 1.2;
  103. $result = $this->Dbo->value(1.2, 'float');
  104. $this->assertEquals($expected, $result);
  105. $expected = "'1,2'";
  106. $result = $this->Dbo->value('1,2', 'float');
  107. $this->assertEquals($expected, $result);
  108. $expected = "'4713e29446'";
  109. $result = $this->Dbo->value('4713e29446');
  110. $this->assertEquals($expected, $result);
  111. $expected = 'NULL';
  112. $result = $this->Dbo->value('', 'integer');
  113. $this->assertEquals($expected, $result);
  114. $expected = "'0'";
  115. $result = $this->Dbo->value('', 'boolean');
  116. $this->assertEquals($expected, $result);
  117. $expected = 10010001;
  118. $result = $this->Dbo->value(10010001);
  119. $this->assertEquals($expected, $result);
  120. $expected = "'00010010001'";
  121. $result = $this->Dbo->value('00010010001');
  122. $this->assertEquals($expected, $result);
  123. }
  124. /**
  125. * test that localized floats don't cause trouble.
  126. *
  127. * @group quoting
  128. * @return void
  129. */
  130. public function testLocalizedFloats() {
  131. $this->skipIf(DS === '\\', 'The locale is not supported in Windows and affect the others tests.');
  132. $restore = setlocale(LC_ALL, 0);
  133. setlocale(LC_ALL, 'de_DE');
  134. $result = $this->Dbo->value(3.141593);
  135. $this->assertEquals('3.141593', $result);
  136. $result = $this->db->value(3.141593, 'float');
  137. $this->assertEquals('3.141593', $result);
  138. $result = $this->db->value(1234567.11, 'float');
  139. $this->assertEquals('1234567.11', $result);
  140. $result = $this->db->value(123456.45464748, 'float');
  141. $this->assertContains('123456.454647', $result);
  142. $result = $this->db->value(0.987654321, 'float');
  143. $this->assertEquals('0.987654321', (string)$result);
  144. $result = $this->db->value(2.2E-54, 'float');
  145. $this->assertEquals('2.2E-54', (string)$result);
  146. $result = $this->db->value(2.2E-54);
  147. $this->assertEquals('2.2E-54', (string)$result);
  148. setlocale(LC_ALL, $restore);
  149. }
  150. /**
  151. * test that scientific notations are working correctly
  152. *
  153. * @return void
  154. */
  155. public function testScientificNotation() {
  156. $result = $this->db->value(2.2E-54, 'float');
  157. $this->assertEquals('2.2E-54', (string)$result);
  158. $result = $this->db->value(2.2E-54);
  159. $this->assertEquals('2.2E-54', (string)$result);
  160. }
  161. /**
  162. * testTinyintCasting method
  163. *
  164. *
  165. * @return void
  166. */
  167. public function testTinyintCasting() {
  168. $this->Dbo->cacheSources = false;
  169. $tableName = 'tinyint_' . uniqid();
  170. $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  171. $this->model = new CakeTestModel(array(
  172. 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
  173. ));
  174. $result = $this->model->schema();
  175. $this->assertEquals('boolean', $result['bool']['type']);
  176. $this->assertEquals('integer', $result['small_int']['type']);
  177. $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
  178. $result = $this->model->find('first');
  179. $this->assertSame($result['Tinyint']['bool'], true);
  180. $this->assertSame($result['Tinyint']['small_int'], '5');
  181. $this->model->deleteAll(true);
  182. $this->assertTrue((bool)$this->model->save(array('bool' => 0, 'small_int' => 100)));
  183. $result = $this->model->find('first');
  184. $this->assertSame($result['Tinyint']['bool'], false);
  185. $this->assertSame($result['Tinyint']['small_int'], '100');
  186. $this->model->deleteAll(true);
  187. $this->assertTrue((bool)$this->model->save(array('bool' => true, 'small_int' => 0)));
  188. $result = $this->model->find('first');
  189. $this->assertSame($result['Tinyint']['bool'], true);
  190. $this->assertSame($result['Tinyint']['small_int'], '0');
  191. $this->model->deleteAll(true);
  192. $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
  193. }
  194. /**
  195. * testLastAffected method
  196. *
  197. *
  198. * @return void
  199. */
  200. public function testLastAffected() {
  201. $this->Dbo->cacheSources = false;
  202. $tableName = 'tinyint_' . uniqid();
  203. $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  204. $this->model = new CakeTestModel(array(
  205. 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
  206. ));
  207. $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
  208. $this->assertEquals(1, $this->model->find('count'));
  209. $this->model->deleteAll(true);
  210. $result = $this->Dbo->lastAffected();
  211. $this->assertEquals(1, $result);
  212. $this->assertEquals(0, $this->model->find('count'));
  213. $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
  214. }
  215. /**
  216. * testIndexDetection method
  217. *
  218. * @group indices
  219. * @return void
  220. */
  221. public function testIndexDetection() {
  222. $this->Dbo->cacheSources = false;
  223. $name = $this->Dbo->fullTableName('simple');
  224. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  225. $expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
  226. $result = $this->Dbo->index('simple', false);
  227. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  228. $this->assertEquals($expected, $result);
  229. $name = $this->Dbo->fullTableName('with_a_key');
  230. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
  231. $expected = array(
  232. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  233. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  234. );
  235. $result = $this->Dbo->index('with_a_key', false);
  236. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  237. $this->assertEquals($expected, $result);
  238. $name = $this->Dbo->fullTableName('with_two_keys');
  239. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
  240. $expected = array(
  241. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  242. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  243. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  244. );
  245. $result = $this->Dbo->index('with_two_keys', false);
  246. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  247. $this->assertEquals($expected, $result);
  248. $name = $this->Dbo->fullTableName('with_compound_keys');
  249. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
  250. $expected = array(
  251. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  252. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  253. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  254. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  255. );
  256. $result = $this->Dbo->index('with_compound_keys', false);
  257. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  258. $this->assertEquals($expected, $result);
  259. $name = $this->Dbo->fullTableName('with_multiple_compound_keys');
  260. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
  261. $expected = array(
  262. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  263. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  264. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  265. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  266. 'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
  267. );
  268. $result = $this->Dbo->index('with_multiple_compound_keys', false);
  269. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  270. $this->assertEquals($expected, $result);
  271. }
  272. /**
  273. * testBuildColumn method
  274. *
  275. * @return void
  276. */
  277. public function testBuildColumn() {
  278. $restore = $this->Dbo->columns;
  279. $this->Dbo->columns = array('varchar(255)' => 1);
  280. $data = array(
  281. 'name' => 'testName',
  282. 'type' => 'varchar(255)',
  283. 'default',
  284. 'null' => true,
  285. 'key',
  286. 'comment' => 'test'
  287. );
  288. $result = $this->Dbo->buildColumn($data);
  289. $expected = '`testName` DEFAULT NULL COMMENT \'test\'';
  290. $this->assertEquals($expected, $result);
  291. $data = array(
  292. 'name' => 'testName',
  293. 'type' => 'varchar(255)',
  294. 'default',
  295. 'null' => true,
  296. 'key',
  297. 'charset' => 'utf8',
  298. 'collate' => 'utf8_unicode_ci'
  299. );
  300. $result = $this->Dbo->buildColumn($data);
  301. $expected = '`testName` CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL';
  302. $this->assertEquals($expected, $result);
  303. $this->Dbo->columns = $restore;
  304. }
  305. /**
  306. * MySQL 4.x returns index data in a different format,
  307. * Using a mock ensure that MySQL 4.x output is properly parsed.
  308. *
  309. * @group indices
  310. * @return void
  311. */
  312. public function testIndexOnMySQL4Output() {
  313. $name = $this->Dbo->fullTableName('simple');
  314. $mockDbo = $this->getMock('Mysql', array('connect', '_execute', 'getVersion'));
  315. $columnData = array(
  316. array('0' => array(
  317. 'Table' => 'with_compound_keys',
  318. 'Non_unique' => '0',
  319. 'Key_name' => 'PRIMARY',
  320. 'Seq_in_index' => '1',
  321. 'Column_name' => 'id',
  322. 'Collation' => 'A',
  323. 'Cardinality' => '0',
  324. 'Sub_part' => null,
  325. 'Packed' => null,
  326. 'Null' => '',
  327. 'Index_type' => 'BTREE',
  328. 'Comment' => ''
  329. )),
  330. array('0' => array(
  331. 'Table' => 'with_compound_keys',
  332. 'Non_unique' => '1',
  333. 'Key_name' => 'pointless_bool',
  334. 'Seq_in_index' => '1',
  335. 'Column_name' => 'bool',
  336. 'Collation' => 'A',
  337. 'Cardinality' => null,
  338. 'Sub_part' => null,
  339. 'Packed' => null,
  340. 'Null' => 'YES',
  341. 'Index_type' => 'BTREE',
  342. 'Comment' => ''
  343. )),
  344. array('0' => array(
  345. 'Table' => 'with_compound_keys',
  346. 'Non_unique' => '1',
  347. 'Key_name' => 'pointless_small_int',
  348. 'Seq_in_index' => '1',
  349. 'Column_name' => 'small_int',
  350. 'Collation' => 'A',
  351. 'Cardinality' => null,
  352. 'Sub_part' => null,
  353. 'Packed' => null,
  354. 'Null' => 'YES',
  355. 'Index_type' => 'BTREE',
  356. 'Comment' => ''
  357. )),
  358. array('0' => array(
  359. 'Table' => 'with_compound_keys',
  360. 'Non_unique' => '1',
  361. 'Key_name' => 'one_way',
  362. 'Seq_in_index' => '1',
  363. 'Column_name' => 'bool',
  364. 'Collation' => 'A',
  365. 'Cardinality' => null,
  366. 'Sub_part' => null,
  367. 'Packed' => null,
  368. 'Null' => 'YES',
  369. 'Index_type' => 'BTREE',
  370. 'Comment' => ''
  371. )),
  372. array('0' => array(
  373. 'Table' => 'with_compound_keys',
  374. 'Non_unique' => '1',
  375. 'Key_name' => 'one_way',
  376. 'Seq_in_index' => '2',
  377. 'Column_name' => 'small_int',
  378. 'Collation' => 'A',
  379. 'Cardinality' => null,
  380. 'Sub_part' => null,
  381. 'Packed' => null,
  382. 'Null' => 'YES',
  383. 'Index_type' => 'BTREE',
  384. 'Comment' => ''
  385. ))
  386. );
  387. $mockDbo->expects($this->once())->method('getVersion')->will($this->returnValue('4.1'));
  388. $resultMock = $this->getMock('PDOStatement', array('fetch'));
  389. $mockDbo->expects($this->once())
  390. ->method('_execute')
  391. ->with('SHOW INDEX FROM ' . $name)
  392. ->will($this->returnValue($resultMock));
  393. foreach ($columnData as $i => $data) {
  394. $resultMock->expects($this->at($i))->method('fetch')->will($this->returnValue((object)$data));
  395. }
  396. $result = $mockDbo->index($name, false);
  397. $expected = array(
  398. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  399. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  400. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  401. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  402. );
  403. $this->assertEquals($expected, $result);
  404. }
  405. /**
  406. * testColumn method
  407. *
  408. * @return void
  409. */
  410. public function testColumn() {
  411. $result = $this->Dbo->column('varchar(50)');
  412. $expected = 'string';
  413. $this->assertEquals($expected, $result);
  414. $result = $this->Dbo->column('text');
  415. $expected = 'text';
  416. $this->assertEquals($expected, $result);
  417. $result = $this->Dbo->column('int(11)');
  418. $expected = 'integer';
  419. $this->assertEquals($expected, $result);
  420. $result = $this->Dbo->column('int(11) unsigned');
  421. $expected = 'integer';
  422. $this->assertEquals($expected, $result);
  423. $result = $this->Dbo->column('tinyint(1)');
  424. $expected = 'boolean';
  425. $this->assertEquals($expected, $result);
  426. $result = $this->Dbo->column('boolean');
  427. $expected = 'boolean';
  428. $this->assertEquals($expected, $result);
  429. $result = $this->Dbo->column('float');
  430. $expected = 'float';
  431. $this->assertEquals($expected, $result);
  432. $result = $this->Dbo->column('float unsigned');
  433. $expected = 'float';
  434. $this->assertEquals($expected, $result);
  435. $result = $this->Dbo->column('double unsigned');
  436. $expected = 'float';
  437. $this->assertEquals($expected, $result);
  438. $result = $this->Dbo->column('decimal(14,7) unsigned');
  439. $expected = 'float';
  440. $this->assertEquals($expected, $result);
  441. }
  442. /**
  443. * testAlterSchemaIndexes method
  444. *
  445. * @group indices
  446. * @return void
  447. */
  448. public function testAlterSchemaIndexes() {
  449. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  450. $table = $this->Dbo->fullTableName('altertest');
  451. $schemaA = new CakeSchema(array(
  452. 'name' => 'AlterTest1',
  453. 'connection' => 'test',
  454. 'altertest' => array(
  455. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  456. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  457. 'group1' => array('type' => 'integer', 'null' => true),
  458. 'group2' => array('type' => 'integer', 'null' => true)
  459. )));
  460. $result = $this->Dbo->createSchema($schemaA);
  461. $this->assertContains('`id` int(11) DEFAULT 0 NOT NULL,', $result);
  462. $this->assertContains('`name` varchar(50) NOT NULL,', $result);
  463. $this->assertContains('`group1` int(11) DEFAULT NULL', $result);
  464. $this->assertContains('`group2` int(11) DEFAULT NULL', $result);
  465. //Test that the string is syntactically correct
  466. $query = $this->Dbo->getConnection()->prepare($result);
  467. $this->assertEquals($query->queryString, $result);
  468. $schemaB = new CakeSchema(array(
  469. 'name' => 'AlterTest2',
  470. 'connection' => 'test',
  471. 'altertest' => array(
  472. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  473. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  474. 'group1' => array('type' => 'integer', 'null' => true),
  475. 'group2' => array('type' => 'integer', 'null' => true),
  476. 'indexes' => array(
  477. 'name_idx' => array('column' => 'name', 'unique' => 0),
  478. 'group_idx' => array('column' => 'group1', 'unique' => 0),
  479. 'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0),
  480. 'PRIMARY' => array('column' => 'id', 'unique' => 1))
  481. )));
  482. $result = $this->Dbo->alterSchema($schemaB->compare($schemaA));
  483. $this->assertContains("ALTER TABLE $table", $result);
  484. $this->assertContains('ADD KEY name_idx (`name`),', $result);
  485. $this->assertContains('ADD KEY group_idx (`group1`),', $result);
  486. $this->assertContains('ADD KEY compound_idx (`group1`, `group2`),', $result);
  487. $this->assertContains('ADD PRIMARY KEY (`id`);', $result);
  488. //Test that the string is syntactically correct
  489. $query = $this->Dbo->getConnection()->prepare($result);
  490. $this->assertEquals($query->queryString, $result);
  491. // Change three indexes, delete one and add another one
  492. $schemaC = new CakeSchema(array(
  493. 'name' => 'AlterTest3',
  494. 'connection' => 'test',
  495. 'altertest' => array(
  496. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  497. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  498. 'group1' => array('type' => 'integer', 'null' => true),
  499. 'group2' => array('type' => 'integer', 'null' => true),
  500. 'indexes' => array(
  501. 'name_idx' => array('column' => 'name', 'unique' => 1),
  502. 'group_idx' => array('column' => 'group2', 'unique' => 0),
  503. 'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0),
  504. 'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0))
  505. )));
  506. $result = $this->Dbo->alterSchema($schemaC->compare($schemaB));
  507. $this->assertContains("ALTER TABLE $table", $result);
  508. $this->assertContains('DROP PRIMARY KEY,', $result);
  509. $this->assertContains('DROP KEY name_idx,', $result);
  510. $this->assertContains('DROP KEY group_idx,', $result);
  511. $this->assertContains('DROP KEY compound_idx,', $result);
  512. $this->assertContains('ADD KEY id_name_idx (`id`, `name`),', $result);
  513. $this->assertContains('ADD UNIQUE KEY name_idx (`name`),', $result);
  514. $this->assertContains('ADD KEY group_idx (`group2`),', $result);
  515. $this->assertContains('ADD KEY compound_idx (`group2`, `group1`);', $result);
  516. $query = $this->Dbo->getConnection()->prepare($result);
  517. $this->assertEquals($query->queryString, $result);
  518. // Compare us to ourself.
  519. $this->assertEquals(array(), $schemaC->compare($schemaC));
  520. // Drop the indexes
  521. $result = $this->Dbo->alterSchema($schemaA->compare($schemaC));
  522. $this->assertContains("ALTER TABLE $table", $result);
  523. $this->assertContains('DROP KEY name_idx,', $result);
  524. $this->assertContains('DROP KEY group_idx,', $result);
  525. $this->assertContains('DROP KEY compound_idx,', $result);
  526. $this->assertContains('DROP KEY id_name_idx;', $result);
  527. $query = $this->Dbo->getConnection()->prepare($result);
  528. $this->assertEquals($query->queryString, $result);
  529. }
  530. /**
  531. * test saving and retrieval of blobs
  532. *
  533. * @return void
  534. */
  535. public function testBlobSaving() {
  536. $this->loadFixtures('BinaryTest');
  537. $this->Dbo->cacheSources = false;
  538. $data = file_get_contents(CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif');
  539. $model = new CakeTestModel(array('name' => 'BinaryTest', 'ds' => 'test'));
  540. $model->save(compact('data'));
  541. $result = $model->find('first');
  542. $this->assertEquals($data, $result['BinaryTest']['data']);
  543. }
  544. /**
  545. * test altering the table settings with schema.
  546. *
  547. * @return void
  548. */
  549. public function testAlteringTableParameters() {
  550. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  551. $schemaA = new CakeSchema(array(
  552. 'name' => 'AlterTest1',
  553. 'connection' => 'test',
  554. 'altertest' => array(
  555. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  556. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  557. 'tableParameters' => array(
  558. 'charset' => 'latin1',
  559. 'collate' => 'latin1_general_ci',
  560. 'engine' => 'MyISAM'
  561. )
  562. )
  563. ));
  564. $this->Dbo->rawQuery($this->Dbo->createSchema($schemaA));
  565. $schemaB = new CakeSchema(array(
  566. 'name' => 'AlterTest1',
  567. 'connection' => 'test',
  568. 'altertest' => array(
  569. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  570. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  571. 'tableParameters' => array(
  572. 'charset' => 'utf8',
  573. 'collate' => 'utf8_general_ci',
  574. 'engine' => 'InnoDB'
  575. )
  576. )
  577. ));
  578. $result = $this->Dbo->alterSchema($schemaB->compare($schemaA));
  579. $this->assertContains('DEFAULT CHARSET=utf8', $result);
  580. $this->assertContains('ENGINE=InnoDB', $result);
  581. $this->assertContains('COLLATE=utf8_general_ci', $result);
  582. $this->Dbo->rawQuery($result);
  583. $result = $this->Dbo->listDetailedSources($this->Dbo->fullTableName('altertest', false, false));
  584. $this->assertEquals('utf8_general_ci', $result['Collation']);
  585. $this->assertEquals('InnoDB', $result['Engine']);
  586. $this->assertEquals('utf8', $result['charset']);
  587. $this->Dbo->rawQuery($this->Dbo->dropSchema($schemaA));
  588. }
  589. /**
  590. * test alterSchema on two tables.
  591. *
  592. * @return void
  593. */
  594. public function testAlteringTwoTables() {
  595. $schema1 = new CakeSchema(array(
  596. 'name' => 'AlterTest1',
  597. 'connection' => 'test',
  598. 'altertest' => array(
  599. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  600. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  601. ),
  602. 'other_table' => array(
  603. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  604. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  605. )
  606. ));
  607. $schema2 = new CakeSchema(array(
  608. 'name' => 'AlterTest1',
  609. 'connection' => 'test',
  610. 'altertest' => array(
  611. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  612. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  613. ),
  614. 'other_table' => array(
  615. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  616. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  617. )
  618. ));
  619. $result = $this->Dbo->alterSchema($schema2->compare($schema1));
  620. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  621. }
  622. /**
  623. * testReadTableParameters method
  624. *
  625. * @return void
  626. */
  627. public function testReadTableParameters() {
  628. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  629. $tableName = 'tinyint_' . uniqid();
  630. $table = $this->Dbo->fullTableName($tableName);
  631. $this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
  632. $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false));
  633. $this->Dbo->rawQuery('DROP TABLE ' . $table);
  634. $expected = array(
  635. 'charset' => 'utf8',
  636. 'collate' => 'utf8_unicode_ci',
  637. 'engine' => 'InnoDB');
  638. $this->assertEquals($expected, $result);
  639. $table = $this->Dbo->fullTableName($tableName);
  640. $this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
  641. $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false));
  642. $this->Dbo->rawQuery('DROP TABLE ' . $table);
  643. $expected = array(
  644. 'charset' => 'cp1250',
  645. 'collate' => 'cp1250_general_ci',
  646. 'engine' => 'MyISAM');
  647. $this->assertEquals($expected, $result);
  648. }
  649. /**
  650. * testBuildTableParameters method
  651. *
  652. * @return void
  653. */
  654. public function testBuildTableParameters() {
  655. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  656. $data = array(
  657. 'charset' => 'utf8',
  658. 'collate' => 'utf8_unicode_ci',
  659. 'engine' => 'InnoDB');
  660. $result = $this->Dbo->buildTableParameters($data);
  661. $expected = array(
  662. 'DEFAULT CHARSET=utf8',
  663. 'COLLATE=utf8_unicode_ci',
  664. 'ENGINE=InnoDB');
  665. $this->assertEquals($expected, $result);
  666. }
  667. /**
  668. * testBuildTableParameters method
  669. *
  670. * @return void
  671. */
  672. public function testGetCharsetName() {
  673. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  674. $result = $this->Dbo->getCharsetName('utf8_unicode_ci');
  675. $this->assertEquals('utf8', $result);
  676. $result = $this->Dbo->getCharsetName('cp1250_general_ci');
  677. $this->assertEquals('cp1250', $result);
  678. }
  679. /**
  680. * test that changing the virtualFieldSeparator allows for __ fields.
  681. *
  682. * @return void
  683. */
  684. public function testVirtualFieldSeparators() {
  685. $this->loadFixtures('BinaryTest');
  686. $model = new CakeTestModel(array('table' => 'binary_tests', 'ds' => 'test', 'name' => 'BinaryTest'));
  687. $model->virtualFields = array(
  688. 'other__field' => 'SUM(id)'
  689. );
  690. $this->Dbo->virtualFieldSeparator = '_$_';
  691. $result = $this->Dbo->fields($model, null, array('data', 'other__field'));
  692. $expected = array('`BinaryTest`.`data`', '(SUM(id)) AS `BinaryTest_$_other__field`');
  693. $this->assertEquals($expected, $result);
  694. }
  695. /**
  696. * Test describe() on a fixture.
  697. *
  698. * @return void
  699. */
  700. public function testDescribe() {
  701. $this->loadFixtures('Apple');
  702. $model = new Apple();
  703. $result = $this->Dbo->describe($model);
  704. $this->assertTrue(isset($result['id']));
  705. $this->assertTrue(isset($result['color']));
  706. $result = $this->Dbo->describe($model->useTable);
  707. $this->assertTrue(isset($result['id']));
  708. $this->assertTrue(isset($result['color']));
  709. }
  710. /**
  711. * test that a describe() gets additional fieldParameters
  712. *
  713. * @return void
  714. */
  715. public function testDescribeGettingFieldParameters() {
  716. $schema = new CakeSchema(array(
  717. 'connection' => 'test',
  718. 'testdescribes' => array(
  719. 'id' => array('type' => 'integer', 'key' => 'primary'),
  720. 'stringy' => array(
  721. 'type' => 'string',
  722. 'null' => true,
  723. 'charset' => 'cp1250',
  724. 'collate' => 'cp1250_general_ci',
  725. ),
  726. 'other_col' => array(
  727. 'type' => 'string',
  728. 'null' => false,
  729. 'charset' => 'latin1',
  730. 'comment' => 'Test Comment'
  731. )
  732. )
  733. ));
  734. $this->Dbo->execute($this->Dbo->createSchema($schema));
  735. $model = new CakeTestModel(array('table' => 'testdescribes', 'name' => 'Testdescribes'));
  736. $result = $model->getDataSource()->describe($model);
  737. $this->Dbo->execute($this->Dbo->dropSchema($schema));
  738. $this->assertEquals('cp1250_general_ci', $result['stringy']['collate']);
  739. $this->assertEquals('cp1250', $result['stringy']['charset']);
  740. $this->assertEquals('Test Comment', $result['other_col']['comment']);
  741. }
  742. /**
  743. * Tests that listSources method sends the correct query and parses the result accordingly
  744. * @return void
  745. */
  746. public function testListSources() {
  747. $db = $this->getMock('Mysql', array('connect', '_execute'));
  748. $queryResult = $this->getMock('PDOStatement');
  749. $db->expects($this->once())
  750. ->method('_execute')
  751. ->with('SHOW TABLES FROM `cake`')
  752. ->will($this->returnValue($queryResult));
  753. $queryResult->expects($this->at(0))
  754. ->method('fetch')
  755. ->will($this->returnValue(array('cake_table')));
  756. $queryResult->expects($this->at(1))
  757. ->method('fetch')
  758. ->will($this->returnValue(array('another_table')));
  759. $queryResult->expects($this->at(2))
  760. ->method('fetch')
  761. ->will($this->returnValue(null));
  762. $tables = $db->listSources();
  763. $this->assertEquals(array('cake_table', 'another_table'), $tables);
  764. }
  765. /**
  766. * test that listDetailedSources with a named table that doesn't exist.
  767. *
  768. * @return void
  769. */
  770. public function testListDetailedSourcesNamed() {
  771. $this->loadFixtures('Apple');
  772. $result = $this->Dbo->listDetailedSources('imaginary');
  773. $this->assertEquals(array(), $result, 'Should be empty when table does not exist.');
  774. $result = $this->Dbo->listDetailedSources();
  775. $tableName = $this->Dbo->fullTableName('apples', false, false);
  776. $this->assertTrue(isset($result[$tableName]), 'Key should exist');
  777. }
  778. /**
  779. * Tests that getVersion method sends the correct query for getting the mysql version
  780. * @return void
  781. */
  782. public function testGetVersion() {
  783. $version = $this->Dbo->getVersion();
  784. $this->assertTrue(is_string($version));
  785. }
  786. /**
  787. * Tests that getVersion method sends the correct query for getting the client encoding
  788. * @return void
  789. */
  790. public function testGetEncoding() {
  791. $db = $this->getMock('Mysql', array('connect', '_execute'));
  792. $queryResult = $this->getMock('PDOStatement');
  793. $db->expects($this->once())
  794. ->method('_execute')
  795. ->with('SHOW VARIABLES LIKE ?', array('character_set_client'))
  796. ->will($this->returnValue($queryResult));
  797. $result = new StdClass;
  798. $result->Value = 'utf-8';
  799. $queryResult->expects($this->once())
  800. ->method('fetchObject')
  801. ->will($this->returnValue($result));
  802. $encoding = $db->getEncoding();
  803. $this->assertEquals('utf-8', $encoding);
  804. }
  805. /**
  806. * testFieldDoubleEscaping method
  807. *
  808. * @return void
  809. */
  810. public function testFieldDoubleEscaping() {
  811. $db = $this->Dbo->config['database'];
  812. $test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  813. $test->config['database'] = $db;
  814. $this->Model = $this->getMock('Article2', array('getDataSource'));
  815. $this->Model->alias = 'Article';
  816. $this->Model->expects($this->any())
  817. ->method('getDataSource')
  818. ->will($this->returnValue($test));
  819. $this->assertEquals('`Article`.`id`', $this->Model->escapeField());
  820. $result = $test->fields($this->Model, null, $this->Model->escapeField());
  821. $this->assertEquals(array('`Article`.`id`'), $result);
  822. $test->expects($this->at(0))->method('execute')
  823. ->with('SELECT `Article`.`id` FROM ' . $test->fullTableName('articles') . ' AS `Article` WHERE 1 = 1');
  824. $result = $test->read($this->Model, array(
  825. 'fields' => $this->Model->escapeField(),
  826. 'conditions' => null,
  827. 'recursive' => -1
  828. ));
  829. $test->startQuote = '[';
  830. $test->endQuote = ']';
  831. $this->assertEquals('[Article].[id]', $this->Model->escapeField());
  832. $result = $test->fields($this->Model, null, $this->Model->escapeField());
  833. $this->assertEquals(array('[Article].[id]'), $result);
  834. $test->expects($this->at(0))->method('execute')
  835. ->with('SELECT [Article].[id] FROM ' . $test->fullTableName('articles') . ' AS [Article] WHERE 1 = 1');
  836. $result = $test->read($this->Model, array(
  837. 'fields' => $this->Model->escapeField(),
  838. 'conditions' => null,
  839. 'recursive' => -1
  840. ));
  841. }
  842. /**
  843. * testGenerateAssociationQuerySelfJoin method
  844. *
  845. * @return void
  846. */
  847. public function testGenerateAssociationQuerySelfJoin() {
  848. $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  849. $this->startTime = microtime(true);
  850. $this->Model = new Article2();
  851. $this->_buildRelatedModels($this->Model);
  852. $this->_buildRelatedModels($this->Model->Category2);
  853. $this->Model->Category2->ChildCat = new Category2();
  854. $this->Model->Category2->ParentCat = new Category2();
  855. $queryData = array();
  856. foreach ($this->Model->Category2->associations() as $type) {
  857. foreach ($this->Model->Category2->{$type} as $assoc => $assocData) {
  858. $linkModel = $this->Model->Category2->{$assoc};
  859. $external = isset($assocData['external']);
  860. if ($this->Model->Category2->alias == $linkModel->alias && $type != 'hasAndBelongsToMany' && $type != 'hasMany') {
  861. $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
  862. $this->assertFalse(empty($result));
  863. } else {
  864. if ($this->Model->Category2->useDbConfig == $linkModel->useDbConfig) {
  865. $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
  866. $this->assertFalse(empty($result));
  867. }
  868. }
  869. }
  870. }
  871. $query = $this->Dbo->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null);
  872. $this->assertRegExp('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query);
  873. $this->Model = new TestModel4();
  874. $this->Model->schema();
  875. $this->_buildRelatedModels($this->Model);
  876. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
  877. $queryData = array();
  878. $resultSet = null;
  879. $null = null;
  880. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  881. $_queryData = $queryData;
  882. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  883. $this->assertTrue($result);
  884. $expected = array(
  885. 'conditions' => array(),
  886. 'fields' => array(
  887. '`TestModel4`.`id`',
  888. '`TestModel4`.`name`',
  889. '`TestModel4`.`created`',
  890. '`TestModel4`.`updated`',
  891. '`TestModel4Parent`.`id`',
  892. '`TestModel4Parent`.`name`',
  893. '`TestModel4Parent`.`created`',
  894. '`TestModel4Parent`.`updated`'
  895. ),
  896. 'joins' => array(
  897. array(
  898. 'table' => $this->Dbo->fullTableName($this->Model),
  899. 'alias' => 'TestModel4Parent',
  900. 'type' => 'LEFT',
  901. 'conditions' => '`TestModel4`.`parent_id` = `TestModel4Parent`.`id`'
  902. )
  903. ),
  904. 'order' => array(),
  905. 'limit' => array(),
  906. 'offset' => array(),
  907. 'group' => array(),
  908. 'callbacks' => null
  909. );
  910. $queryData['joins'][0]['table'] = $this->Dbo->fullTableName($queryData['joins'][0]['table']);
  911. $this->assertEquals($expected, $queryData);
  912. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  913. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
  914. $this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result);
  915. $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
  916. $this->assertRegExp('/\s+WHERE\s+1 = 1\s+$/', $result);
  917. $params['assocData']['type'] = 'INNER';
  918. $this->Model->belongsTo['TestModel4Parent']['type'] = 'INNER';
  919. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $_queryData, $params['external'], $resultSet);
  920. $this->assertTrue($result);
  921. $this->assertEquals('INNER', $_queryData['joins'][0]['type']);
  922. }
  923. /**
  924. * buildRelatedModels method
  925. *
  926. * @param mixed $model
  927. * @return void
  928. */
  929. protected function _buildRelatedModels(Model $model) {
  930. foreach ($model->associations() as $type) {
  931. foreach ($model->{$type} as $assoc => $assocData) {
  932. if (is_string($assocData)) {
  933. $className = $assocData;
  934. } elseif (isset($assocData['className'])) {
  935. $className = $assocData['className'];
  936. }
  937. $model->$className = new $className();
  938. $model->$className->schema();
  939. }
  940. }
  941. }
  942. /**
  943. * &_prepareAssociationQuery method
  944. *
  945. * @param mixed $model
  946. * @param mixed $queryData
  947. * @param mixed $binding
  948. * @return void
  949. */
  950. protected function &_prepareAssociationQuery(Model $model, &$queryData, $binding) {
  951. $type = $binding['type'];
  952. $assoc = $binding['model'];
  953. $assocData = $model->{$type}[$assoc];
  954. $className = $assocData['className'];
  955. $linkModel = $model->{$className};
  956. $external = isset($assocData['external']);
  957. $queryData = $this->_scrubQueryData($queryData);
  958. $result = array_merge(array('linkModel' => &$linkModel), compact('type', 'assoc', 'assocData', 'external'));
  959. return $result;
  960. }
  961. /**
  962. * Helper method copied from DboSource::_scrubQueryData()
  963. *
  964. * @param array $data
  965. * @return array
  966. */
  967. protected function _scrubQueryData($data) {
  968. static $base = null;
  969. if ($base === null) {
  970. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  971. $base['callbacks'] = null;
  972. }
  973. return (array)$data + $base;
  974. }
  975. /**
  976. * testGenerateInnerJoinAssociationQuery method
  977. *
  978. * @return void
  979. */
  980. public function testGenerateInnerJoinAssociationQuery() {
  981. $db = $this->Dbo->config['database'];
  982. $test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  983. $test->config['database'] = $db;
  984. $this->Model = $this->getMock('TestModel9', array('getDataSource'));
  985. $this->Model->expects($this->any())
  986. ->method('getDataSource')
  987. ->will($this->returnValue($test));
  988. $this->Model->TestModel8 = $this->getMock('TestModel8', array('getDataSource'));
  989. $this->Model->TestModel8->expects($this->any())
  990. ->method('getDataSource')
  991. ->will($this->returnValue($test));
  992. $testModel8Table = $this->Model->TestModel8->getDataSource()->fullTableName($this->Model->TestModel8);
  993. $test->expects($this->at(0))->method('execute')
  994. ->with($this->stringContains('`TestModel9` LEFT JOIN ' . $testModel8Table));
  995. $test->expects($this->at(1))->method('execute')
  996. ->with($this->stringContains('TestModel9` INNER JOIN ' . $testModel8Table));
  997. $test->read($this->Model, array('recursive' => 1));
  998. $this->Model->belongsTo['TestModel8']['type'] = 'INNER';
  999. $test->read($this->Model, array('recursive' => 1));
  1000. }
  1001. /**
  1002. * testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding method
  1003. *
  1004. * @return void
  1005. */
  1006. public function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() {
  1007. $this->Model = new TestModel8();
  1008. $this->Model->schema();
  1009. $this->_buildRelatedModels($this->Model);
  1010. $binding = array('type' => 'hasOne', 'model' => 'TestModel9');
  1011. $queryData = array();
  1012. $resultSet = null;
  1013. $null = null;
  1014. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1015. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1016. $this->assertTrue($result);
  1017. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1018. $this->assertRegExp('/^SELECT\s+`TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`, `TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`\s+/', $result);
  1019. $this->assertRegExp('/FROM\s+\S+`test_model8` AS `TestModel8`\s+LEFT JOIN\s+\S+`test_model9` AS `TestModel9`/', $result);
  1020. $this->assertRegExp('/\s+ON\s+\(`TestModel9`\.`name` != \'mariano\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
  1021. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1022. }
  1023. /**
  1024. * testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding method
  1025. *
  1026. * @return void
  1027. */
  1028. public function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() {
  1029. $this->Model = new TestModel9();
  1030. $this->Model->schema();
  1031. $this->_buildRelatedModels($this->Model);
  1032. $binding = array('type' => 'belongsTo', 'model' => 'TestModel8');
  1033. $queryData = array();
  1034. $resultSet = null;
  1035. $null = null;
  1036. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1037. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1038. $this->assertTrue($result);
  1039. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1040. $this->assertRegExp('/^SELECT\s+`TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`, `TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`\s+/', $result);
  1041. $this->assertRegExp('/FROM\s+\S+`test_model9` AS `TestModel9`\s+LEFT JOIN\s+\S+`test_model8` AS `TestModel8`/', $result);
  1042. $this->assertRegExp('/\s+ON\s+\(`TestModel8`\.`name` != \'larry\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
  1043. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1044. }
  1045. /**
  1046. * testGenerateAssociationQuerySelfJoinWithConditions method
  1047. *
  1048. * @return void
  1049. */
  1050. public function testGenerateAssociationQuerySelfJoinWithConditions() {
  1051. $this->Model = new TestModel4();
  1052. $this->Model->schema();
  1053. $this->_buildRelatedModels($this->Model);
  1054. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
  1055. $queryData = array('conditions' => array('TestModel4Parent.name !=' => 'mariano'));
  1056. $resultSet = null;
  1057. $null = null;
  1058. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1059. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1060. $this->assertTrue($result);
  1061. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1062. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
  1063. $this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result);
  1064. $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
  1065. $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1066. $this->Featured2 = new Featured2();
  1067. $this->Featured2->schema();
  1068. $this->Featured2->bindModel(array(
  1069. 'belongsTo' => array(
  1070. 'ArticleFeatured2' => array(
  1071. 'conditions' => 'ArticleFeatured2.published = \'Y\'',
  1072. 'fields' => 'id, title, user_id, published'
  1073. )
  1074. )
  1075. ));
  1076. $this->_buildRelatedModels($this->Featured2);
  1077. $binding = array('type' => 'belongsTo', 'model' => 'ArticleFeatured2');
  1078. $queryData = array('conditions' => array());
  1079. $resultSet = null;
  1080. $null = null;
  1081. $params = &$this->_prepareAssociationQuery($this->Featured2, $queryData, $binding);
  1082. $result = $this->Dbo->generateAssociationQuery($this->Featured2, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1083. $this->assertTrue($result);
  1084. $result = $this->Dbo->generateAssociationQuery($this->Featured2, $null, null, null, null, $queryData, false, $null);
  1085. $this->assertRegExp(
  1086. '/^SELECT\s+`Featured2`\.`id`, `Featured2`\.`article_id`, `Featured2`\.`category_id`, `Featured2`\.`name`,\s+' .
  1087. '`ArticleFeatured2`\.`id`, `ArticleFeatured2`\.`title`, `ArticleFeatured2`\.`user_id`, `ArticleFeatured2`\.`published`\s+' .
  1088. 'FROM\s+\S+`featured2` AS `Featured2`\s+LEFT JOIN\s+\S+`article_featured` AS `ArticleFeatured2`' .
  1089. '\s+ON\s+\(`ArticleFeatured2`.`published` = \'Y\'\s+AND\s+`Featured2`\.`article_featured2_id` = `ArticleFeatured2`\.`id`\)' .
  1090. '\s+WHERE\s+1\s+=\s+1\s*$/',
  1091. $result
  1092. );
  1093. }
  1094. /**
  1095. * testGenerateAssociationQueryHasOne method
  1096. *
  1097. * @return void
  1098. */
  1099. public function testGenerateAssociationQueryHasOne() {
  1100. $this->Model = new TestModel4();
  1101. $this->Model->schema();
  1102. $this->_buildRelatedModels($this->Model);
  1103. $binding = array('type' => 'hasOne', 'model' => 'TestModel5');
  1104. $queryData = array();
  1105. $resultSet = null;
  1106. $null = null;
  1107. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1108. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1109. $this->assertTrue($result);
  1110. $testModel5Table = $this->Dbo->fullTableName($this->Model->TestModel5);
  1111. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1112. $expected = ' LEFT JOIN ' . $testModel5Table . ' AS `TestModel5` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1113. $this->assertEquals(trim($expected), trim($result));
  1114. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1115. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1116. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+/', $result);
  1117. $this->assertRegExp('/`test_model5` AS `TestModel5`\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE/', $result);
  1118. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1119. }
  1120. /**
  1121. * testGenerateAssociationQueryHasOneWithConditions method
  1122. *
  1123. * @return void
  1124. */
  1125. public function testGenerateAssociationQueryHasOneWithConditions() {
  1126. $this->Model = new TestModel4();
  1127. $this->Model->schema();
  1128. $this->_buildRelatedModels($this->Model);
  1129. $binding = array('type' => 'hasOne', 'model' => 'TestModel5');
  1130. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1131. $resultSet = null;
  1132. $null = null;
  1133. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1134. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1135. $this->assertTrue($result);
  1136. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1137. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1138. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model5` AS `TestModel5`/', $result);
  1139. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id`\s+=\s+`TestModel4`.`id`\)\s+WHERE/', $result);
  1140. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*`TestModel5`.`name`\s+!=\s+\'mariano\'\s*(?:\))?\s*$/', $result);
  1141. }
  1142. /**
  1143. * testGenerateAssociationQueryBelongsTo method
  1144. *
  1145. * @return void
  1146. */
  1147. public function testGenerateAssociationQueryBelongsTo() {
  1148. $this->Model = new TestModel5();
  1149. $this->Model->schema();
  1150. $this->_buildRelatedModels($this->Model);
  1151. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
  1152. $queryData = array();
  1153. $resultSet = null;
  1154. $null = null;
  1155. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1156. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1157. $this->assertTrue($result);
  1158. $testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true);
  1159. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1160. $expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1161. $this->assertEquals(trim($expected), trim($result));
  1162. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1163. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1164. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result);
  1165. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
  1166. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1167. }
  1168. /**
  1169. * testGenerateAssociationQueryBelongsToWithConditions method
  1170. *
  1171. * @return void
  1172. */
  1173. public function testGenerateAssociationQueryBelongsToWithConditions() {
  1174. $this->Model = new TestModel5();
  1175. $this->Model->schema();
  1176. $this->_buildRelatedModels($this->Model);
  1177. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
  1178. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1179. $resultSet = null;
  1180. $null = null;
  1181. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1182. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1183. $this->assertTrue($result);
  1184. $testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true);
  1185. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1186. $expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1187. $this->assertEquals(trim($expected), trim($result));
  1188. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1189. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1190. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result);
  1191. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
  1192. $this->assertRegExp('/\s+WHERE\s+`TestModel5`.`name` != \'mariano\'\s*$/', $result);
  1193. }
  1194. /**
  1195. * testGenerateAssociationQueryHasMany method
  1196. *
  1197. * @return void
  1198. */
  1199. public function testGenerateAssociationQueryHasMany() {
  1200. $this->Model = new TestModel5();
  1201. $this->Model->schema();
  1202. $this->_buildRelatedModels($this->Model);
  1203. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1204. $queryData = array();
  1205. $resultSet = null;
  1206. $null = null;
  1207. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1208. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1209. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1210. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE/', $result);
  1211. $this->assertRegExp('/\s+WHERE\s+`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)/', $result);
  1212. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1213. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1214. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1215. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1216. }
  1217. /**
  1218. * testGenerateAssociationQueryHasManyWithLimit method
  1219. *
  1220. * @return void
  1221. */
  1222. public function testGenerateAssociationQueryHasManyWithLimit() {
  1223. $this->Model = new TestModel5();
  1224. $this->Model->schema();
  1225. $this->_buildRelatedModels($this->Model);
  1226. $this->Model->hasMany['TestModel6']['limit'] = 2;
  1227. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1228. $queryData = array();
  1229. $resultSet = null;
  1230. $null = null;
  1231. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1232. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1233. $this->assertRegExp(
  1234. '/^SELECT\s+' .
  1235. '`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+' .
  1236. 'FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+' .
  1237. '`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)\s*' .
  1238. 'LIMIT \d*' .
  1239. '\s*$/', $result
  1240. );
  1241. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1242. $this->assertRegExp(
  1243. '/^SELECT\s+' .
  1244. '`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+' .
  1245. 'FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+' .
  1246. '(?:\()?\s*1 = 1\s*(?:\))?' .
  1247. '\s*$/', $result
  1248. );
  1249. }
  1250. /**
  1251. * testGenerateAssociationQueryHasManyWithConditions method
  1252. *
  1253. * @return void
  1254. */
  1255. public function testGenerateAssociationQueryHasManyWithConditions() {
  1256. $this->Model = new TestModel5();
  1257. $this->Model->schema();
  1258. $this->_buildRelatedModels($this->Model);
  1259. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1260. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1261. $resultSet = null;
  1262. $null = null;
  1263. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1264. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1265. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1266. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1267. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1268. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1269. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1270. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1271. $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel5`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1272. }
  1273. /**
  1274. * testGenerateAssociationQueryHasManyWithOffsetAndLimit method
  1275. *
  1276. * @return void
  1277. */
  1278. public function testGenerateAssociationQueryHasManyWithOffsetAndLimit() {
  1279. $this->Model = new TestModel5();
  1280. $this->Model->schema();
  1281. $this->_buildRelatedModels($this->Model);
  1282. $backup = $this->Model->hasMany['TestModel6'];
  1283. $this->Model->hasMany['TestModel6']['offset'] = 2;
  1284. $this->Model->hasMany['TestModel6']['limit'] = 5;
  1285. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1286. $queryData = array();
  1287. $resultSet = null;
  1288. $null = null;
  1289. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1290. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1291. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1292. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1293. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1294. $this->assertRegExp('/\s+LIMIT 2,\s*5\s*$/', $result);
  1295. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1296. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1297. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1298. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1299. $this->Model->hasMany['TestModel6'] = $backup;
  1300. }
  1301. /**
  1302. * testGenerateAssociationQueryHasManyWithPageAndLimit method
  1303. *
  1304. * @return void
  1305. */
  1306. public function testGenerateAssociationQueryHasManyWithPageAndLimit() {
  1307. $this->Model = new TestModel5();
  1308. $this->Model->schema();
  1309. $this->_buildRelatedModels($this->Model);
  1310. $backup = $this->Model->hasMany['TestModel6'];
  1311. $this->Model->hasMany['TestModel6']['page'] = 2;
  1312. $this->Model->hasMany['TestModel6']['limit'] = 5;
  1313. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1314. $queryData = array();
  1315. $resultSet = null;
  1316. $null = null;
  1317. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1318. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1319. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1320. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1321. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1322. $this->assertRegExp('/\s+LIMIT 5,\s*5\s*$/', $result);
  1323. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1324. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1325. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1326. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1327. $this->Model->hasMany['TestModel6'] = $backup;
  1328. }
  1329. /**
  1330. * testGenerateAssociationQueryHasManyWithFields method
  1331. *
  1332. * @return void
  1333. */
  1334. public function testGenerateAssociationQueryHasManyWithFields() {
  1335. $this->Model = new TestModel5();
  1336. $this->Model->schema();
  1337. $this->_buildRelatedModels($this->Model);
  1338. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1339. $queryData = array('fields' => array('`TestModel5`.`name`'));
  1340. $resultSet = null;
  1341. $null = null;
  1342. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1343. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1344. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1345. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1346. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1347. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1348. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`id`\s+/', $result);
  1349. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1350. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1351. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1352. $queryData = array('fields' => array('`TestModel5`.`id`, `TestModel5`.`name`'));
  1353. $resultSet = null;
  1354. $null = null;
  1355. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1356. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1357. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1358. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1359. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1360. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1361. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1362. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1363. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1364. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1365. $queryData = array('fields' => array('`TestModel5`.`name`', '`TestModel5`.`created`'));
  1366. $resultSet = null;
  1367. $null = null;
  1368. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1369. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1370. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1371. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1372. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1373. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1374. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`id`\s+/', $result);
  1375. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1376. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1377. $this->Model->hasMany['TestModel6']['fields'] = array('name');
  1378. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1379. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1380. $resultSet = null;
  1381. $null = null;
  1382. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1383. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1384. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
  1385. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1386. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1387. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1388. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1389. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1390. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1391. unset($this->Model->hasMany['TestModel6']['fields']);
  1392. $this->Model->hasMany['TestModel6']['fields'] = array('id', 'name');
  1393. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1394. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1395. $resultSet = null;
  1396. $null = null;
  1397. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1398. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1399. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
  1400. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1401. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1402. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1403. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1404. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1405. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1406. unset($this->Model->hasMany['TestModel6']['fields']);
  1407. $this->Model->hasMany['TestModel6']['fields'] = array('test_model5_id', 'name');
  1408. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1409. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1410. $resultSet = null;
  1411. $null = null;
  1412. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1413. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1414. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`test_model5_id`, `TestModel6`\.`name`\s+/', $result);
  1415. $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1416. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1417. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1418. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1419. $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1420. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1421. unset($this->Model->hasMany['TestModel6']['fields']);
  1422. }
  1423. /**
  1424. * test generateAssociationQuery with a hasMany and an aggregate function.
  1425. *
  1426. * @return void
  1427. */
  1428. public function testGenerateAssociationQueryHasManyAndAggregateFunction() {
  1429. $this->Model = new TestModel5();
  1430. $this->Model->schema();
  1431. $this->_buildRelatedModels($this->Model);
  1432. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1433. $queryData = array('fields' => array('MIN(`TestModel5`.`test_model4_id`)'));
  1434. $resultSet = null;
  1435. $null = null;
  1436. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1437. $this->Model->recursive = 0;
  1438. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, $params['type'], $params['assoc'], $params['assocData'], $queryData, false, $resultSet);
  1439. $this->assertRegExp('/^SELECT\s+MIN\(`TestModel5`\.`test_model4_id`\)\s+FROM/', $result);
  1440. }
  1441. /**
  1442. * testGenerateAssociationQueryHasAndBelongsToMany method
  1443. *
  1444. * @return void
  1445. */
  1446. public function testGenerateAssociationQueryHasAndBelongsToMany() {
  1447. $this->Model = new TestModel4();
  1448. $this->Model->schema();
  1449. $this->_buildRelatedModels($this->Model);
  1450. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1451. $queryData = array();
  1452. $resultSet = null;
  1453. $null = null;
  1454. $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1455. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1456. $assocTable = $this->Dbo->fullTableName($this->Model->TestModel4TestModel7, true, true);
  1457. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1458. $this->assertRegExp('/\s+FROM\s+\S+`test_model7` AS `TestModel7`\s+JOIN\s+' . $assocTable . '/', $result);
  1459. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+AND/', $result);
  1460. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)/', $result);
  1461. $this->assertRegExp('/WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
  1462. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1463. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1464. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE/', $result);
  1465. $this->assertRegExp('/\s+WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
  1466. }
  1467. /**
  1468. * testGenerateAssociationQueryHasAndBelongsToManyWithConditions method
  1469. *
  1470. * @return void
  1471. */
  1472. public function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() {
  1473. $this->Model = new TestModel4();
  1474. $this->Model->schema();
  1475. $this->_buildRelatedModels($this->Model);
  1476. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1477. $queryData = array('conditions' => array('TestModel4.name !=' => 'mariano'));
  1478. $resultSet = null;
  1479. $null = null;
  1480. $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1481. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1482. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1483. $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1484. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
  1485. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1486. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1487. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1488. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?`TestModel4`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1489. }
  1490. /**
  1491. * testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit method
  1492. *
  1493. * @return void
  1494. */
  1495. public function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() {
  1496. $this->Model = new TestModel4();
  1497. $this->Model->schema();
  1498. $this->_buildRelatedModels($this->Model);
  1499. $backup = $this->Model->hasAndBelongsToMany['TestModel7'];
  1500. $this->Model->hasAndBelongsToMany['TestModel7']['offset'] = 2;
  1501. $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
  1502. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1503. $queryData = array();
  1504. $resultSet = null;
  1505. $null = null;
  1506. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1507. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1508. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1509. $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1510. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+/', $result);
  1511. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1512. $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 2,\s*5\s*$/', $result);
  1513. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1514. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1515. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1516. $this->Model->hasAndBelongsToMany['TestModel7'] = $backup;
  1517. }
  1518. /**
  1519. * testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit method
  1520. *
  1521. * @return void
  1522. */
  1523. public function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() {
  1524. $this->Model = new TestModel4();
  1525. $this->Model->schema();
  1526. $this->_buildRelatedModels($this->Model);
  1527. $backup = $this->Model->hasAndBelongsToMany['TestModel7'];
  1528. $this->Model->hasAndBelongsToMany['TestModel7']['page'] = 2;
  1529. $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
  1530. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1531. $queryData = array();
  1532. $resultSet = null;
  1533. $null = null;
  1534. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1535. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1536. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1537. $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1538. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
  1539. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1540. $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 5,\s*5\s*$/', $result);
  1541. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1542. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1543. $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1544. $this->Model->hasAndBelongsToMany['TestModel7'] = $backup;
  1545. }
  1546. /**
  1547. * testSelectDistict method
  1548. *
  1549. * @return void
  1550. */
  1551. public function testSelectDistict() {
  1552. $this->Model = new TestModel4();
  1553. $result = $this->Dbo->fields($this->Model, 'Vendor', "DISTINCT Vendor.id, Vendor.name");
  1554. $expected = array('DISTINCT `Vendor`.`id`', '`Vendor`.`name`');
  1555. $this->assertEquals($expected, $result);
  1556. }
  1557. /**
  1558. * testStringConditionsParsing method
  1559. *
  1560. * @return void
  1561. */
  1562. public function testStringConditionsParsing() {
  1563. $result = $this->Dbo->conditions("ProjectBid.project_id = Project.id");
  1564. $expected = " WHERE `ProjectBid`.`project_id` = `Project`.`id`";
  1565. $this->assertEquals($expected, $result);
  1566. $result = $this->Dbo->conditions("Candy.name LIKE 'a' AND HardCandy.name LIKE 'c'");
  1567. $expected = " WHERE `Candy`.`name` LIKE 'a' AND `HardCandy`.`name` LIKE 'c'";
  1568. $this->assertEquals($expected, $result);
  1569. $result = $this->Dbo->conditions("HardCandy.name LIKE 'a' AND Candy.name LIKE 'c'");
  1570. $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
  1571. $this->assertEquals($expected, $result);
  1572. $result = $this->Dbo->conditions("Post.title = '1.1'");
  1573. $expected = " WHERE `Post`.`title` = '1.1'";
  1574. $this->assertEquals($expected, $result);
  1575. $result = $this->Dbo->conditions("User.id != 0 AND User.user LIKE '%arr%'");
  1576. $expected = " WHERE `User`.`id` != 0 AND `User`.`user` LIKE '%arr%'";
  1577. $this->assertEquals($expected, $result);
  1578. $result = $this->Dbo->conditions("SUM(Post.comments_count) > 500");
  1579. $expected = " WHERE SUM(`Post`.`comments_count`) > 500";
  1580. $this->assertEquals($expected, $result);
  1581. $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
  1582. $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
  1583. $this->assertEquals($expected, $result);
  1584. $result = $this->Dbo->conditions("score BETWEEN 90.1 AND 95.7");
  1585. $expected = " WHERE score BETWEEN 90.1 AND 95.7";
  1586. $this->assertEquals($expected, $result);
  1587. $result = $this->Dbo->conditions(array('score' => array(2 => 1, 2, 10)));
  1588. $expected = " WHERE score IN (1, 2, 10)";
  1589. $this->assertEquals($expected, $result);
  1590. $result = $this->Dbo->conditions("Aro.rght = Aro.lft + 1.1");
  1591. $expected = " WHERE `Aro`.`rght` = `Aro`.`lft` + 1.1";
  1592. $this->assertEquals($expected, $result);
  1593. $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
  1594. $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
  1595. $this->assertEquals($expected, $result);
  1596. $result = $this->Dbo->conditions('Sportstaette.sportstaette LIKE "%ru%" AND Sportstaette.sportstaettenart_id = 2');
  1597. $expected = ' WHERE `Sportstaette`.`sportstaette` LIKE "%ru%" AND `Sportstaette`.`sportstaettenart_id` = 2';
  1598. $this->assertRegExp('/\s*WHERE\s+`Sportstaette`\.`sportstaette`\s+LIKE\s+"%ru%"\s+AND\s+`Sports/', $result);
  1599. $this->assertEquals($expected, $result);
  1600. $result = $this->Dbo->conditions('Sportstaette.sportstaettenart_id = 2 AND Sportstaette.sportstaette LIKE "%ru%"');
  1601. $expected = ' WHERE `Sportstaette`.`sportstaettenart_id` = 2 AND `Sportstaette`.`sportstaette` LIKE "%ru%"';
  1602. $this->assertEquals($expected, $result);
  1603. $result = $this->Dbo->conditions('SUM(Post.comments_count) > 500 AND NOT Post.title IS NULL AND NOT Post.extended_title IS NULL');
  1604. $expected = ' WHERE SUM(`Post`.`comments_count`) > 500 AND NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL';
  1605. $this->assertEquals($expected, $result);
  1606. $result = $this->Dbo->conditions('NOT Post.title IS NULL AND NOT Post.extended_title IS NULL AND SUM(Post.comments_count) > 500');
  1607. $expected = ' WHERE NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL AND SUM(`Post`.`comments_count`) > 500';
  1608. $this->assertEquals($expected, $result);
  1609. $result = $this->Dbo->conditions('NOT Post.extended_title IS NULL AND NOT Post.title IS NULL AND Post.title != "" AND SPOON(SUM(Post.comments_count) + 1.1) > 500');
  1610. $expected = ' WHERE NOT `Post`.`extended_title` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title` != "" AND SPOON(SUM(`Post`.`comments_count`) + 1.1) > 500';
  1611. $this->assertEquals($expected, $result);
  1612. $result = $this->Dbo->conditions('NOT Post.title_extended IS NULL AND NOT Post.title IS NULL AND Post.title_extended != Post.title');
  1613. $expected = ' WHERE NOT `Post`.`title_extended` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title_extended` != `Post`.`title`';
  1614. $this->assertEquals($expected, $result);
  1615. $result = $this->Dbo->conditions("Comment.id = 'a'");
  1616. $expected = " WHERE `Comment`.`id` = 'a'";
  1617. $this->assertEquals($expected, $result);
  1618. $result = $this->Dbo->conditions("lower(Article.title) LIKE 'a%'");
  1619. $expected = " WHERE lower(`Article`.`title`) LIKE 'a%'";
  1620. $this->assertEquals($expected, $result);
  1621. $result = $this->Dbo->conditions('((MATCH(Video.title) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(Video.description) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(Video.tags) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))');
  1622. $expected = ' WHERE ((MATCH(`Video`.`title`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(`Video`.`description`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(`Video`.`tags`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))';
  1623. $this->assertEquals($expected, $result);
  1624. $result = $this->Dbo->conditions('DATEDIFF(NOW(),Article.published) < 1 && Article.live=1');
  1625. $expected = " WHERE DATEDIFF(NOW(),`Article`.`published`) < 1 && `Article`.`live`=1";
  1626. $this->assertEquals($expected, $result);
  1627. $result = $this->Dbo->conditions('file = "index.html"');
  1628. $expected = ' WHERE file = "index.html"';
  1629. $this->assertEquals($expected, $result);
  1630. $result = $this->Dbo->conditions("file = 'index.html'");
  1631. $expected = " WHERE file = 'index.html'";
  1632. $this->assertEquals($expected, $result);
  1633. $letter = $letter = 'd.a';
  1634. $conditions = array('Company.name like ' => $letter . '%');
  1635. $result = $this->Dbo->conditions($conditions);
  1636. $expected = " WHERE `Company`.`name` like 'd.a%'";
  1637. $this->assertEquals($expected, $result);
  1638. $conditions = array('Artist.name' => 'JUDY and MARY');
  1639. $result = $this->Dbo->conditions($conditions);
  1640. $expected = " WHERE `Artist`.`name` = 'JUDY and MARY'";
  1641. $this->assertEquals($expected, $result);
  1642. $conditions = array('Artist.name' => 'JUDY AND MARY');
  1643. $result = $this->Dbo->conditions($conditions);
  1644. $expected = " WHERE `Artist`.`name` = 'JUDY AND MARY'";
  1645. $this->assertEquals($expected, $result);
  1646. $conditions = array('Company.name similar to ' => 'a word');
  1647. $result = $this->Dbo->conditions($conditions);
  1648. $expected = " WHERE `Company`.`name` similar to 'a word'";
  1649. $this->assertEquals($expected, $result);
  1650. }
  1651. /**
  1652. * testQuotesInStringConditions method
  1653. *
  1654. * @return void
  1655. */
  1656. public function testQuotesInStringConditions() {
  1657. $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\'');
  1658. $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\'';
  1659. $this->assertEquals($expected, $result);
  1660. $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com"');
  1661. $expected = ' WHERE `Member`.`email` = "mariano@cricava.com"';
  1662. $this->assertEquals($expected, $result);
  1663. $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\' AND Member.user LIKE \'mariano.iglesias%\'');
  1664. $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\' AND `Member`.`user` LIKE \'mariano.iglesias%\'';
  1665. $this->assertEquals($expected, $result);
  1666. $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com" AND Member.user LIKE "mariano.iglesias%"');
  1667. $expected = ' WHERE `Member`.`email` = "mariano@cricava.com" AND `Member`.`user` LIKE "mariano.iglesias%"';
  1668. $this->assertEquals($expected, $result);
  1669. }
  1670. /**
  1671. * testParenthesisInStringConditions method
  1672. *
  1673. * @return void
  1674. */
  1675. public function testParenthesisInStringConditions() {
  1676. $result = $this->Dbo->conditions('Member.name = \'(lu\'');
  1677. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
  1678. $result = $this->Dbo->conditions('Member.name = \')lu\'');
  1679. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
  1680. $result = $this->Dbo->conditions('Member.name = \'va(lu\'');
  1681. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
  1682. $result = $this->Dbo->conditions('Member.name = \'va)lu\'');
  1683. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
  1684. $result = $this->Dbo->conditions('Member.name = \'va(lu)\'');
  1685. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
  1686. $result = $this->Dbo->conditions('Member.name = \'va(lu)e\'');
  1687. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
  1688. $result = $this->Dbo->conditions('Member.name = \'(mariano)\'');
  1689. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
  1690. $result = $this->Dbo->conditions('Member.name = \'(mariano)iglesias\'');
  1691. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
  1692. $result = $this->Dbo->conditions('Member.name = \'(mariano) iglesias\'');
  1693. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
  1694. $result = $this->Dbo->conditions('Member.name = \'(mariano word) iglesias\'');
  1695. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
  1696. $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias)\'');
  1697. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
  1698. $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias)\'');
  1699. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
  1700. $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias) CakePHP\'');
  1701. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
  1702. $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias) CakePHP\'');
  1703. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
  1704. }
  1705. /**
  1706. * testParenthesisInArrayConditions method
  1707. *
  1708. * @return void
  1709. */
  1710. public function testParenthesisInArrayConditions() {
  1711. $result = $this->Dbo->conditions(array('Member.name' => '(lu'));
  1712. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
  1713. $result = $this->Dbo->conditions(array('Member.name' => ')lu'));
  1714. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
  1715. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu'));
  1716. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
  1717. $result = $this->Dbo->conditions(array('Member.name' => 'va)lu'));
  1718. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
  1719. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)'));
  1720. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
  1721. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)e'));
  1722. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
  1723. $result = $this->Dbo->conditions(array('Member.name' => '(mariano)'));
  1724. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
  1725. $result = $this->Dbo->conditions(array('Member.name' => '(mariano)iglesias'));
  1726. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
  1727. $result = $this->Dbo->conditions(array('Member.name' => '(mariano) iglesias'));
  1728. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
  1729. $result = $this->Dbo->conditions(array('Member.name' => '(mariano word) iglesias'));
  1730. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
  1731. $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias)'));
  1732. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
  1733. $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias)'));
  1734. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
  1735. $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias) CakePHP'));
  1736. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
  1737. $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias) CakePHP'));
  1738. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
  1739. }
  1740. /**
  1741. * testArrayConditionsParsing method
  1742. *
  1743. * @return void
  1744. */
  1745. public function testArrayConditionsParsing() {
  1746. $this->loadFixtures('Post', 'Author');
  1747. $result = $this->Dbo->conditions(array('Stereo.type' => 'in dash speakers'));
  1748. $this->assertRegExp("/^\s+WHERE\s+`Stereo`.`type`\s+=\s+'in dash speakers'/", $result);
  1749. $result = $this->Dbo->conditions(array('Candy.name LIKE' => 'a', 'HardCandy.name LIKE' => 'c'));
  1750. $this->assertRegExp("/^\s+WHERE\s+`Candy`.`name` LIKE\s+'a'\s+AND\s+`HardCandy`.`name`\s+LIKE\s+'c'/", $result);
  1751. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a', 'Candy.name LIKE' => 'c'));
  1752. $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
  1753. $this->assertEquals($expected, $result);
  1754. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a%', 'Candy.name LIKE' => '%c%'));
  1755. $expected = " WHERE `HardCandy`.`name` LIKE 'a%' AND `Candy`.`name` LIKE '%c%'";
  1756. $this->assertEquals($expected, $result);
  1757. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'to be or%', 'Candy.name LIKE' => '%not to be%'));
  1758. $expected = " WHERE `HardCandy`.`name` LIKE 'to be or%' AND `Candy`.`name` LIKE '%not to be%'";
  1759. $this->assertEquals($expected, $result);
  1760. $result = $this->Dbo->conditions(array('score BETWEEN ? AND ?' => array(90.1, 95.7)));
  1761. $expected = " WHERE `score` BETWEEN 90.1 AND 95.7";
  1762. $this->assertEquals($expected, $result);
  1763. $result = $this->Dbo->conditions(array('Post.title' => 1.1));
  1764. $expected = " WHERE `Post`.`title` = 1.1";
  1765. $this->assertEquals($expected, $result);
  1766. $result = $this->Dbo->conditions(array('Post.title' => 1.1), true, true, new Post());
  1767. $expected = " WHERE `Post`.`title` = '1.1'";
  1768. $this->assertEquals($expected, $result);
  1769. $result = $this->Dbo->conditions(array('SUM(Post.comments_count) >' => '500'));
  1770. $expected = " WHERE SUM(`Post`.`comments_count`) > '500'";
  1771. $this->assertEquals($expected, $result);
  1772. $result = $this->Dbo->conditions(array('MAX(Post.rating) >' => '50'));
  1773. $expected = " WHERE MAX(`Post`.`rating`) > '50'";
  1774. $this->assertEquals($expected, $result);
  1775. $result = $this->Dbo->conditions(array('lower(Article.title)' => 'secrets'));
  1776. $expected = " WHERE lower(`Article`.`title`) = 'secrets'";
  1777. $this->assertEquals($expected, $result);
  1778. $result = $this->Dbo->conditions(array('title LIKE' => '%hello'));
  1779. $expected = " WHERE `title` LIKE '%hello'";
  1780. $this->assertEquals($expected, $result);
  1781. $result = $this->Dbo->conditions(array('Post.name' => 'mad(g)ik'));
  1782. $expected = " WHERE `Post`.`name` = 'mad(g)ik'";
  1783. $this->assertEquals($expected, $result);
  1784. $result = $this->Dbo->conditions(array('score' => array(1, 2, 10)));
  1785. $expected = " WHERE score IN (1, 2, 10)";
  1786. $this->assertEquals($expected, $result);
  1787. $result = $this->Dbo->conditions(array('score' => array()));
  1788. $expected = " WHERE `score` IS NULL";
  1789. $this->assertEquals($expected, $result);
  1790. $result = $this->Dbo->conditions(array('score !=' => array()));
  1791. $expected = " WHERE `score` IS NOT NULL";
  1792. $this->assertEquals($expected, $result);
  1793. $result = $this->Dbo->conditions(array('score !=' => '20'));
  1794. $expected = " WHERE `score` != '20'";
  1795. $this->assertEquals($expected, $result);
  1796. $result = $this->Dbo->conditions(array('score >' => '20'));
  1797. $expected = " WHERE `score` > '20'";
  1798. $this->assertEquals($expected, $result);
  1799. $result = $this->Dbo->conditions(array('client_id >' => '20'), true, true, new TestModel());
  1800. $expected = " WHERE `client_id` > 20";
  1801. $this->assertEquals($expected, $result);
  1802. $result = $this->Dbo->conditions(array('OR' => array(
  1803. array('User.user' => 'mariano'),
  1804. array('User.user' => 'nate')
  1805. )));
  1806. $expected = " WHERE ((`User`.`user` = 'mariano') OR (`User`.`user` = 'nate'))";
  1807. $this->assertEquals($expected, $result);
  1808. $result = $this->Dbo->conditions(array('or' => array(
  1809. 'score BETWEEN ? AND ?' => array('4', '5'), 'rating >' => '20'
  1810. )));
  1811. $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`rating` > '20'))";
  1812. $this->assertEquals($expected, $result);
  1813. $result = $this->Dbo->conditions(array('or' => array(
  1814. 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
  1815. )));
  1816. $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`score` > '20'))";
  1817. $this->assertEquals($expected, $result);
  1818. $result = $this->Dbo->conditions(array('and' => array(
  1819. 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
  1820. )));
  1821. $expected = " WHERE ((`score` BETWEEN '4' AND '5') AND (`score` > '20'))";
  1822. $this->assertEquals($expected, $result);
  1823. $result = $this->Dbo->conditions(array(
  1824. 'published' => 1, 'or' => array('score >' => '2', array('score >' => '20'))
  1825. ));
  1826. $expected = " WHERE `published` = 1 AND ((`score` > '2') OR (`score` > '20'))";
  1827. $this->assertEquals($expected, $result);
  1828. $result = $this->Dbo->conditions(array(array('Project.removed' => false)));
  1829. $expected = " WHERE `Project`.`removed` = '0'";
  1830. $this->assertEquals($expected, $result);
  1831. $result = $this->Dbo->conditions(array(array('Project.removed' => true)));
  1832. $expected = " WHERE `Project`.`removed` = '1'";
  1833. $this->assertEquals($expected, $result);
  1834. $result = $this->Dbo->conditions(array(array('Project.removed' => null)));
  1835. $expected = " WHERE `Project`.`removed` IS NULL";
  1836. $this->assertEquals($expected, $result);
  1837. $result = $this->Dbo->conditions(array(array('Project.removed !=' => null)));
  1838. $expected = " WHERE `Project`.`removed` IS NOT NULL";
  1839. $this->assertEquals($expected, $result);
  1840. $result = $this->Dbo->conditions(array('(Usergroup.permissions) & 4' => 4));
  1841. $expected = " WHERE (`Usergroup`.`permissions`) & 4 = 4";
  1842. $this->assertEquals($expected, $result);
  1843. $result = $this->Dbo->conditions(array('((Usergroup.permissions) & 4)' => 4));
  1844. $expected = " WHERE ((`Usergroup`.`permissions`) & 4) = 4";
  1845. $this->assertEquals($expected, $result);
  1846. $result = $this->Dbo->conditions(array('Post.modified >=' => 'DATE_SUB(NOW(), INTERVAL 7 DAY)'));
  1847. $expected = " WHERE `Post`.`modified` >= 'DATE_SUB(NOW(), INTERVAL 7 DAY)'";
  1848. $this->assertEquals($expected, $result);
  1849. $result = $this->Dbo->conditions(array('Post.modified >= DATE_SUB(NOW(), INTERVAL 7 DAY)'));
  1850. $expected = " WHERE `Post`.`modified` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
  1851. $this->assertEquals($expected, $result);
  1852. $result = $this->Dbo->conditions(array(
  1853. 'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)),
  1854. 'Enrollment.yearcompleted >' => '0')
  1855. );
  1856. $this->assertRegExp('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(level_of_education_id IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result);
  1857. $result = $this->Dbo->conditions(array('id <>' => '8'));
  1858. $this->assertRegExp('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
  1859. $result = $this->Dbo->conditions(array('TestModel.field =' => 'gribe$@()lu'));
  1860. $expected = " WHERE `TestModel`.`field` = 'gribe$@()lu'";
  1861. $this->assertEquals($expected, $result);
  1862. $conditions['NOT'] = array('Listing.expiration BETWEEN ? AND ?' => array("1", "100"));
  1863. $conditions[0]['OR'] = array(
  1864. "Listing.title LIKE" => "%term%",
  1865. "Listing.description LIKE" => "%term%"
  1866. );
  1867. $conditions[1]['OR'] = array(
  1868. "Listing.title LIKE" => "%term_2%",
  1869. "Listing.description LIKE" => "%term_2%"
  1870. );
  1871. $result = $this->Dbo->conditions($conditions);
  1872. $expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND" .
  1873. " ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND" .
  1874. " ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))";
  1875. $this->assertEquals($expected, $result);
  1876. $result = $this->Dbo->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah'));
  1877. $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'";
  1878. $this->assertEquals($expected, $result);
  1879. $result = $this->Dbo->conditions(array(
  1880. 'MD5(CONCAT(Reg.email,Reg.id))' => array('blah', 'blahblah')
  1881. ));
  1882. $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) IN ('blah', 'blahblah')";
  1883. $this->assertEquals($expected, $result);
  1884. $conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76));
  1885. $result = $this->Dbo->conditions($conditions);
  1886. $expected = " WHERE id IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
  1887. $this->assertEquals($expected, $result);
  1888. $conditions = array('title' => 'user(s)');
  1889. $result = $this->Dbo->conditions($conditions);
  1890. $expected = " WHERE `title` = 'user(s)'";
  1891. $this->assertEquals($expected, $result);
  1892. $conditions = array('title' => 'user(s) data');
  1893. $result = $this->Dbo->conditions($conditions);
  1894. $expected = " WHERE `title` = 'user(s) data'";
  1895. $this->assertEquals($expected, $result);
  1896. $conditions = array('title' => 'user(s,arg) data');
  1897. $result = $this->Dbo->conditions($conditions);
  1898. $expected = " WHERE `title` = 'user(s,arg) data'";
  1899. $this->assertEquals($expected, $result);
  1900. $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM)'));
  1901. $expected = " WHERE `Book`.`book_name` = 'Java(TM)'";
  1902. $this->assertEquals($expected, $result);
  1903. $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM) '));
  1904. $expected = " WHERE `Book`.`book_name` = 'Java(TM) '";
  1905. $this->assertEquals($expected, $result);
  1906. $result = $this->Dbo->conditions(array("Book.id" => 0));
  1907. $expected = " WHERE `Book`.`id` = 0";
  1908. $this->assertEquals($expected, $result);
  1909. $result = $this->Dbo->conditions(array("Book.id" => null));
  1910. $expected = " WHERE `Book`.`id` IS NULL";
  1911. $this->assertEquals($expected, $result);
  1912. $conditions = array('MysqlModel.id' => '');
  1913. $result = $this->Dbo->conditions($conditions, true, true, $this->model);
  1914. $expected = " WHERE `MysqlModel`.`id` IS NULL";
  1915. $this->assertEquals($expected, $result);
  1916. $result = $this->Dbo->conditions(array('Listing.beds >=' => 0));
  1917. $expected = " WHERE `Listing`.`beds` >= 0";
  1918. $this->assertEquals($expected, $result);
  1919. $result = $this->Dbo->conditions(array(
  1920. 'ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN ? AND ?' => array(65, 90)
  1921. ));
  1922. $expected = ' WHERE ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN 65 AND 90';
  1923. $this->assertEquals($expected, $result);
  1924. $result = $this->Dbo->conditions(array('or' => array(
  1925. '? BETWEEN Model.field1 AND Model.field2' => '2009-03-04'
  1926. )));
  1927. $expected = " WHERE '2009-03-04' BETWEEN Model.field1 AND Model.field2";
  1928. $this->assertEquals($expected, $result);
  1929. }
  1930. /**
  1931. * testArrayConditionsParsingComplexKeys method
  1932. *
  1933. * @return void
  1934. */
  1935. public function testArrayConditionsParsingComplexKeys() {
  1936. $result = $this->Dbo->conditions(array(
  1937. 'CAST(Book.created AS DATE)' => '2008-08-02'
  1938. ));
  1939. $expected = " WHERE CAST(`Book`.`created` AS DATE) = '2008-08-02'";
  1940. $this->assertEquals($expected, $result);
  1941. $result = $this->Dbo->conditions(array(
  1942. 'CAST(Book.created AS DATE) <=' => '2008-08-02'
  1943. ));
  1944. $expected = " WHERE CAST(`Book`.`created` AS DATE) <= '2008-08-02'";
  1945. $this->assertEquals($expected, $result);
  1946. $result = $this->Dbo->conditions(array(
  1947. '(Stats.clicks * 100) / Stats.views >' => 50
  1948. ));
  1949. $expected = " WHERE (`Stats`.`clicks` * 100) / `Stats`.`views` > 50";
  1950. $this->assertEquals($expected, $result);
  1951. }
  1952. /**
  1953. * testMixedConditionsParsing method
  1954. *
  1955. * @return void
  1956. */
  1957. public function testMixedConditionsParsing() {
  1958. $conditions[] = 'User.first_name = \'Firstname\'';
  1959. $conditions[] = array('User.last_name' => 'Lastname');
  1960. $result = $this->Dbo->conditions($conditions);
  1961. $expected = " WHERE `User`.`first_name` = 'Firstname' AND `User`.`last_name` = 'Lastname'";
  1962. $this->assertEquals($expected, $result);
  1963. $conditions = array(
  1964. 'Thread.project_id' => 5,
  1965. 'Thread.buyer_id' => 14,
  1966. '1=1 GROUP BY Thread.project_id'
  1967. );
  1968. $result = $this->Dbo->conditions($conditions);
  1969. $this->assertRegExp('/^\s*WHERE\s+`Thread`.`project_id`\s*=\s*5\s+AND\s+`Thread`.`buyer_id`\s*=\s*14\s+AND\s+1\s*=\s*1\s+GROUP BY `Thread`.`project_id`$/', $result);
  1970. }
  1971. /**
  1972. * testConditionsOptionalArguments method
  1973. *
  1974. * @return void
  1975. */
  1976. public function testConditionsOptionalArguments() {
  1977. $result = $this->Dbo->conditions( array('Member.name' => 'Mariano'), true, false);
  1978. $this->assertRegExp('/^\s*`Member`.`name`\s*=\s*\'Mariano\'\s*$/', $result);
  1979. $result = $this->Dbo->conditions( array(), true, false);
  1980. $this->assertRegExp('/^\s*1\s*=\s*1\s*$/', $result);
  1981. }
  1982. /**
  1983. * testConditionsWithModel
  1984. *
  1985. * @return void
  1986. */
  1987. public function testConditionsWithModel() {
  1988. $this->Model = new Article2();
  1989. $result = $this->Dbo->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model);
  1990. $expected = " WHERE `Article2`.`viewed` >= 0";
  1991. $this->assertEquals($expected, $result);
  1992. $result = $this->Dbo->conditions(array('Article2.viewed >=' => '0'), true, true, $this->Model);
  1993. $expected = " WHERE `Article2`.`viewed` >= 0";
  1994. $this->assertEquals($expected, $result);
  1995. $result = $this->Dbo->conditions(array('Article2.viewed >=' => '1'), true, true, $this->Model);
  1996. $expected = " WHERE `Article2`.`viewed` >= 1";
  1997. $this->assertEquals($expected, $result);
  1998. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array(0, 10)), true, true, $this->Model);
  1999. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
  2000. $this->assertEquals($expected, $result);
  2001. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('0', '10')), true, true, $this->Model);
  2002. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
  2003. $this->assertEquals($expected, $result);
  2004. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('1', '10')), true, true, $this->Model);
  2005. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 1 AND 10";
  2006. $this->assertEquals($expected, $result);
  2007. }
  2008. /**
  2009. * testFieldParsing method
  2010. *
  2011. * @return void
  2012. */
  2013. public function testFieldParsing() {
  2014. $this->Model = new TestModel();
  2015. $result = $this->Dbo->fields($this->Model, 'Vendor', "Vendor.id, COUNT(Model.vendor_id) AS `Vendor`.`count`");
  2016. $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
  2017. $this->assertEquals($expected, $result);
  2018. $result = $this->Dbo->fields($this->Model, 'Vendor', "`Vendor`.`id`, COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`");
  2019. $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
  2020. $this->assertEquals($expected, $result);
  2021. $result = $this->Dbo->fields($this->Model, 'Post', "CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name, Node.created");
  2022. $expected = array("CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", "`Node`.`created`");
  2023. $this->assertEquals($expected, $result);
  2024. $result = $this->Dbo->fields($this->Model, null, 'round( (3.55441 * fooField), 3 ) AS test');
  2025. $this->assertEquals(array('round( (3.55441 * fooField), 3 ) AS test'), $result);
  2026. $result = $this->Dbo->fields($this->Model, null, 'ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating');
  2027. $this->assertEquals(array('ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating'), $result);
  2028. $result = $this->Dbo->fields($this->Model, null, 'ROUND(Rating.rate_total / Rating.rate_count,2) AS rating');
  2029. $this->assertEquals(array('ROUND(Rating.rate_total / Rating.rate_count,2) AS rating'), $result);
  2030. $result = $this->Dbo->fields($this->Model, 'Post', "Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name");
  2031. $expected = array("`Node`.`created`", "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name");
  2032. $this->assertEquals($expected, $result);
  2033. $result = $this->Dbo->fields($this->Model, 'Post', "2.2,COUNT(*), SUM(Something.else) as sum, Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name,Post.title,Post.1,1.1");
  2034. $expected = array(
  2035. '2.2', 'COUNT(*)', 'SUM(`Something`.`else`) as sum', '`Node`.`created`',
  2036. "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", '`Post`.`title`', '`Post`.`1`', '1.1'
  2037. );
  2038. $this->assertEquals($expected, $result);
  2039. $result = $this->Dbo->fields($this->Model, null, "(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
  2040. $expected = array("(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
  2041. $this->assertEquals($expected, $result);
  2042. $result = $this->Dbo->fields($this->Model, 'Post');
  2043. $expected = array(
  2044. '`Post`.`id`', '`Post`.`client_id`', '`Post`.`name`', '`Post`.`login`',
  2045. '`Post`.`passwd`', '`Post`.`addr_1`', '`Post`.`addr_2`', '`Post`.`zip_code`',
  2046. '`Post`.`city`', '`Post`.`country`', '`Post`.`phone`', '`Post`.`fax`',
  2047. '`Post`.`url`', '`Post`.`email`', '`Post`.`comments`', '`Post`.`last_login`',
  2048. '`Post`.`created`', '`Post`.`updated`'
  2049. );
  2050. $this->assertEquals($expected, $result);
  2051. $result = $this->Dbo->fields($this->Model, 'Other');
  2052. $expected = array(
  2053. '`Other`.`id`', '`Other`.`client_id`', '`Other`.`name`', '`Other`.`login`',
  2054. '`Other`.`passwd`', '`Other`.`addr_1`', '`Other`.`addr_2`', '`Other`.`zip_code`',
  2055. '`Other`.`city`', '`Other`.`country`', '`Other`.`phone`', '`Other`.`fax`',
  2056. '`Other`.`url`', '`Other`.`email`', '`Other`.`comments`', '`Other`.`last_login`',
  2057. '`Other`.`created`', '`Other`.`updated`'
  2058. );
  2059. $this->assertEquals($expected, $result);
  2060. $result = $this->Dbo->fields($this->Model, null, array(), false);
  2061. $expected = array('id', 'client_id', 'name', 'login', 'passwd', 'addr_1', 'addr_2', 'zip_code', 'city', 'country', 'phone', 'fax', 'url', 'email', 'comments', 'last_login', 'created', 'updated');
  2062. $this->assertEquals($expected, $result);
  2063. $result = $this->Dbo->fields($this->Model, null, 'COUNT(*)');
  2064. $expected = array('COUNT(*)');
  2065. $this->assertEquals($expected, $result);
  2066. $result = $this->Dbo->fields($this->Model, null, 'SUM(Thread.unread_buyer) AS ' . $this->Dbo->name('sum_unread_buyer'));
  2067. $expected = array('SUM(`Thread`.`unread_buyer`) AS `sum_unread_buyer`');
  2068. $this->assertEquals($expected, $result);
  2069. $result = $this->Dbo->fields($this->Model, null, 'name, count(*)');
  2070. $expected = array('`TestModel`.`name`', 'count(*)');
  2071. $this->assertEquals($expected, $result);
  2072. $result = $this->Dbo->fields($this->Model, null, 'count(*), name');
  2073. $expected = array('count(*)', '`TestModel`.`name`');
  2074. $this->assertEquals($expected, $result);
  2075. $result = $this->Dbo->fields(
  2076. $this->Model, null, 'field1, field2, field3, count(*), name'
  2077. );
  2078. $expected = array(
  2079. '`TestModel`.`field1`', '`TestModel`.`field2`',
  2080. '`TestModel`.`field3`', 'count(*)', '`TestModel`.`name`'
  2081. );
  2082. $this->assertEquals($expected, $result);
  2083. $result = $this->Dbo->fields($this->Model, null, array('dayofyear(now())'));
  2084. $expected = array('dayofyear(now())');
  2085. $this->assertEquals($expected, $result);
  2086. $result = $this->Dbo->fields($this->Model, null, array('MAX(Model.field) As Max'));
  2087. $expected = array('MAX(`Model`.`field`) As Max');
  2088. $this->assertEquals($expected, $result);
  2089. $result = $this->Dbo->fields($this->Model, null, array('Model.field AS AnotherName'));
  2090. $expected = array('`Model`.`field` AS `AnotherName`');
  2091. $this->assertEquals($expected, $result);
  2092. $result = $this->Dbo->fields($this->Model, null, array('field AS AnotherName'));
  2093. $expected = array('`field` AS `AnotherName`');
  2094. $this->assertEquals($expected, $result);
  2095. $result = $this->Dbo->fields($this->Model, null, array(
  2096. 'TestModel.field AS AnotherName'
  2097. ));
  2098. $expected = array('`TestModel`.`field` AS `AnotherName`');
  2099. $this->assertEquals($expected, $result);
  2100. $result = $this->Dbo->fields($this->Model, 'Foo', array(
  2101. 'id', 'title', '(user_count + discussion_count + post_count) AS score'
  2102. ));
  2103. $expected = array(
  2104. '`Foo`.`id`',
  2105. '`Foo`.`title`',
  2106. '(user_count + discussion_count + post_count) AS score'
  2107. );
  2108. $this->assertEquals($expected, $result);
  2109. }
  2110. /**
  2111. * test that fields() will accept objects made from DboSource::expression
  2112. *
  2113. * @return void
  2114. */
  2115. public function testFieldsWithExpression() {
  2116. $this->Model = new TestModel;
  2117. $expression = $this->Dbo->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col");
  2118. $result = $this->Dbo->fields($this->Model, null, array("id", $expression));
  2119. $expected = array(
  2120. '`TestModel`.`id`',
  2121. "CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"
  2122. );
  2123. $this->assertEquals($expected, $result);
  2124. }
  2125. /**
  2126. * testRenderStatement method
  2127. *
  2128. * @return void
  2129. */
  2130. public function testRenderStatement() {
  2131. $result = $this->Dbo->renderStatement('select', array(
  2132. 'fields' => 'id', 'table' => 'table', 'conditions' => 'WHERE 1=1',
  2133. 'alias' => '', 'joins' => '', 'order' => '', 'limit' => '', 'group' => ''
  2134. ));
  2135. $this->assertRegExp('/^\s*SELECT\s+id\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
  2136. $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
  2137. $this->assertRegExp('/^\s*UPDATE\s+table\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
  2138. $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
  2139. $this->assertRegExp('/^\s*UPDATE\s+table\s+AS\s+alias\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
  2140. $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
  2141. $this->assertRegExp('/^\s*DELETE\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
  2142. $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
  2143. $this->assertRegExp('/^\s*DELETE\s+alias\s+FROM\s+table\s+AS\s+alias\s+WHERE\s+1=1\s*$/', $result);
  2144. }
  2145. /**
  2146. * testSchema method
  2147. *
  2148. * @return void
  2149. */
  2150. public function testSchema() {
  2151. $Schema = new CakeSchema();
  2152. $Schema->tables = array('table' => array(), 'anotherTable' => array());
  2153. $result = $this->Dbo->dropSchema($Schema, 'non_existing');
  2154. $this->assertTrue(empty($result));
  2155. $result = $this->Dbo->dropSchema($Schema, 'table');
  2156. $this->assertRegExp('/^\s*DROP TABLE IF EXISTS\s+' . $this->Dbo->fullTableName('table') . ';\s*$/s', $result);
  2157. }
  2158. /**
  2159. * testDropSchemaNoSchema method
  2160. *
  2161. * @expectedException PHPUnit_Framework_Error
  2162. * @return void
  2163. */
  2164. public function testDropSchemaNoSchema() {
  2165. $result = $this->Dbo->dropSchema(null);
  2166. }
  2167. /**
  2168. * testOrderParsing method
  2169. *
  2170. * @return void
  2171. */
  2172. public function testOrderParsing() {
  2173. $result = $this->Dbo->order("ADDTIME(Event.time_begin, '-06:00:00') ASC");
  2174. $expected = " ORDER BY ADDTIME(`Event`.`time_begin`, '-06:00:00') ASC";
  2175. $this->assertEquals($expected, $result);
  2176. $result = $this->Dbo->order("title, id");
  2177. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2178. $result = $this->Dbo->order("title desc, id desc");
  2179. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
  2180. $result = $this->Dbo->order(array("title desc, id desc"));
  2181. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
  2182. $result = $this->Dbo->order(array("title", "id"));
  2183. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2184. $result = $this->Dbo->order(array(array('title'), array('id')));
  2185. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2186. $result = $this->Dbo->order(array("Post.title" => 'asc', "Post.id" => 'desc'));
  2187. $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
  2188. $result = $this->Dbo->order(array(array("Post.title" => 'asc', "Post.id" => 'desc')));
  2189. $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
  2190. $result = $this->Dbo->order(array("title"));
  2191. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
  2192. $result = $this->Dbo->order(array(array("title")));
  2193. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
  2194. $result = $this->Dbo->order("Dealer.id = 7 desc, Dealer.id = 3 desc, Dealer.title asc");
  2195. $expected = " ORDER BY `Dealer`.`id` = 7 desc, `Dealer`.`id` = 3 desc, `Dealer`.`title` asc";
  2196. $this->assertEquals($expected, $result);
  2197. $result = $this->Dbo->order(array("Page.name" => "='test' DESC"));
  2198. $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*='test'\s+DESC\s*$/", $result);
  2199. $result = $this->Dbo->order("Page.name = 'view' DESC");
  2200. $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*=\s*'view'\s+DESC\s*$/", $result);
  2201. $result = $this->Dbo->order("(Post.views)");
  2202. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\s+ASC\s*$/", $result);
  2203. $result = $this->Dbo->order("(Post.views)*Post.views");
  2204. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\*`Post`\.`views`\s+ASC\s*$/", $result);
  2205. $result = $this->Dbo->order("(Post.views) * Post.views");
  2206. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\) \* `Post`\.`views`\s+ASC\s*$/", $result);
  2207. $result = $this->Dbo->order("(Model.field1 + Model.field2) * Model.field3");
  2208. $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field1` \+ `Model`\.`field2`\) \* `Model`\.`field3`\s+ASC\s*$/", $result);
  2209. $result = $this->Dbo->order("Model.name+0 ASC");
  2210. $this->assertRegExp("/^\s*ORDER BY\s+`Model`\.`name`\+0\s+ASC\s*$/", $result);
  2211. $result = $this->Dbo->order("Anuncio.destaque & 2 DESC");
  2212. $expected = ' ORDER BY `Anuncio`.`destaque` & 2 DESC';
  2213. $this->assertEquals($expected, $result);
  2214. $result = $this->Dbo->order("3963.191 * id");
  2215. $expected = ' ORDER BY 3963.191 * id ASC';
  2216. $this->assertEquals($expected, $result);
  2217. $result = $this->Dbo->order(array('Property.sale_price IS NULL'));
  2218. $expected = ' ORDER BY `Property`.`sale_price` IS NULL ASC';
  2219. $this->assertEquals($expected, $result);
  2220. }
  2221. /**
  2222. * testComplexSortExpression method
  2223. *
  2224. * @return void
  2225. */
  2226. public function testComplexSortExpression() {
  2227. $result = $this->Dbo->order(array('(Model.field > 100) DESC', 'Model.field ASC'));
  2228. $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field`\s+>\s+100\)\s+DESC,\s+`Model`\.`field`\s+ASC\s*$/", $result);
  2229. }
  2230. /**
  2231. * testCalculations method
  2232. *
  2233. * @return void
  2234. */
  2235. public function testCalculations() {
  2236. $this->Model = new TestModel();
  2237. $result = $this->Dbo->calculate($this->Model, 'count');
  2238. $this->assertEquals('COUNT(*) AS `count`', $result);
  2239. $result = $this->Dbo->calculate($this->Model, 'count', array('id'));
  2240. $this->assertEquals('COUNT(`id`) AS `count`', $result);
  2241. $result = $this->Dbo->calculate(
  2242. $this->Model,
  2243. 'count',
  2244. array($this->Dbo->expression('DISTINCT id'))
  2245. );
  2246. $this->assertEquals('COUNT(DISTINCT id) AS `count`', $result);
  2247. $result = $this->Dbo->calculate($this->Model, 'count', array('id', 'id_count'));
  2248. $this->assertEquals('COUNT(`id`) AS `id_count`', $result);
  2249. $result = $this->Dbo->calculate($this->Model, 'count', array('Model.id', 'id_count'));
  2250. $this->assertEquals('COUNT(`Model`.`id`) AS `id_count`', $result);
  2251. $result = $this->Dbo->calculate($this->Model, 'max', array('id'));
  2252. $this->assertEquals('MAX(`id`) AS `id`', $result);
  2253. $result = $this->Dbo->calculate($this->Model, 'max', array('Model.id', 'id'));
  2254. $this->assertEquals('MAX(`Model`.`id`) AS `id`', $result);
  2255. $result = $this->Dbo->calculate($this->Model, 'max', array('`Model`.`id`', 'id'));
  2256. $this->assertEquals('MAX(`Model`.`id`) AS `id`', $result);
  2257. $result = $this->Dbo->calculate($this->Model, 'min', array('`Model`.`id`', 'id'));
  2258. $this->assertEquals('MIN(`Model`.`id`) AS `id`', $result);
  2259. $result = $this->Dbo->calculate($this->Model, 'min', 'left');
  2260. $this->assertEquals('MIN(`left`) AS `left`', $result);
  2261. }
  2262. /**
  2263. * testLength method
  2264. *
  2265. * @return void
  2266. */
  2267. public function testLength() {
  2268. $result = $this->Dbo->length('varchar(255)');
  2269. $expected = 255;
  2270. $this->assertSame($expected, $result);
  2271. $result = $this->Dbo->length('int(11)');
  2272. $expected = 11;
  2273. $this->assertSame($expected, $result);
  2274. $result = $this->Dbo->length('float(5,3)');
  2275. $expected = '5,3';
  2276. $this->assertSame($expected, $result);
  2277. $result = $this->Dbo->length('decimal(5,2)');
  2278. $expected = '5,2';
  2279. $this->assertSame($expected, $result);
  2280. $result = $this->Dbo->length("enum('test','me','now')");
  2281. $expected = 4;
  2282. $this->assertSame($expected, $result);
  2283. $result = $this->Dbo->length("set('a','b','cd')");
  2284. $expected = 2;
  2285. $this->assertSame($expected, $result);
  2286. $result = $this->Dbo->length(false);
  2287. $this->assertTrue($result === null);
  2288. $result = $this->Dbo->length('datetime');
  2289. $expected = null;
  2290. $this->assertSame($expected, $result);
  2291. $result = $this->Dbo->length('text');
  2292. $expected = null;
  2293. $this->assertSame($expected, $result);
  2294. }
  2295. /**
  2296. * testBuildIndex method
  2297. *
  2298. * @return void
  2299. */
  2300. public function testBuildIndex() {
  2301. $data = array(
  2302. 'PRIMARY' => array('column' => 'id')
  2303. );
  2304. $result = $this->Dbo->buildIndex($data);
  2305. $expected = array('PRIMARY KEY (`id`)');
  2306. $this->assertSame($expected, $result);
  2307. $data = array(
  2308. 'MyIndex' => array('column' => 'id', 'unique' => true)
  2309. );
  2310. $result = $this->Dbo->buildIndex($data);
  2311. $expected = array('UNIQUE KEY `MyIndex` (`id`)');
  2312. $this->assertEquals($expected, $result);
  2313. $data = array(
  2314. 'MyIndex' => array('column' => array('id', 'name'), 'unique' => true)
  2315. );
  2316. $result = $this->Dbo->buildIndex($data);
  2317. $expected = array('UNIQUE KEY `MyIndex` (`id`, `name`)');
  2318. $this->assertEquals($expected, $result);
  2319. }
  2320. /**
  2321. * testBuildColumn method
  2322. *
  2323. * @return void
  2324. */
  2325. public function testBuildColumn2() {
  2326. $data = array(
  2327. 'name' => 'testName',
  2328. 'type' => 'string',
  2329. 'length' => 255,
  2330. 'default',
  2331. 'null' => true,
  2332. 'key'
  2333. );
  2334. $result = $this->Dbo->buildColumn($data);
  2335. $expected = '`testName` varchar(255) DEFAULT NULL';
  2336. $this->assertEquals($expected, $result);
  2337. $data = array(
  2338. 'name' => 'int_field',
  2339. 'type' => 'integer',
  2340. 'default' => '',
  2341. 'null' => false,
  2342. );
  2343. $restore = $this->Dbo->columns;
  2344. $this->Dbo->columns = array('integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'), );
  2345. $result = $this->Dbo->buildColumn($data);
  2346. $expected = '`int_field` int(11) NOT NULL';
  2347. $this->assertEquals($expected, $result);
  2348. $this->Dbo->fieldParameters['param'] = array(
  2349. 'value' => 'COLLATE',
  2350. 'quote' => false,
  2351. 'join' => ' ',
  2352. 'column' => 'Collate',
  2353. 'position' => 'beforeDefault',
  2354. 'options' => array('GOOD', 'OK')
  2355. );
  2356. $data = array(
  2357. 'name' => 'int_field',
  2358. 'type' => 'integer',
  2359. 'default' => '',
  2360. 'null' => false,
  2361. 'param' => 'BAD'
  2362. );
  2363. $result = $this->Dbo->buildColumn($data);
  2364. $expected = '`int_field` int(11) NOT NULL';
  2365. $this->assertEquals($expected, $result);
  2366. $data = array(
  2367. 'name' => 'int_field',
  2368. 'type' => 'integer',
  2369. 'default' => '',
  2370. 'null' => false,
  2371. 'param' => 'GOOD'
  2372. );
  2373. $result = $this->Dbo->buildColumn($data);
  2374. $expected = '`int_field` int(11) COLLATE GOOD NOT NULL';
  2375. $this->assertEquals($expected, $result);
  2376. $this->Dbo->columns = $restore;
  2377. $data = array(
  2378. 'name' => 'created',
  2379. 'type' => 'timestamp',
  2380. 'default' => 'current_timestamp',
  2381. 'null' => false,
  2382. );
  2383. $result = $this->Dbo->buildColumn($data);
  2384. $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL';
  2385. $this->assertEquals($expected, $result);
  2386. $data = array(
  2387. 'name' => 'created',
  2388. 'type' => 'timestamp',
  2389. 'default' => 'CURRENT_TIMESTAMP',
  2390. 'null' => true,
  2391. );
  2392. $result = $this->Dbo->buildColumn($data);
  2393. $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP';
  2394. $this->assertEquals($expected, $result);
  2395. $data = array(
  2396. 'name' => 'modified',
  2397. 'type' => 'timestamp',
  2398. 'null' => true,
  2399. );
  2400. $result = $this->Dbo->buildColumn($data);
  2401. $expected = '`modified` timestamp NULL';
  2402. $this->assertEquals($expected, $result);
  2403. $data = array(
  2404. 'name' => 'modified',
  2405. 'type' => 'timestamp',
  2406. 'default' => null,
  2407. 'null' => true,
  2408. );
  2409. $result = $this->Dbo->buildColumn($data);
  2410. $expected = '`modified` timestamp NULL';
  2411. $this->assertEquals($expected, $result);
  2412. }
  2413. /**
  2414. * testBuildColumnBadType method
  2415. *
  2416. * @expectedException PHPUnit_Framework_Error
  2417. * @return void
  2418. */
  2419. public function testBuildColumnBadType() {
  2420. $data = array(
  2421. 'name' => 'testName',
  2422. 'type' => 'varchar(255)',
  2423. 'default',
  2424. 'null' => true,
  2425. 'key'
  2426. );
  2427. $this->Dbo->buildColumn($data);
  2428. }
  2429. /**
  2430. * test hasAny()
  2431. *
  2432. * @return void
  2433. */
  2434. public function testHasAny() {
  2435. $db = $this->Dbo->config['database'];
  2436. $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute', 'value'));
  2437. $this->Dbo->config['database'] = $db;
  2438. $this->Model = $this->getMock('TestModel', array('getDataSource'));
  2439. $this->Model->expects($this->any())
  2440. ->method('getDataSource')
  2441. ->will($this->returnValue($this->Dbo));
  2442. $this->Dbo->expects($this->at(0))->method('value')
  2443. ->with('harry')
  2444. ->will($this->returnValue("'harry'"));
  2445. $modelTable = $this->Dbo->fullTableName($this->Model);
  2446. $this->Dbo->expects($this->at(1))->method('execute')
  2447. ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE `TestModel`.`name` = \'harry\'');
  2448. $this->Dbo->expects($this->at(2))->method('execute')
  2449. ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE 1 = 1');
  2450. $this->Dbo->hasAny($this->Model, array('TestModel.name' => 'harry'));
  2451. $this->Dbo->hasAny($this->Model, array());
  2452. }
  2453. /**
  2454. * test fields generating usable virtual fields to use in query
  2455. *
  2456. * @return void
  2457. */
  2458. public function testVirtualFields() {
  2459. $this->loadFixtures('Article', 'Comment', 'Tag');
  2460. $this->Dbo->virtualFieldSeparator = '__';
  2461. $Article = ClassRegistry::init('Article');
  2462. $commentsTable = $this->Dbo->fullTableName('comments', false, false);
  2463. $Article->virtualFields = array(
  2464. 'this_moment' => 'NOW()',
  2465. 'two' => '1 + 1',
  2466. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2467. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2468. );
  2469. $result = $this->Dbo->fields($Article);
  2470. $expected = array(
  2471. '`Article`.`id`',
  2472. '`Article`.`user_id`',
  2473. '`Article`.`title`',
  2474. '`Article`.`body`',
  2475. '`Article`.`published`',
  2476. '`Article`.`created`',
  2477. '`Article`.`updated`',
  2478. '(NOW()) AS `Article__this_moment`',
  2479. '(1 + 1) AS `Article__two`',
  2480. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2481. );
  2482. $this->assertEquals($expected, $result);
  2483. $result = $this->Dbo->fields($Article, null, array('this_moment', 'title'));
  2484. $expected = array(
  2485. '`Article`.`title`',
  2486. '(NOW()) AS `Article__this_moment`',
  2487. );
  2488. $this->assertEquals($expected, $result);
  2489. $result = $this->Dbo->fields($Article, null, array('Article.title', 'Article.this_moment'));
  2490. $expected = array(
  2491. '`Article`.`title`',
  2492. '(NOW()) AS `Article__this_moment`',
  2493. );
  2494. $this->assertEquals($expected, $result);
  2495. $result = $this->Dbo->fields($Article, null, array('Article.this_moment', 'Article.title'));
  2496. $expected = array(
  2497. '`Article`.`title`',
  2498. '(NOW()) AS `Article__this_moment`',
  2499. );
  2500. $this->assertEquals($expected, $result);
  2501. $result = $this->Dbo->fields($Article, null, array('Article.*'));
  2502. $expected = array(
  2503. '`Article`.*',
  2504. '(NOW()) AS `Article__this_moment`',
  2505. '(1 + 1) AS `Article__two`',
  2506. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2507. );
  2508. $this->assertEquals($expected, $result);
  2509. $result = $this->Dbo->fields($Article, null, array('*'));
  2510. $expected = array(
  2511. '*',
  2512. '(NOW()) AS `Article__this_moment`',
  2513. '(1 + 1) AS `Article__two`',
  2514. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2515. );
  2516. $this->assertEquals($expected, $result);
  2517. }
  2518. /**
  2519. * test conditions to generate query conditions for virtual fields
  2520. *
  2521. * @return void
  2522. */
  2523. public function testVirtualFieldsInConditions() {
  2524. $Article = ClassRegistry::init('Article');
  2525. $commentsTable = $this->Dbo->fullTableName('comments', false, false);
  2526. $Article->virtualFields = array(
  2527. 'this_moment' => 'NOW()',
  2528. 'two' => '1 + 1',
  2529. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2530. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2531. );
  2532. $conditions = array('two' => 2);
  2533. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2534. $expected = '(1 + 1) = 2';
  2535. $this->assertEquals($expected, $result);
  2536. $conditions = array('this_moment BETWEEN ? AND ?' => array(1,2));
  2537. $expected = 'NOW() BETWEEN 1 AND 2';
  2538. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2539. $this->assertEquals($expected, $result);
  2540. $conditions = array('comment_count >' => 5);
  2541. $expected = "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) > 5";
  2542. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2543. $this->assertEquals($expected, $result);
  2544. $conditions = array('NOT' => array('two' => 2));
  2545. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2546. $expected = 'NOT ((1 + 1) = 2)';
  2547. $this->assertEquals($expected, $result);
  2548. }
  2549. /**
  2550. * test that virtualFields with complex functions and aliases work.
  2551. *
  2552. * @return void
  2553. */
  2554. public function testConditionsWithComplexVirtualFields() {
  2555. $Article = ClassRegistry::init('Article', 'Comment', 'Tag');
  2556. $Article->virtualFields = array(
  2557. 'distance' => 'ACOS(SIN(20 * PI() / 180)
  2558. * SIN(Article.latitude * PI() / 180)
  2559. + COS(20 * PI() / 180)
  2560. * COS(Article.latitude * PI() / 180)
  2561. * COS((50 - Article.longitude) * PI() / 180)
  2562. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2563. );
  2564. $conditions = array('distance >=' => 20);
  2565. $result = $this->Dbo->conditions($conditions, true, true, $Article);
  2566. $this->assertRegExp('/\) >= 20/', $result);
  2567. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result);
  2568. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result);
  2569. }
  2570. /**
  2571. * test calculate to generate claculate statements on virtual fields
  2572. *
  2573. * @return void
  2574. */
  2575. public function testVirtualFieldsInCalculate() {
  2576. $Article = ClassRegistry::init('Article');
  2577. $commentsTable = $this->Dbo->fullTableName('comments', false, false);
  2578. $Article->virtualFields = array(
  2579. 'this_moment' => 'NOW()',
  2580. 'two' => '1 + 1',
  2581. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2582. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2583. );
  2584. $result = $this->Dbo->calculate($Article, 'count', array('this_moment'));
  2585. $expected = 'COUNT(NOW()) AS `count`';
  2586. $this->assertEquals($expected, $result);
  2587. $result = $this->Dbo->calculate($Article, 'max', array('comment_count'));
  2588. $expected = "MAX(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `comment_count`";
  2589. $this->assertEquals($expected, $result);
  2590. }
  2591. /**
  2592. * test reading virtual fields containing newlines when recursive > 0
  2593. *
  2594. * @return void
  2595. */
  2596. public function testReadVirtualFieldsWithNewLines() {
  2597. $Article = new Article();
  2598. $Article->recursive = 1;
  2599. $Article->virtualFields = array(
  2600. 'test' => '
  2601. User.id + User.id
  2602. '
  2603. );
  2604. $result = $this->Dbo->fields($Article, null, array());
  2605. $result = $this->Dbo->fields($Article, $Article->alias, $result);
  2606. $this->assertRegExp('/[`\"]User[`\"]\.[`\"]id[`\"] \+ [`\"]User[`\"]\.[`\"]id[`\"]/', $result[7]);
  2607. }
  2608. /**
  2609. * test group to generate GROUP BY statements on virtual fields
  2610. *
  2611. * @return void
  2612. */
  2613. public function testVirtualFieldsInGroup() {
  2614. $Article = ClassRegistry::init('Article');
  2615. $Article->virtualFields = array(
  2616. 'this_year' => 'YEAR(Article.created)'
  2617. );
  2618. $result = $this->Dbo->group('this_year', $Article);
  2619. $expected = " GROUP BY (YEAR(`Article`.`created`))";
  2620. $this->assertEquals($expected, $result);
  2621. }
  2622. /**
  2623. * test that virtualFields with complex functions and aliases work.
  2624. *
  2625. * @return void
  2626. */
  2627. public function testFieldsWithComplexVirtualFields() {
  2628. $Article = new Article();
  2629. $Article->virtualFields = array(
  2630. 'distance' => 'ACOS(SIN(20 * PI() / 180)
  2631. * SIN(Article.latitude * PI() / 180)
  2632. + COS(20 * PI() / 180)
  2633. * COS(Article.latitude * PI() / 180)
  2634. * COS((50 - Article.longitude) * PI() / 180)
  2635. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2636. );
  2637. $fields = array('id', 'distance');
  2638. $result = $this->Dbo->fields($Article, null, $fields);
  2639. $qs = $this->Dbo->startQuote;
  2640. $qe = $this->Dbo->endQuote;
  2641. $this->assertEquals("{$qs}Article{$qe}.{$qs}id{$qe}", $result[0]);
  2642. $this->assertRegExp('/Article__distance/', $result[1]);
  2643. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result[1]);
  2644. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result[1]);
  2645. }
  2646. /**
  2647. * test that execute runs queries.
  2648. *
  2649. * @return void
  2650. */
  2651. public function testExecute() {
  2652. $query = 'SELECT * FROM ' . $this->Dbo->fullTableName('articles') . ' WHERE 1 = 1';
  2653. $this->Dbo->took = null;
  2654. $this->Dbo->affected = null;
  2655. $result = $this->Dbo->execute($query, array('log' => false));
  2656. $this->assertNotNull($result, 'No query performed! %s');
  2657. $this->assertNull($this->Dbo->took, 'Stats were set %s');
  2658. $this->assertNull($this->Dbo->affected, 'Stats were set %s');
  2659. $result = $this->Dbo->execute($query);
  2660. $this->assertNotNull($result, 'No query performed! %s');
  2661. $this->assertNotNull($this->Dbo->took, 'Stats were not set %s');
  2662. $this->assertNotNull($this->Dbo->affected, 'Stats were not set %s');
  2663. }
  2664. /**
  2665. * test a full example of using virtual fields
  2666. *
  2667. * @return void
  2668. */
  2669. public function testVirtualFieldsFetch() {
  2670. $this->loadFixtures('Article', 'Comment');
  2671. $Article = ClassRegistry::init('Article');
  2672. $Article->virtualFields = array(
  2673. 'comment_count' => 'SELECT COUNT(*) FROM ' . $this->Dbo->fullTableName('comments') .
  2674. ' WHERE Article.id = ' . $this->Dbo->fullTableName('comments') . '.article_id'
  2675. );
  2676. $conditions = array('comment_count >' => 2);
  2677. $query = 'SELECT ' . join(',', $this->Dbo->fields($Article, null, array('id', 'comment_count'))) .
  2678. ' FROM ' . $this->Dbo->fullTableName($Article) . ' Article ' . $this->Dbo->conditions($conditions, true, true, $Article);
  2679. $result = $this->Dbo->fetchAll($query);
  2680. $expected = array(array(
  2681. 'Article' => array('id' => 1, 'comment_count' => 4)
  2682. ));
  2683. $this->assertEquals($expected, $result);
  2684. }
  2685. /**
  2686. * test reading complex virtualFields with subqueries.
  2687. *
  2688. * @return void
  2689. */
  2690. public function testVirtualFieldsComplexRead() {
  2691. $this->loadFixtures('DataTest', 'Article', 'Comment', 'User', 'Tag', 'ArticlesTag');
  2692. $Article = ClassRegistry::init('Article');
  2693. $commentTable = $this->Dbo->fullTableName('comments');
  2694. $Article = ClassRegistry::init('Article');
  2695. $Article->virtualFields = array(
  2696. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentTable .
  2697. ' AS Comment WHERE Article.id = Comment.article_id'
  2698. );
  2699. $result = $Article->find('all');
  2700. $this->assertTrue(count($result) > 0);
  2701. $this->assertTrue($result[0]['Article']['comment_count'] > 0);
  2702. $DataTest = ClassRegistry::init('DataTest');
  2703. $DataTest->virtualFields = array(
  2704. 'complicated' => 'ACOS(SIN(20 * PI() / 180)
  2705. * SIN(DataTest.float * PI() / 180)
  2706. + COS(20 * PI() / 180)
  2707. * COS(DataTest.count * PI() / 180)
  2708. * COS((50 - DataTest.float) * PI() / 180)
  2709. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2710. );
  2711. $result = $DataTest->find('all');
  2712. $this->assertTrue(count($result) > 0);
  2713. $this->assertTrue($result[0]['DataTest']['complicated'] > 0);
  2714. }
  2715. /**
  2716. * testIntrospectType method
  2717. *
  2718. * @return void
  2719. */
  2720. public function testIntrospectType() {
  2721. $this->assertEquals('integer', $this->Dbo->introspectType(0));
  2722. $this->assertEquals('integer', $this->Dbo->introspectType(2));
  2723. $this->assertEquals('string', $this->Dbo->introspectType('2'));
  2724. $this->assertEquals('string', $this->Dbo->introspectType('2.2'));
  2725. $this->assertEquals('float', $this->Dbo->introspectType(2.2));
  2726. $this->assertEquals('string', $this->Dbo->introspectType('stringme'));
  2727. $this->assertEquals('string', $this->Dbo->introspectType('0stringme'));
  2728. $data = array(2.2);
  2729. $this->assertEquals('float', $this->Dbo->introspectType($data));
  2730. $data = array('2.2');
  2731. $this->assertEquals('float', $this->Dbo->introspectType($data));
  2732. $data = array(2);
  2733. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2734. $data = array('2');
  2735. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2736. $data = array('string');
  2737. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2738. $data = array(2.2, '2.2');
  2739. $this->assertEquals('float', $this->Dbo->introspectType($data));
  2740. $data = array(2, '2');
  2741. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2742. $data = array('string one', 'string two');
  2743. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2744. $data = array('2.2', 3);
  2745. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2746. $data = array('2.2', '0stringme');
  2747. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2748. $data = array(2.2, 3);
  2749. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2750. $data = array(2.2, '0stringme');
  2751. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2752. $data = array(2, 'stringme');
  2753. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2754. $data = array(2, '2.2', 'stringgme');
  2755. $this->assertEquals('string', $this->Dbo->introspectType($data));
  2756. $data = array(2, '2.2');
  2757. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2758. $data = array(2, 2.2);
  2759. $this->assertEquals('integer', $this->Dbo->introspectType($data));
  2760. // null
  2761. $result = $this->Dbo->value(null, 'boolean');
  2762. $this->assertEquals('NULL', $result);
  2763. // EMPTY STRING
  2764. $result = $this->Dbo->value('', 'boolean');
  2765. $this->assertEquals("'0'", $result);
  2766. // BOOLEAN
  2767. $result = $this->Dbo->value('true', 'boolean');
  2768. $this->assertEquals("'1'", $result);
  2769. $result = $this->Dbo->value('false', 'boolean');
  2770. $this->assertEquals("'1'", $result);
  2771. $result = $this->Dbo->value(true, 'boolean');
  2772. $this->assertEquals("'1'", $result);
  2773. $result = $this->Dbo->value(false, 'boolean');
  2774. $this->assertEquals("'0'", $result);
  2775. $result = $this->Dbo->value(1, 'boolean');
  2776. $this->assertEquals("'1'", $result);
  2777. $result = $this->Dbo->value(0, 'boolean');
  2778. $this->assertEquals("'0'", $result);
  2779. $result = $this->Dbo->value('abc', 'boolean');
  2780. $this->assertEquals("'1'", $result);
  2781. $result = $this->Dbo->value(1.234, 'boolean');
  2782. $this->assertEquals("'1'", $result);
  2783. $result = $this->Dbo->value('1.234e05', 'boolean');
  2784. $this->assertEquals("'1'", $result);
  2785. // NUMBERS
  2786. $result = $this->Dbo->value(123, 'integer');
  2787. $this->assertEquals(123, $result);
  2788. $result = $this->Dbo->value('123', 'integer');
  2789. $this->assertEquals('123', $result);
  2790. $result = $this->Dbo->value('0123', 'integer');
  2791. $this->assertEquals("'0123'", $result);
  2792. $result = $this->Dbo->value('0x123ABC', 'integer');
  2793. $this->assertEquals("'0x123ABC'", $result);
  2794. $result = $this->Dbo->value('0x123', 'integer');
  2795. $this->assertEquals("'0x123'", $result);
  2796. $result = $this->Dbo->value(1.234, 'float');
  2797. $this->assertEquals(1.234, $result);
  2798. $result = $this->Dbo->value('1.234', 'float');
  2799. $this->assertEquals('1.234', $result);
  2800. $result = $this->Dbo->value(' 1.234 ', 'float');
  2801. $this->assertEquals("' 1.234 '", $result);
  2802. $result = $this->Dbo->value('1.234e05', 'float');
  2803. $this->assertEquals("'1.234e05'", $result);
  2804. $result = $this->Dbo->value('1.234e+5', 'float');
  2805. $this->assertEquals("'1.234e+5'", $result);
  2806. $result = $this->Dbo->value('1,234', 'float');
  2807. $this->assertEquals("'1,234'", $result);
  2808. $result = $this->Dbo->value('FFF', 'integer');
  2809. $this->assertEquals("'FFF'", $result);
  2810. $result = $this->Dbo->value('abc', 'integer');
  2811. $this->assertEquals("'abc'", $result);
  2812. // STRINGS
  2813. $result = $this->Dbo->value('123', 'string');
  2814. $this->assertEquals("'123'", $result);
  2815. $result = $this->Dbo->value(123, 'string');
  2816. $this->assertEquals("'123'", $result);
  2817. $result = $this->Dbo->value(1.234, 'string');
  2818. $this->assertEquals("'1.234'", $result);
  2819. $result = $this->Dbo->value('abc', 'string');
  2820. $this->assertEquals("'abc'", $result);
  2821. $result = $this->Dbo->value(' abc ', 'string');
  2822. $this->assertEquals("' abc '", $result);
  2823. $result = $this->Dbo->value('a bc', 'string');
  2824. $this->assertEquals("'a bc'", $result);
  2825. }
  2826. /**
  2827. * testRealQueries method
  2828. *
  2829. * @return void
  2830. */
  2831. public function testRealQueries() {
  2832. $this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample', 'ArticlesTag');
  2833. $Apple = ClassRegistry::init('Apple');
  2834. $Article = ClassRegistry::init('Article');
  2835. $result = $this->Dbo->rawQuery('SELECT color, name FROM ' . $this->Dbo->fullTableName('apples'));
  2836. $this->assertTrue(!empty($result));
  2837. $result = $this->Dbo->fetchRow($result);
  2838. $expected = array($this->Dbo->fullTableName('apples', false, false) => array(
  2839. 'color' => 'Red 1',
  2840. 'name' => 'Red Apple 1'
  2841. ));
  2842. $this->assertEquals($expected, $result);
  2843. $result = $this->Dbo->fetchAll('SELECT name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
  2844. $expected = array(
  2845. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Red Apple 1')),
  2846. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Bright Red Apple')),
  2847. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'green blue')),
  2848. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Test Name')),
  2849. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Blue Green')),
  2850. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'My new apple')),
  2851. array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Some odd color'))
  2852. );
  2853. $this->assertEquals($expected, $result);
  2854. $result = $this->Dbo->field($this->Dbo->fullTableName('apples', false, false), 'SELECT color, name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
  2855. $expected = array(
  2856. 'color' => 'Red 1',
  2857. 'name' => 'Red Apple 1'
  2858. );
  2859. $this->assertEquals($expected, $result);
  2860. $Apple->unbindModel(array(), false);
  2861. $result = $this->Dbo->read($Apple, array(
  2862. 'fields' => array($Apple->escapeField('name')),
  2863. 'conditions' => null,
  2864. 'recursive' => -1
  2865. ));
  2866. $expected = array(
  2867. array('Apple' => array('name' => 'Red Apple 1')),
  2868. array('Apple' => array('name' => 'Bright Red Apple')),
  2869. array('Apple' => array('name' => 'green blue')),
  2870. array('Apple' => array('name' => 'Test Name')),
  2871. array('Apple' => array('name' => 'Blue Green')),
  2872. array('Apple' => array('name' => 'My new apple')),
  2873. array('Apple' => array('name' => 'Some odd color'))
  2874. );
  2875. $this->assertEquals($expected, $result);
  2876. $result = $this->Dbo->read($Article, array(
  2877. 'fields' => array('id', 'user_id', 'title'),
  2878. 'conditions' => null,
  2879. 'recursive' => 1
  2880. ));
  2881. $this->assertTrue(Set::matches('/Article[id=1]', $result));
  2882. $this->assertTrue(Set::matches('/Comment[id=1]', $result));
  2883. $this->assertTrue(Set::matches('/Comment[id=2]', $result));
  2884. $this->assertFalse(Set::matches('/Comment[id=10]', $result));
  2885. }
  2886. /**
  2887. * @expectedException MissingConnectionException
  2888. * @return void
  2889. */
  2890. public function testExceptionOnBrokenConnection() {
  2891. $dbo = new Mysql(array(
  2892. 'driver' => 'mysql',
  2893. 'host' => 'imaginary_host',
  2894. 'login' => 'mark',
  2895. 'password' => 'inyurdatabase',
  2896. 'database' => 'imaginary'
  2897. ));
  2898. }
  2899. /**
  2900. * testStatements method
  2901. *
  2902. * @return void
  2903. */
  2904. public function testUpdateStatements() {
  2905. $this->loadFixtures('Article', 'User');
  2906. $test = ConnectionManager::getDatasource('test');
  2907. $db = $test->config['database'];
  2908. $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
  2909. $this->Dbo->expects($this->at(0))->method('execute')
  2910. ->with("UPDATE `$db`.`articles` SET `field1` = 'value1' WHERE 1 = 1");
  2911. $this->Dbo->expects($this->at(1))->method('execute')
  2912. ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " .
  2913. "(`Article`.`user_id` = `User`.`id`)" .
  2914. " SET `Article`.`field1` = 2 WHERE 2=2");
  2915. $this->Dbo->expects($this->at(2))->method('execute')
  2916. ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " .
  2917. "(`Article`.`user_id` = `User`.`id`)" .
  2918. " SET `Article`.`field1` = 'value' WHERE `index` = 'val'");
  2919. $Article = new Article();
  2920. $this->Dbo->update($Article, array('field1'), array('value1'));
  2921. $this->Dbo->update($Article, array('field1'), array('2'), '2=2');
  2922. $this->Dbo->update($Article, array('field1'), array("'value'"), array('index' => 'val'));
  2923. }
  2924. /**
  2925. * Test deletes with a mock.
  2926. *
  2927. * @return void
  2928. */
  2929. public function testDeleteStatements() {
  2930. $this->loadFixtures('Article', 'User');
  2931. $test = ConnectionManager::getDatasource('test');
  2932. $db = $test->config['database'];
  2933. $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
  2934. $this->Dbo->expects($this->at(0))->method('execute')
  2935. ->with("DELETE FROM `$db`.`articles` WHERE 1 = 1");
  2936. $this->Dbo->expects($this->at(1))->method('execute')
  2937. ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " .
  2938. "ON (`Article`.`user_id` = `User`.`id`)" .
  2939. " WHERE 1 = 1");
  2940. $this->Dbo->expects($this->at(2))->method('execute')
  2941. ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " .
  2942. "ON (`Article`.`user_id` = `User`.`id`)" .
  2943. " WHERE 2=2");
  2944. $Article = new Article();
  2945. $this->Dbo->delete($Article);
  2946. $this->Dbo->delete($Article, true);
  2947. $this->Dbo->delete($Article, '2=2');
  2948. }
  2949. /**
  2950. * Test truncate with a mock.
  2951. *
  2952. * @return void
  2953. */
  2954. public function testTruncateStatements() {
  2955. $this->loadFixtures('Article', 'User');
  2956. $db = ConnectionManager::getDatasource('test');
  2957. $schema = $db->config['database'];
  2958. $Article = new Article();
  2959. $this->Dbo = $this->getMock('Mysql', array('execute'), array($db->config));
  2960. $this->Dbo->expects($this->at(0))->method('execute')
  2961. ->with("TRUNCATE TABLE `$schema`.`articles`");
  2962. $this->Dbo->truncate($Article);
  2963. $this->Dbo->expects($this->at(0))->method('execute')
  2964. ->with("TRUNCATE TABLE `$schema`.`articles`");
  2965. $this->Dbo->truncate('articles');
  2966. // #2355: prevent duplicate prefix
  2967. $this->Dbo->config['prefix'] = 'tbl_';
  2968. $Article->tablePrefix = 'tbl_';
  2969. $this->Dbo->expects($this->at(0))->method('execute')
  2970. ->with("TRUNCATE TABLE `$schema`.`tbl_articles`");
  2971. $this->Dbo->truncate($Article);
  2972. $this->Dbo->expects($this->at(0))->method('execute')
  2973. ->with("TRUNCATE TABLE `$schema`.`tbl_articles`");
  2974. $this->Dbo->truncate('articles');
  2975. }
  2976. /**
  2977. * Test nested transaction
  2978. *
  2979. * @return void
  2980. */
  2981. public function testNestedTransaction() {
  2982. $nested = $this->Dbo->useNestedTransactions;
  2983. $this->Dbo->useNestedTransactions = true;
  2984. if ($this->Dbo->nestedTransactionSupported() === false) {
  2985. $this->Dbo->useNestedTransactions = $nested;
  2986. $this->skipIf(true, 'The MySQL server do not support nested transaction');
  2987. }
  2988. $this->loadFixtures('Inno');
  2989. $model = ClassRegistry::init('Inno');
  2990. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  2991. $model->cacheQueries = false;
  2992. $this->Dbo->cacheMethods = false;
  2993. $this->assertTrue($this->Dbo->begin());
  2994. $this->assertNotEmpty($model->read(null, 1));
  2995. $this->assertTrue($this->Dbo->begin());
  2996. $this->assertTrue($model->delete(1));
  2997. $this->assertEmpty($model->read(null, 1));
  2998. $this->assertTrue($this->Dbo->rollback());
  2999. $this->assertNotEmpty($model->read(null, 1));
  3000. $this->assertTrue($this->Dbo->begin());
  3001. $this->assertTrue($model->delete(1));
  3002. $this->assertEmpty($model->read(null, 1));
  3003. $this->assertTrue($this->Dbo->commit());
  3004. $this->assertEmpty($model->read(null, 1));
  3005. $this->assertTrue($this->Dbo->rollback());
  3006. $this->assertNotEmpty($model->read(null, 1));
  3007. $this->Dbo->useNestedTransactions = $nested;
  3008. }
  3009. }