MysqlTest.php 133 KB

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