MysqlTest.php 148 KB

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