MysqlTest.php 149 KB

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