MysqlTest.php 146 KB

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