MysqlTest.php 151 KB

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