MysqlTest.php 149 KB

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