MysqlTest.php 144 KB

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