| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 3.0.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\Database;
- use Cake\Database\ExpressionInterface;
- use Cake\Database\Expression\IdentifierExpression;
- use Cake\Database\Expression\QueryExpression;
- use Cake\Database\Query;
- use Cake\Database\StatementInterface;
- use Cake\Database\Statement\StatementDecorator;
- use Cake\Database\Type;
- use Cake\Database\TypeMap;
- use Cake\Datasource\ConnectionManager;
- use Cake\TestSuite\TestCase;
- use TestApp\Database\Type\BarType;
- /**
- * Tests Query class
- */
- class QueryTest extends TestCase
- {
- public $fixtures = [
- 'core.Articles',
- 'core.Authors',
- 'core.Comments',
- 'core.Profiles',
- 'core.MenuLinkTrees',
- ];
- public $autoFixtures = false;
- const ARTICLE_COUNT = 3;
- const AUTHOR_COUNT = 4;
- const COMMENT_COUNT = 6;
- /**
- * @var \Cake\Database\Connection
- */
- protected $connection;
- /**
- * @var bool
- */
- protected $autoQuote;
- public function setUp()
- {
- parent::setUp();
- $this->connection = ConnectionManager::get('test');
- $this->autoQuote = $this->connection->getDriver()->isAutoQuotingEnabled();
- }
- public function tearDown()
- {
- parent::tearDown();
- $this->connection->getDriver()->enableAutoQuoting($this->autoQuote);
- unset($this->connection);
- }
- /**
- * Queries need a default type to prevent fatal errors
- * when an uninitialized query has its sql() method called.
- *
- * @return void
- */
- public function testDefaultType()
- {
- $query = new Query($this->connection);
- $this->assertEquals('', $query->sql());
- $this->assertEquals('select', $query->type());
- }
- /**
- * Tests that it is possible to obtain expression results from a query
- *
- * @return void
- */
- public function testSelectFieldsOnly()
- {
- $this->connection->getDriver()->enableAutoQuoting(false);
- $query = new Query($this->connection);
- $result = $query->select('1 + 1')->execute();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertEquals([2], $result->fetch());
- $result->closeCursor();
- //This new field should be appended
- $result = $query->select(['1 + 3'])->execute();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertEquals([2, 4], $result->fetch());
- $result->closeCursor();
- //This should now overwrite all previous fields
- $result = $query->select(['1 + 2', '1 + 5'], true)->execute();
- $this->assertEquals([3, 6], $result->fetch());
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to pass a closure as fields in select()
- *
- * @return void
- */
- public function testSelectClosure()
- {
- $this->connection->getDriver()->enableAutoQuoting(false);
- $query = new Query($this->connection);
- $result = $query->select(function ($q) use ($query) {
- $this->assertSame($query, $q);
- return ['1 + 2', '1 + 5'];
- })->execute();
- $this->assertEquals([3, 6], $result->fetch());
- $result->closeCursor();
- }
- /**
- * Tests it is possible to select fields from tables with no conditions
- *
- * @return void
- */
- public function testSelectFieldsFromTable()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query->select(['body', 'author_id'])->from('articles')->execute();
- $this->assertEquals(['body' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['body' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- //Append more tables to next execution
- $result = $query->select('name')->from(['authors'])->order(['name' => 'desc', 'articles.id' => 'asc'])->execute();
- $this->assertEquals(['body' => 'First Article Body', 'author_id' => 1, 'name' => 'nate'], $result->fetch('assoc'));
- $this->assertEquals(['body' => 'Second Article Body', 'author_id' => 3, 'name' => 'nate'], $result->fetch('assoc'));
- $this->assertEquals(['body' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'], $result->fetch('assoc'));
- $result->closeCursor();
- // Overwrite tables and only fetch from authors
- $result = $query->select('name', true)->from('authors', true)->order(['name' => 'desc'], true)->execute();
- $this->assertEquals(['nate'], $result->fetch());
- $this->assertEquals(['mariano'], $result->fetch());
- $this->assertCount(4, $result);
- $result->closeCursor();
- }
- /**
- * Tests it is possible to select aliased fields
- *
- * @return void
- */
- public function testSelectAliasedFieldsFromTable()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query->select(['text' => 'comment', 'article_id'])->from('comments')->execute();
- $this->assertEquals(['text' => 'First Comment for First Article', 'article_id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['text' => 'Second Comment for First Article', 'article_id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query->select(['text' => 'comment', 'article' => 'article_id'])->from('comments')->execute();
- $this->assertEquals(['text' => 'First Comment for First Article', 'article' => 1], $result->fetch('assoc'));
- $this->assertEquals(['text' => 'Second Comment for First Article', 'article' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $query->select(['text' => 'comment'])->select(['article_id', 'foo' => 'comment']);
- $result = $query->from('comments')->execute();
- $this->assertEquals(
- ['foo' => 'First Comment for First Article', 'text' => 'First Comment for First Article', 'article_id' => 1],
- $result->fetch('assoc')
- );
- $result->closeCursor();
- $query = new Query($this->connection);
- $exp = $query->newExpr('1 + 1');
- $comp = $query->newExpr(['article_id +' => 2]);
- $result = $query->select(['text' => 'comment', 'two' => $exp, 'three' => $comp])
- ->from('comments')->execute();
- $this->assertEquals(['text' => 'First Comment for First Article', 'two' => 2, 'three' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that tables can also be aliased and referenced in the select clause using such alias
- *
- * @return void
- */
- public function testSelectAliasedTables()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query->select(['text' => 'a.body', 'a.author_id'])
- ->from(['a' => 'articles'])->execute();
- $this->assertEquals(['text' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['text' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->select(['name' => 'b.name'])->from(['b' => 'authors'])
- ->order(['text' => 'desc', 'name' => 'desc'])
- ->execute();
- $this->assertEquals(
- ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'],
- $result->fetch('assoc')
- );
- $this->assertEquals(
- ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'mariano'],
- $result->fetch('assoc')
- );
- $result->closeCursor();
- }
- /**
- * Tests it is possible to add joins to a select query
- *
- * @return void
- */
- public function testSelectWithJoins()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->order(['title' => 'asc'])
- ->execute();
- $this->assertCount(3, $result);
- $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->join('authors', [], true)->execute();
- $this->assertCount(12, $result, 'Cross join results in 12 records');
- $result->closeCursor();
- $result = $query->join([
- ['table' => 'authors', 'type' => 'INNER', 'conditions' => $query->newExpr()->equalFields('author_id', 'authors.id')],
- ], [], true)->execute();
- $this->assertCount(3, $result);
- $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests it is possible to add joins to a select query using array or expression as conditions
- *
- * @return void
- */
- public function testSelectWithJoinsConditions()
- {
- $this->loadFixtures('Authors', 'Articles', 'Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => [$query->newExpr()->equalFields('author_id ', 'a.id')]])
- ->order(['title' => 'asc'])
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $conditions = $query->newExpr()->equalFields('author_id', 'a.id');
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $conditions])
- ->order(['title' => 'asc'])
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $time = new \DateTime('2007-03-18 10:50:00');
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'comment' => 'c.comment'])
- ->from('articles')
- ->join(['table' => 'comments', 'alias' => 'c', 'conditions' => ['created <=' => $time]], $types)
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'comment' => 'First Comment for First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that joins can be aliased using array keys
- *
- * @return void
- */
- public function testSelectAliasedJoins()
- {
- $this->loadFixtures('Authors', 'Articles', 'Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['a' => 'authors'])
- ->order(['name' => 'desc', 'articles.id' => 'asc'])
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => 'nate'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'nate'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $conditions = $query->newExpr('author_id = a.id');
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['a' => ['table' => 'authors', 'conditions' => $conditions]])
- ->order(['title' => 'asc'])
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
- $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $time = new \DateTime('2007-03-18 10:45:23');
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->join(['c' => ['table' => 'comments', 'conditions' => ['created' => $time]]], $types)
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => 'First Comment for First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests the leftJoin method
- *
- * @return void
- */
- public function testSelectLeftJoin()
- {
- $this->loadFixtures('Articles', 'Comments');
- $query = new Query($this->connection);
- $time = new \DateTime('2007-03-18 10:45:23');
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->leftJoin(['c' => 'comments'], ['created <' => $time], $types)
- ->execute();
- $this->assertEquals(['title' => 'First Article', 'name' => null], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->leftJoin(['c' => 'comments'], ['created >' => $time], $types)
- ->execute();
- $this->assertEquals(
- ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
- $result->fetch('assoc')
- );
- $result->closeCursor();
- }
- /**
- * Tests the innerJoin method
- *
- * @return void
- */
- public function testSelectInnerJoin()
- {
- $this->loadFixtures('Articles', 'Comments');
- $query = new Query($this->connection);
- $time = new \DateTime('2007-03-18 10:45:23');
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->innerJoin(['c' => 'comments'], ['created <' => $time], $types)
- ->execute();
- $this->assertCount(0, $result->fetchAll());
- $result->closeCursor();
- }
- /**
- * Tests the rightJoin method
- *
- * @return void
- */
- public function testSelectRightJoin()
- {
- $this->loadFixtures('Articles', 'Comments');
- $this->skipIf(
- $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite,
- 'SQLite does not support RIGHT joins'
- );
- $query = new Query($this->connection);
- $time = new \DateTime('2007-03-18 10:45:23');
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->rightJoin(['c' => 'comments'], ['created <' => $time], $types)
- ->execute();
- $this->assertCount(6, $result);
- $this->assertEquals(
- ['title' => null, 'name' => 'First Comment for First Article'],
- $result->fetch('assoc')
- );
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to pass a callable as conditions for a join
- *
- * @return void
- */
- public function testSelectJoinWithCallback()
- {
- $this->loadFixtures('Articles', 'Comments');
- $query = new Query($this->connection);
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['title', 'name' => 'c.comment'])
- ->from('articles')
- ->innerJoin(['c' => 'comments'], function ($exp, $q) use ($query, $types) {
- $this->assertSame($q, $query);
- $exp->add(['created <' => new \DateTime('2007-03-18 10:45:23')], $types);
- return $exp;
- })
- ->execute();
- $this->assertCount(0, $result->fetchAll());
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to pass a callable as conditions for a join
- *
- * @return void
- */
- public function testSelectJoinWithCallback2()
- {
- $this->loadFixtures('Authors', 'Comments');
- $query = new Query($this->connection);
- $types = ['created' => 'datetime'];
- $result = $query
- ->select(['name', 'commentary' => 'comments.comment'])
- ->from('authors')
- ->innerJoin('comments', function ($exp, $q) use ($query, $types) {
- $this->assertSame($q, $query);
- $exp->add(['created >' => new \DateTime('2007-03-18 10:45:23')], $types);
- return $exp;
- })
- ->execute();
- $this->assertEquals(
- ['name' => 'mariano', 'commentary' => 'Second Comment for First Article'],
- $result->fetch('assoc')
- );
- $result->closeCursor();
- }
- /**
- * Tests it is possible to filter a query by using simple AND joined conditions
- *
- * @return void
- */
- public function testSelectSimpleWhere()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id' => 1, 'title' => 'First Article'])
- ->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id' => 100], ['id' => 'integer'])
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorMoreThan()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['comment'])
- ->from('comments')
- ->where(['id >' => 4])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['comment' => 'First Comment for Second Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorLessThan()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id <' => 2])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorLessThanEqual()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id <=' => 2])
- ->execute();
- $this->assertCount(2, $result);
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorMoreThanEqual()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id >=' => 1])
- ->execute();
- $this->assertCount(3, $result);
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorNotEqual()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['id !=' => 2])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorLike()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['title LIKE' => 'First Article'])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorLikeExpansion()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['title like' => '%Article%'])
- ->execute();
- $this->assertCount(3, $result);
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operators and scalar values works
- *
- * @return void
- */
- public function testSelectWhereOperatorNotLike()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(['title not like' => '%Article%'])
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Test that unary expressions in selects are built correctly.
- *
- * @return void
- */
- public function testSelectWhereUnary()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('articles')
- ->where([
- 'title is not' => null,
- 'user_id is' => null,
- ])
- ->sql();
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE \(\(<title>\) IS NOT NULL AND \(<user_id>\) IS NULL\)',
- $result,
- !$this->autoQuote
- );
- }
- /**
- * Tests selecting with conditions and specifying types for those
- *
- * @return void
- */
- public function testSelectWhereTypes()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created >' => new \DateTime('2007-03-18 10:46:00')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(5, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(
- [
- 'created >' => new \DateTime('2007-03-18 10:40:00'),
- 'created <' => new \DateTime('2007-03-18 10:46:00'),
- ],
- ['created' => 'datetime']
- )
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(
- [
- 'id' => '3',
- 'created <' => new \DateTime('2013-01-01 12:00'),
- ],
- ['created' => 'datetime', 'id' => 'integer']
- )
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(
- [
- 'id' => '1',
- 'created <' => new \DateTime('2013-01-01 12:00'),
- ],
- ['created' => 'datetime', 'id' => 'integer']
- )
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests Query::whereNull()
- *
- * @return void
- */
- public function testSelectWhereNull()
- {
- $this->loadFixtures('MenuLinkTrees');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id', 'parent_id'])
- ->from('menu_link_trees')
- ->whereNull(['parent_id'])
- ->execute();
- $this->assertCount(5, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('menu_link_trees')
- ->whereNull($this->connection->newQuery()->select('parent_id'))
- ->execute();
- $this->assertCount(5, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('menu_link_trees')
- ->whereNull('parent_id')
- ->execute();
- $this->assertCount(5, $result);
- $result->closeCursor();
- }
- /**
- * Tests Query::whereNotNull()
- *
- * @return void
- */
- public function testSelectWhereNotNull()
- {
- $this->loadFixtures('MenuLinkTrees');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id', 'parent_id'])
- ->from('menu_link_trees')
- ->whereNotNull(['parent_id'])
- ->execute();
- $this->assertCount(13, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('menu_link_trees')
- ->whereNotNull($this->connection->newQuery()->select('parent_id'))
- ->execute();
- $this->assertCount(13, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('menu_link_trees')
- ->whereNotNull('parent_id')
- ->execute();
- $this->assertCount(13, $result);
- $result->closeCursor();
- }
- /**
- * Tests that passing an array type to any where condition will replace
- * the passed array accordingly as a proper IN condition
- *
- * @return void
- */
- public function testSelectWhereArrayType()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => ['1', '3']], ['id' => 'integer[]'])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that passing an empty array type to any where condition will not
- * result in a SQL error, but an internal exception
- *
- * @return void
- */
- public function testSelectWhereArrayTypeEmpty()
- {
- $this->expectException(\Cake\Database\Exception::class);
- $this->expectExceptionMessage('Impossible to generate condition with empty list of values for field');
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => []], ['id' => 'integer[]'])
- ->execute();
- }
- /**
- * Tests exception message for impossible condition when using an expression
- * @return void
- */
- public function testSelectWhereArrayTypeEmptyWithExpression()
- {
- $this->expectException(\Cake\Database\Exception::class);
- $this->expectExceptionMessage('with empty list of values for field (SELECT 1)');
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp, $q) {
- return $exp->in($q->newExpr('SELECT 1'), []);
- })
- ->execute();
- }
- /**
- * Tests that Query::orWhere() can be used to concatenate conditions with OR
- *
- * @group deprecated
- * @return void
- */
- public function testSelectOrWhere()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- });
- }
- /**
- * Tests that Query::andWhere() can be used to concatenate conditions with AND
- *
- * @return void
- */
- public function testSelectAndWhere()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->andWhere(['id' => 1])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:50:55')], ['created' => 'datetime'])
- ->andWhere(['id' => 2])
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests that combining Query::andWhere() and Query::orWhere() produces
- * correct conditions nesting
- *
- * @group deprecated
- * @return void
- */
- public function testSelectExpressionNesting()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->orWhere(['id' => 2])
- ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->orWhere(['id' => 2])
- ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
- ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(3, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- });
- }
- /**
- * Tests that Query::orWhere() can be used without calling where() before
- *
- * @group deprecated
- * @return void
- */
- public function testSelectOrWhereNoPreviousCondition()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- });
- }
- /**
- * Tests that Query::andWhere() can be used without calling where() before
- *
- * @return void
- */
- public function testSelectAndWhereNoPreviousCondition()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->andWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
- ->andWhere(['id' => 1])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to pass a closure to where() to build a set of
- * conditions and return the expression to be used
- *
- * @return void
- */
- public function testSelectWhereUsingClosure()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->eq('id', 1);
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp
- ->eq('id', 1)
- ->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp
- ->eq('id', 1)
- ->eq('created', new \DateTime('2021-12-30 15:00'), 'datetime');
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests generating tuples in the values side containing closure expressions
- *
- * @return void
- */
- public function testTupleWithClosureExpression()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('comments')
- ->where([
- 'OR' => [
- 'id' => 1,
- function ($exp) {
- return $exp->eq('id', 2);
- },
- ],
- ]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <comments> WHERE \(<id> = :c0 OR <id> = :c1\)',
- $result,
- !$this->autoQuote
- );
- }
- /**
- * Tests that it is possible to pass a closure to andWhere() to build a set of
- * conditions and return the expression to be used
- *
- * @return void
- */
- public function testSelectAndWhereUsingClosure()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => '1'])
- ->andWhere(function ($exp) {
- return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => '1'])
- ->andWhere(function ($exp) {
- return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime');
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to pass a closure to orWhere() to build a set of
- * conditions and return the expression to be used
- *
- * @group deprecated
- * @return void
- */
- public function testSelectOrWhereUsingClosure()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => '1'])
- ->orWhere(function ($exp) {
- return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['id' => '1'])
- ->orWhere(function ($exp) {
- return $exp
- ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
- ->eq('id', 3);
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- });
- }
- /**
- * Tests that expression objects can be used as the field in a comparison
- * and the values will be bound correctly to the query
- *
- * @return void
- */
- public function testSelectWhereUsingExpressionInField()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $field = clone $exp;
- $field->add('SELECT min(id) FROM comments');
- return $exp
- ->eq($field, 100, 'integer');
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- }
- /**
- * Tests using where conditions with operator methods
- *
- * @return void
- */
- public function testSelectWhereOperatorMethods()
- {
- $this->loadFixtures('Articles', 'Comments', 'Authors');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->gt('id', 1);
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['title' => 'Second Article'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->lt('id', 2);
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->lte('id', 2);
- })
- ->execute();
- $this->assertCount(2, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->gte('id', 1);
- })
- ->execute();
- $this->assertCount(3, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->lte('id', 1);
- })
- ->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->notEq('id', 2);
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->like('title', 'First Article');
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->like('title', '%Article%');
- })
- ->execute();
- $this->assertCount(3, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['title'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->notLike('title', '%Article%');
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->isNull('published');
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->isNotNull('published');
- })
- ->execute();
- $this->assertCount(6, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->in('published', ['Y', 'N']);
- })
- ->execute();
- $this->assertCount(6, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->in(
- 'created',
- [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
- 'datetime'
- );
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->notIn(
- 'created',
- [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
- 'datetime'
- );
- })
- ->execute();
- $this->assertCount(4, $result);
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that calling "in" and "notIn" will cast the passed values to an array
- *
- * @return void
- */
- public function testInValueCast()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
- })
- ->execute();
- $this->assertCount(5, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $this->assertEquals(['id' => 4], $result->fetch('assoc'));
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp, $q) {
- return $exp->in(
- 'created',
- $q->newExpr("'2007-03-18 10:45:23'"),
- 'datetime'
- );
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp, $q) {
- return $exp->notIn(
- 'created',
- $q->newExpr("'2007-03-18 10:45:23'"),
- 'datetime'
- );
- })
- ->execute();
- $this->assertCount(5, $result);
- $result->closeCursor();
- }
- /**
- * Tests that calling "in" and "notIn" will cast the passed values to an array
- *
- * @return void
- */
- public function testInValueCast2()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created IN' => '2007-03-18 10:45:23'])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(['created NOT IN' => '2007-03-18 10:45:23'])
- ->execute();
- $this->assertCount(5, $result);
- $result->closeCursor();
- }
- /**
- * Tests that IN clauses generate correct placeholders
- *
- * @return void
- */
- public function testInClausePlaceholderGeneration()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('comments')
- ->where(['id IN' => [1, 2]])
- ->sql();
- $bindings = $query->getValueBinder()->bindings();
- $this->assertArrayHasKey(':c0', $bindings);
- $this->assertEquals('c0', $bindings[':c0']['placeholder']);
- $this->assertArrayHasKey(':c1', $bindings);
- $this->assertEquals('c1', $bindings[':c1']['placeholder']);
- }
- /**
- * Tests where() with callable types.
- *
- * @return void
- */
- public function testWhereCallables()
- {
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->where([
- 'id' => '\Cake\Error\Debugger::dump',
- 'title' => ['\Cake\Error\Debugger', 'dump'],
- 'author_id' => function ($exp) {
- return 1;
- },
- ]);
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE \(<id> = :c0 AND <title> = :c1 AND <author_id> = :c2\)',
- $query->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Tests that empty values don't set where clauses.
- *
- * @return void
- */
- public function testWhereEmptyValues()
- {
- $query = new Query($this->connection);
- $query->from('comments')
- ->where('');
- $this->assertCount(0, $query->clause('where'));
- $query->where([]);
- $this->assertCount(0, $query->clause('where'));
- }
- /**
- * Tests that it is possible to use a between expression
- * in a where condition
- *
- * @return void
- */
- public function testWhereWithBetween()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->between('id', 5, 6, 'integer');
- })
- ->execute();
- $this->assertCount(2, $result);
- $first = $result->fetch('assoc');
- $this->assertEquals(5, $first['id']);
- $second = $result->fetch('assoc');
- $this->assertEquals(6, $second['id']);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to use a between expression
- * in a where condition with a complex data type
- *
- * @return void
- */
- public function testWhereWithBetweenComplex()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $from = new \DateTime('2007-03-18 10:51:00');
- $to = new \DateTime('2007-03-18 10:54:00');
- return $exp->between('created', $from, $to, 'datetime');
- })
- ->execute();
- $this->assertCount(2, $result);
- $first = $result->fetch('assoc');
- $this->assertEquals(4, $first['id']);
- $second = $result->fetch('assoc');
- $this->assertEquals(5, $second['id']);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to use an expression object
- * as the field for a between expression
- *
- * @return void
- */
- public function testWhereWithBetweenWithExpressionField()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp, $q) {
- $field = $q->func()->coalesce([new IdentifierExpression('id'), 1 => 'literal']);
- return $exp->between($field, 5, 6, 'integer');
- })
- ->execute();
- $this->assertCount(2, $result);
- $first = $result->fetch('assoc');
- $this->assertEquals(5, $first['id']);
- $second = $result->fetch('assoc');
- $this->assertEquals(6, $second['id']);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to use an expression object
- * as any of the parts of the between expression
- *
- * @return void
- */
- public function testWhereWithBetweenWithExpressionParts()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp, $q) {
- $from = $q->newExpr("'2007-03-18 10:51:00'");
- $to = $q->newExpr("'2007-03-18 10:54:00'");
- return $exp->between('created', $from, $to);
- })
- ->execute();
- $this->assertCount(2, $result);
- $first = $result->fetch('assoc');
- $this->assertEquals(4, $first['id']);
- $second = $result->fetch('assoc');
- $this->assertEquals(5, $second['id']);
- $result->closeCursor();
- }
- /**
- * Tests nesting query expressions both using arrays and closures
- *
- * @return void
- */
- public function testSelectExpressionComposition()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $and = $exp->and(['id' => 2, 'id >' => 1]);
- return $exp->add($and);
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $and = $exp->and(['id' => 2, 'id <' => 2]);
- return $exp->add($and);
- })
- ->execute();
- $this->assertCount(0, $result);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $and = $exp->and(function ($and) {
- return $and->eq('id', 1)->gt('id', 0);
- });
- return $exp->add($and);
- })
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $or = $exp->or(['id' => 1]);
- $and = $exp->and(['id >' => 2, 'id <' => 4]);
- return $or->add($and);
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- $or = $exp->or(function ($or) {
- return $or->eq('id', 1)->eq('id', 2);
- });
- return $or;
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that conditions can be nested with an unary operator using the array notation
- * and the not() method
- *
- * @return void
- */
- public function testSelectWhereNot()
- {
- $this->loadFixtures('Articles', 'Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->not(
- $exp->and(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
- );
- })
- ->execute();
- $this->assertCount(5, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->where(function ($exp) {
- return $exp->not(
- $exp->and(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
- );
- })
- ->execute();
- $this->assertCount(6, $result);
- $result->closeCursor();
- }
- /**
- * Tests that conditions can be nested with an unary operator using the array notation
- * and the not() method
- *
- * @return void
- */
- public function testSelectWhereNot2()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('articles')
- ->where([
- 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3],
- ])
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests whereInArray() and its input types.
- *
- * @return void
- */
- public function testWhereInArray()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->whereInList('id', [2, 3])
- ->execute();
- $sql = $query->sql();
- $result = $query->execute();
- $this->assertEquals(['id' => '2'], $result->fetch('assoc'));
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE <id> in \\(:c0,:c1\\)',
- $sql,
- !$this->autoQuote
- );
- }
- /**
- * Tests whereInArray() and empty array input.
- *
- * @return void
- */
- public function testWhereInArrayEmpty()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->whereInList('id', [], ['allowEmpty' => true])
- ->execute();
- $sql = $query->sql();
- $result = $query->execute();
- $this->assertFalse($result->fetch('assoc'));
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE 1=0',
- $sql,
- !$this->autoQuote
- );
- }
- /**
- * Tests whereNotInArray() and its input types.
- *
- * @return void
- */
- public function testWhereNotInArray()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->whereNotInList('id', [1, 3])
- ->execute();
- $sql = $query->sql();
- $result = $query->execute();
- $this->assertEquals(['id' => '2'], $result->fetch('assoc'));
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE <id> not in \\(:c0,:c1\\)',
- $sql,
- !$this->autoQuote
- );
- }
- /**
- * Tests whereNotInArray() and empty array input.
- *
- * @return void
- */
- public function testWhereNotInArrayEmpty()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->whereNotInList('id', [], ['allowEmpty' => true])
- ->execute();
- $sql = $query->sql();
- $result = $query->execute();
- $this->assertEquals(['id' => '1'], $result->fetch('assoc'));
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> WHERE \(<id>\) IS NOT NULL',
- $sql,
- !$this->autoQuote
- );
- }
- /**
- * Tests order() method both with simple fields and expressions
- *
- * @return void
- */
- public function testSelectOrderBy()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id'])
- ->from('comments')
- ->order(['id' => 'desc'])
- ->execute();
- $this->assertEquals(['id' => 6], $result->fetch('assoc'));
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $this->assertEquals(['id' => 4], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->order(['id' => 'asc'])->execute();
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->order(['comment' => 'asc'])->execute();
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->order(['comment' => 'asc'], true)->execute();
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $this->assertEquals(['id' => 4], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query->order(['user_id' => 'asc', 'created' => 'desc'], true)
- ->execute();
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $this->assertEquals(['id' => 4], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- $expression = $query->newExpr(['(id + :offset) % 2']);
- $result = $query
- ->order([$expression, 'id' => 'desc'], true)
- ->bind(':offset', 1, null)
- ->execute();
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- $result = $query
- ->order($expression, true)
- ->order(['id' => 'asc'])
- ->bind(':offset', 1, null)
- ->execute();
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $this->assertEquals(['id' => 5], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Test that order() being a string works.
- *
- * @return void
- */
- public function testSelectOrderByString()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->order('id asc');
- $result = $query->execute();
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result->closeCursor();
- }
- /**
- * Test that order() works with an associative array which contains extra values.
- *
- * @return void
- */
- public function testSelectOrderByAssociativeArrayContainingExtraExpressions()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->order([
- 'id' => 'desc -- Comment',
- ]);
- $result = $query->execute();
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $result->closeCursor();
- });
- }
- /**
- * Tests that order() works with closures.
- *
- * @return void
- */
- public function testSelectOrderByClosure()
- {
- $query = new Query($this->connection);
- $query
- ->select('*')
- ->from('articles')
- ->order(function ($exp, $q) use ($query) {
- $this->assertInstanceOf(QueryExpression::class, $exp);
- $this->assertSame($query, $q);
- return ['id' => 'ASC'];
- });
- $this->assertQuotedQuery(
- 'SELECT \* FROM <articles> ORDER BY <id> ASC',
- $query->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $query
- ->select('*')
- ->from('articles')
- ->order(function ($exp) {
- return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
- });
- $this->assertQuotedQuery(
- 'SELECT \* FROM <articles> ORDER BY id % 2 = 0, <title> ASC',
- $query->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $query
- ->select('*')
- ->from('articles')
- ->order(function ($exp) {
- return $exp->add('a + b');
- });
- $this->assertQuotedQuery(
- 'SELECT \* FROM <articles> ORDER BY a \+ b',
- $query->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $query
- ->select('*')
- ->from('articles')
- ->order(function ($exp, $q) {
- return $q->func()->sum('a');
- });
- $this->assertQuotedQuery(
- 'SELECT \* FROM <articles> ORDER BY SUM\(a\)',
- $query->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Test orderAsc() and its input types.
- *
- * @return void
- */
- public function testSelectOrderAsc()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->orderAsc('id');
- $sql = $query->sql();
- $result = $query->execute()->fetchAll('assoc');
- $expected = [
- ['id' => 1],
- ['id' => 2],
- ['id' => 3],
- ];
- $this->assertEquals($expected, $result);
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> ORDER BY <id> ASC',
- $sql,
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->orderAsc($query->func()->concat(['id' => 'identifier', '3']));
- $result = $query->execute()->fetchAll('assoc');
- $expected = [
- ['id' => 1],
- ['id' => 2],
- ['id' => 3],
- ];
- $this->assertEquals($expected, $result);
- }
- /**
- * Test orderDesc() and its input types.
- *
- * @return void
- */
- public function testSelectOrderDesc()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->orderDesc('id');
- $sql = $query->sql();
- $result = $query->execute()->fetchAll('assoc');
- $expected = [
- ['id' => 3],
- ['id' => 2],
- ['id' => 1],
- ];
- $this->assertEquals($expected, $result);
- $this->assertQuotedQuery(
- 'SELECT <id> FROM <articles> ORDER BY <id> DESC',
- $sql,
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $query->select(['id'])
- ->from('articles')
- ->orderDesc($query->func()->concat(['id' => 'identifier', '3']));
- $result = $query->execute()->fetchAll('assoc');
- $expected = [
- ['id' => 3],
- ['id' => 2],
- ['id' => 1],
- ];
- $this->assertEquals($expected, $result);
- }
- /**
- * Tests that group by fields can be passed similar to select fields
- * and that it sends the correct query to the database
- *
- * @return void
- */
- public function testSelectGroup()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
- ->group('author_id')
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result = $query->select(['total' => 'count(title)', 'name'], true)
- ->group(['name'], true)
- ->order(['total' => 'asc'])
- ->execute();
- $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result = $query->select(['articles.id'])
- ->group(['articles.id'])
- ->execute();
- $this->assertCount(3, $result);
- }
- /**
- * Tests that it is possible to select distinct rows
- *
- * @return void
- */
- public function testSelectDistinct()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['author_id'])
- ->from(['a' => 'articles'])
- ->execute();
- $this->assertCount(3, $result);
- $result = $query->distinct()->execute();
- $this->assertCount(2, $result);
- $result = $query->select(['id'])->distinct(false)->execute();
- $this->assertCount(3, $result);
- }
- /**
- * Tests that it is possible to select distinct rows, even filtering by one column
- * this is testing that there is a specific implementation for DISTINCT ON
- *
- * @return void
- */
- public function testSelectDistinctON()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id', 'author_id'])
- ->distinct(['author_id'])
- ->from(['a' => 'articles'])
- ->order(['author_id' => 'ASC'])
- ->execute();
- $this->assertCount(2, $result);
- $results = $result->fetchAll('assoc');
- $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
- $this->assertEquals(
- [3, 1],
- collection($results)->sortBy('author_id')->extract('author_id')->toList()
- );
- $query = new Query($this->connection);
- $result = $query
- ->select(['id', 'author_id'])
- ->distinct('author_id')
- ->from(['a' => 'articles'])
- ->order(['author_id' => 'ASC'])
- ->execute();
- $this->assertCount(2, $result);
- $results = $result->fetchAll('assoc');
- $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
- $this->assertEquals(
- [3, 1],
- collection($results)->sortBy('author_id')->extract('author_id')->toList()
- );
- }
- /**
- * Test use of modifiers in the query
- *
- * Testing the generated SQL since the modifiers are usually different per driver
- *
- * @return void
- */
- public function testSelectModifiers()
- {
- $query = new Query($this->connection);
- $result = $query
- ->select(['city', 'state', 'country'])
- ->from(['addresses'])
- ->modifier('DISTINCTROW');
- $this->assertQuotedQuery(
- 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query
- ->select(['city', 'state', 'country'])
- ->from(['addresses'])
- ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
- $this->assertQuotedQuery(
- 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query
- ->select(['city', 'state', 'country'])
- ->from(['addresses'])
- ->modifier('DISTINCTROW')
- ->modifier('SQL_NO_CACHE');
- $this->assertQuotedQuery(
- 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
- $result->sql(),
- true
- );
- $query = new Query($this->connection);
- $result = $query
- ->select(['city', 'state', 'country'])
- ->from(['addresses'])
- ->modifier(['TOP 10']);
- $this->assertQuotedQuery(
- 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
- $result->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Tests that having() behaves pretty much the same as the where() method
- *
- * @return void
- */
- public function testSelectHaving()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
- ->execute();
- $expected = [['total' => 1, 'author_id' => 3]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result = $query->having(function ($e) {
- return $e->add('count(author_id) = 1 + 1');
- }, [], true)
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- }
- /**
- * Tests that Query::orHaving() can be used to concatenate conditions with OR
- * in the having clause
- *
- * @group deprecated
- * @return void
- */
- public function testSelectOrHaving()
- {
- $this->deprecated(function () {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
- ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
- ->execute();
- $expected = [['total' => 1, 'author_id' => 3]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
- ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
- ->orHaving(function ($e) {
- return $e->add('count(author_id) = 1 + 1');
- })
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- });
- }
- /**
- * Tests that Query::andHaving() can be used to concatenate conditions with AND
- * in the having clause
- *
- * @return void
- */
- public function testSelectAndHaving()
- {
- $this->loadFixtures('Authors', 'Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
- ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
- ->execute();
- $this->assertCount(0, $result);
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
- ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
- ->execute();
- $expected = [['total' => 2, 'author_id' => 1]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $result = $query
- ->select(['total' => 'count(author_id)', 'author_id'])
- ->from('articles')
- ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
- ->group('author_id')
- ->andHaving(function ($e) {
- return $e->add('count(author_id) = 2 - 1');
- })
- ->execute();
- $expected = [['total' => 1, 'author_id' => 3]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- }
- /**
- * Tests selecting rows using a limit clause
- *
- * @return void
- */
- public function testSelectLimit()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query->select('id')->from('articles')->limit(1)->execute();
- $this->assertCount(1, $result);
- $query = new Query($this->connection);
- $result = $query->select('id')->from('articles')->limit(2)->execute();
- $this->assertCount(2, $result);
- }
- /**
- * Tests selecting rows combining a limit and offset clause
- *
- * @return void
- */
- public function testSelectOffset()
- {
- $this->loadFixtures('Articles', 'Comments');
- $query = new Query($this->connection);
- $result = $query->select('id')->from('comments')
- ->limit(1)
- ->offset(0)
- ->order(['id' => 'ASC'])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $result = $query->select('id')->from('comments')
- ->limit(1)
- ->offset(1)
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $result = $query->select('id')->from('comments')
- ->limit(1)
- ->offset(2)
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $result = $query->select('id')->from('articles')
- ->order(['id' => 'DESC'])
- ->limit(1)
- ->offset(0)
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $result = $query->limit(2)->offset(1)->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $query->select('id')->from('comments')
- ->limit(1)
- ->offset(1)
- ->execute();
- $dirty = $this->readAttribute($query, '_dirty');
- $this->assertFalse($dirty);
- $query->offset(2);
- $dirty = $this->readAttribute($query, '_dirty');
- $this->assertTrue($dirty);
- }
- /**
- * Test Pages number.
- *
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Pages must start at 1.
- * @return void
- */
- public function testPageShouldStartAtOne()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query->from('comments')->page(0);
- }
- /**
- * Test selecting rows using the page() method.
- *
- * @return void
- */
- public function testSelectPage()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query->select('id')->from('comments')
- ->limit(1)
- ->page(1)
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $result = $query->select('id')->from('comments')
- ->limit(1)
- ->page(2)
- ->order(['id' => 'asc'])
- ->execute();
- $this->assertCount(1, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $query->select('id')->from('comments')->page(3, 10);
- $this->assertEquals(10, $query->clause('limit'));
- $this->assertEquals(20, $query->clause('offset'));
- $query = new Query($this->connection);
- $query->select('id')->from('comments')->page(1);
- $this->assertEquals(25, $query->clause('limit'));
- $this->assertEquals(0, $query->clause('offset'));
- $query->select('id')->from('comments')->page(2);
- $this->assertEquals(25, $query->clause('limit'));
- $this->assertEquals(25, $query->clause('offset'));
- }
- /**
- * Test selecting rows using the page() method and ordering the results
- * by a calculated column.
- *
- * @return void
- */
- public function testSelectPageWithOrder()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query
- ->select([
- 'id',
- 'ids_added' => $query->newExpr()->add('(user_id + article_id)'),
- ])
- ->from('comments')
- ->order(['ids_added' => 'asc'])
- ->limit(2)
- ->page(3)
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(
- [
- ['id' => '6', 'ids_added' => '4'],
- ['id' => '2', 'ids_added' => '5'],
- ],
- $result->fetchAll('assoc')
- );
- }
- /**
- * Tests that Query objects can be included inside the select clause
- * and be used as a normal field, including binding any passed parameter
- *
- * @return void
- */
- public function testSubqueryInSelect()
- {
- $this->loadFixtures('Authors', 'Articles', 'Comments');
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select('name')
- ->from(['b' => 'authors'])
- ->where([$query->newExpr()->equalFields('b.id', 'a.id')]);
- $result = $query
- ->select(['id', 'name' => $subquery])
- ->from(['a' => 'comments'])->execute();
- $expected = [
- ['id' => 1, 'name' => 'mariano'],
- ['id' => 2, 'name' => 'nate'],
- ['id' => 3, 'name' => 'larry'],
- ['id' => 4, 'name' => 'garrett'],
- ['id' => 5, 'name' => null],
- ['id' => 6, 'name' => null],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select('name')
- ->from(['b' => 'authors'])
- ->where(['name' => 'mariano'], ['name' => 'string']);
- $result = $query
- ->select(['id', 'name' => $subquery])
- ->from(['a' => 'articles'])->execute();
- $expected = [
- ['id' => 1, 'name' => 'mariano'],
- ['id' => 2, 'name' => 'mariano'],
- ['id' => 3, 'name' => 'mariano'],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- }
- /**
- * Tests that Query objects can be included inside the from clause
- * and be used as a normal table, including binding any passed parameter
- *
- * @return void
- */
- public function testSuqueryInFrom()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select(['id', 'comment'])
- ->from('comments')
- ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
- $result = $query
- ->select(['say' => 'comment'])
- ->from(['b' => $subquery])
- ->where(['id !=' => 3])
- ->execute();
- $expected = [
- ['say' => 'Second Comment for First Article'],
- ['say' => 'Fourth Comment for First Article'],
- ['say' => 'First Comment for Second Article'],
- ['say' => 'Second Comment for Second Article'],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- }
- /**
- * Tests that Query objects can be included inside the where clause
- * and be used as a normal condition, including binding any passed parameter
- *
- * @return void
- */
- public function testSubqueryInWhere()
- {
- $this->loadFixtures('Authors', 'Comments');
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select(['id'])
- ->from('authors')
- ->where(['id' => 1]);
- $result = $query
- ->select(['name'])
- ->from(['authors'])
- ->where(['id !=' => $subquery])
- ->execute();
- $expected = [
- ['name' => 'nate'],
- ['name' => 'larry'],
- ['name' => 'garrett'],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result->closeCursor();
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select(['id'])
- ->from('comments')
- ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
- $result = $query
- ->select(['name'])
- ->from(['authors'])
- ->where(['id not in' => $subquery])
- ->execute();
- $expected = [
- ['name' => 'mariano'],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $result->closeCursor();
- }
- /**
- * Tests that Query objects can be included inside the where clause
- * and be used as a EXISTS and NOT EXISTS conditions
- *
- * @return void
- */
- public function testSubqueryExistsWhere()
- {
- $this->loadFixtures('Articles', 'Authors');
- $query = new Query($this->connection);
- $subQuery = (new Query($this->connection))
- ->select(['id'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->equalFields('authors.id', 'articles.author_id');
- });
- $result = $query
- ->select(['id'])
- ->from('authors')
- ->where(function ($exp) use ($subQuery) {
- return $exp->exists($subQuery);
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 1], $result->fetch('assoc'));
- $this->assertEquals(['id' => 3], $result->fetch('assoc'));
- $query = new Query($this->connection);
- $subQuery = (new Query($this->connection))
- ->select(['id'])
- ->from('articles')
- ->where(function ($exp) {
- return $exp->equalFields('authors.id', 'articles.author_id');
- });
- $result = $query
- ->select(['id'])
- ->from('authors')
- ->where(function ($exp) use ($subQuery) {
- return $exp->notExists($subQuery);
- })
- ->execute();
- $this->assertCount(2, $result);
- $this->assertEquals(['id' => 2], $result->fetch('assoc'));
- $this->assertEquals(['id' => 4], $result->fetch('assoc'));
- }
- /**
- * Tests that it is possible to use a subquery in a join clause
- *
- * @return void
- */
- public function testSubqueryInJoin()
- {
- $this->loadFixtures('Authors', 'Articles');
- $subquery = (new Query($this->connection))->select('*')->from('authors');
- $query = new Query($this->connection);
- $result = $query
- ->select(['title', 'name'])
- ->from('articles')
- ->join(['b' => $subquery])
- ->execute();
- $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
- $result->closeCursor();
- $subquery->where(['id' => 1]);
- $result = $query->execute();
- $this->assertCount(3, $result);
- $result->closeCursor();
- $query->join(['b' => ['table' => $subquery, 'conditions' => [$query->newExpr()->equalFields('b.id', 'articles.id')]]], [], true);
- $result = $query->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to one or multiple UNION statements in a query
- *
- * @return void
- */
- public function testUnion()
- {
- $this->loadFixtures('Authors', 'Articles', 'Comments');
- $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
- $query = new Query($this->connection);
- $result = $query->select(['id', 'comment'])
- ->from(['c' => 'comments'])
- ->union($union)
- ->execute();
- $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
- $rows = $result->fetchAll();
- $result->closeCursor();
- $union->select(['foo' => 'id', 'bar' => 'title']);
- $union = (new Query($this->connection))
- ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
- ->from(['b' => 'authors'])
- ->where(['id ' => 1])
- ->order(['id' => 'desc']);
- $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
- $result = $query->execute();
- $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
- $this->assertNotEquals($rows, $result->fetchAll());
- $result->closeCursor();
- $union = (new Query($this->connection))
- ->select(['id', 'title'])
- ->from(['c' => 'articles']);
- $query->select(['id', 'comment'], true)->union($union, true);
- $result = $query->execute();
- $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
- $this->assertEquals($rows, $result->fetchAll());
- $result->closeCursor();
- }
- /**
- * Tests that it is possible to run unions with order statements
- *
- * @return void
- */
- public function testUnionOrderBy()
- {
- $this->loadFixtures('Articles', 'Comments');
- $this->skipIf(
- ($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite ||
- $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver),
- 'Driver does not support ORDER BY in UNIONed queries.'
- );
- $union = (new Query($this->connection))
- ->select(['id', 'title'])
- ->from(['a' => 'articles'])
- ->order(['a.id' => 'asc']);
- $query = new Query($this->connection);
- $result = $query->select(['id', 'comment'])
- ->from(['c' => 'comments'])
- ->order(['c.id' => 'asc'])
- ->union($union)
- ->execute();
- $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
- $rows = $result->fetchAll();
- $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
- }
- /**
- * Tests that UNION ALL can be built by setting the second param of union() to true
- *
- * @return void
- */
- public function testUnionAll()
- {
- $this->loadFixtures('Authors', 'Articles', 'Comments');
- $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
- $query = new Query($this->connection);
- $result = $query->select(['id', 'comment'])
- ->from(['c' => 'comments'])
- ->union($union)
- ->execute();
- $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
- $rows = $result->fetchAll();
- $result->closeCursor();
- $union->select(['foo' => 'id', 'bar' => 'title']);
- $union = (new Query($this->connection))
- ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
- ->from(['b' => 'authors'])
- ->where(['id ' => 1])
- ->order(['id' => 'desc']);
- $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
- $result = $query->execute();
- $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
- $this->assertNotEquals($rows, $result->fetchAll());
- $result->closeCursor();
- }
- /**
- * Tests stacking decorators for results and resetting the list of decorators
- *
- * @return void
- */
- public function testDecorateResults()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query
- ->select(['id', 'title'])
- ->from('articles')
- ->order(['id' => 'ASC'])
- ->decorateResults(function ($row) {
- $row['modified_id'] = $row['id'] + 1;
- return $row;
- })
- ->execute();
- while ($row = $result->fetch('assoc')) {
- $this->assertEquals($row['id'] + 1, $row['modified_id']);
- }
- $result = $query->decorateResults(function ($row) {
- $row['modified_id']--;
- return $row;
- })->execute();
- while ($row = $result->fetch('assoc')) {
- $this->assertEquals($row['id'], $row['modified_id']);
- }
- $result->closeCursor();
- $result = $query
- ->decorateResults(function ($row) {
- $row['foo'] = 'bar';
- return $row;
- }, true)
- ->execute();
- while ($row = $result->fetch('assoc')) {
- $this->assertEquals('bar', $row['foo']);
- $this->assertArrayNotHasKey('modified_id', $row);
- }
- $results = $query->decorateResults(null, true)->execute();
- while ($row = $results->fetch('assoc')) {
- $this->assertArrayNotHasKey('foo', $row);
- $this->assertArrayNotHasKey('modified_id', $row);
- }
- $results->closeCursor();
- }
- /**
- * Test a basic delete using from()
- *
- * @return void
- */
- public function testDeleteWithFrom()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $query->delete()
- ->from('authors')
- ->where('1 = 1');
- $result = $query->sql();
- $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertCount(self::AUTHOR_COUNT, $result);
- $result->closeCursor();
- }
- /**
- * Test delete with from and alias.
- *
- * @return void
- */
- public function testDeleteWithAliasedFrom()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $query->delete()
- ->from(['a ' => 'authors'])
- ->where(['a.id !=' => 99]);
- $result = $query->sql();
- $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertCount(self::AUTHOR_COUNT, $result);
- $result->closeCursor();
- }
- /**
- * Test a basic delete with no from() call.
- *
- * @return void
- */
- public function testDeleteNoFrom()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $query->delete('authors')
- ->where('1 = 1');
- $result = $query->sql();
- $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
- $this->assertCount(self::AUTHOR_COUNT, $result);
- $result->closeCursor();
- }
- /**
- * Tests that delete queries that contain joins do trigger a notice,
- * warning about possible incompatibilities with aliases being removed
- * from the conditions.
- *
- *
- * @return void
- */
- public function testDeleteRemovingAliasesCanBreakJoins()
- {
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.');
- $query = new Query($this->connection);
- $query
- ->delete('authors')
- ->from(['a ' => 'authors'])
- ->innerJoin('articles')
- ->where(['a.id' => 1]);
- $query->sql();
- }
- /**
- * Tests that aliases are stripped from delete query conditions
- * where possible.
- *
- * @return void
- */
- public function testDeleteStripAliasesFromConditions()
- {
- $query = new Query($this->connection);
- $query
- ->delete(['a' => 'authors'])
- ->where([
- 'OR' => [
- 'a.id' => 1,
- 'a.name IS' => null,
- 'a.email IS NOT' => null,
- 'AND' => [
- 'b.name NOT IN' => ['foo', 'bar'],
- 'OR' => [
- $query->newExpr()->eq(new IdentifierExpression('c.name'), 'zap'),
- 'd.name' => 'baz',
- (new Query($this->connection))->select(['e.name'])->where(['e.name' => 'oof']),
- ],
- ],
- ],
- ]);
- $this->assertQuotedQuery(
- 'DELETE FROM <authors> WHERE \(' .
- '<id> = :c0 OR \(<name>\) IS NULL OR \(<email>\) IS NOT NULL OR \(' .
- '<name> not in \(:c1,:c2\) AND \(' .
- '\(<name>\) = :c3 OR <name> = :c4 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c5\)' .
- '\)' .
- '\)' .
- '\)',
- $query->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Test setting select() & delete() modes.
- *
- * @return void
- */
- public function testSelectAndDeleteOnSameQuery()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $result = $query->select()
- ->delete('authors')
- ->where('1 = 1');
- $result = $query->sql();
- $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
- $this->assertContains(' WHERE 1 = 1', $result);
- }
- /**
- * Test a simple update.
- *
- * @return void
- */
- public function testUpdateSimple()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $query->update('authors')
- ->set('name', 'mark')
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Test update with type checking
- * by passing an array as table arg
- *
- *
- * @return void
- */
- public function testUpdateArgTypeChecking()
- {
- $this->expectException(\InvalidArgumentException::class);
- $query = new Query($this->connection);
- $query->update(['Articles']);
- }
- /**
- * Test update with multiple fields.
- *
- * @return void
- */
- public function testUpdateMultipleFields()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->update('articles')
- ->set('title', 'mark', 'string')
- ->set('body', 'some text', 'string')
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
- $result,
- !$this->autoQuote
- );
- $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Test updating multiple fields with an array.
- *
- * @return void
- */
- public function testUpdateMultipleFieldsArray()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->update('articles')
- ->set([
- 'title' => 'mark',
- 'body' => 'some text',
- ], ['title' => 'string', 'body' => 'string'])
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
- $result,
- !$this->autoQuote
- );
- $this->assertQuotedQuery('WHERE <id> = :', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Test updates with an expression.
- *
- * @return void
- */
- public function testUpdateWithExpression()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $expr = $query->newExpr()->equalFields('article_id', 'user_id');
- $query->update('comments')
- ->set($expr)
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'UPDATE <comments> SET <article_id> = \(<user_id>\) WHERE <id> = :',
- $result,
- !$this->autoQuote
- );
- $result = $query->execute();
- $this->assertCount(1, $result);
- $result->closeCursor();
- }
- /**
- * Test update with array fields and types.
- *
- * @return void
- */
- public function testUpdateArrayFields()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $date = new \DateTime();
- $query->update('comments')
- ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
- $result,
- !$this->autoQuote
- );
- $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertCount(1, $result);
- $query = new Query($this->connection);
- $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
- $result = $result->fetchAll('assoc')[0]['created'];
- $this->assertStringStartsWith($date->format('Y-m-d'), $result);
- }
- /**
- * Test update with callable in set
- *
- * @return void
- */
- public function testUpdateSetCallable()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $date = new \DateTime();
- $query->update('comments')
- ->set(function ($exp) use ($date) {
- return $exp
- ->eq('comment', 'mark')
- ->eq('created', $date, 'date');
- })
- ->where(['id' => 1]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
- $result,
- !$this->autoQuote
- );
- $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
- $result = $query->execute();
- $this->assertCount(1, $result);
- }
- /**
- * Tests that aliases are stripped from update query conditions
- * where possible.
- *
- * @return void
- */
- public function testUpdateStripAliasesFromConditions()
- {
- $query = new Query($this->connection);
- $query
- ->update('authors')
- ->set(['name' => 'name'])
- ->where([
- 'OR' => [
- 'a.id' => 1,
- 'a.name IS' => null,
- 'a.email IS NOT' => null,
- 'AND' => [
- 'b.name NOT IN' => ['foo', 'bar'],
- 'OR' => [
- $query->newExpr()->eq(new IdentifierExpression('c.name'), 'zap'),
- 'd.name' => 'baz',
- (new Query($this->connection))->select(['e.name'])->where(['e.name' => 'oof']),
- ],
- ],
- ],
- ]);
- $this->assertQuotedQuery(
- 'UPDATE <authors> SET <name> = :c0 WHERE \(' .
- '<id> = :c1 OR \(<name>\) IS NULL OR \(<email>\) IS NOT NULL OR \(' .
- '<name> not in \(:c2,:c3\) AND \(' .
- '\(<name>\) = :c4 OR <name> = :c5 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c6\)' .
- '\)' .
- '\)' .
- '\)',
- $query->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Tests that update queries that contain joins do trigger a notice,
- * warning about possible incompatibilities with aliases being removed
- * from the conditions.
- *
- * @return void
- */
- public function testUpdateRemovingAliasesCanBreakJoins()
- {
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.');
- $query = new Query($this->connection);
- $query
- ->update('authors')
- ->set(['name' => 'name'])
- ->innerJoin('articles')
- ->where(['a.id' => 1]);
- $query->sql();
- }
- /**
- * You cannot call values() before insert() it causes all sorts of pain.
- *
- * @return void
- */
- public function testInsertValuesBeforeInsertFailure()
- {
- $this->expectException(\Cake\Database\Exception::class);
- $query = new Query($this->connection);
- $query->select('*')->values([
- 'id' => 1,
- 'title' => 'mark',
- 'body' => 'test insert',
- ]);
- }
- /**
- * Inserting nothing should not generate an error.
- *
- * @return void
- */
- public function testInsertNothing()
- {
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('At least 1 column is required to perform an insert.');
- $query = new Query($this->connection);
- $query->insert([]);
- }
- /**
- * Test insert overwrites values
- *
- * @return void
- */
- public function testInsertOverwritesValues()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['title', 'body'])
- ->insert(['title'])
- ->into('articles')
- ->values([
- 'title' => 'mark',
- ]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'INSERT INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?' .
- 'VALUES \(:c0\)',
- $result,
- !$this->autoQuote
- );
- }
- /**
- * Test inserting a single row.
- *
- * @return void
- */
- public function testInsertSimple()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['title', 'body'])
- ->into('articles')
- ->values([
- 'title' => 'mark',
- 'body' => 'test insert',
- ]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
- 'VALUES \(:c0, :c1\)',
- $result,
- !$this->autoQuote
- );
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(1, $result, '1 row should be inserted');
- }
- $expected = [
- [
- 'id' => 4,
- 'author_id' => null,
- 'title' => 'mark',
- 'body' => 'test insert',
- 'published' => 'N',
- ],
- ];
- $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
- }
- /**
- * Test insert queries quote integer column names
- *
- * @return void
- */
- public function testInsertQuoteColumns()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert([123])
- ->into('articles')
- ->values([
- '123' => 'mark',
- ]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'INSERT INTO <articles> \(<123>\) (OUTPUT INSERTED\.\* )?' .
- 'VALUES \(:c0\)',
- $result,
- !$this->autoQuote
- );
- }
- /**
- * Test an insert when not all the listed fields are provided.
- * Columns should be matched up where possible.
- *
- * @return void
- */
- public function testInsertSparseRow()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['title', 'body'])
- ->into('articles')
- ->values([
- 'title' => 'mark',
- ]);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
- 'VALUES \(:c0, :c1\)',
- $result,
- !$this->autoQuote
- );
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(1, $result, '1 row should be inserted');
- }
- $expected = [
- [
- 'id' => 4,
- 'author_id' => null,
- 'title' => 'mark',
- 'body' => null,
- 'published' => 'N',
- ],
- ];
- $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
- }
- /**
- * Test inserting multiple rows with sparse data.
- *
- * @return void
- */
- public function testInsertMultipleRowsSparse()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['title', 'body'])
- ->into('articles')
- ->values([
- 'body' => 'test insert',
- ])
- ->values([
- 'title' => 'jose',
- ]);
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(2, $result, '2 rows should be inserted');
- }
- $expected = [
- [
- 'id' => 4,
- 'author_id' => null,
- 'title' => null,
- 'body' => 'test insert',
- 'published' => 'N',
- ],
- [
- 'id' => 5,
- 'author_id' => null,
- 'title' => 'jose',
- 'body' => null,
- 'published' => 'N',
- ],
- ];
- $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
- }
- /**
- * Test that INSERT INTO ... SELECT works.
- *
- * @return void
- */
- public function testInsertFromSelect()
- {
- $this->loadFixtures('Authors', 'Articles');
- $select = (new Query($this->connection))->select(['name', "'some text'", 99])
- ->from('authors')
- ->where(['id' => 1]);
- $query = new Query($this->connection);
- $query->insert(
- ['title', 'body', 'author_id'],
- ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
- )
- ->into('articles')
- ->values($select);
- $result = $query->sql();
- $this->assertQuotedQuery(
- 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
- $result,
- !$this->autoQuote
- );
- $this->assertQuotedQuery(
- 'SELECT <name>, \'some text\', 99 FROM <authors>',
- $result,
- !$this->autoQuote
- );
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(1, $result);
- }
- $result = (new Query($this->connection))->select('*')
- ->from('articles')
- ->where(['author_id' => 99])
- ->execute();
- $this->assertCount(1, $result);
- $expected = [
- 'id' => 4,
- 'title' => 'mariano',
- 'body' => 'some text',
- 'author_id' => 99,
- 'published' => 'N',
- ];
- $this->assertEquals($expected, $result->fetch('assoc'));
- }
- /**
- * Test that an exception is raised when mixing query + array types.
- *
- */
- public function testInsertFailureMixingTypesArrayFirst()
- {
- $this->expectException(\Cake\Database\Exception::class);
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['name'])
- ->into('articles')
- ->values(['name' => 'mark'])
- ->values(new Query($this->connection));
- }
- /**
- * Test that an exception is raised when mixing query + array types.
- *
- */
- public function testInsertFailureMixingTypesQueryFirst()
- {
- $this->expectException(\Cake\Database\Exception::class);
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->insert(['name'])
- ->into('articles')
- ->values(new Query($this->connection))
- ->values(['name' => 'mark']);
- }
- /**
- * Test that insert can use expression objects as values.
- *
- * @return void
- */
- public function testInsertExpressionValues()
- {
- $this->loadFixtures('Articles', 'Authors');
- $query = new Query($this->connection);
- $query->insert(['title', 'author_id'])
- ->into('articles')
- ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(1, $result);
- }
- $result = (new Query($this->connection))->select('*')
- ->from('articles')
- ->where(['author_id' => 99])
- ->execute();
- $this->assertCount(1, $result);
- $expected = [
- 'id' => 4,
- 'title' => 'jose',
- 'body' => null,
- 'author_id' => '99',
- 'published' => 'N',
- ];
- $this->assertEquals($expected, $result->fetch('assoc'));
- $subquery = new Query($this->connection);
- $subquery->select(['name'])
- ->from('authors')
- ->where(['id' => 1]);
- $query = new Query($this->connection);
- $query->insert(['title', 'author_id'])
- ->into('articles')
- ->values(['title' => $subquery, 'author_id' => 100]);
- $result = $query->execute();
- $result->closeCursor();
- //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
- if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
- $this->assertCount(1, $result);
- }
- $result = (new Query($this->connection))->select('*')
- ->from('articles')
- ->where(['author_id' => 100])
- ->execute();
- $this->assertCount(1, $result);
- $expected = [
- 'id' => 5,
- 'title' => 'mariano',
- 'body' => null,
- 'author_id' => '100',
- 'published' => 'N',
- ];
- $this->assertEquals($expected, $result->fetch('assoc'));
- }
- /**
- * Tests that the identifier method creates an expression object.
- *
- * @return void
- */
- public function testIdentifierExpression()
- {
- $query = new Query($this->connection);
- /** @var \Cake\Database\Expression\IdentifierExpression $identifier */
- $identifier = $query->identifier('foo');
- $this->assertInstanceOf(IdentifierExpression::class, $identifier);
- $this->assertEquals('foo', $identifier->getIdentifier());
- }
- /**
- * Tests the interface contract of identifier
- *
- * @return void
- */
- public function testIdentifierInterface()
- {
- $query = new Query($this->connection);
- $identifier = $query->identifier('description');
- $this->assertInstanceOf(ExpressionInterface::class, $identifier);
- $this->assertEquals('description', $identifier->getIdentifier());
- $identifier->setIdentifier('title');
- $this->assertEquals('title', $identifier->getIdentifier());
- }
- /**
- * Tests that functions are correctly transformed and their parameters are bound
- *
- * @group FunctionExpression
- * @return void
- */
- public function testSQLFunctions()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $result = $query->select(
- function ($q) {
- return ['total' => $q->func()->count('*')];
- }
- )
- ->from('comments')
- ->execute();
- $expected = [['total' => 6]];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $result = $query->select([
- 'c' => $query->func()->concat(['comment' => 'literal', ' is appended']),
- ])
- ->from('comments')
- ->order(['c' => 'ASC'])
- ->limit(1)
- ->execute();
- $expected = [
- ['c' => 'First Comment for First Article is appended'],
- ];
- $this->assertEquals($expected, $result->fetchAll('assoc'));
- $query = new Query($this->connection);
- $result = $query
- ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
- ->execute()
- ->fetchAll('assoc');
- $this->assertEquals(3, abs($result[0]['d']));
- $query = new Query($this->connection);
- $result = $query
- ->select(['d' => $query->func()->now('date')])
- ->execute();
- $this->assertEquals([(object)['d' => date('Y-m-d')]], $result->fetchAll('obj'));
- $query = new Query($this->connection);
- $result = $query
- ->select(['d' => $query->func()->now('time')])
- ->execute();
- $this->assertWithinRange(
- date('U'),
- (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
- 1
- );
- $query = new Query($this->connection);
- $result = $query
- ->select(['d' => $query->func()->now()])
- ->execute();
- $this->assertWithinRange(
- date('U'),
- (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
- 1
- );
- $query = new Query($this->connection);
- $result = $query
- ->select([
- 'd' => $query->func()->datePart('day', 'created'),
- 'm' => $query->func()->datePart('month', 'created'),
- 'y' => $query->func()->datePart('year', 'created'),
- 'de' => $query->func()->extract('day', 'created'),
- 'me' => $query->func()->extract('month', 'created'),
- 'ye' => $query->func()->extract('year', 'created'),
- 'wd' => $query->func()->weekday('created'),
- 'dow' => $query->func()->dayOfWeek('created'),
- 'addDays' => $query->func()->dateAdd('created', 2, 'day'),
- 'substractYears' => $query->func()->dateAdd('created', -2, 'year'),
- ])
- ->from('comments')
- ->where(['created' => '2007-03-18 10:45:23'])
- ->execute()
- ->fetchAll('assoc');
- $result[0]['m'] = ltrim($result[0]['m'], '0');
- $result[0]['me'] = ltrim($result[0]['me'], '0');
- $result[0]['addDays'] = substr($result[0]['addDays'], 0, 10);
- $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 10);
- $expected = [
- 'd' => '18',
- 'm' => '3',
- 'y' => '2007',
- 'de' => '18',
- 'me' => '3',
- 'ye' => '2007',
- 'wd' => '1', // Sunday
- 'dow' => '1',
- 'addDays' => '2007-03-20',
- 'substractYears' => '2005-03-18',
- ];
- $this->assertEquals($expected, $result[0]);
- }
- /**
- * Tests that default types are passed to functions accepting a $types param
- *
- * @return void
- */
- public function testDefaultTypes()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $this->assertEquals([], $query->getDefaultTypes());
- $types = ['id' => 'integer', 'created' => 'datetime'];
- $this->assertSame($query, $query->setDefaultTypes($types));
- $this->assertSame($types, $query->getDefaultTypes());
- $results = $query->select(['id', 'comment'])
- ->from('comments')
- ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
- ->execute();
- $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
- $this->assertEquals($expected, $results->fetchAll('assoc'));
- // Now test default can be overridden
- $types = ['created' => 'date'];
- $results = $query
- ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
- ->execute();
- $this->assertCount(6, $results, 'All 6 rows should match.');
- }
- /**
- * Tests parameter binding
- *
- * @return void
- */
- public function testBind()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $results = $query->select(['id', 'comment'])
- ->from('comments')
- ->where(['created BETWEEN :foo AND :bar'])
- ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
- ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
- ->execute();
- $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
- $this->assertEquals($expected, $results->fetchAll('assoc'));
- $query = new Query($this->connection);
- $results = $query->select(['id', 'comment'])
- ->from('comments')
- ->where(['created BETWEEN :foo AND :bar'])
- ->bind(':foo', '2007-03-18 10:50:00')
- ->bind(':bar', '2007-03-18 10:52:00')
- ->execute();
- $this->assertEquals($expected, $results->fetchAll('assoc'));
- }
- /**
- * Test that epilog() will actually append a string to a select query
- *
- * @return void
- */
- public function testAppendSelect()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $sql = $query
- ->select(['id', 'title'])
- ->from('articles')
- ->where(['id' => 1])
- ->epilog('FOR UPDATE')
- ->sql();
- $this->assertContains('SELECT', $sql);
- $this->assertContains('FROM', $sql);
- $this->assertContains('WHERE', $sql);
- $this->assertEquals(' FOR UPDATE', substr($sql, -11));
- }
- /**
- * Test that epilog() will actually append a string to an insert query
- *
- * @return void
- */
- public function testAppendInsert()
- {
- $query = new Query($this->connection);
- $sql = $query
- ->insert(['id', 'title'])
- ->into('articles')
- ->values([1, 'a title'])
- ->epilog('RETURNING id')
- ->sql();
- $this->assertContains('INSERT', $sql);
- $this->assertContains('INTO', $sql);
- $this->assertContains('VALUES', $sql);
- $this->assertEquals(' RETURNING id', substr($sql, -13));
- }
- /**
- * Test that epilog() will actually append a string to an update query
- *
- * @return void
- */
- public function testAppendUpdate()
- {
- $query = new Query($this->connection);
- $sql = $query
- ->update('articles')
- ->set(['title' => 'foo'])
- ->where(['id' => 1])
- ->epilog('RETURNING id')
- ->sql();
- $this->assertContains('UPDATE', $sql);
- $this->assertContains('SET', $sql);
- $this->assertContains('WHERE', $sql);
- $this->assertEquals(' RETURNING id', substr($sql, -13));
- }
- /**
- * Test that epilog() will actually append a string to a delete query
- *
- * @return void
- */
- public function testAppendDelete()
- {
- $query = new Query($this->connection);
- $sql = $query
- ->delete('articles')
- ->where(['id' => 1])
- ->epilog('RETURNING id')
- ->sql();
- $this->assertContains('DELETE FROM', $sql);
- $this->assertContains('WHERE', $sql);
- $this->assertEquals(' RETURNING id', substr($sql, -13));
- }
- /**
- * Tests automatic identifier quoting in the select clause
- *
- * @return void
- */
- public function testQuotingSelectFieldsAndAlias()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select(['something'])->sql();
- $this->assertQuotedQuery('SELECT <something>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select(['foo' => 'something'])->sql();
- $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select(['foo' => 1])->sql();
- $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select(['foo' => '1 + 1'])->sql();
- $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
- $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
- $this->assertQuotedQuery('<bar>', $sql);
- }
- /**
- * Tests automatic identifier quoting in the from clause
- *
- * @return void
- */
- public function testQuotingFromAndAlias()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select('*')->from(['something'])->sql();
- $this->assertQuotedQuery('FROM <something>', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->from(['foo' => 'something'])->sql();
- $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
- $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
- }
- /**
- * Tests automatic identifier quoting for DISTINCT ON
- *
- * @return void
- */
- public function testQuotingDistinctOn()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select('*')->distinct(['something'])->sql();
- $this->assertQuotedQuery('<something>', $sql);
- }
- /**
- * Tests automatic identifier quoting in the join clause
- *
- * @return void
- */
- public function testQuotingJoinsAndAlias()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select('*')->join(['something'])->sql();
- $this->assertQuotedQuery('JOIN <something>', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->join(['foo' => 'something'])->sql();
- $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
- $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->join([
- 'alias' => 'orders',
- 'table' => 'Order',
- 'conditions' => ['1 = 1'],
- ])->sql();
- $this->assertQuotedQuery('JOIN <Order> <orders> ON 1 = 1', $sql);
- }
- /**
- * Tests automatic identifier quoting in the group by clause
- *
- * @return void
- */
- public function testQuotingGroupBy()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select('*')->group(['something'])->sql();
- $this->assertQuotedQuery('GROUP BY <something>', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
- $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
- $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
- }
- /**
- * Tests automatic identifier quoting strings inside conditions expressions
- *
- * @return void
- */
- public function testQuotingExpressions()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->select('*')
- ->where(['something' => 'value'])
- ->sql();
- $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
- $query = new Query($this->connection);
- $sql = $query->select('*')
- ->where([
- 'something' => 'value',
- 'OR' => ['foo' => 'bar', 'baz' => 'cake'],
- ])
- ->sql();
- $this->assertQuotedQuery('<something> = :c0 AND', $sql);
- $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
- }
- /**
- * Tests that insert query parts get quoted automatically
- *
- * @return void
- */
- public function testQuotingInsert()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $sql = $query->insert(['bar', 'baz'])
- ->into('foo')
- ->where(['something' => 'value'])
- ->sql();
- $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
- $query = new Query($this->connection);
- $sql = $query->insert([$query->newExpr('bar')])
- ->into('foo')
- ->where(['something' => 'value'])
- ->sql();
- $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
- }
- /**
- * Tests converting a query to a string
- *
- * @return void
- */
- public function testToString()
- {
- $query = new Query($this->connection);
- $query
- ->select(['title'])
- ->from('articles');
- $result = (string)$query;
- $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, !$this->autoQuote);
- }
- /**
- * Tests __debugInfo
- *
- * @return void
- */
- public function testDebugInfo()
- {
- $query = (new Query($this->connection))->select('*')
- ->from('articles')
- ->setDefaultTypes(['id' => 'integer'])
- ->where(['id' => '1']);
- $expected = [
- '(help)' => 'This is a Query object, to get the results execute or iterate it.',
- 'sql' => $query->sql(),
- 'params' => [
- ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0'],
- ],
- 'defaultTypes' => ['id' => 'integer'],
- 'decorators' => 0,
- 'executed' => false,
- ];
- $result = $query->__debugInfo();
- $this->assertEquals($expected, $result);
- $query->execute();
- $expected = [
- '(help)' => 'This is a Query object, to get the results execute or iterate it.',
- 'sql' => $query->sql(),
- 'params' => [
- ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0'],
- ],
- 'defaultTypes' => ['id' => 'integer'],
- 'decorators' => 0,
- 'executed' => true,
- ];
- $result = $query->__debugInfo();
- $this->assertEquals($expected, $result);
- }
- /**
- * Tests __debugInfo on incomplete query
- *
- * @return void
- */
- public function testDebugInfoIncompleteQuery()
- {
- $query = (new Query($this->connection))
- ->insert(['title']);
- $result = $query->__debugInfo();
- $this->assertContains('incomplete', $result['sql']);
- $this->assertSame([], $result['params']);
- }
- /**
- * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
- *
- * @return void
- */
- public function testIsNullWithExpressions()
- {
- $this->loadFixtures('Authors');
- $query = new Query($this->connection);
- $subquery = (new Query($this->connection))
- ->select(['id'])
- ->from('authors')
- ->where(['id' => 1]);
- $result = $query
- ->select(['name'])
- ->from(['authors'])
- ->where(function ($exp) use ($subquery) {
- return $exp->isNotNull($subquery);
- })
- ->execute();
- $this->assertNotEmpty($result->fetchAll('assoc'));
- $result = (new Query($this->connection))
- ->select(['name'])
- ->from(['authors'])
- ->where(function ($exp) use ($subquery) {
- return $exp->isNull($subquery);
- })
- ->execute();
- $this->assertEmpty($result->fetchAll('assoc'));
- }
- /**
- * Tests that strings passed to isNull and isNotNull will be treated as identifiers
- * when using autoQuoting
- *
- * @return void
- */
- public function testIsNullAutoQuoting()
- {
- $this->connection->getDriver()->enableAutoQuoting(true);
- $query = new Query($this->connection);
- $query->select('*')->from('things')->where(function ($exp) {
- return $exp->isNull('field');
- });
- $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
- $query = new Query($this->connection);
- $query->select('*')->from('things')->where(function ($exp) {
- return $exp->isNotNull('field');
- });
- $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
- }
- /**
- * Tests that using the IS operator will automatically translate to the best
- * possible operator depending on the passed value
- *
- * @return void
- */
- public function testDirectIsNull()
- {
- $this->loadFixtures('Authors');
- $sql = (new Query($this->connection))
- ->select(['name'])
- ->from(['authors'])
- ->where(['name IS' => null])
- ->sql();
- $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, !$this->autoQuote);
- $results = (new Query($this->connection))
- ->select(['name'])
- ->from(['authors'])
- ->where(['name IS' => 'larry'])
- ->execute();
- $this->assertCount(1, $results);
- $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
- }
- /**
- * Tests that using the IS NOT operator will automatically translate to the best
- * possible operator depending on the passed value
- *
- * @return void
- */
- public function testDirectIsNotNull()
- {
- $this->loadFixtures('Authors');
- $sql = (new Query($this->connection))
- ->select(['name'])
- ->from(['authors'])
- ->where(['name IS NOT' => null])
- ->sql();
- $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, !$this->autoQuote);
- $results = (new Query($this->connection))
- ->select(['name'])
- ->from(['authors'])
- ->where(['name IS NOT' => 'larry'])
- ->execute();
- $this->assertCount(3, $results);
- $this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
- }
- /**
- * Performs the simple update query and verifies the row count.
- *
- * @return void
- */
- public function testRowCountAndClose()
- {
- $this->loadFixtures('Authors');
- $statementMock = $this->getMockBuilder(StatementInterface::class)
- ->setMethods(['rowCount', 'closeCursor'])
- ->getMockForAbstractClass();
- $statementMock->expects($this->once())
- ->method('rowCount')
- ->willReturn(500);
- $statementMock->expects($this->once())
- ->method('closeCursor');
- /** @var \Cake\ORM\Query|\PHPUnit_Framework_MockObject_MockObject $queryMock */
- $queryMock = $this->getMockBuilder(Query::class)
- ->setMethods(['execute'])
- ->setConstructorArgs((array)$this->connection)
- ->getMock();
- $queryMock->expects($this->once())
- ->method('execute')
- ->willReturn($statementMock);
- $rowCount = $queryMock->update('authors')
- ->set('name', 'mark')
- ->where(['id' => 1])
- ->rowCountAndClose();
- $this->assertEquals(500, $rowCount);
- }
- /**
- * Tests that case statements work correctly for various use-cases.
- *
- * @return void
- */
- public function testSqlCaseStatement()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $publishedCase = $query
- ->newExpr()
- ->addCase(
- $query
- ->newExpr()
- ->add(['published' => 'Y']),
- 1,
- 'integer'
- );
- $notPublishedCase = $query
- ->newExpr()
- ->addCase(
- $query
- ->newExpr()
- ->add(['published' => 'N']),
- 1,
- 'integer'
- );
- //Postgres requires the case statement to be cast to a integer
- if ($this->connection->getDriver() instanceof \Cake\Database\Driver\Postgres) {
- $publishedCase = $query->func()
- ->cast([$publishedCase, 'integer' => 'literal'])
- ->setConjunction(' AS ');
- $notPublishedCase = $query->func()
- ->cast([$notPublishedCase, 'integer' => 'literal'])
- ->setConjunction(' AS ');
- }
- $results = $query
- ->select([
- 'published' => $query->func()->sum($publishedCase),
- 'not_published' => $query->func()->sum($notPublishedCase),
- ])
- ->from(['comments'])
- ->execute()
- ->fetchAll('assoc');
- $this->assertEquals(5, $results[0]['published']);
- $this->assertEquals(1, $results[0]['not_published']);
- $query = new Query($this->connection);
- $query
- ->insert(['article_id', 'user_id', 'comment', 'published'])
- ->into('comments')
- ->values([
- 'article_id' => 2,
- 'user_id' => 1,
- 'comment' => 'In limbo',
- 'published' => 'L',
- ])
- ->execute()
- ->closeCursor();
- $query = new Query($this->connection);
- $conditions = [
- $query
- ->newExpr()
- ->add(['published' => 'Y']),
- $query
- ->newExpr()
- ->add(['published' => 'N']),
- ];
- $values = [
- 'Published',
- 'Not published',
- 'None',
- ];
- $results = $query
- ->select([
- 'id',
- 'comment',
- 'status' => $query->newExpr()->addCase($conditions, $values),
- ])
- ->from(['comments'])
- ->execute()
- ->fetchAll('assoc');
- $this->assertEquals('Published', $results[2]['status']);
- $this->assertEquals('Not published', $results[3]['status']);
- $this->assertEquals('None', $results[6]['status']);
- }
- /**
- * Shows that bufferResults(false) will prevent client-side results buffering
- *
- * @return void
- */
- public function testUnbufferedQuery()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $result = $query->select(['body', 'author_id'])
- ->from('articles')
- ->enableBufferedResults(false)
- ->execute();
- if (!method_exists($result, 'bufferResults')) {
- $result->closeCursor();
- $this->markTestSkipped('This driver does not support unbuffered queries');
- }
- $this->assertCount(0, $result, 'Unbuffered queries only have a count when results are fetched');
- $list = $result->fetchAll('assoc');
- $this->assertCount(3, $list);
- $result->closeCursor();
- $query = new Query($this->connection);
- $result = $query->select(['body', 'author_id'])
- ->from('articles')
- ->execute();
- $this->assertCount(3, $result, 'Buffered queries can be counted any time.');
- $list = $result->fetchAll('assoc');
- $this->assertCount(3, $list);
- $result->closeCursor();
- }
- /**
- * Test that cloning goes deep.
- *
- * @return void
- */
- public function testDeepClone()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id', 'title' => $query->func()->concat(['title' => 'literal', 'test'])])
- ->from('articles')
- ->where(['Articles.id' => 1])
- ->offset(10)
- ->limit(1)
- ->order(['Articles.id' => 'DESC']);
- $dupe = clone $query;
- $this->assertEquals($query->clause('where'), $dupe->clause('where'));
- $this->assertNotSame($query->clause('where'), $dupe->clause('where'));
- $dupe->where(['Articles.title' => 'thinger']);
- $this->assertNotEquals($query->clause('where'), $dupe->clause('where'));
- $this->assertNotSame(
- $query->clause('select')['title'],
- $dupe->clause('select')['title']
- );
- $this->assertEquals($query->clause('order'), $dupe->clause('order'));
- $this->assertNotSame($query->clause('order'), $dupe->clause('order'));
- $query->order(['Articles.title' => 'ASC']);
- $this->assertNotEquals($query->clause('order'), $dupe->clause('order'));
- $this->assertNotSame(
- $query->getSelectTypeMap(),
- $dupe->getSelectTypeMap()
- );
- }
- /**
- * Tests the selectTypeMap method
- *
- * @return void
- */
- public function testSelectTypeMap()
- {
- $query = new Query($this->connection);
- $typeMap = $query->getSelectTypeMap();
- $this->assertInstanceOf(TypeMap::class, $typeMap);
- $another = clone $typeMap;
- $query->setSelectTypeMap($another);
- $this->assertSame($another, $query->getSelectTypeMap());
- }
- /**
- * Tests the automatic type conversion for the fields in the result
- *
- * @return void
- */
- public function testSelectTypeConversion()
- {
- Type::set('custom_datetime', new BarType('custom_datetime'));
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $query
- ->select(['id', 'comment', 'the_date' => 'created', 'updated'])
- ->from('comments')
- ->limit(1)
- ->getSelectTypeMap()
- ->setTypes([
- 'id' => 'integer',
- 'the_date' => 'datetime',
- 'updated' => 'custom_datetime',
- ]);
- $result = $query->execute()->fetchAll('assoc');
- $this->assertInternalType('integer', $result[0]['id']);
- $this->assertInstanceOf('DateTime', $result[0]['the_date']);
- $this->assertInstanceOf('DateTime', $result[0]['updated']);
- }
- /**
- * Tests that the json type can save and get data symmetrically
- *
- * @return void
- */
- public function testSymmetricJsonType()
- {
- $query = new Query($this->connection);
- $insert = $query
- ->insert(['comment', 'article_id', 'user_id'], ['comment' => 'json'])
- ->into('comments')
- ->values([
- 'comment' => ['a' => 'b', 'c' => true],
- 'article_id' => 1,
- 'user_id' => 1,
- ])
- ->execute();
- $id = $insert->lastInsertId('comments', 'id');
- $insert->closeCursor();
- $query = new Query($this->connection);
- $query
- ->select(['comment'])
- ->from('comments')
- ->where(['id' => $id])
- ->getSelectTypeMap()->setTypes(['comment' => 'json']);
- $result = $query->execute();
- $comment = $result->fetchAll('assoc')[0]['comment'];
- $result->closeCursor();
- $this->assertSame(['a' => 'b', 'c' => true], $comment);
- }
- /**
- * Test removeJoin().
- *
- * @return void
- */
- public function testRemoveJoin()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id', 'title'])
- ->from('articles')
- ->join(['authors' => [
- 'type' => 'INNER',
- 'conditions' => ['articles.author_id = authors.id'],
- ]]);
- $this->assertArrayHasKey('authors', $query->clause('join'));
- $this->assertSame($query, $query->removeJoin('authors'));
- $this->assertArrayNotHasKey('authors', $query->clause('join'));
- }
- /**
- * Test join read mode
- *
- * @deprecated
- * @return void
- */
- public function testJoinReadMode()
- {
- $this->loadFixtures('Articles');
- $query = new Query($this->connection);
- $query->select(['id', 'title'])
- ->from('articles')
- ->join(['authors' => [
- 'type' => 'INNER',
- 'conditions' => ['articles.author_id = authors.id'],
- ]]);
- $this->deprecated(function () use ($query) {
- $this->assertArrayHasKey('authors', $query->join());
- });
- }
- /**
- * Tests that types in the type map are used in the
- * specific comparison functions when using a callable
- *
- * @return void
- */
- public function testBetweenExpressionAndTypeMap()
- {
- $this->loadFixtures('Comments');
- $query = new Query($this->connection);
- $query->select('id')
- ->from('comments')
- ->setDefaultTypes(['created' => 'datetime'])
- ->where(function ($expr) {
- $from = new \DateTime('2007-03-18 10:45:00');
- $to = new \DateTime('2007-03-18 10:48:00');
- return $expr->between('created', $from, $to);
- });
- $this->assertCount(2, $query->execute()->fetchAll());
- }
- /**
- * Test use of modifiers in a INSERT query
- *
- * Testing the generated SQL since the modifiers are usually different per driver
- *
- * @return void
- */
- public function testInsertModifiers()
- {
- $query = new Query($this->connection);
- $result = $query
- ->insert(['title'])
- ->into('articles')
- ->values(['title' => 'foo'])
- ->modifier('IGNORE');
- $this->assertQuotedQuery(
- 'INSERT IGNORE INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query
- ->insert(['title'])
- ->into('articles')
- ->values(['title' => 'foo'])
- ->modifier(['IGNORE', 'LOW_PRIORITY']);
- $this->assertQuotedQuery(
- 'INSERT IGNORE LOW_PRIORITY INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
- $result->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Test use of modifiers in a UPDATE query
- *
- * Testing the generated SQL since the modifiers are usually different per driver
- *
- * @return void
- */
- public function testUpdateModifiers()
- {
- $query = new Query($this->connection);
- $result = $query
- ->update('authors')
- ->set('name', 'mark')
- ->modifier('TOP 10 PERCENT');
- $this->assertQuotedQuery(
- 'UPDATE TOP 10 PERCENT <authors> SET <name> = :c0',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query
- ->update('authors')
- ->set('name', 'mark')
- ->modifier(['TOP 10 PERCENT', 'FOO']);
- $this->assertQuotedQuery(
- 'UPDATE TOP 10 PERCENT FOO <authors> SET <name> = :c0',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query
- ->update('authors')
- ->set('name', 'mark')
- ->modifier([$query->newExpr('TOP 10 PERCENT')]);
- $this->assertQuotedQuery(
- 'UPDATE TOP 10 PERCENT <authors> SET <name> = :c0',
- $result->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Test use of modifiers in a DELETE query
- *
- * Testing the generated SQL since the modifiers are usually different per driver
- *
- * @return void
- */
- public function testDeleteModifiers()
- {
- $query = new Query($this->connection);
- $result = $query->delete()
- ->from('authors')
- ->where('1 = 1')
- ->modifier('IGNORE');
- $this->assertQuotedQuery(
- 'DELETE IGNORE FROM <authors> WHERE 1 = 1',
- $result->sql(),
- !$this->autoQuote
- );
- $query = new Query($this->connection);
- $result = $query->delete()
- ->from('authors')
- ->where('1 = 1')
- ->modifier(['IGNORE', 'QUICK']);
- $this->assertQuotedQuery(
- 'DELETE IGNORE QUICK FROM <authors> WHERE 1 = 1',
- $result->sql(),
- !$this->autoQuote
- );
- }
- /**
- * Test getValueBinder()
- *
- * @return void
- */
- public function testGetValueBinder()
- {
- $query = new Query($this->connection);
- $this->assertInstanceOf('\Cake\Database\ValueBinder', $query->getValueBinder());
- }
- /**
- * Test automatic results casting
- *
- * @return void
- */
- public function testCastResults()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $fields = [
- 'user_id' => 'integer',
- 'is_active' => 'boolean',
- ];
- $typeMap = new TypeMap($fields + ['a' => 'integer']);
- $results = $query
- ->select(array_keys($fields))
- ->select(['a' => 'is_active'])
- ->from('profiles')
- ->setSelectTypeMap($typeMap)
- ->where(['user_id' => 1])
- ->execute()
- ->fetchAll('assoc');
- $this->assertSame([['user_id' => 1, 'is_active' => false, 'a' => 0]], $results);
- }
- /**
- * Test disabling type casting
- *
- * @return void
- */
- public function testCastResultsDisable()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $typeMap = new TypeMap(['a' => 'datetime']);
- $results = $query
- ->select(['a' => 'id'])
- ->from('profiles')
- ->setSelectTypeMap($typeMap)
- ->limit(1)
- ->disableResultsCasting()
- ->execute()
- ->fetchAll('assoc');
- $this->assertEquals([['a' => '1']], $results);
- }
- /**
- * Test that type conversion is only applied once.
- *
- * @return void
- */
- public function testAllNoDuplicateTypeCasting()
- {
- $this->skipIf($this->autoQuote, 'Produces bad SQL in postgres with autoQuoting');
- $query = new Query($this->connection);
- $query
- ->select('1.5 AS a')
- ->setSelectTypeMap(new TypeMap(['a' => 'integer']));
- // Convert to an array and make the query dirty again.
- $result = $query->execute()->fetchAll('assoc');
- $this->assertEquals([['a' => 1]], $result);
- $query->setSelectTypeMap(new TypeMap(['a' => 'float']));
- // Get results a second time.
- $result = $query->execute()->fetchAll('assoc');
- // Had the type casting being remembered from the first time,
- // The value would be a truncated float (1.0)
- $this->assertEquals([['a' => 1.5]], $result);
- }
- /**
- * Test that reading an undefined clause does not emit an error.
- *
- * @return void
- */
- public function testClauseUndefined()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The \'nope\' clause is not defined. Valid clauses are: delete, update');
- $query = new Query($this->connection);
- $this->assertEmpty($query->clause('where'));
- $query->clause('nope');
- }
- /**
- * Assertion for comparing a table's contents with what is in it.
- *
- * @param string $table
- * @param int $count
- * @param array $rows
- * @param array $conditions
- * @return void
- */
- public function assertTable($table, $count, $rows, $conditions = [])
- {
- $result = (new Query($this->connection))->select('*')
- ->from($table)
- ->where($conditions)
- ->execute();
- $this->assertCount($count, $result, 'Row count is incorrect');
- $this->assertEquals($rows, $result->fetchAll('assoc'));
- $result->closeCursor();
- }
- /**
- * Assertion for comparing a regex pattern against a query having its identifiers
- * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
- * parameter is set to true, it will alter the pattern to both accept quoted and
- * unquoted queries
- *
- * @param string $pattern
- * @param string $query the result to compare against
- * @param bool $optional
- * @return void
- */
- public function assertQuotedQuery($pattern, $query, $optional = false)
- {
- if ($optional) {
- $optional = '?';
- }
- $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
- $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
- $this->assertRegExp('#' . $pattern . '#', $query);
- }
- /**
- * Test that calling fetchAssoc return an associated array.
- * @return void
- * @throws \Exception
- */
- public function testFetchAssoc()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $fields = [
- 'id' => 'integer',
- 'user_id' => 'integer',
- 'is_active' => 'boolean',
- ];
- $typeMap = new TypeMap($fields);
- $results = $query
- ->select([
- 'id',
- 'user_id',
- 'is_active',
- ])
- ->from('profiles')
- ->setSelectTypeMap($typeMap)
- ->limit(1)
- ->execute()
- ->fetchAssoc();
- $this->assertSame(['id' => 1, 'user_id' => 1, 'is_active' => false], $results);
- }
- /**
- * Test that calling fetchAssoc return an empty associated array.
- * @return void
- * @throws \Exception
- */
- public function testFetchAssocWithEmptyResult()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $results = $query
- ->select(['id'])
- ->from('profiles')
- ->where(['id' => -1])
- ->execute()
- ->fetchAssoc();
- $this->assertSame([], $results);
- }
- /**
- * Test that calling fetch with with FETCH_TYPE_OBJ return stdClass object.
- * @return void
- * @throws \Exception
- */
- public function testFetchObjects()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $results = $query
- ->select([
- 'id',
- 'user_id',
- 'is_active',
- ])
- ->from('profiles')
- ->limit(1)
- ->execute()
- ->fetch(StatementDecorator::FETCH_TYPE_OBJ);
- $this->assertInstanceOf(\stdClass::class, $results);
- }
- /**
- * Test that fetchColumn() will return the correct value at $position.
- * @throws \Exception
- * @return void
- */
- public function testFetchColumn()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $fields = [
- 'integer',
- 'integer',
- 'boolean',
- ];
- $typeMap = new TypeMap($fields);
- $query
- ->select([
- 'id',
- 'user_id',
- 'is_active',
- ])
- ->from('profiles')
- ->setSelectTypeMap($typeMap)
- ->where(['id' => 2])
- ->limit(1);
- $statement = $query->execute();
- $results = $statement->fetchColumn(0);
- $this->assertSame(2, $results);
- $statement = $query->execute();
- $results = $statement->fetchColumn(1);
- $this->assertSame(2, $results);
- $statement = $query->execute();
- $results = $statement->fetchColumn(2);
- $this->assertSame(false, $results);
- }
- /**
- * Test that fetchColumn() will return false if $position is not set.
- * @throws \Exception
- * @return void
- */
- public function testFetchColumnReturnsFalse()
- {
- $this->loadFixtures('Profiles');
- $query = new Query($this->connection);
- $fields = [
- 'integer',
- 'integer',
- 'boolean',
- ];
- $typeMap = new TypeMap($fields);
- $query
- ->select([
- 'id',
- 'user_id',
- 'is_active',
- ])
- ->from('profiles')
- ->setSelectTypeMap($typeMap)
- ->where(['id' => 2])
- ->limit(1);
- $statement = $query->execute();
- $results = $statement->fetchColumn(3);
- $this->assertFalse($results);
- }
- }
|