MysqlTest.php 134 KB

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