MysqlTest.php 152 KB

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