MysqlTest.php 149 KB

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