hqlcppds.cpp 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "jliball.hpp"
  15. #include "hql.hpp"
  16. #include "platform.h"
  17. #include "jlib.hpp"
  18. #include "jmisc.hpp"
  19. #include "jstream.ipp"
  20. #include "jdebug.hpp"
  21. #include "hql.hpp"
  22. #include "hqlthql.hpp"
  23. #include "hqlhtcpp.ipp"
  24. #include "hqlttcpp.ipp"
  25. #include "hqlutil.hpp"
  26. #include "hqlthql.hpp"
  27. #include "hqlpmap.hpp"
  28. #include "hqlattr.hpp"
  29. #include "hqlwcpp.hpp"
  30. #include "hqlcpputil.hpp"
  31. #include "hqltcppc.ipp"
  32. #include "hqlopt.hpp"
  33. #include "hqlfold.hpp"
  34. #include "hqlcerrors.hpp"
  35. #include "hqlcatom.hpp"
  36. #include "hqlresource.hpp"
  37. #include "hqlregex.ipp"
  38. #include "hqlsource.ipp"
  39. #include "hqlcse.ipp"
  40. #include "hqlgraph.ipp"
  41. #include "hqlccommon.hpp"
  42. #include "hqliter.ipp"
  43. #include "hqlinline.hpp"
  44. #include "hqlusage.hpp"
  45. #define MAX_FIXED_SIZE_RAW 1024
  46. #define INLINE_TABLE_EXPAND_LIMIT 4
  47. void addGraphIdAttribute(ActivityInstance * instance, BuildCtx & ctx, IHqlExpression * graphId)
  48. {
  49. SubGraphInfo * match = matchActiveGraph(ctx, graphId);
  50. assertex(match);
  51. instance->addAttributeInt("_graphId", match->graphId);
  52. }
  53. //===========================================================================
  54. void HqlCppTranslator::doBuildRowIfBranch(BuildCtx & initctx, BuildCtx & ctx, BoundRow * targetRow, IHqlExpression * branchExpr)
  55. {
  56. IHqlExpression * targetRowExpr = targetRow->queryBound();
  57. Owned<IReferenceSelector> rowSelector = buildNewRow(ctx, branchExpr);
  58. Owned<BoundRow> boundRow = rowSelector->getRow(ctx);
  59. OwnedHqlExpr rowExpr = getPointer(boundRow->queryBound());
  60. OwnedHqlExpr castRow = createValue(no_implicitcast, targetRowExpr->getType(), LINK(rowExpr));
  61. ctx.addAssign(targetRowExpr, castRow);
  62. if (rowSelector->isConditional())
  63. targetRow->setConditional(true);
  64. }
  65. IReferenceSelector * HqlCppTranslator::doBuildRowIf(BuildCtx & ctx, IHqlExpression * expr)
  66. {
  67. OwnedHqlExpr foldedCond = foldHqlExpression(expr->queryChild(0));
  68. if (foldedCond->queryValue())
  69. {
  70. unsigned branch = (foldedCond->queryValue()->getBoolValue()) ? 1 : 2;
  71. return buildNewRow(ctx, expr->queryChild(branch));
  72. }
  73. IHqlExpression * trueBranch = expr->queryChild(1);
  74. IHqlExpression * falseBranch = expr->queryChild(2);
  75. //Ideally should have a constant modifier on the following row...
  76. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  77. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  78. Owned<BoundRow> row = createBoundRow(expr->queryBody(), rowExpr);
  79. //MORE: Need casts because cursor may be (probably are) constant, but temporary isn't
  80. //should find out by looking at the a const modifier on the cursor.
  81. BuildCtx condctx(ctx);
  82. IHqlStmt * cond = buildFilterViaExpr(condctx, foldedCond);
  83. //Mark the context as conditional after the filter test, so any temporaries from the filter aren't affected.
  84. condctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  85. doBuildRowIfBranch(ctx, condctx, row, trueBranch);
  86. condctx.selectElse(cond);
  87. condctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  88. doBuildRowIfBranch(ctx, condctx, row, falseBranch);
  89. ctx.associate(*row);
  90. return createReferenceSelector(row);
  91. }
  92. IReferenceSelector * HqlCppTranslator::doBuildRowDeserializeRow(BuildCtx & ctx, IHqlExpression * expr)
  93. {
  94. IHqlExpression * srcRow = expr->queryChild(0);
  95. IHqlExpression * record = expr->queryRecord();
  96. Owned<BoundRow> tempRow = declareLinkedRow(ctx, expr, false);
  97. CHqlBoundTarget target;
  98. target.expr.set(tempRow->queryBound());
  99. HqlExprArray args;
  100. args.append(*createRowAllocator(ctx, record));
  101. args.append(*createRowSerializer(ctx, record, deserializerAtom));
  102. args.append(*LINK(srcRow));
  103. Owned<ITypeInfo> resultType = makeReferenceModifier(makeAttributeModifier(makeRowType(record->getType()), getLinkCountedAttr()));
  104. OwnedHqlExpr call = bindFunctionCall(rtlDeserializeRowAtom, args, resultType);
  105. buildExprAssign(ctx, target, call);
  106. ctx.associate(*tempRow);
  107. return createReferenceSelector(tempRow);
  108. }
  109. void HqlCppTranslator::buildConstRow(IHqlExpression * record, IHqlExpression * rowData, CHqlBoundExpr & bound)
  110. {
  111. OwnedHqlExpr marker = createAttribute(rowAtom, LINK(record), LINK(rowData));
  112. BuildCtx declareCtx(*code, literalAtom);
  113. if (declareCtx.getMatchExpr(marker, bound))
  114. return;
  115. //MORE: This probably needs to go in the header as well...
  116. Owned<ITypeInfo> rowType = makeConstantModifier(makeRowType(record->getType()));
  117. StringBuffer rowName;
  118. getUniqueId(rowName.append("r"));
  119. //Generate two variables to cope with the different ways the data is interpreted.
  120. //Would prefer it to be cleaner... row value would need an associated size
  121. unsigned dataSize = rowData->queryType()->getSize();
  122. OwnedITypeInfo declareType;
  123. OwnedHqlExpr initializer;
  124. if (options.staticRowsUseStringInitializer)
  125. {
  126. //Generates smaller code (and probably more efficient representation in the c++ compiler
  127. //const byte[5+1] = "Hello"; need an extra byte for the implicit \0
  128. declareType.setown(makeDataType(dataSize+1));
  129. initializer.set(rowData);
  130. }
  131. else
  132. {
  133. //Following is strictly correct, but much larger.
  134. //const byte[5] = { 'H','e','l','l','o' };
  135. declareType.set(rowData->queryType());
  136. initializer.setown(createValue(no_create_initializer, rowData->getType(), LINK(rowData)));
  137. }
  138. //MORE: Currently these are marked as const rows, but not generated as such
  139. OwnedHqlExpr boundDeclare = createVariable(rowName, makeConstantModifier(LINK(declareType)));
  140. OwnedHqlExpr boundRow = createVariable(rowName, LINK(rowType));
  141. declareCtx.addDeclare(boundDeclare, initializer);
  142. if (options.spanMultipleCpp)
  143. {
  144. BuildCtx protoctx(*code, mainprototypesAtom);
  145. protoctx.addDeclareExternal(boundDeclare);
  146. }
  147. bound.length.setown(getSizetConstant(dataSize));
  148. bound.expr.set(boundRow);
  149. declareCtx.associateExpr(marker, bound);
  150. }
  151. bool HqlCppTranslator::doBuildRowConstantTransform(IHqlExpression * transform, CHqlBoundExpr & bound)
  152. {
  153. if (!transform->isConstant() || !options.generateStaticInlineTables)
  154. return false;
  155. OwnedHqlExpr constRow = createConstantRowExpr(transform);
  156. if (!constRow || !canGenerateStringInline(constRow->queryType()->getSize()))
  157. return false;
  158. buildConstRow(transform->queryRecord(), constRow, bound);
  159. return true;
  160. }
  161. IReferenceSelector * HqlCppTranslator::doBuildRowCreateRow(BuildCtx & ctx, IHqlExpression * expr)
  162. {
  163. CHqlBoundExpr bound;
  164. if (!doBuildRowConstantTransform(expr->queryChild(0), bound))
  165. return doBuildRowViaTemp(ctx, expr);
  166. BoundRow * row = bindConstantRow(ctx, expr, bound);
  167. return createReferenceSelector(row);
  168. }
  169. BoundRow * HqlCppTranslator::bindConstantRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  170. {
  171. BoundRow * row = bindRow(ctx, expr, bound.expr);
  172. //MORE: This should be done more cleanly
  173. OwnedHqlExpr sizeOfRow = createSizeof(row->querySelector());
  174. ctx.associateExpr(sizeOfRow, bound.length);
  175. return row;
  176. }
  177. bool HqlCppTranslator::doBuildRowConstantNull(IHqlExpression * expr, CHqlBoundExpr & bound)
  178. {
  179. if (!options.generateStaticInlineTables)
  180. return false;
  181. IHqlExpression * record = expr->queryRecord();
  182. OwnedHqlExpr constRow = createConstantNullRowExpr(record);
  183. if (!constRow)
  184. return false;
  185. buildConstRow(record, constRow, bound);
  186. return true;
  187. }
  188. IReferenceSelector * HqlCppTranslator::doBuildRowNull(BuildCtx & ctx, IHqlExpression * expr)
  189. {
  190. CHqlBoundExpr bound;
  191. if (!doBuildRowConstantNull(expr, bound))
  192. return doBuildRowViaTemp(ctx, expr);
  193. BoundRow * row = bindRow(ctx, expr, bound.expr);
  194. return createReferenceSelector(row);
  195. }
  196. IReferenceSelector * HqlCppTranslator::doBuildRowViaTemp(BuildCtx & ctx, IHqlExpression * expr)
  197. {
  198. HqlExprAssociation * match;
  199. if (expr->isDataset())
  200. match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  201. else
  202. match = ctx.queryAssociation(expr, AssocRow, NULL);
  203. if (match)
  204. {
  205. BoundRow * row = (BoundRow *)match;
  206. return createReferenceSelector(row, expr);
  207. }
  208. Owned<BoundRow> tempRow = declareTempRow(ctx, ctx, expr);
  209. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  210. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  211. buildRowAssign(ctx, createdRef, expr);
  212. finalizeTempRow(ctx, tempRow, rowBuilder);
  213. ctx.associate(*tempRow);
  214. return createReferenceSelector(tempRow);
  215. }
  216. void HqlCppTranslator::buildDefaultRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  217. {
  218. OwnedHqlExpr clearExpr = createRow(no_null, LINK(expr->queryRecord()), createAttribute(clearAtom));
  219. BoundRow * matchedRow = (BoundRow *)ctx.queryAssociation(clearExpr, AssocRow, NULL);
  220. if (!matchedRow)
  221. {
  222. if (doBuildRowConstantNull(expr, bound))
  223. {
  224. bindRow(ctx, clearExpr, bound.expr);
  225. }
  226. else
  227. {
  228. BuildCtx * declarectx = &ctx;
  229. BuildCtx * callCtx = &ctx;
  230. getInvariantMemberContext(ctx, &declarectx, &callCtx, true, false);
  231. Owned<BoundRow> tempRow = declareTempRow(*declarectx, *callCtx, clearExpr);
  232. Owned<BoundRow> rowBuilder = createRowBuilder(*callCtx, tempRow);
  233. OwnedHqlExpr size = createVariable(LINK(sizetType));
  234. OwnedHqlExpr clearCall = createClearRowCall(*callCtx, rowBuilder);
  235. callCtx->addDeclare(size, clearCall);
  236. OwnedHqlExpr sizeOfRow = createSizeof(rowBuilder->querySelector());
  237. callCtx->associateExpr(sizeOfRow, size);
  238. finalizeTempRow(*callCtx, tempRow, rowBuilder);
  239. declarectx->associate(*tempRow);
  240. bound.expr.set(tempRow->queryBound());
  241. }
  242. }
  243. else
  244. bound.expr.set(matchedRow->queryBound());
  245. //yuk yuk, hack. If called from a const context then need to make the reference unconst.
  246. //The real fix is to implement real const tracking throughout the code generator, but that is far from trivial.
  247. //rkc39.hql is an example...
  248. if (ctx.queryMatchExpr(constantMemberMarkerExpr))
  249. bound.expr.setown(createValue(no_cast, makeReferenceModifier(bound.expr->getType()), getPointer(bound.expr)));
  250. }
  251. void HqlCppTranslator::buildNullRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  252. {
  253. bound.expr.setown(createValue(no_nullptr, makeRowReferenceType(expr)));
  254. }
  255. IReferenceSelector * HqlCppTranslator::doBuildRowFromXML(BuildCtx & ctx, IHqlExpression * expr)
  256. {
  257. // assertex(supportsLinkCountedRows);
  258. Owned<ITypeInfo> overrideType = setLinkCountedAttr(expr->queryType(), true);
  259. Owned<ITypeInfo> utf8Type = makeUtf8Type(UNKNOWN_LENGTH, NULL);
  260. IHqlExpression * record = expr->queryRecord();
  261. OwnedHqlExpr ds = createDataset(no_anon, LINK(record));
  262. StringBuffer xmlInstanceName, xmlFactoryName, s;
  263. bool usesContents = false;
  264. getUniqueId(xmlInstanceName.append("xml"));
  265. buildXmlReadTransform(ds, xmlFactoryName, usesContents);
  266. OwnedHqlExpr curActivityId = getCurrentActivityId(ctx);
  267. s.append("Owned<IXmlToRowTransformer> ").append(xmlInstanceName).append(" = ").append(xmlFactoryName).append("(ctx,");
  268. generateExprCpp(s, curActivityId).append(");");
  269. ctx.addQuoted(s);
  270. HqlExprArray args;
  271. args.append(*createRowAllocator(ctx, record));
  272. args.append(*ensureExprType(expr->queryChild(1), utf8Type));
  273. args.append(*createQuoted(xmlInstanceName, makeBoolType()));
  274. args.append(*createConstant(expr->hasProperty(trimAtom)));
  275. OwnedHqlExpr function = bindFunctionCall(createRowFromXmlAtom, args, overrideType);
  276. CHqlBoundExpr bound;
  277. buildExpr(ctx, function, bound);
  278. Owned<ITypeInfo> rowType = makeReferenceModifier(LINK(overrideType));
  279. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  280. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  281. ctx.associate(*row); // associate here because it is compared inside the loop
  282. OwnedHqlExpr defaultRowPtr = getPointer(bound.expr);
  283. ctx.addAssign(rowExpr, defaultRowPtr);
  284. return createReferenceSelector(row);
  285. }
  286. //NB: If this is a dataset operation, this function assumes that any parent datasets are already in scope
  287. // i.e. processed in buildDatasetAssign()
  288. // the one exception is aggregate because it needs to treat its input differently.
  289. IReferenceSelector * HqlCppTranslator::buildNewOrActiveRow(BuildCtx & ctx, IHqlExpression * expr, bool isNew)
  290. {
  291. if (isNew)
  292. return buildNewRow(ctx, expr);
  293. else
  294. return buildActiveRow(ctx, expr);
  295. }
  296. IReferenceSelector * HqlCppTranslator::buildNewRow(BuildCtx & ctx, IHqlExpression * expr)
  297. {
  298. assertex(!expr->isDataset());
  299. BoundRow * match = static_cast<BoundRow *>(ctx.queryAssociation(expr, AssocRow, NULL));
  300. if (match)
  301. return createReferenceSelector(match, expr);
  302. BoundRow * row = NULL;
  303. node_operator op = expr->getOperator();
  304. switch (op)
  305. {
  306. case no_activerow:
  307. return buildActiveRow(ctx, expr->queryChild(0));
  308. case no_if:
  309. return doBuildRowIf(ctx, expr);
  310. case no_id2blob:
  311. return doBuildRowIdToBlob(ctx, expr, true);
  312. case no_index:
  313. case no_selectnth:
  314. return buildDatasetIndex(ctx, expr);
  315. case no_left:
  316. case no_right:
  317. case no_self:
  318. case no_top:
  319. case no_activetable:
  320. return buildActiveRow(ctx, expr);
  321. case no_fromxml:
  322. return doBuildRowFromXML(ctx, expr);
  323. case no_serialize:
  324. if (isDummySerializeDeserialize(expr))
  325. return buildNewRow(ctx, expr->queryChild(0)->queryChild(0));
  326. return doBuildRowViaTemp(ctx, expr);
  327. case no_deserialize:
  328. if (isDummySerializeDeserialize(expr))
  329. return buildNewRow(ctx, expr->queryChild(0)->queryChild(0));
  330. return doBuildRowDeserializeRow(ctx, expr);
  331. case no_deref:
  332. {
  333. //Untested
  334. CHqlBoundExpr bound;
  335. buildExpr(ctx, expr, bound);
  336. row = bindRow(ctx, expr, bound.expr);
  337. break;
  338. }
  339. case no_createrow:
  340. return doBuildRowCreateRow(ctx, expr);
  341. case no_newusertable:
  342. case no_hqlproject:
  343. case no_temprow:
  344. case no_projectrow:
  345. return doBuildRowViaTemp(ctx, expr);
  346. case no_null:
  347. return doBuildRowNull(ctx, expr);
  348. case no_typetransfer:
  349. {
  350. CHqlBoundExpr bound;
  351. IHqlExpression * value = expr->queryChild(1);
  352. if (value->isDatarow())
  353. buildAddress(ctx, value, bound);
  354. else
  355. buildExpr(ctx, value, bound);
  356. OwnedHqlExpr cursorExpr = createValue(no_implicitcast, makeReferenceModifier(expr->getType()), LINK(bound.expr));
  357. row = bindRow(ctx, expr, cursorExpr);
  358. break;
  359. }
  360. case no_getresult:
  361. {
  362. IHqlExpression * seqAttr = expr->queryProperty(sequenceAtom);
  363. IHqlExpression * nameAttr = expr->queryProperty(namedAtom);
  364. IHqlExpression * record = expr->queryRecord();
  365. OwnedHqlExpr serializedRecord = getSerializedForm(record);
  366. OwnedHqlExpr temp = createDatasetF(no_getresult, LINK(serializedRecord), LINK(seqAttr), LINK(nameAttr), NULL);
  367. OwnedHqlExpr row = createRow(no_selectnth, LINK(temp), createComma(getSizetConstant(1), createAttribute(noBoundCheckAtom)));
  368. row.setown(ensureDeserialized(row, expr->queryType()));
  369. return buildNewRow(ctx, row);
  370. }
  371. case no_matchattr:
  372. return doBuildRowMatchAttr(ctx, expr);
  373. case no_matchrow:
  374. return doBuildRowMatchRow(ctx, expr, true);
  375. case no_getgraphresult:
  376. case no_call:
  377. case no_externalcall:
  378. case no_alias:
  379. case no_translated:
  380. case no_libraryinput:
  381. {
  382. CHqlBoundExpr bound;
  383. buildExpr(ctx, expr, bound);
  384. Owned<ITypeInfo> rawType = removeModifier(expr->queryType(), typemod_ref);
  385. OwnedHqlExpr cursorExpr = createValue(no_implicitcast, makeReferenceModifier(LINK(rawType)), LINK(bound.expr));
  386. row = bindRow(ctx, expr, cursorExpr);
  387. if (bound.length)
  388. {
  389. OwnedHqlExpr sizeOfRow = createSizeof(row->querySelector());
  390. ctx.associateExpr(sizeOfRow, bound.length);
  391. }
  392. //We could associate the original expression to allow better cse for child datasets in transforms, but it doesn't actually improve any examples
  393. //IHqlExpression * original = queryPropertyChild(expr, _original_Atom, 0);
  394. //if (original)
  395. // bindRow(ctx, original, cursorExpr)->setResultAlias();
  396. break;//return createReferenceSelector(cursor);
  397. }
  398. case no_comma:
  399. case no_compound:
  400. buildStmt(ctx, expr->queryChild(0));
  401. return buildNewRow(ctx, expr->queryChild(1));
  402. case no_select:
  403. {
  404. #ifdef _DEBUG
  405. IHqlExpression * field = expr->queryChild(1);
  406. #endif
  407. Owned<IReferenceSelector> selector;
  408. if (isNewSelector(expr))
  409. selector.setown(buildNewRow(ctx, expr->queryChild(0)));
  410. else
  411. selector.setown(buildActiveRow(ctx, expr->queryChild(0)));
  412. return selector->select(ctx, expr);
  413. }
  414. //If called because known to be a single row.
  415. case no_datasetfromrow:
  416. case no_nofold:
  417. case no_nohoist:
  418. case no_section:
  419. case no_sectioninput:
  420. return buildNewRow(ctx, expr->queryChild(0));
  421. case no_skip:
  422. {
  423. buildStmt(ctx, expr);
  424. OwnedHqlExpr null = createNullExpr(expr);
  425. return buildNewRow(ctx, null);
  426. }
  427. case no_alias_scope:
  428. {
  429. expandAliasScope(ctx, expr);
  430. return buildNewRow(ctx, expr->queryChild(0));
  431. }
  432. case no_split:
  433. throwUnexpected();
  434. //not at all sure about this.....
  435. return buildNewRow(ctx, expr->queryChild(0));
  436. default:
  437. {
  438. HqlExprAssociation * match;
  439. if (expr->isDataset())
  440. match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  441. else
  442. match = ctx.queryAssociation(expr, AssocRow, NULL);
  443. if (match)
  444. {
  445. BoundRow * row = (BoundRow *)match;
  446. IReferenceSelector * alias = row->queryAlias();
  447. if (alias)
  448. return LINK(alias);
  449. return createReferenceSelector(row, expr);
  450. }
  451. UNIMPLEMENTED_XY("row", getOpString(expr->getOperator()));
  452. }
  453. }
  454. assertex(row);
  455. return createReferenceSelector(row);
  456. }
  457. IReferenceSelector * HqlCppTranslator::buildActiveRow(BuildCtx & ctx, IHqlExpression * expr)
  458. {
  459. node_operator op = expr->getOperator();
  460. switch (op)
  461. {
  462. case no_left:
  463. case no_right:
  464. case no_self:
  465. case no_top:
  466. case no_activetable:
  467. case no_selfref: // shouldn't ever occur...
  468. //All selectors should be listed here...
  469. break;
  470. case no_activerow:
  471. return buildActiveRow(ctx, expr->queryChild(0));
  472. default:
  473. if (!expr->isDataset())
  474. return buildNewRow(ctx, expr);
  475. break;
  476. }
  477. HqlExprAssociation * match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  478. if (match)
  479. {
  480. BoundRow * row = (BoundRow *)match;
  481. IReferenceSelector * alias = row->queryAlias();
  482. if (alias)
  483. return LINK(alias);
  484. return createReferenceSelector(row, expr);
  485. }
  486. switch (op)
  487. {
  488. case no_select:
  489. {
  490. #ifdef _DEBUG
  491. IHqlExpression * field = expr->queryChild(1);
  492. #endif
  493. Owned<IReferenceSelector> selector = buildNewOrActiveRow(ctx, expr->queryChild(0), isNewSelector(expr));
  494. return selector->select(ctx, expr);
  495. }
  496. case no_id2blob:
  497. return doBuildRowIdToBlob(ctx, expr, false);
  498. }
  499. StringBuffer tablename;
  500. getExprIdentifier(tablename, expr);
  501. traceExpression("Dataset not found", expr);
  502. RowAssociationIterator iter(ctx);
  503. ForEach(iter)
  504. {
  505. BoundRow & cur = iter.get();
  506. traceExpression("BoundCursor:", cur.querySelector());
  507. }
  508. throwError1(HQLERR_DatasetNotActive, tablename.str());
  509. return NULL; //remove warning about control paths
  510. }
  511. //---------------------------------------------------------------------------
  512. void HqlCppTranslator::doBuildExprAggregate(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  513. {
  514. OwnedHqlExpr normalized = normalizeAnyDatasetAliases(expr);
  515. if (expr != normalized)
  516. {
  517. buildExpr(ctx, normalized, tgt);
  518. return;
  519. }
  520. node_operator op = expr->getOperator();
  521. ITypeInfo * type = expr->queryType();
  522. ITypeInfo * tempType = op == no_count ? unsignedType : type;
  523. LoopInvariantHelper helper;
  524. BuildCtx aggctx(ctx);
  525. if (options.optimizeLoopInvariant)
  526. helper.getBestContext(aggctx, expr);
  527. CHqlBoundTarget result;
  528. createTempFor(aggctx, tempType, result, typemod_none, FormatNatural);
  529. doBuildAssignAggregate(aggctx, result, expr);
  530. tgt.setFromTarget(result);
  531. if (!isSameBasicType(type, tempType))
  532. tgt.expr.setown(createValue(no_implicitcast, LINK(type), tgt.expr.getClear()));
  533. if (expr->isPure())
  534. aggctx.associateExpr(expr, tgt);
  535. }
  536. void HqlCppTranslator::doBuildAssignAggregateLoop(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr, IHqlExpression * dataset, IHqlExpression * doneFirstVar)
  537. {
  538. node_operator op = expr->getOperator();
  539. switch (op)
  540. {
  541. case no_exists:
  542. {
  543. OwnedHqlExpr optimized = queryOptimizedExists(ctx, expr, dataset);
  544. if (optimized)
  545. {
  546. assignBound(ctx, target, optimized);
  547. return;
  548. }
  549. break;
  550. }
  551. case no_count:
  552. {
  553. CHqlBoundExpr temp;
  554. if (canBuildOptimizedCount(ctx, dataset, temp))
  555. {
  556. OwnedHqlExpr thisCount = temp.getTranslatedExpr();
  557. buildIncrementAssign(ctx, target, thisCount);
  558. return;
  559. }
  560. break;
  561. }
  562. }
  563. switch (dataset->getOperator())
  564. {
  565. case no_if:
  566. {
  567. BuildCtx subctx(ctx);
  568. IHqlStmt * stmt = buildFilterViaExpr(subctx, dataset->queryChild(0));
  569. doBuildAssignAggregateLoop(subctx, target, expr, dataset->queryChild(1), doneFirstVar);
  570. subctx.selectElse(stmt);
  571. doBuildAssignAggregateLoop(subctx, target, expr, dataset->queryChild(2), doneFirstVar);
  572. return;
  573. }
  574. case no_addfiles:
  575. {
  576. doBuildAssignAggregateLoop(ctx, target, expr, dataset->queryChild(0), doneFirstVar);
  577. doBuildAssignAggregateLoop(ctx, target, expr, dataset->queryChild(1), doneFirstVar);
  578. return;
  579. }
  580. case no_null:
  581. return;
  582. }
  583. LinkedHqlExpr arg = expr->queryChild(1);
  584. IHqlExpression * oldDataset = expr->queryChild(0);
  585. //If no_if or no_addfiles has been optimized above then the selector for the argument will have changed => map it.
  586. if (arg && (dataset != oldDataset))
  587. arg.setown(replaceSelector(arg, oldDataset, dataset));
  588. bool needToBreak = (op == no_exists);
  589. if (needToBreak)
  590. {
  591. //if it can have at most one row (fairly strange code!) then don't add a break
  592. //unless it was deliberately a choosen to restrict the number of iterations.
  593. if (hasNoMoreRowsThan(dataset, 1) && (dataset->getOperator() != no_choosen))
  594. needToBreak = false;
  595. }
  596. BuildCtx loopctx(ctx);
  597. buildDatasetIterate(loopctx, dataset, needToBreak);
  598. switch (op)
  599. {
  600. case no_exists:
  601. buildExprAssign(loopctx, target, queryBoolExpr(true));
  602. if (needToBreak)
  603. loopctx.addBreak();
  604. break;
  605. case no_count:
  606. {
  607. OwnedHqlExpr inc = createValue(no_postinc, makeVoidType(), LINK(target.expr));
  608. loopctx.addExpr(inc);
  609. break;
  610. }
  611. case no_sum:
  612. {
  613. OwnedHqlExpr cseArg = options.spotCSE ? spotScalarCSE(arg) : LINK(arg);
  614. buildIncrementAssign(loopctx, target, cseArg);
  615. break;
  616. }
  617. case no_min:
  618. case no_max:
  619. {
  620. BuildCtx maxctx(loopctx);
  621. OwnedHqlExpr resultExpr = target.getTranslatedExpr();
  622. OwnedHqlExpr cseArg = options.spotCSE ? spotScalarCSE(arg) : LINK(arg);
  623. OwnedHqlExpr simpleArg = buildSimplifyExpr(loopctx, cseArg);
  624. OwnedHqlExpr test = createBoolExpr((op == no_min) ? no_lt : no_gt, LINK(simpleArg), LINK(resultExpr));
  625. if (doneFirstVar)
  626. {
  627. IHqlExpression * firstTest = createValue(no_not, makeBoolType(), LINK(doneFirstVar));
  628. test.setown(createBoolExpr(no_or, firstTest, test.getClear()));
  629. }
  630. buildFilter(maxctx, test);
  631. buildExprAssign(maxctx, target, simpleArg);
  632. if (doneFirstVar)
  633. buildAssignToTemp(maxctx, doneFirstVar, queryBoolExpr(true));
  634. break;
  635. }
  636. default:
  637. assertex(!"unknown aggregate on child datasets");
  638. break;
  639. }
  640. }
  641. bool assignAggregateDirect(const CHqlBoundTarget & target, IHqlExpression * expr)
  642. {
  643. node_operator op = expr->getOperator();
  644. ITypeInfo * type = expr->queryType();
  645. ITypeInfo * tempType = op == no_count ? unsignedType : type;
  646. if (!isSameUnqualifiedType(target.queryType(), tempType))
  647. return false;
  648. //For exists/count/sum use a temporary variable, and then assign rather than accumulating directly in the target
  649. switch (op)
  650. {
  651. case no_sum:
  652. if (type->getTypeCode() != type_int)
  653. break;
  654. //fall through
  655. case no_exists:
  656. case no_count:
  657. if (target.expr->getOperator() != no_variable)
  658. return false;
  659. break;
  660. }
  661. return true;
  662. }
  663. static bool isNullValueMinimumValue(ITypeInfo * type)
  664. {
  665. switch (type->getTypeCode())
  666. {
  667. case type_int:
  668. case type_swapint:
  669. case type_decimal:
  670. return !type->isSigned();
  671. case type_data:
  672. case type_qstring:
  673. return true;
  674. }
  675. return false;
  676. }
  677. void HqlCppTranslator::doBuildAssignAggregate(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * _expr)
  678. {
  679. OwnedHqlExpr expr = normalizeAnyDatasetAliases(_expr);
  680. if (assignAggregateDirect(target, expr))
  681. {
  682. IHqlExpression * dataset = expr->queryChild(0);
  683. OwnedHqlExpr resultExpr = target.getTranslatedExpr();
  684. node_operator op = expr->getOperator();
  685. switch (op)
  686. {
  687. case no_exists:
  688. buildExprAssign(ctx, target, queryBoolExpr(false));
  689. break;
  690. default:
  691. {
  692. OwnedHqlExpr null = createNullExpr(target.queryType());
  693. buildExprAssign(ctx, target, null);
  694. break;
  695. }
  696. }
  697. OwnedHqlExpr doneFirstVar;
  698. if ((op == no_min) || ((op == no_max) && !isNullValueMinimumValue(target.queryType())))
  699. {
  700. doneFirstVar.setown(ctx.getTempDeclare(queryBoolType(), queryBoolExpr(false)));
  701. }
  702. doBuildAssignAggregateLoop(ctx, target, expr, dataset, doneFirstVar);
  703. }
  704. else
  705. {
  706. doBuildExprAssign(ctx, target, expr);
  707. }
  708. }
  709. //---------------------------------------------------------------------------
  710. bool HqlCppTranslator::canBuildOptimizedCount(BuildCtx & ctx, IHqlExpression * dataset, CHqlBoundExpr & tgt)
  711. {
  712. switch (dataset->getOperator())
  713. {
  714. case no_select:
  715. {
  716. if (isMultiLevelDatasetSelector(dataset, false))
  717. return false;
  718. Owned<IReferenceSelector> selector = buildReference(ctx, dataset);
  719. CHqlBoundExpr temp;
  720. selector->get(ctx, temp);
  721. tgt.expr.setown(getBoundCount(temp));
  722. return true;
  723. }
  724. break;
  725. default:
  726. if (!options.tempDatasetsUseLinkedRows)
  727. break;
  728. if (!alwaysEvaluatesToBound(dataset))
  729. break;
  730. //fall through
  731. case no_rows:
  732. case no_null:
  733. {
  734. CHqlBoundExpr temp;
  735. buildDataset(ctx, dataset, temp, FormatNatural);
  736. tgt.expr.setown(getBoundCount(temp));
  737. return true;
  738. }
  739. }
  740. #if 0
  741. //This is improves a few obscure cases (normally in the global context). I'm not convinced it is worth the extra cycles.
  742. //Could also remove the bound.count test.
  743. CHqlBoundExpr bound;
  744. if (ctx.getMatchExpr(dataset, bound) && bound.count)
  745. {
  746. tgt.expr.setown(getBoundCount(bound));
  747. return true;
  748. }
  749. #endif
  750. return false;
  751. }
  752. void HqlCppTranslator::doBuildExprCount(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  753. {
  754. if (expr->hasProperty(keyedAtom))
  755. throwError(HQLERR_KeyedCountNonKeyable);
  756. IHqlExpression * dataset = expr->queryChild(0);
  757. CHqlBoundExpr temp;
  758. if (canBuildOptimizedCount(ctx, dataset, temp))
  759. {
  760. OwnedHqlExpr translated = temp.getTranslatedExpr();
  761. OwnedHqlExpr cast = ensureExprType(translated, expr->queryType());
  762. buildExpr(ctx, cast, tgt);
  763. }
  764. else
  765. doBuildExprAggregate(ctx, expr, tgt);
  766. }
  767. //---------------------------------------------------------------------------
  768. IHqlExpression * HqlCppTranslator::queryOptimizedExists(BuildCtx & ctx, IHqlExpression * expr, IHqlExpression * dataset)
  769. {
  770. node_operator dsOp = dataset->getOperator();
  771. //really this is isSimple()
  772. CHqlBoundExpr optimized;
  773. bool canOptimizeCount = canBuildOptimizedCount(ctx, dataset, optimized);
  774. node_operator op = (expr->getOperator() == no_exists) ? no_ne : no_eq;
  775. bool specialCase = false;
  776. switch (dsOp)
  777. {
  778. case no_select:
  779. specialCase = canOptimizeCount;
  780. break;
  781. default:
  782. specialCase = !canOptimizeCount && alwaysEvaluatesToBound(dataset);
  783. break;
  784. }
  785. if (specialCase)
  786. {
  787. CHqlBoundExpr temp;
  788. buildDataset(ctx, dataset, temp, FormatNatural);
  789. IHqlExpression * test;
  790. if (temp.count)
  791. test = LINK(temp.count);
  792. else
  793. test = getBoundSize(temp);
  794. return createBoolExpr(op, test, createConstant(test->queryType()->castFrom(false, 0)));
  795. }
  796. else if (canOptimizeCount)
  797. {
  798. IHqlExpression * count = optimized.expr;
  799. return createBoolExpr(op, LINK(count), createConstant(count->queryType()->castFrom(false, 0)));
  800. }
  801. return NULL;
  802. }
  803. void HqlCppTranslator::doBuildExprExists(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  804. {
  805. OwnedHqlExpr optimized = queryOptimizedExists(ctx, expr, expr->queryChild(0));
  806. if (optimized)
  807. tgt.expr.setown(optimized.getClear());
  808. else
  809. doBuildExprAggregate(ctx, expr, tgt);
  810. }
  811. //---------------------------------------------------------------------------
  812. static IHqlExpression * createMinMax(node_operator compareOp, ITypeInfo * type, IHqlExpression * left, IHqlExpression * right)
  813. {
  814. return createValue(no_if, LINK(type),
  815. createBoolExpr(compareOp, LINK(left), LINK(right)),
  816. LINK(left), LINK(right));
  817. }
  818. bool HqlCppTranslator::doBuildAggregateMinMaxList(BuildCtx & ctx, const CHqlBoundTarget * target, IHqlExpression * expr, IHqlExpression * list, CHqlBoundExpr * tgt, node_operator compareOp)
  819. {
  820. OwnedHqlExpr value;
  821. unsigned max = list->numChildren();
  822. switch(max)
  823. {
  824. case 0:
  825. value.setown(createNullExpr(expr));
  826. break;
  827. case 1:
  828. value.set(list->queryChild(0));
  829. break;
  830. case 2:
  831. case 3:
  832. {
  833. OwnedHqlExpr simple[3];
  834. for (unsigned i=0; i < max; i++)
  835. {
  836. CHqlBoundExpr bound;
  837. buildSimpleExpr(ctx, list->queryChild(i), bound);
  838. simple[i].setown(bound.getTranslatedExpr());
  839. }
  840. ITypeInfo * type = expr->queryType();
  841. if (max == 2)
  842. value.setown(createMinMax(compareOp, type, simple[0], simple[1]));
  843. else
  844. {
  845. OwnedHqlExpr cmp02 = createMinMax(compareOp, type, simple[0], simple[2]);
  846. OwnedHqlExpr cmp12 = createMinMax(compareOp, type, simple[1], simple[2]);
  847. value.setown(createValue(no_if, expr->getType(),
  848. createBoolExpr(compareOp, LINK(simple[0]), LINK(simple[1])),
  849. LINK(cmp02), LINK(cmp12)));
  850. }
  851. }
  852. }
  853. if (value)
  854. {
  855. buildExprOrAssign(ctx, target, value, tgt);
  856. return true;
  857. }
  858. {
  859. CHqlBoundTarget temp;
  860. createTempFor(ctx, expr, temp);
  861. buildExprAssign(ctx, temp, list->queryChild(0));
  862. OwnedHqlExpr best = temp.getTranslatedExpr();
  863. for (unsigned i=1; i < list->numChildren(); i++)
  864. {
  865. CHqlBoundExpr bound;
  866. buildSimpleExpr(ctx, list->queryChild(i), bound);
  867. OwnedHqlExpr simple = bound.getTranslatedExpr();
  868. BuildCtx subctx(ctx);
  869. OwnedHqlExpr cond = createBoolExpr(compareOp, LINK(simple), LINK(best));
  870. buildFilter(subctx, cond);
  871. buildExprAssign(subctx, temp, simple);
  872. }
  873. buildExprOrAssign(ctx, target, best, tgt);
  874. return true;
  875. }
  876. }
  877. void HqlCppTranslator::doBuildAggregateList(BuildCtx & ctx, const CHqlBoundTarget * target, IHqlExpression * expr, CHqlBoundExpr * tgt)
  878. {
  879. OwnedHqlExpr list = normalizeListCasts(expr->queryChild(0));
  880. if (list->getOperator() == no_alias_scope)
  881. {
  882. expandAliasScope(ctx, list);
  883. list.set(list->queryChild(0));
  884. }
  885. node_operator aggOp;
  886. switch (expr->getOperator())
  887. {
  888. case no_existslist:
  889. {
  890. //Fixed length lists should have been optimized away
  891. CHqlBoundExpr bound;
  892. buildExpr(ctx, list, bound);
  893. OwnedHqlExpr test;
  894. if (bound.count)
  895. test.set(bound.count);
  896. else
  897. test.setown(getBoundLength(bound));
  898. OwnedHqlExpr value = createValue(no_ne, makeBoolType(), LINK(test), ensureExprType(queryZero(), test->queryType()));
  899. OwnedHqlExpr translated = createTranslated(value);
  900. buildExprOrAssign(ctx, target, translated, tgt);
  901. return;
  902. }
  903. case no_countlist:
  904. {
  905. //Fixed length lists should have been optimized away
  906. CHqlBoundExpr bound;
  907. buildExpr(ctx, list, bound);
  908. OwnedHqlExpr test = getBoundCount(bound);
  909. OwnedHqlExpr value = ensureExprType(test, expr->queryType());
  910. OwnedHqlExpr translated = createTranslated(value);
  911. buildExprOrAssign(ctx, target, translated, tgt);
  912. return;
  913. }
  914. case no_sumlist:
  915. aggOp = no_sumgroup;
  916. if (list->getOperator() == no_list)
  917. {
  918. HqlExprArray args;
  919. ITypeInfo * exprType = expr->queryType();
  920. ForEachChild(i, list)
  921. args.append(*ensureExprType(list->queryChild(i), exprType));
  922. OwnedHqlExpr balanced = createBalanced(no_add, exprType, args);
  923. if (!balanced)
  924. balanced.setown(ensureExprType(queryZero(), exprType));
  925. buildExprOrAssign(ctx, target, balanced, tgt);
  926. return;
  927. }
  928. //special case fixed length lists
  929. break;
  930. case no_minlist:
  931. aggOp = no_mingroup;
  932. if (list->getOperator() == no_list)
  933. {
  934. if (doBuildAggregateMinMaxList(ctx, target, expr, list, tgt, no_lt))
  935. return;
  936. }
  937. break;
  938. case no_maxlist:
  939. aggOp = no_maxgroup;
  940. if (list->getOperator() == no_list)
  941. {
  942. if (doBuildAggregateMinMaxList(ctx, target, expr, list, tgt, no_gt))
  943. return;
  944. }
  945. break;
  946. default:
  947. throwUnexpectedOp(expr->getOperator());
  948. }
  949. ITypeInfo * elemType = list->queryType()->queryChildType();
  950. if (!elemType) elemType = defaultIntegralType;
  951. //Default implementation in terms of a dataset
  952. OwnedHqlExpr field = createField(valueAtom, LINK(elemType), NULL);
  953. OwnedHqlExpr record = createRecord(field);
  954. OwnedHqlExpr ds = createDataset(no_temptable, LINK(list), LINK(record));
  955. OwnedHqlExpr aggField = createField(valueAtom, expr->getType(), NULL);
  956. OwnedHqlExpr aggRecord = createRecord(aggField);
  957. OwnedHqlExpr self = createSelector(no_self, aggRecord, NULL);
  958. OwnedHqlExpr aggExpr = createValue(aggOp, expr->getType(), createSelectExpr(LINK(ds), LINK(field)));
  959. OwnedHqlExpr aggAssign = createAssign(createSelectExpr(LINK(self), LINK(aggField)), LINK(aggExpr));
  960. OwnedHqlExpr aggTransform = createValue(no_newtransform, makeTransformType(aggRecord->getType()), LINK(aggAssign));
  961. OwnedHqlExpr agg = createDataset(no_newaggregate, LINK(ds), createComma(LINK(aggRecord), LINK(aggTransform)));
  962. OwnedHqlExpr result = createNewSelectExpr(createRow(no_selectnth, LINK(agg), createConstantOne()), LINK(aggField));
  963. buildExprOrAssign(ctx, target, result, tgt);
  964. }
  965. //---------------------------------------------------------------------------
  966. static HqlTransformerInfo graphIndependanceCheckerInfo("GraphIndependanceChecker");
  967. class GraphIndependanceChecker : public NewHqlTransformer
  968. {
  969. public:
  970. GraphIndependanceChecker(IHqlExpression * _graph) : NewHqlTransformer(graphIndependanceCheckerInfo), graph(_graph) { independent = true; }
  971. void analyseExpr(IHqlExpression * expr)
  972. {
  973. if (!independent || alreadyVisited(expr))
  974. return;
  975. switch (expr->getOperator())
  976. {
  977. case no_getgraphresult:
  978. case no_getgraphloopresultset:
  979. case no_getgraphloopresult:
  980. if (expr->queryChild(1) == graph)
  981. {
  982. independent = false;
  983. return;
  984. }
  985. break;
  986. }
  987. NewHqlTransformer::analyseExpr(expr);
  988. }
  989. inline bool isIndependent() const { return independent; }
  990. protected:
  991. LinkedHqlExpr graph;
  992. bool independent;
  993. };
  994. bool isGraphIndependent(IHqlExpression * expr, IHqlExpression * graph)
  995. {
  996. switch (expr->getOperator())
  997. {
  998. case no_constant:
  999. return true;
  1000. }
  1001. GraphIndependanceChecker checker(graph);
  1002. checker.analyse(expr, 0);
  1003. return checker.isIndependent();
  1004. }
  1005. ///--------------------------------------------------------------------------------------------------------------------
  1006. ChildGraphExprBuilder::ChildGraphExprBuilder(unsigned _numInputs)
  1007. : numInputs(_numInputs)
  1008. {
  1009. numOutputs=0;
  1010. represents.setown(createAttribute(graphAtom, createUniqueId()));
  1011. resultsExpr.setown(createAttribute(resultsAtom, LINK(represents)));
  1012. }
  1013. IHqlExpression * ChildGraphExprBuilder::addDataset(IHqlExpression * expr)
  1014. {
  1015. OwnedHqlExpr resultNumExpr;
  1016. ForEachItemIn(i, results)
  1017. {
  1018. IHqlExpression & curSetResult = results.item(i);
  1019. if (expr->queryBody() == curSetResult.queryChild(0)->queryBody())
  1020. {
  1021. resultNumExpr.set(curSetResult.queryChild(2));
  1022. break;
  1023. }
  1024. }
  1025. if (!resultNumExpr)
  1026. {
  1027. resultNumExpr.setown(getSizetConstant(numResults()));
  1028. results.append(*createValue(no_setgraphresult, makeVoidType(), LINK(expr), LINK(represents), LINK(resultNumExpr)));
  1029. numOutputs++;
  1030. }
  1031. HqlExprArray args;
  1032. args.append(*LINK(expr->queryRecord()));
  1033. args.append(*LINK(represents));
  1034. args.append(*LINK(resultNumExpr));
  1035. if (isGrouped(expr))
  1036. args.append(*createAttribute(groupedAtom));
  1037. if (!expr->isDataset())
  1038. args.append(*createAttribute(rowAtom));
  1039. args.append(*createAttribute(externalAtom, LINK(resultsExpr)));
  1040. args.append(*createAttribute(_original_Atom, LINK(expr)));
  1041. OwnedHqlExpr ret = createDataset(no_getgraphresult, args);
  1042. if (expr->isDatarow())
  1043. ret.setown(createRow(no_selectnth, LINK(ret), createComma(getSizetConstant(1), createAttribute(noBoundCheckAtom))));
  1044. return ret.getClear();
  1045. }
  1046. void ChildGraphExprBuilder::addAction(IHqlExpression * expr)
  1047. {
  1048. results.append(*LINK(expr));
  1049. }
  1050. unsigned ChildGraphExprBuilder::addInput()
  1051. {
  1052. unsigned id = numResults();
  1053. numInputs++;
  1054. return id;
  1055. }
  1056. IHqlExpression * ChildGraphExprBuilder::getGraph()
  1057. {
  1058. HqlExprArray args;
  1059. args.append(*LINK(represents));
  1060. args.append(*getSizetConstant(numResults()));
  1061. args.append(*createActionList(results));
  1062. return createValue(no_childquery, makeVoidType(), args);
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. // Child dataset processing
  1066. ChildGraphBuilder::ChildGraphBuilder(HqlCppTranslator & _translator, IHqlExpression * subgraph)
  1067. : translator(_translator)
  1068. {
  1069. represents.set(subgraph->queryChild(0));
  1070. id = translator.nextActivityId();
  1071. appendUniqueId(instanceName.append("child"), id);
  1072. instanceExpr.setown(createQuoted(instanceName, makeBoolType()));
  1073. resultsExpr.setown(createAttribute(resultsAtom, LINK(represents)));
  1074. StringBuffer s;
  1075. resultInstanceExpr.setown(createQuoted(appendUniqueId(s.append("res"), id), makeBoolType()));
  1076. numResults = (unsigned)getIntValue(subgraph->queryChild(1));
  1077. IHqlExpression * actions = subgraph->queryChild(2);
  1078. actions->unwindList(results, no_actionlist);
  1079. }
  1080. void ChildGraphBuilder::generateGraph(BuildCtx & ctx)
  1081. {
  1082. BuildCtx graphctx(ctx);
  1083. //Make sure at least one results - because currently that's how we determine if new resourcing is being used
  1084. //Remove this line once all engines use the new child queries exclusively
  1085. if (numResults == 0) numResults++;
  1086. OwnedHqlExpr query = createActionList(results);
  1087. OwnedHqlExpr resourced = translator.getResourcedChildGraph(graphctx, query, represents, numResults, no_none);
  1088. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(graphctx, PETchild, represents, resourced, true);
  1089. if (!translator.queryOptions().serializeRowsetInExtract)
  1090. extractBuilder->setAllowDestructor();
  1091. translator.beginExtract(graphctx, extractBuilder);
  1092. translator.doBuildThorSubGraph(graphctx, resourced, SubGraphChild, id, represents);
  1093. EvalContext * instance = translator.queryEvalContext(graphctx);
  1094. OwnedHqlExpr retInstanceExpr;
  1095. if (instance && !translator.insideOnCreate(graphctx))
  1096. retInstanceExpr.setown(instance->createGraphLookup(id, true));
  1097. else
  1098. retInstanceExpr.setown(translator.doCreateGraphLookup(graphctx, graphctx, id, "this", true));
  1099. assertex(retInstanceExpr == instanceExpr);
  1100. CHqlBoundExpr boundExtract;
  1101. extractBuilder->endCreateExtract(boundExtract);
  1102. HqlExprArray args;
  1103. args.append(*LINK(instanceExpr));
  1104. args.append(*createTranslated(boundExtract.length));
  1105. args.append(*boundExtract.getTranslatedExpr());
  1106. OwnedHqlExpr call = translator.bindFunctionCall(evaluateChildQueryInstanceAtom, args);
  1107. CHqlBoundExpr bound;
  1108. translator.buildExpr(graphctx, call, bound);
  1109. StringBuffer s;
  1110. s.append("Owned<IEclGraphResults> ");
  1111. translator.generateExprCpp(s, resultInstanceExpr);
  1112. s.append(" = ");
  1113. translator.generateExprCpp(s, bound.expr);
  1114. s.append(";");
  1115. graphctx.addQuoted(s);
  1116. translator.endExtract(graphctx, extractBuilder);
  1117. ctx.associateExpr(resultsExpr, resultInstanceExpr);
  1118. }
  1119. void ChildGraphBuilder::generatePrefetchGraph(BuildCtx & _ctx, OwnedHqlExpr * retGraphExpr)
  1120. {
  1121. BuildCtx ctx(_ctx);
  1122. ctx.addGroup();
  1123. BuildCtx aliasctx(ctx);
  1124. aliasctx.addGroup();
  1125. OwnedHqlExpr query = createActionList(results);
  1126. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, query, represents, numResults, no_none);
  1127. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(ctx, PETchild, represents, resourced, false);
  1128. createBuilderAlias(aliasctx, extractBuilder);
  1129. translator.beginExtract(ctx, extractBuilder);
  1130. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1131. EvalContext * instance = translator.queryEvalContext(ctx);
  1132. OwnedHqlExpr retInstanceExpr;
  1133. assertex(instance && !translator.insideOnCreate(ctx));
  1134. retInstanceExpr.setown(instance->createGraphLookup(id, true));
  1135. assertex(retInstanceExpr == instanceExpr);
  1136. retGraphExpr->setown(retInstanceExpr.getClear());
  1137. }
  1138. void ChildGraphBuilder::createBuilderAlias(BuildCtx & ctx, ParentExtract * extractBuilder)
  1139. {
  1140. StringBuffer s;
  1141. s.append("rtlRowBuilder & ");
  1142. translator.generateExprCpp(s, extractBuilder->queryExtractName());
  1143. s.append(" = builder;");
  1144. ctx.addQuoted(s);
  1145. }
  1146. unique_id_t ChildGraphBuilder::buildLoopBody(BuildCtx & ctx, bool multiInstance)
  1147. {
  1148. BuildCtx subctx(ctx);
  1149. subctx.addGroup();
  1150. OwnedHqlExpr query = createActionList(results);
  1151. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, query, represents, numResults, no_loop);
  1152. //Add a flag to indicate multi instance
  1153. if (multiInstance)
  1154. resourced.setown(appendOwnedOperand(resourced, createAttribute(multiInstanceAtom)));
  1155. bool isGlobalThorLoop = translator.targetThor() && !translator.insideChildQuery(ctx);
  1156. Owned<ParentExtract> extractBuilder = isGlobalThorLoop ? translator.createExtractBuilder(ctx, PETloop, represents, GraphRemote, false)
  1157. : translator.createExtractBuilder(ctx, PETloop, represents, resourced, false);
  1158. createBuilderAlias(subctx, extractBuilder);
  1159. translator.beginExtract(ctx, extractBuilder);
  1160. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1161. translator.endExtract(ctx, extractBuilder);
  1162. return id;
  1163. }
  1164. static HqlTransformerInfo graphLoopReplacerInfo("GraphLoopReplacer");
  1165. class GraphLoopReplacer : public NewHqlTransformer
  1166. {
  1167. public:
  1168. GraphLoopReplacer(IHqlExpression * _rowsid, IHqlExpression * _represents, IHqlExpression * _counter, bool _isParallel) :
  1169. NewHqlTransformer(graphLoopReplacerInfo), rowsid(_rowsid), represents(_represents), counter(_counter), isParallel(_isParallel)
  1170. {
  1171. }
  1172. virtual IHqlExpression * createTransformed(IHqlExpression * expr)
  1173. {
  1174. switch (expr->getOperator())
  1175. {
  1176. case no_counter:
  1177. if (expr->queryBody() == counter)
  1178. {
  1179. if (isParallel)
  1180. {
  1181. HqlExprArray args;
  1182. args.append(*LINK(represents));
  1183. // unwindChildren(args, expr);
  1184. OwnedHqlExpr ret = createValue(no_loopcounter, expr->getType(), args);
  1185. //Yuk: Wrap this in an alias to ensure it is evaluated at the correct place.
  1186. //there has to be a better way..... We could...
  1187. //a) strictly defined when it can be evaluated - e.g., ctx->defines(graph) && (!parentctx || !parentctx->definesGraph)
  1188. //b) set a flag in the expression to indicate forced evaluation (even worse than the alias)
  1189. //c) add the code to evaluate no_loopcounter inside evaluateInContext
  1190. return createAlias(ret, internalAttrExpr);
  1191. }
  1192. else
  1193. {
  1194. counterResult.setown(createCounterAsResult(counter, represents, 0));
  1195. return LINK(counterResult);
  1196. }
  1197. }
  1198. break;
  1199. case no_rowsetindex:
  1200. {
  1201. IHqlExpression * rowset = expr->queryChild(0);
  1202. if (rowset->getOperator() != no_rowset)
  1203. break;
  1204. IHqlExpression * rows = rowset->queryChild(0);
  1205. if (rows->queryChild(1) != rowsid)
  1206. break;
  1207. HqlExprArray args;
  1208. args.append(*LINK(rows->queryChild(0)->queryRecord()));
  1209. args.append(*LINK(represents));
  1210. args.append(*transform(expr->queryChild(1)));
  1211. return createDataset(no_getgraphloopresult, args);
  1212. }
  1213. case no_rowset:
  1214. {
  1215. IHqlExpression * rows = expr->queryChild(0);
  1216. if (rows->queryChild(1) != rowsid)
  1217. break;
  1218. HqlExprArray args;
  1219. args.append(*LINK(rows->queryChild(0)->queryRecord()));
  1220. args.append(*LINK(represents));
  1221. return createValue(no_getgraphloopresultset, expr->getType(), args);
  1222. }
  1223. }
  1224. return NewHqlTransformer::createTransformed(expr);
  1225. }
  1226. inline IHqlExpression * queryCounterResult() { return counterResult; }
  1227. protected:
  1228. IHqlExpression * rowsid;
  1229. IHqlExpression * represents;
  1230. IHqlExpression * counter;
  1231. OwnedHqlExpr counterResult;
  1232. bool isParallel;
  1233. };
  1234. unique_id_t ChildGraphBuilder::buildGraphLoopBody(BuildCtx & ctx, bool isParallel)
  1235. {
  1236. BuildCtx subctx(ctx);
  1237. subctx.addGroup();
  1238. OwnedHqlExpr query = createActionList(results);
  1239. translator.traceExpression("Before Loop resource", query);
  1240. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, query, represents, numResults, no_loop);
  1241. translator.traceExpression("After Loop resource", resourced);
  1242. //Add a flag to indicate multi instance
  1243. if (isParallel)
  1244. {
  1245. HqlExprArray args;
  1246. unwindChildren(args, resourced);
  1247. args.append(*createAttribute(multiInstanceAtom));
  1248. args.append(*createAttribute(delayedAtom));
  1249. resourced.setown(resourced->clone(args));
  1250. }
  1251. bool isGlobalThorLoop = translator.targetThor() && !translator.insideChildQuery(ctx);
  1252. Owned<ParentExtract> extractBuilder = isGlobalThorLoop ? translator.createExtractBuilder(ctx, PETloop, represents, GraphRemote, false)
  1253. : translator.createExtractBuilder(ctx, PETloop, represents, resourced, false);
  1254. createBuilderAlias(subctx, extractBuilder);
  1255. translator.beginExtract(ctx, extractBuilder);
  1256. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1257. translator.endExtract(ctx, extractBuilder);
  1258. return id;
  1259. }
  1260. unique_id_t ChildGraphBuilder::buildRemoteGraph(BuildCtx & ctx)
  1261. {
  1262. BuildCtx subctx(ctx);
  1263. subctx.addGroup();
  1264. OwnedHqlExpr query = createActionList(results);
  1265. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, query, represents, numResults, no_allnodes);
  1266. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(ctx, PETremote, represents, GraphRemote, false);
  1267. createBuilderAlias(subctx, extractBuilder);
  1268. translator.beginExtract(ctx, extractBuilder);
  1269. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1270. translator.endExtract(ctx, extractBuilder);
  1271. return id;
  1272. }
  1273. void HqlCppTranslator::buildChildGraph(BuildCtx & ctx, IHqlExpression * expr)
  1274. {
  1275. IHqlExpression * represents= expr->queryChild(0);
  1276. OwnedHqlExpr resultsExpr = createAttribute(resultsAtom, LINK(represents));
  1277. //Shouldn't really happen, but if this graph has already benn called just use the results
  1278. if (ctx.queryMatchExpr(resultsExpr))
  1279. return;
  1280. ChildGraphBuilder graphBuilder(*this, expr);
  1281. graphBuilder.generateGraph(ctx);
  1282. }
  1283. void HqlCppTranslator::beginExtract(BuildCtx & ctx, ParentExtract * extractBuilder)
  1284. {
  1285. ctx.associate(*extractBuilder);
  1286. }
  1287. void HqlCppTranslator::endExtract(BuildCtx & ctx, ParentExtract * extractBuilder)
  1288. {
  1289. extractBuilder->endUseExtract(ctx);
  1290. ctx.removeAssociation(extractBuilder);
  1291. }
  1292. void HqlCppTranslator::buildAssignChildDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  1293. {
  1294. switch (expr->getOperator())
  1295. {
  1296. case no_call:
  1297. case no_externalcall:
  1298. case no_libraryinput:
  1299. buildDatasetAssign(ctx, target, expr);
  1300. return;
  1301. }
  1302. OwnedHqlExpr call;
  1303. {
  1304. ChildGraphExprBuilder builder(0);
  1305. call.setown(builder.addDataset(expr));
  1306. OwnedHqlExpr subquery = builder.getGraph();
  1307. buildStmt(ctx, subquery);
  1308. }
  1309. buildExprAssign(ctx, target, call);
  1310. }
  1311. IHqlExpression * HqlCppTranslator::getResourcedChildGraph(BuildCtx & ctx, IHqlExpression * expr, IHqlExpression * graphIdExpr, unsigned numResults, node_operator graphKind)
  1312. {
  1313. if (options.paranoidCheckNormalized || options.paranoidCheckDependencies)
  1314. DBGLOG("Before resourcing a child graph");
  1315. LinkedHqlExpr resourced = expr;
  1316. checkNormalized(ctx, resourced);
  1317. unsigned csfFlags = CSFindex|options.optimizeDiskFlag;
  1318. switch (targetClusterType)
  1319. {
  1320. case HThorCluster:
  1321. csfFlags |= CSFcompoundSpill;
  1322. break;
  1323. case ThorCluster:
  1324. case ThorLCRCluster:
  1325. //Don't compound spills inside a child query because it can cause non remote projects to become remote
  1326. //And we'll also probably be using the roxie code to implement
  1327. break;
  1328. case RoxieCluster:
  1329. break;
  1330. }
  1331. {
  1332. unsigned time = msTick();
  1333. CompoundSourceTransformer transformer(*this, CSFpreload|csfFlags);
  1334. resourced.setown(transformer.process(resourced));
  1335. checkNormalized(ctx, resourced);
  1336. DEBUG_TIMER("EclServer: tree transform: optimize disk read", msTick()-time);
  1337. }
  1338. if (options.optimizeChildGraph)
  1339. {
  1340. unsigned time = msTick();
  1341. traceExpression("BeforeOptimizeSub", resourced);
  1342. resourced.setown(optimizeHqlExpression(resourced, getOptimizeFlags()|HOOcompoundproject));
  1343. traceExpression("AfterOptimizeSub", resourced);
  1344. DEBUG_TIMER("EclServer: optimize graph", msTick()-time);
  1345. }
  1346. traceExpression("BeforeResourcing Child", resourced);
  1347. cycle_t time = msTick();
  1348. HqlExprCopyArray activeRows;
  1349. gatherActiveCursors(ctx, activeRows);
  1350. if (graphKind == no_loop)
  1351. {
  1352. bool insideChild = insideChildQuery(ctx);
  1353. resourced.setown(resourceLoopGraph(*this, activeRows, resourced, targetClusterType, graphIdExpr, &numResults, insideChild));
  1354. }
  1355. else
  1356. resourced.setown(resourceNewChildGraph(*this, activeRows, resourced, targetClusterType, graphIdExpr, &numResults));
  1357. DEBUG_TIMER("EclServer: resource graph", msTick()-time);
  1358. checkNormalized(ctx, resourced);
  1359. traceExpression("AfterResourcing Child", resourced);
  1360. //Convert queries on preloaded into compound activities - before resourcing so keyed gets done correctly
  1361. // Second attempt to spot compound disk reads - this time of spill files. Since resourcing has removed
  1362. // any sharing we don't need to bother about sharing.
  1363. {
  1364. unsigned time = msTick();
  1365. CompoundSourceTransformer transformer(*this, csfFlags);
  1366. resourced.setown(transformer.process(resourced));
  1367. DEBUG_TIMER("EclServer: tree transform: optimize disk read", msTick()-time);
  1368. }
  1369. //Now call the optimizer again - the main purpose is to move projects over limits and into compound index/disk reads
  1370. if (options.optimizeChildGraph)
  1371. {
  1372. unsigned time = msTick();
  1373. traceExpression("BeforeOptimize2", resourced);
  1374. resourced.setown(optimizeHqlExpression(resourced, getOptimizeFlags()|HOOcompoundproject));
  1375. traceExpression("AfterOptimize2", resourced);
  1376. DEBUG_TIMER("EclServer: optimize graph", msTick()-time);
  1377. }
  1378. if (numResults == 0) numResults++;
  1379. HqlExprArray children;
  1380. resourced->unwindList(children, no_actionlist);
  1381. children.append(*createAttribute(numResultsAtom, getSizetConstant(numResults)));
  1382. children.append(*LINK(graphIdExpr));
  1383. resourced.setown(createValue(no_subgraph, makeVoidType(), children));
  1384. if (options.paranoidCheckNormalized || options.paranoidCheckDependencies)
  1385. DBGLOG("After resourcing a child graph");
  1386. return resourced.getClear();
  1387. }
  1388. void HqlCppTranslator::buildChildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  1389. {
  1390. if (expr->isPure() && ctx.getMatchExpr(expr, tgt))
  1391. return;
  1392. LoopInvariantHelper helper;
  1393. BuildCtx bestctx(ctx);
  1394. if (options.optimizeLoopInvariant)
  1395. helper.getBestContext(bestctx, expr);
  1396. CHqlBoundTarget temp;
  1397. //MORE: Should have similar code to buildTempExpr()
  1398. createTempFor(bestctx, expr, temp);
  1399. buildAssignChildDataset(bestctx, temp, expr);
  1400. tgt.setFromTarget(temp);
  1401. if (expr->isPure())
  1402. bestctx.associateExpr(expr, tgt);
  1403. }
  1404. unique_id_t HqlCppTranslator::buildGraphLoopSubgraph(BuildCtx & ctx, IHqlExpression * dataset, IHqlExpression * selSeq, IHqlExpression * rowsid, IHqlExpression * body, IHqlExpression * counter, bool multiInstance)
  1405. {
  1406. ChildGraphExprBuilder graphBuilder(0);
  1407. OwnedHqlExpr transformedBody;
  1408. OwnedHqlExpr counterResult;
  1409. IHqlExpression * graphid = graphBuilder.queryRepresents();
  1410. {
  1411. const bool isParallel = multiInstance;
  1412. GraphLoopReplacer replacer(rowsid, graphid, counter, isParallel);
  1413. transformedBody.setown(replacer.transformRoot(body));
  1414. counterResult.set(replacer.queryCounterResult());
  1415. }
  1416. if (counterResult)
  1417. graphBuilder.addInput();
  1418. OwnedHqlExpr result = createValue(no_setgraphloopresult, makeVoidType(), LINK(transformedBody), LINK(graphid));
  1419. graphBuilder.addAction(result);
  1420. OwnedHqlExpr subquery = graphBuilder.getGraph();
  1421. ChildGraphBuilder builder(*this, subquery);
  1422. return builder.buildGraphLoopBody(ctx, multiInstance);
  1423. }
  1424. unique_id_t HqlCppTranslator::buildRemoteSubgraph(BuildCtx & ctx, IHqlExpression * dataset)
  1425. {
  1426. ChildGraphExprBuilder graphBuilder(0);
  1427. if (dataset->isAction())
  1428. {
  1429. graphBuilder.addAction(dataset);
  1430. }
  1431. else
  1432. {
  1433. OwnedHqlExpr ignoredResult = graphBuilder.addDataset(dataset);
  1434. }
  1435. OwnedHqlExpr subquery = graphBuilder.getGraph();
  1436. ChildGraphBuilder builder(*this, subquery);
  1437. return builder.buildRemoteGraph(ctx);
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. // Functions to check whether a dataset can be evaluated inline or not.
  1441. //MORE: These should probably be split out into an hqlinline.cpp
  1442. bool HqlCppTranslator::canIterateInline(BuildCtx * ctx, IHqlExpression * expr)
  1443. {
  1444. return (isInlineOk() && ::canIterateInline(ctx, expr));
  1445. }
  1446. bool HqlCppTranslator::canAssignInline(BuildCtx * ctx, IHqlExpression * expr)
  1447. {
  1448. if (!isInlineOk())
  1449. return false;
  1450. return options.allowInlineSpill ? ::canProcessInline(ctx, expr) : ::canAssignInline(ctx, expr);
  1451. }
  1452. bool HqlCppTranslator::canEvaluateInline(BuildCtx * ctx, IHqlExpression * expr)
  1453. {
  1454. if (!isInlineOk())
  1455. return false;
  1456. return options.allowInlineSpill ? ::canProcessInline(ctx, expr) : ::canEvaluateInline(ctx, expr);
  1457. }
  1458. bool HqlCppTranslator::canProcessInline(BuildCtx * ctx, IHqlExpression * expr)
  1459. {
  1460. if (!isInlineOk())
  1461. return false;
  1462. return ::canProcessInline(ctx, expr);
  1463. }
  1464. bool HqlCppTranslator::isInlineOk()
  1465. {
  1466. if (!activeGraphCtx)
  1467. return true;
  1468. return true;
  1469. }
  1470. IHqlExpression * HqlCppTranslator::buildSpillChildDataset(BuildCtx & ctx, IHqlExpression * expr)
  1471. {
  1472. CHqlBoundExpr bound;
  1473. buildChildDataset(ctx, expr, bound);
  1474. return bound.getTranslatedExpr();
  1475. }
  1476. IHqlExpression * HqlCppTranslator::forceInlineAssignDataset(BuildCtx & ctx, IHqlExpression * expr)
  1477. {
  1478. loop
  1479. {
  1480. CHqlBoundExpr bound;
  1481. if (expr->isPure() && ctx.getMatchExpr(expr, bound))
  1482. return bound.getTranslatedExpr();
  1483. if (canProcessInline(&ctx, expr) || (expr->getOperator() == no_translated))
  1484. return LINK(expr);
  1485. switch (expr->getOperator())
  1486. {
  1487. case no_compound:
  1488. buildStmt(ctx, expr->queryChild(0));
  1489. expr = expr->queryChild(1);
  1490. break;
  1491. default:
  1492. return buildSpillChildDataset(ctx, expr);
  1493. }
  1494. }
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. // Dataset temp creation
  1498. IHqlExpression * createGetResultFromWorkunitDataset(IHqlExpression * expr)
  1499. {
  1500. IHqlExpression * name = queryPropertyChild(expr, nameAtom, 0);
  1501. if (name)
  1502. name = createExprAttribute(namedAtom, LINK(name));
  1503. assertex(expr->isDataset());
  1504. return createDataset(no_getresult, LINK(expr->queryRecord()), createComma(LINK(expr->queryProperty(sequenceAtom)), name));
  1505. }
  1506. void HqlCppTranslator::buildAssignSerializedDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  1507. {
  1508. OwnedITypeInfo serializedType = getSerializedForm(expr->queryType());
  1509. assertex(recordTypesMatch(target.queryType(), serializedType));
  1510. HqlExprArray args;
  1511. args.append(*createRowSerializer(ctx, expr->queryRecord(), serializerAtom));
  1512. args.append(*LINK(expr));
  1513. OwnedHqlExpr call = bindFunctionCall(rowset2DatasetXAtom, args);
  1514. buildExprAssign(ctx, target, call);
  1515. }
  1516. void HqlCppTranslator::buildSerializedDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  1517. {
  1518. CHqlBoundTarget target;
  1519. OwnedITypeInfo serializedType = getSerializedForm(expr->queryType());
  1520. createTempFor(ctx, serializedType, target, typemod_none, FormatBlockedDataset);
  1521. buildAssignSerializedDataset(ctx, target, expr);
  1522. tgt.setFromTarget(target);
  1523. }
  1524. void HqlCppTranslator::buildAssignLinkedDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  1525. {
  1526. OwnedITypeInfo serializedType = getSerializedForm(target.queryType());
  1527. assertex(recordTypesMatch(serializedType, expr->queryType()));
  1528. IHqlExpression * record = ::queryRecord(target.queryType());
  1529. HqlExprArray args;
  1530. args.append(*createRowSerializer(ctx, record, deserializerAtom));
  1531. args.append(*LINK(expr));
  1532. OwnedHqlExpr call = bindFunctionCall(isGrouped(expr) ? groupedDataset2RowsetXAtom : dataset2RowsetXAtom, args, target.queryType());
  1533. buildExprAssign(ctx, target, call);
  1534. }
  1535. void HqlCppTranslator::buildLinkedDataset(BuildCtx & ctx, ITypeInfo * type, IHqlExpression * expr, CHqlBoundExpr & tgt)
  1536. {
  1537. CHqlBoundTarget target;
  1538. createTempFor(ctx, type, target, typemod_none, FormatLinkedDataset);
  1539. if (hasLinkedRow(expr->queryType()))
  1540. buildDatasetAssign(ctx, target, expr);
  1541. else
  1542. buildAssignLinkedDataset(ctx, target, expr);
  1543. tgt.setFromTarget(target);
  1544. }
  1545. void HqlCppTranslator::ensureDatasetFormat(BuildCtx & ctx, ITypeInfo * type, CHqlBoundExpr & tgt, ExpressionFormat format)
  1546. {
  1547. switch (format)
  1548. {
  1549. case FormatBlockedDataset:
  1550. if (isArrayRowset(tgt.queryType()))
  1551. {
  1552. OwnedHqlExpr deserializedExpr = tgt.getTranslatedExpr();
  1553. LinkedHqlExpr savedCount = tgt.count;
  1554. buildSerializedDataset(ctx, deserializedExpr, tgt);
  1555. if (savedCount && !isFixedWidthDataset(deserializedExpr))
  1556. tgt.count.set(savedCount);
  1557. return;
  1558. }
  1559. break;
  1560. case FormatLinkedDataset:
  1561. if (!hasLinkCountedModifier(tgt.queryType()))
  1562. {
  1563. OwnedHqlExpr serializedExpr = tgt.getTranslatedExpr();
  1564. buildLinkedDataset(ctx, type, serializedExpr, tgt);
  1565. return;
  1566. }
  1567. break;
  1568. case FormatArrayDataset:
  1569. if (!isArrayRowset(tgt.queryType()))
  1570. {
  1571. OwnedHqlExpr serializedExpr = tgt.getTranslatedExpr();
  1572. buildLinkedDataset(ctx, type, serializedExpr, tgt);
  1573. return;
  1574. }
  1575. break;
  1576. }
  1577. }
  1578. void HqlCppTranslator::buildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  1579. {
  1580. doBuildDataset(ctx, expr, tgt, format);
  1581. ensureDatasetFormat(ctx, expr->queryType(), tgt, format);
  1582. }
  1583. void HqlCppTranslator::doBuildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  1584. {
  1585. if (expr->isPure() && ctx.getMatchExpr(expr, tgt))
  1586. return;
  1587. /*
  1588. OwnedHqlExpr transformed = normalizeAnyDatasetAliases(expr);
  1589. if (transformed && (transformed != expr))
  1590. {
  1591. doBuildDataset(ctx, transformed, tgt, format);
  1592. ctx.associateExpr(expr, tgt);
  1593. return;
  1594. }
  1595. */
  1596. node_operator op = expr->getOperator();
  1597. switch (op)
  1598. {
  1599. case no_dataset_alias:
  1600. if (!expr->hasProperty(_normalized_Atom))
  1601. {
  1602. OwnedHqlExpr uniqueChild = normalizeDatasetAlias(expr);
  1603. doBuildDataset(ctx, uniqueChild, tgt, format);
  1604. }
  1605. else
  1606. doBuildDataset(ctx, expr->queryChild(0), tgt, format);
  1607. return;
  1608. case no_alias:
  1609. doBuildExprAlias(ctx, expr, &tgt);
  1610. return;
  1611. case no_owned_ds:
  1612. buildTempExpr(ctx, expr, tgt);
  1613. return;
  1614. case no_null:
  1615. {
  1616. tgt.count.setown(getSizetConstant(0));
  1617. tgt.length.setown(getSizetConstant(0));
  1618. IHqlExpression * record = expr->queryRecord();
  1619. ITypeInfo * type = makeTableType(makeRowType(record->getType()), NULL, NULL, NULL);
  1620. if ((format == FormatLinkedDataset) || (format == FormatArrayDataset))
  1621. type = makeAttributeModifier(type, getLinkCountedAttr());
  1622. tgt.expr.setown(createValue(no_nullptr, makeReferenceModifier(type)));
  1623. return;
  1624. }
  1625. case no_translated:
  1626. expandTranslated(expr, tgt);
  1627. return;
  1628. case no_select:
  1629. {
  1630. if (isMultiLevelDatasetSelector(expr, false))
  1631. break;
  1632. Owned<IReferenceSelector> selected = buildReference(ctx, expr);
  1633. selected->get(ctx, tgt);
  1634. return;
  1635. }
  1636. case no_libraryinput:
  1637. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  1638. throwUnexpected();
  1639. return;
  1640. case no_call:
  1641. case no_externalcall:
  1642. if (!hasStreamedModifier(expr->queryType()))
  1643. {
  1644. buildTempExpr(ctx, expr, tgt);
  1645. return;
  1646. }
  1647. break;
  1648. case no_newaggregate:
  1649. if (canAssignInline(&ctx, expr))
  1650. {
  1651. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  1652. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  1653. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  1654. BuildCtx subctx(ctx);
  1655. subctx.addGroup();
  1656. doBuildRowAssignAggregate(subctx, createdRef, expr);
  1657. finalizeTempRow(ctx, tempRow, rowBuilder);
  1658. convertBoundRowToDataset(ctx, tgt, tempRow, format);
  1659. return;
  1660. }
  1661. break;
  1662. case no_id2blob:
  1663. doBuildExprIdToBlob(ctx, expr, tgt);
  1664. return;
  1665. case no_rows:
  1666. {
  1667. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  1668. throwError(HQLERR_RowsUsedOutsideContext);
  1669. return;
  1670. }
  1671. case no_limit:
  1672. if (expr->hasProperty(skipAtom) || expr->hasProperty(onFailAtom))
  1673. break;
  1674. doBuildDatasetLimit(ctx, expr, tgt, format);
  1675. return;
  1676. case no_compound_childread:
  1677. case no_compound_childnormalize:
  1678. case no_compound_childaggregate:
  1679. case no_compound_selectnew:
  1680. case no_compound_inline:
  1681. case no_distributed:
  1682. case no_preservemeta:
  1683. case no_sorted:
  1684. case no_nofold:
  1685. case no_nohoist:
  1686. case no_section:
  1687. case no_sectioninput:
  1688. buildDataset(ctx, expr->queryChild(0), tgt, format);
  1689. return;
  1690. case no_forcegraph:
  1691. #ifdef _DEBUG
  1692. throwUnexpected();
  1693. #endif
  1694. buildDataset(ctx, expr->queryChild(0), tgt, format);
  1695. return;
  1696. case no_getgraphresult:
  1697. doBuildExprGetGraphResult(ctx, expr, tgt, format);
  1698. return;
  1699. case no_getresult:
  1700. case no_workunit_dataset:
  1701. if (!isGrouped(expr))
  1702. {
  1703. doBuildExprGetResult(ctx, expr, tgt);
  1704. return;
  1705. }
  1706. break;
  1707. case no_skip:
  1708. {
  1709. buildStmt(ctx, expr);
  1710. OwnedHqlExpr null = createNullExpr(expr);
  1711. buildDataset(ctx, null, tgt, format);
  1712. return;
  1713. }
  1714. case no_serialize:
  1715. if (isDummySerializeDeserialize(expr))
  1716. doBuildDataset(ctx, expr->queryChild(0)->queryChild(0), tgt, format);
  1717. else
  1718. buildSerializedDataset(ctx, expr->queryChild(0), tgt);
  1719. return;
  1720. case no_deserialize:
  1721. if (isDummySerializeDeserialize(expr))
  1722. doBuildDataset(ctx, expr->queryChild(0)->queryChild(0), tgt, format);
  1723. else
  1724. buildLinkedDataset(ctx, expr->queryType(), expr->queryChild(0), tgt);
  1725. return;
  1726. case no_datasetfromrow:
  1727. {
  1728. IHqlExpression * row = expr->queryChild(0);
  1729. if (isAlwaysActiveRow(row) && (format == FormatNatural))
  1730. {
  1731. Owned<IReferenceSelector> selector = buildActiveRow(ctx, row);
  1732. BuildCtx groupctx(ctx);
  1733. groupctx.addGroup();
  1734. BoundRow * bound = bindSelectorAsRootRow(groupctx, selector, row);
  1735. convertBoundRowToDataset(groupctx, tgt, bound, format);
  1736. tgt.count.setown(getSizetConstant(1));
  1737. ctx.associateExpr(expr, tgt);
  1738. return;
  1739. }
  1740. break;
  1741. }
  1742. case no_inlinetable:
  1743. if (doBuildDatasetInlineTable(ctx, expr, tgt, format))
  1744. return;
  1745. break;
  1746. case no_compound:
  1747. {
  1748. buildStmt(ctx, expr->queryChild(0));
  1749. buildDataset(ctx, expr->queryChild(1), tgt, format);
  1750. return;
  1751. }
  1752. }
  1753. bool singleRow = hasSingleRow(expr);
  1754. bool useTempRow = singleRow && canAssignInline(&ctx, expr) && (format != FormatLinkedDataset) && (format != FormatArrayDataset);
  1755. //Conditional row assignment if variable length causes offset to be recalculated outside of the if()
  1756. //if (useTempRow && (op == no_if) && isVariableSizeRecord(expr->queryRecord()))
  1757. // useTempRow = false;
  1758. if (useTempRow)
  1759. {
  1760. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  1761. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  1762. Owned<IHqlCppDatasetBuilder> builder = createSingleRowTempDatasetBuilder(expr->queryRecord(), rowBuilder);
  1763. builder->buildDeclare(ctx);
  1764. buildDatasetAssign(ctx, builder, expr);
  1765. //builder->buildFinish(ctx, tempTarget);
  1766. finalizeTempRow(ctx, tempRow, rowBuilder);
  1767. convertBoundRowToDataset(ctx, tgt, tempRow, format);
  1768. }
  1769. else
  1770. {
  1771. if (!canAssignInline(&ctx, expr))
  1772. {
  1773. CHqlBoundTarget tempTarget;
  1774. createTempFor(ctx, expr->queryType(), tempTarget, typemod_none, format);
  1775. buildDatasetAssign(ctx, tempTarget, expr);
  1776. tgt.setFromTarget(tempTarget);
  1777. //buildTempExpr(ctx, expr, tgt); // can't use this because it causes recursion on no_selectnth
  1778. }
  1779. else
  1780. {
  1781. Owned<IHqlCppDatasetBuilder> builder;
  1782. IHqlExpression * record = expr->queryRecord();
  1783. OwnedHqlExpr serializedRecord = getSerializedForm(record);
  1784. if (format == FormatNatural)
  1785. {
  1786. if (record != serializedRecord)
  1787. ensureContextAvailable(ctx);
  1788. if (!ctx.queryMatchExpr(codeContextMarkerExpr))
  1789. {
  1790. if (record != serializedRecord)
  1791. throwError(HQLERR_LinkedDatasetNoContext);
  1792. format = FormatBlockedDataset;
  1793. }
  1794. else if ((record == serializedRecord) && !options.tempDatasetsUseLinkedRows)
  1795. {
  1796. format = FormatBlockedDataset;
  1797. }
  1798. else
  1799. {
  1800. format = FormatLinkedDataset;
  1801. }
  1802. }
  1803. else if (record != serializedRecord)
  1804. format = FormatLinkedDataset; // Have to serialize it later - otherwise it won't be compatible
  1805. if (format == FormatLinkedDataset || format == FormatArrayDataset)
  1806. {
  1807. IHqlExpression * choosenLimit = NULL;
  1808. if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  1809. {
  1810. choosenLimit = expr->queryChild(1);
  1811. expr = expr->queryChild(0);
  1812. }
  1813. //MORE: Extract limit and choosen and pass as parameters
  1814. builder.setown(createLinkedDatasetBuilder(record, choosenLimit));
  1815. }
  1816. else if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  1817. {
  1818. //Build a limited builder - it is likely to be just as efficient, and often much more e.g., choosen(a+b, n)
  1819. builder.setown(createChoosenDatasetBuilder(serializedRecord, expr->queryChild(1)));
  1820. expr = expr->queryChild(0);
  1821. }
  1822. else
  1823. builder.setown(createBlockedDatasetBuilder(serializedRecord));
  1824. builder->buildDeclare(ctx);
  1825. buildDatasetAssign(ctx, builder, expr);
  1826. builder->buildFinish(ctx, tgt);
  1827. }
  1828. }
  1829. if (singleRow)
  1830. tgt.count.setown(getSizetConstant(1));
  1831. else if (op == no_inlinetable)
  1832. {
  1833. IHqlExpression * transforms = expr->queryChild(0);
  1834. if (!transformListContainsSkip(transforms))
  1835. tgt.count.setown(getSizetConstant(transforms->numChildren()));
  1836. }
  1837. ctx.associateExpr(expr, tgt);
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. // Dataset assignment - to temp
  1841. void HqlCppTranslator::buildDatasetAssign(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  1842. {
  1843. node_operator op = expr->getOperator();
  1844. switch (op)
  1845. {
  1846. case no_call:
  1847. case no_externalcall:
  1848. if (!hasStreamedModifier(expr->queryType()))
  1849. {
  1850. doBuildCall(ctx, &target, expr, NULL);
  1851. return;
  1852. }
  1853. break;
  1854. case no_getgraphresult:
  1855. doBuildAssignGetGraphResult(ctx, target, expr);
  1856. return;
  1857. case no_workunit_dataset:
  1858. case no_getresult:
  1859. buildExprAssign(ctx, target, expr);
  1860. return;
  1861. case no_null:
  1862. {
  1863. CHqlBoundExpr bound;
  1864. buildDataset(ctx, expr, bound, isArrayRowset(expr->queryType()) ? FormatLinkedDataset : FormatBlockedDataset);
  1865. OwnedHqlExpr translated = bound.getTranslatedExpr();
  1866. if (target.count) ctx.addAssign(target.count, bound.count);
  1867. if (target.length) ctx.addAssign(target.length, bound.length);
  1868. ctx.addAssign(target.expr, bound.expr);
  1869. return;
  1870. }
  1871. case no_inlinetable:
  1872. {
  1873. //This will typically generate a loop. If few items then it is more efficient to expand the assigns/clones out.
  1874. if (expr->queryChild(0)->numChildren() > INLINE_TABLE_EXPAND_LIMIT)
  1875. {
  1876. CHqlBoundExpr bound;
  1877. if (doBuildDatasetInlineTable(ctx, expr, bound, FormatNatural))
  1878. {
  1879. OwnedHqlExpr translated = bound.getTranslatedExpr();
  1880. buildDatasetAssign(ctx, target, translated);
  1881. return;
  1882. }
  1883. }
  1884. break;
  1885. }
  1886. case no_alias:
  1887. {
  1888. CHqlBoundExpr bound;
  1889. buildDataset(ctx, expr, bound, FormatNatural);
  1890. OwnedHqlExpr translated = bound.getTranslatedExpr();
  1891. buildDatasetAssign(ctx, target, translated);
  1892. return;
  1893. }
  1894. case no_owned_ds:
  1895. {
  1896. ITypeInfo * targetType = target.queryType();
  1897. if (hasLinkCountedModifier(targetType) && hasWrapperModifier(targetType))
  1898. {
  1899. CHqlBoundExpr bound;
  1900. buildDataset(ctx, expr->queryChild(0), bound, FormatLinkedDataset);
  1901. OwnedHqlExpr compound = createValue(no_complex, bound.expr->getType(), LINK(bound.count), LINK(bound.expr));
  1902. ctx.addAssign(target.expr, compound);
  1903. return;
  1904. }
  1905. break;
  1906. }
  1907. case no_compound:
  1908. {
  1909. buildStmt(ctx, expr->queryChild(0));
  1910. buildDatasetAssign(ctx, target, expr->queryChild(1));
  1911. return;
  1912. }
  1913. case no_compound_childread:
  1914. case no_compound_childnormalize:
  1915. case no_compound_childaggregate:
  1916. case no_compound_selectnew:
  1917. case no_compound_inline:
  1918. case no_distributed:
  1919. case no_preservemeta:
  1920. case no_sorted:
  1921. case no_nofold:
  1922. case no_nohoist:
  1923. case no_section:
  1924. case no_sectioninput:
  1925. buildDatasetAssign(ctx, target, expr->queryChild(0));
  1926. return;
  1927. case no_serialize:
  1928. if (isDummySerializeDeserialize(expr))
  1929. buildDatasetAssign(ctx, target, expr->queryChild(0)->queryChild(0));
  1930. else
  1931. buildAssignSerializedDataset(ctx, target, expr->queryChild(0));
  1932. return;
  1933. case no_deserialize:
  1934. if (isDummySerializeDeserialize(expr))
  1935. buildDatasetAssign(ctx, target, expr->queryChild(0)->queryChild(0));
  1936. else
  1937. buildAssignLinkedDataset(ctx, target, expr->queryChild(0));
  1938. return;
  1939. case no_select:
  1940. {
  1941. bool isNew;
  1942. IHqlExpression * ds = querySelectorDataset(expr, isNew);
  1943. if (!isNew || ds->isDatarow())
  1944. {
  1945. Owned<IReferenceSelector> selected = buildReference(ctx, expr);
  1946. selected->assignTo(ctx, target);
  1947. return;
  1948. }
  1949. break;
  1950. }
  1951. case no_typetransfer:
  1952. {
  1953. IHqlExpression * child = expr->queryChild(0);
  1954. if (expr->isDataset() && child->isDataset())
  1955. {
  1956. //Special case no-op type transfers and assignment from a call returning unknown-type dataset
  1957. if (!recordTypesMatch(expr, child) &&
  1958. !(child->getOperator() == no_externalcall && recordTypesMatch(child, queryNullRecord())))
  1959. {
  1960. CHqlBoundExpr bound;
  1961. buildDataset(ctx, child, bound, FormatNatural);
  1962. ITypeInfo * newType = cloneModifiers(bound.expr->queryType(), expr->queryType());
  1963. bound.expr.setown(createValue(no_typetransfer, newType, LINK(bound.expr)));
  1964. OwnedHqlExpr translated = bound.getTranslatedExpr();
  1965. buildDatasetAssign(ctx, target, translated);
  1966. }
  1967. else
  1968. buildDatasetAssign(ctx, target, child);
  1969. return;
  1970. }
  1971. break;
  1972. }
  1973. }
  1974. if (!canAssignInline(&ctx, expr) && (op != no_translated))
  1975. {
  1976. buildAssignChildDataset(ctx, target, expr);
  1977. return;
  1978. }
  1979. ITypeInfo * to = target.queryType();
  1980. ITypeInfo * exprType = expr->queryType();
  1981. bool targetOutOfLine = isArrayRowset(to);
  1982. switch (op)
  1983. {
  1984. case no_limit:
  1985. assertex(!expr->hasProperty(skipAtom) && !expr->hasProperty(onFailAtom));
  1986. //Do the limit check as a post test.
  1987. //It means we may read more records than we need to, but the code is inline, and the code is generally much better.
  1988. if (target.count)
  1989. {
  1990. buildDatasetAssign(ctx, target, expr->queryChild(0));
  1991. CHqlBoundExpr bound;
  1992. bound.setFromTarget(target);
  1993. doBuildCheckDatasetLimit(ctx, expr, bound);
  1994. return;
  1995. }
  1996. break;
  1997. case no_translated:
  1998. {
  1999. bool sourceOutOfLine = isArrayRowset(exprType);
  2000. if (sourceOutOfLine != targetOutOfLine)
  2001. {
  2002. OwnedITypeInfo serializedSourceType = getSerializedForm(exprType);
  2003. OwnedITypeInfo serializedTargetType = getSerializedForm(to);
  2004. if (queryUnqualifiedType(serializedSourceType) == queryUnqualifiedType(serializedTargetType))
  2005. {
  2006. if (targetOutOfLine)
  2007. {
  2008. buildAssignLinkedDataset(ctx, target, expr);
  2009. }
  2010. else
  2011. {
  2012. buildAssignSerializedDataset(ctx, target, expr);
  2013. }
  2014. return;
  2015. }
  2016. }
  2017. break;
  2018. }
  2019. }
  2020. if (recordTypesMatch(to, exprType))
  2021. {
  2022. switch (op)
  2023. {
  2024. case no_rows:
  2025. {
  2026. CHqlBoundExpr bound;
  2027. buildDataset(ctx, expr, bound, FormatLinkedDataset);
  2028. OwnedHqlExpr translated = bound.getTranslatedExpr();
  2029. buildDatasetAssign(ctx, target, translated);
  2030. return;
  2031. }
  2032. case no_select:
  2033. {
  2034. bool isNew;
  2035. IHqlExpression * ds = querySelectorDataset(expr, isNew);
  2036. if (isNew && !ds->isDatarow())
  2037. break;
  2038. }
  2039. //fall through
  2040. case no_translated:
  2041. case no_null:
  2042. case no_id2blob:
  2043. {
  2044. _ATOM func = NULL;
  2045. if (!isArrayRowset(to))
  2046. {
  2047. if (!isArrayRowset(exprType))
  2048. func = dataset2DatasetXAtom;
  2049. }
  2050. else if (hasLinkCountedModifier(to))
  2051. {
  2052. if (hasLinkCountedModifier(exprType))
  2053. {
  2054. CHqlBoundExpr bound;
  2055. buildDataset(ctx, expr, bound, FormatLinkedDataset);
  2056. assertex(bound.count && bound.expr);
  2057. if (hasWrapperModifier(to))
  2058. {
  2059. //assigns to count and rows members
  2060. StringBuffer s;
  2061. generateExprCpp(s, target.expr);
  2062. s.append(".set(");
  2063. generateExprCpp(s, bound.count);
  2064. s.append(",");
  2065. generateExprCpp(s, bound.expr);
  2066. s.append(");");
  2067. ctx.addQuoted(s);
  2068. }
  2069. else
  2070. {
  2071. ctx.addAssign(target.count, bound.count);
  2072. HqlExprArray args;
  2073. args.append(*LINK(bound.expr));
  2074. OwnedHqlExpr call = bindTranslatedFunctionCall(linkRowsetAtom, args);
  2075. ctx.addAssign(target.expr, call);
  2076. }
  2077. return;
  2078. }
  2079. }
  2080. if (func)
  2081. {
  2082. HqlExprArray args;
  2083. args.append(*LINK(expr));
  2084. OwnedHqlExpr call = bindFunctionCall(func, args);
  2085. buildExprAssign(ctx, target, call);
  2086. return;
  2087. }
  2088. }
  2089. }
  2090. }
  2091. IHqlExpression * record = ::queryRecord(to);
  2092. Owned<IHqlCppDatasetBuilder> builder;
  2093. if (targetOutOfLine)
  2094. {
  2095. IHqlExpression * choosenLimit = NULL;
  2096. if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  2097. {
  2098. choosenLimit = expr->queryChild(1);
  2099. expr = expr->queryChild(0);
  2100. }
  2101. builder.setown(createLinkedDatasetBuilder(record, choosenLimit));
  2102. }
  2103. else
  2104. builder.setown(createBlockedDatasetBuilder(record));
  2105. builder->buildDeclare(ctx);
  2106. buildDatasetAssign(ctx, builder, expr);
  2107. builder->buildFinish(ctx, target);
  2108. }
  2109. //---------------------------------------------------------------------------
  2110. void HqlCppTranslator::doBuildCheckDatasetLimit(BuildCtx & ctx, IHqlExpression * expr, const CHqlBoundExpr & bound)
  2111. {
  2112. IHqlExpression * record = expr->queryRecord();
  2113. IHqlExpression * limit = expr->queryChild(1);
  2114. OwnedHqlExpr test;
  2115. if (!bound.count && bound.length && isFixedRecordSize(record))
  2116. {
  2117. OwnedHqlExpr size = bound.length->queryValue() ? LINK(bound.length) : createTranslated(bound.length);
  2118. OwnedHqlExpr maxSize = createValue(no_mul, LINK(sizetType), ensureExprType(limit, sizetType), getSizetConstant(getFixedRecordSize(record)));
  2119. test.setown(createBoolExpr(no_gt, ensureExprType(size, sizetType), LINK(maxSize)));
  2120. }
  2121. else
  2122. {
  2123. OwnedHqlExpr count = getBoundCount(bound);
  2124. OwnedHqlExpr translatedCount = count->queryValue() ? LINK(count) : createTranslated(count);
  2125. test.setown(createBoolExpr(no_gt, ensureExprType(translatedCount, sizetType), ensureExprType(limit, sizetType)));
  2126. }
  2127. OwnedHqlExpr folded = foldHqlExpression(test);
  2128. LinkedHqlExpr fail = queryRealChild(expr, 2);
  2129. if (folded->queryValue())
  2130. {
  2131. if (!folded->queryValue()->getBoolValue())
  2132. return;
  2133. StringBuffer failMessageText;
  2134. if (fail)
  2135. {
  2136. OwnedHqlExpr failMessage = getFailMessage(fail, true);
  2137. if (failMessage && failMessage->queryValue())
  2138. failMessage->queryValue()->getStringValue(failMessageText);
  2139. }
  2140. if (failMessageText.length())
  2141. WARNING1(HQLWRN_LimitAlwaysExceededX, failMessageText.str());
  2142. else
  2143. WARNING(HQLWRN_LimitAlwaysExceeded);
  2144. }
  2145. if (!fail)
  2146. fail.setown(createFailAction("Limit exceeded", limit, NULL, queryCurrentActivityId(ctx)));
  2147. BuildCtx subctx(ctx);
  2148. buildFilter(subctx, folded);
  2149. buildStmt(subctx, fail);
  2150. }
  2151. void HqlCppTranslator::doBuildDatasetLimit(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  2152. {
  2153. buildDataset(ctx, expr->queryChild(0), tgt, format);
  2154. doBuildCheckDatasetLimit(ctx, expr, tgt);
  2155. }
  2156. bool HqlCppTranslator::doBuildDatasetInlineTable(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  2157. {
  2158. if (!options.generateStaticInlineTables)
  2159. return false;
  2160. IHqlExpression * transforms = expr->queryChild(0);
  2161. IHqlExpression * record = expr->queryRecord();
  2162. if (transforms->numChildren() == 0)
  2163. {
  2164. OwnedHqlExpr null = createDataset(no_null, LINK(record));
  2165. buildDataset(ctx, null, tgt, format);
  2166. return true;
  2167. }
  2168. BuildCtx declareCtx(*code, literalAtom);
  2169. //Remove unique id when checking for constant datasets already generated
  2170. OwnedHqlExpr exprNoUnique = removeProperty(expr, _uid_Atom);
  2171. if (declareCtx.getMatchExpr(exprNoUnique, tgt))
  2172. return true;
  2173. HqlExprArray rows;
  2174. unsigned maxRows = transforms->numChildren();
  2175. unsigned row;
  2176. for (row = 0; row < maxRows; row++)
  2177. {
  2178. OwnedHqlExpr constRow = createConstantRowExpr(transforms->queryChild(row));
  2179. if (!constRow || !canGenerateStringInline(constRow->queryType()->getSize()))
  2180. return false;
  2181. rows.append(*constRow.getClear());
  2182. }
  2183. HqlExprArray boundRows;
  2184. ForEachItemIn(i, rows)
  2185. {
  2186. CHqlBoundExpr bound;
  2187. buildConstRow(record, &rows.item(i), bound);
  2188. boundRows.append(*bound.expr.getClear());
  2189. }
  2190. Owned<ITypeInfo> rowType = makeConstantModifier(makeReferenceModifier(makeRowType(LINK(queryRecordType(expr->queryType())))));
  2191. OwnedHqlExpr values = createValue(no_list, makeSetType(LINK(rowType)), boundRows);
  2192. Owned<ITypeInfo> tableType = makeConstantModifier(makeArrayType(LINK(rowType), maxRows));
  2193. OwnedITypeInfo rowsType = makeOutOfLineModifier(makeTableType(LINK(rowType), NULL, NULL, NULL));
  2194. OwnedHqlExpr table = declareCtx.getTempDeclare(tableType, values);
  2195. if (options.spanMultipleCpp)
  2196. {
  2197. BuildCtx protoctx(*code, mainprototypesAtom);
  2198. protoctx.addDeclareExternal(table);
  2199. }
  2200. tgt.count.setown(getSizetConstant(maxRows));
  2201. tgt.expr.setown(createValue(no_typetransfer, LINK(rowsType), LINK(table)));
  2202. declareCtx.associateExpr(exprNoUnique, tgt);
  2203. return true;
  2204. }
  2205. //---------------------------------------------------------------------------
  2206. // Dataset creation via builder
  2207. void HqlCppTranslator::buildDatasetAssignTempTable(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2208. {
  2209. OwnedHqlExpr values = normalizeListCasts(expr->queryChild(0));
  2210. if (values->getOperator() == no_null)
  2211. return;
  2212. IHqlExpression * record = expr->queryChild(1);
  2213. OwnedHqlExpr rowsExpr;
  2214. if (values->queryType()->getTypeCode() == type_set)
  2215. {
  2216. if ((values->getOperator() == no_list) && !values->isConstant())
  2217. {
  2218. ForEachChild(i, values)
  2219. {
  2220. BuildCtx loopctx(ctx);
  2221. BoundRow * targetRow = target->buildCreateRow(loopctx);
  2222. OwnedHqlExpr targetField = createSelectExpr(LINK(targetRow->querySelector()), LINK(record->queryChild(0)));
  2223. buildAssign(loopctx, targetField, values->queryChild(i));
  2224. target->finishRow(loopctx, targetRow);
  2225. }
  2226. }
  2227. else
  2228. {
  2229. Owned<IHqlCppSetCursor> cursor = createSetSelector(ctx, values);
  2230. BuildCtx loopctx(ctx);
  2231. CHqlBoundExpr boundCurElement;
  2232. cursor->buildIterateLoop(loopctx, boundCurElement, false);
  2233. BoundRow * targetRow = target->buildCreateRow(loopctx);
  2234. OwnedHqlExpr targetField = createSelectExpr(LINK(targetRow->querySelector()), LINK(record->queryChild(0)));
  2235. OwnedHqlExpr value = boundCurElement.getTranslatedExpr();
  2236. buildAssign(loopctx, targetField, value);
  2237. target->finishRow(loopctx, targetRow);
  2238. }
  2239. }
  2240. else
  2241. {
  2242. BuildCtx subctx(ctx);
  2243. BoundRow * targetRow = target->buildCreateRow(subctx);
  2244. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2245. buildRowAssign(subctx, targetRef, values);
  2246. target->finishRow(subctx, targetRow);
  2247. }
  2248. }
  2249. void HqlCppTranslator::buildDatasetAssignInlineTable(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2250. {
  2251. IHqlExpression * transforms = expr->queryChild(0);
  2252. if (transforms->numChildren() == 0)
  2253. return;
  2254. unsigned maxRows = transforms->numChildren();
  2255. unsigned row;
  2256. const bool copyConstantRows = true;//getFieldCount(expr->queryRecord()) > 2;
  2257. for (row = 0; row < maxRows; row++)
  2258. {
  2259. IHqlExpression * transform = transforms->queryChild(row);
  2260. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(transform));
  2261. BuildCtx subctx(ctx);
  2262. CHqlBoundExpr bound;
  2263. //Work in progress. Check if there are several fields - otherwise not worth it.s
  2264. if (doBuildRowConstantTransform(transform, bound))
  2265. {
  2266. BoundRow * row = bindConstantRow(subctx, rowValue, bound);
  2267. if (target->buildLinkRow(subctx, row))
  2268. continue;
  2269. }
  2270. BoundRow * targetRow = target->buildCreateRow(subctx);
  2271. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2272. buildRowAssign(subctx, targetRef, rowValue);
  2273. target->finishRow(subctx, targetRow);
  2274. }
  2275. }
  2276. class InlineDatasetSkipCallback : public CInterface, implements IHqlCodeCallback
  2277. {
  2278. public:
  2279. IMPLEMENT_IINTERFACE
  2280. virtual void buildCode(HqlCppTranslator & translator, BuildCtx & ctx)
  2281. {
  2282. ctx.addContinue();
  2283. }
  2284. };
  2285. void HqlCppTranslator::buildDatasetAssignProject(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2286. {
  2287. BuildCtx iterctx(ctx);
  2288. IHqlExpression * ds = expr->queryChild(0);
  2289. IHqlExpression * counter = queryPropertyChild(expr, _countProject_Atom, 0);
  2290. OwnedHqlExpr counterVar;
  2291. if (counter)
  2292. {
  2293. counterVar.setown(iterctx.getTempDeclare(unsignedType, queryZero()));
  2294. }
  2295. bool containsSkip = transformContainsSkip(expr->queryChild(1));
  2296. BoundRow * sourceCursor = buildDatasetIterate(iterctx, ds, containsSkip);
  2297. if (counter)
  2298. {
  2299. iterctx.associateExpr(counter, counterVar);
  2300. OwnedHqlExpr inc = createValue(no_postinc, LINK(unsignedType), LINK(counterVar));
  2301. iterctx.addExpr(inc);
  2302. }
  2303. if (sourceCursor)
  2304. {
  2305. BoundRow * targetRow = target->buildCreateRow(iterctx);
  2306. HqlExprAssociation * skipAssociation = NULL;
  2307. if (containsSkip)
  2308. {
  2309. OwnedHqlExpr callback = createUnknown(no_unknown, makeVoidType(), NULL, new InlineDatasetSkipCallback);
  2310. skipAssociation = ctx.associateExpr(skipActionMarker, callback);
  2311. }
  2312. Owned<IReferenceSelector> targetRef = buildActiveRow(iterctx, targetRow->querySelector());
  2313. switch (expr->getOperator())
  2314. {
  2315. case no_hqlproject:
  2316. doBuildRowAssignProject(iterctx, targetRef, expr);
  2317. break;
  2318. case no_newusertable:
  2319. doBuildRowAssignUserTable(iterctx, targetRef, expr);
  2320. break;
  2321. }
  2322. ctx.removeAssociation(skipAssociation);
  2323. target->finishRow(iterctx, targetRow);
  2324. }
  2325. }
  2326. void HqlCppTranslator::buildDatasetAssignJoin(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2327. {
  2328. IHqlExpression * left = expr->queryChild(0);
  2329. IHqlExpression * right = expr->queryChild(1);
  2330. IHqlExpression * cond = expr->queryChild(2);
  2331. IHqlExpression * selSeq = querySelSeq(expr);
  2332. bool leftOuter = expr->hasProperty(leftonlyAtom) || expr->hasProperty(leftouterAtom);
  2333. CHqlBoundExpr nullRhs;
  2334. if (leftOuter)
  2335. buildDefaultRow(ctx, right, nullRhs);
  2336. BuildCtx leftIterCtx(ctx);
  2337. BoundRow * leftCursor = buildDatasetIterate(leftIterCtx, left, false);
  2338. bindTableCursor(leftIterCtx, left, leftCursor->queryBound(), no_left, selSeq);
  2339. OwnedHqlExpr matchedAnyVar;
  2340. if (leftOuter)
  2341. matchedAnyVar.setown(leftIterCtx.getTempDeclare(queryBoolType(), queryBoolExpr(false)));
  2342. BuildCtx rightIterCtx(leftIterCtx);
  2343. BoundRow * rightCursor = buildDatasetIterate(rightIterCtx, right, false);
  2344. bindTableCursor(rightIterCtx, right, rightCursor->queryBound(), no_right, selSeq);
  2345. OwnedHqlExpr cseCond = options.spotCSE ? spotScalarCSE(cond) : LINK(cond);
  2346. buildFilter(rightIterCtx, cseCond);
  2347. if (!expr->hasProperty(leftonlyAtom))
  2348. {
  2349. BoundRow * targetRow = target->buildCreateRow(rightIterCtx);
  2350. Owned<IReferenceSelector> targetRef = buildActiveRow(rightIterCtx, targetRow->querySelector());
  2351. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(expr->queryChild(3)));
  2352. buildRowAssign(rightIterCtx, targetRef, rowValue);
  2353. target->finishRow(rightIterCtx, targetRow);
  2354. }
  2355. if (matchedAnyVar)
  2356. {
  2357. buildAssignToTemp(rightIterCtx, matchedAnyVar, queryBoolExpr(true));
  2358. OwnedHqlExpr test = getInverse(matchedAnyVar);
  2359. leftIterCtx.addFilter(test);
  2360. OwnedHqlExpr defaultRowPtr = getPointer(nullRhs.expr);
  2361. bindTableCursor(leftIterCtx, right, defaultRowPtr, no_right, selSeq);
  2362. BoundRow * targetRow = target->buildCreateRow(leftIterCtx);
  2363. Owned<IReferenceSelector> targetRef = buildActiveRow(leftIterCtx, targetRow->querySelector());
  2364. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(expr->queryChild(3)));
  2365. buildRowAssign(leftIterCtx, targetRef, rowValue);
  2366. target->finishRow(leftIterCtx, targetRow);
  2367. }
  2368. }
  2369. void HqlCppTranslator::buildDatasetAssignAggregate(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2370. {
  2371. BuildCtx subctx(ctx);
  2372. subctx.addGroup();
  2373. BoundRow * targetRow = target->buildCreateRow(subctx);
  2374. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2375. doBuildRowAssignAggregate(subctx, targetRef, expr);
  2376. target->finishRow(subctx, targetRow);
  2377. }
  2378. void HqlCppTranslator::buildDatasetAssign(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * _expr)
  2379. {
  2380. OwnedHqlExpr expr = forceInlineAssignDataset(ctx, _expr);
  2381. bool isRowAssign = false;
  2382. BuildCtx subctx(ctx);
  2383. switch (expr->getOperator())
  2384. {
  2385. case no_addfiles:
  2386. buildDatasetAssign(subctx, target, expr->queryChild(0));
  2387. buildDatasetAssign(subctx, target, expr->queryChild(1));
  2388. return;
  2389. case no_temptable:
  2390. buildDatasetAssignTempTable(subctx, target, expr);
  2391. //MORE: Create rows and assign each one in turn. Could possibly be done with a different dataset selector
  2392. return;
  2393. case no_inlinetable:
  2394. buildDatasetAssignInlineTable(subctx, target, expr);
  2395. return;
  2396. case no_xmlproject:
  2397. buildDatasetAssignXmlProject(subctx, target, expr);
  2398. return;
  2399. case no_datasetfromrow:
  2400. {
  2401. isRowAssign = true;
  2402. expr.set(expr->queryChild(0));
  2403. break;
  2404. }
  2405. case no_if:
  2406. {
  2407. CHqlBoundExpr bound;
  2408. buildExpr(subctx, expr->queryChild(0), bound);
  2409. IHqlStmt * filter = subctx.addFilter(bound.expr);
  2410. buildDatasetAssign(subctx, target, expr->queryChild(1));
  2411. IHqlExpression * elseExpr = expr->queryChild(2);
  2412. if (elseExpr && elseExpr->getOperator() != no_null)
  2413. {
  2414. subctx.selectElse(filter);
  2415. buildDatasetAssign(subctx, target, elseExpr);
  2416. }
  2417. }
  2418. return;
  2419. case no_null:
  2420. return;
  2421. case no_activetable:
  2422. case no_temprow:
  2423. case no_createrow:
  2424. case no_projectrow:
  2425. case no_typetransfer:
  2426. isRowAssign = true;
  2427. break;
  2428. case no_newaggregate:
  2429. buildDatasetAssignAggregate(subctx, target, expr);
  2430. return;
  2431. case no_hqlproject:
  2432. case no_newusertable:
  2433. buildDatasetAssignProject(subctx, target, expr);
  2434. return;
  2435. case no_compound_childread:
  2436. case no_compound_childnormalize:
  2437. case no_compound_childaggregate:
  2438. case no_compound_selectnew:
  2439. case no_compound_inline:
  2440. case no_distributed:
  2441. case no_preservemeta:
  2442. case no_sorted:
  2443. case no_nofold:
  2444. case no_nohoist:
  2445. case no_section:
  2446. case no_sectioninput:
  2447. buildDatasetAssign(subctx, target, expr->queryChild(0));
  2448. return;
  2449. case no_alias_scope:
  2450. // expandAliasScope(subctx, expr);
  2451. buildDatasetAssign(subctx, target, expr->queryChild(0));
  2452. return;
  2453. case no_filter:
  2454. {
  2455. //We want to evaluate invariant conditions outside of the loop, rather than inside the dataset assignment
  2456. //Currently the test is whether the expression is independent of any tables. Better would be to
  2457. //see if the test was dependent on any of the datasets introduced by expr->queryChild(0).
  2458. HqlExprArray conds;
  2459. unwindFilterConditions(conds, expr);
  2460. IHqlExpression * ds = expr->queryChild(0);
  2461. #if 0
  2462. HqlExprCopyArray selectors;
  2463. loop
  2464. {
  2465. selectors.append(*ds->queryNormalizedSelector());
  2466. IHqlExpression * root = queryRoot(expr);
  2467. if (!root || root->getOperator() != no_select)
  2468. break;
  2469. bool isNew;
  2470. ds = querySelectorDataset(root, isNew);
  2471. if (!isNew)
  2472. break;
  2473. }
  2474. #endif
  2475. unsigned max = conds.ordinality();
  2476. unsigned i = 0;
  2477. bool optimized = false;
  2478. while (i < max)
  2479. {
  2480. IHqlExpression & cur = conds.item(i);
  2481. #if 0
  2482. bool overlap = false;
  2483. ForEachItemIn(j, selectors)
  2484. {
  2485. if (containsSelector(&cur, &selectors.item(j)))
  2486. {
  2487. overlap = true;
  2488. break;
  2489. }
  2490. }
  2491. #else
  2492. bool overlap = containsSelector(&cur, ds->queryNormalizedSelector());
  2493. #endif
  2494. if (!overlap)
  2495. {
  2496. buildFilter(subctx, &cur);
  2497. conds.remove(i);
  2498. optimized = true;
  2499. max--;
  2500. }
  2501. else
  2502. i++;
  2503. }
  2504. if (max == 0)
  2505. {
  2506. buildDatasetAssign(subctx, target, ds);
  2507. return;
  2508. }
  2509. if (optimized)
  2510. {
  2511. conds.add(*LINK(ds), 0);
  2512. expr.setown(expr->clone(conds));
  2513. }
  2514. break;
  2515. }
  2516. case no_join:
  2517. buildDatasetAssignJoin(subctx, target, expr);
  2518. return;
  2519. }
  2520. ITypeInfo * type = expr->queryType();
  2521. if (type)
  2522. {
  2523. switch (type->getTypeCode())
  2524. {
  2525. case type_record: // e.g. dataset.recordfield
  2526. case type_row:
  2527. isRowAssign = true;
  2528. break;
  2529. }
  2530. }
  2531. if (isRowAssign)
  2532. {
  2533. bool done = false;
  2534. subctx.addGroup();
  2535. //Some code primarily here to improve the generated code for productions inside parse statements for text parsing.
  2536. //see if we can replace a memcpy of the child record with a link...
  2537. if (!target->isRestricted())
  2538. {
  2539. switch (expr->getOperator())
  2540. {
  2541. case no_matchattr:
  2542. case no_left:
  2543. case no_right:
  2544. {
  2545. //Only try for really simple cases...
  2546. Owned<IReferenceSelector> sourceRef = buildNewRow(subctx, expr);
  2547. Owned<BoundRow> sourceRow = sourceRef->getRow(subctx);
  2548. if (!target->buildLinkRow(subctx, sourceRow))
  2549. {
  2550. BoundRow * targetRow = target->buildCreateRow(subctx);
  2551. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2552. buildRowAssign(subctx, targetRef, sourceRef);
  2553. target->finishRow(subctx, targetRow);
  2554. }
  2555. done = true;
  2556. break;
  2557. }
  2558. }
  2559. }
  2560. if (!done)
  2561. {
  2562. BoundRow * match = static_cast<BoundRow *>(ctx.queryAssociation(expr, AssocRow, NULL));
  2563. if (match && target->buildLinkRow(subctx, match))
  2564. done = true;
  2565. }
  2566. if (!done)
  2567. {
  2568. BoundRow * targetRow = target->buildCreateRow(subctx);
  2569. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2570. buildRowAssign(subctx, targetRef, expr);
  2571. target->finishRow(subctx, targetRow);
  2572. }
  2573. }
  2574. else
  2575. {
  2576. if (!target->buildAppendRows(subctx, expr))
  2577. {
  2578. BoundRow * sourceRow = buildDatasetIterate(subctx, expr, false);
  2579. if (sourceRow)
  2580. {
  2581. if (!target->buildLinkRow(subctx, sourceRow))
  2582. {
  2583. BoundRow * targetRow = target->buildCreateRow(subctx);
  2584. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2585. Owned<IReferenceSelector> sourceRef = buildActiveRow(subctx, sourceRow->querySelector());
  2586. buildRowAssign(subctx, targetRef, sourceRef);
  2587. target->finishRow(subctx, targetRow);
  2588. }
  2589. }
  2590. }
  2591. }
  2592. }
  2593. //---------------------------------------------------------------------------
  2594. // Dataset iteration
  2595. BoundRow * HqlCppTranslator::buildDatasetIterateSelectN(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2596. {
  2597. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, NULL);
  2598. buildAssignToTemp(ctx, counter, expr->queryChild(1));
  2599. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2600. if (cursor)
  2601. {
  2602. OwnedHqlExpr dec = createValue(no_predec, counter->getType(), LINK(counter));
  2603. OwnedHqlExpr test = createBoolExpr(no_eq, LINK(dec), getSizetConstant(0));
  2604. ctx.addFilter(test);
  2605. }
  2606. return cursor;
  2607. }
  2608. BoundRow * HqlCppTranslator::buildDatasetIterateChoosen(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2609. {
  2610. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, queryZero());
  2611. CHqlBoundExpr boundLow, boundHigh;
  2612. OwnedHqlExpr foldedHigh = foldHqlExpression(expr->queryChild(1));
  2613. if (!isChooseNAllLimit(foldedHigh))
  2614. buildSimpleExpr(ctx, foldedHigh, boundHigh);
  2615. if (queryRealChild(expr, 2))
  2616. {
  2617. OwnedHqlExpr foldedLow = foldHqlExpression(expr->queryChild(2));
  2618. OwnedHqlExpr low = adjustValue(foldedLow, -1);
  2619. buildSimpleExpr(ctx, low, boundLow);
  2620. if (boundHigh.expr)
  2621. boundHigh.expr.setown(createValue(no_add, LINK(boundHigh.queryType()), LINK(boundHigh.expr), LINK(boundLow.expr)));
  2622. }
  2623. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2624. if (cursor)
  2625. {
  2626. OwnedHqlExpr inc = createValue(no_postinc, counter->getType(), LINK(counter));
  2627. ctx.addExpr(inc);
  2628. OwnedHqlExpr cond;
  2629. if (boundLow.expr)
  2630. extendConditionOwn(cond, no_and, createBoolExpr(no_gt, LINK(counter), LINK(boundLow.expr)));
  2631. if (boundHigh.expr)
  2632. extendConditionOwn(cond, no_and, createBoolExpr(no_le, LINK(counter), LINK(boundHigh.expr)));
  2633. if (cond)
  2634. ctx.addFilter(cond);
  2635. }
  2636. return cursor;
  2637. }
  2638. BoundRow * HqlCppTranslator::buildDatasetIterateLimit(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2639. {
  2640. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, queryZero());
  2641. CHqlBoundExpr boundHigh;
  2642. OwnedHqlExpr foldedHigh = foldHqlExpression(expr->queryChild(1));
  2643. buildSimpleExpr(ctx, foldedHigh, boundHigh);
  2644. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2645. if (cursor)
  2646. {
  2647. OwnedHqlExpr inc = createValue(no_preinc, counter->getType(), LINK(counter));
  2648. OwnedHqlExpr cond = createBoolExpr(no_gt, LINK(inc), LINK(boundHigh.expr));
  2649. BuildCtx subctx(ctx);
  2650. subctx.addFilter(cond);
  2651. LinkedHqlExpr fail = expr->queryChild(2);
  2652. if (!fail || fail->isAttribute())
  2653. fail.setown(createFailAction("Limit exceeded", foldedHigh, NULL, queryCurrentActivityId(ctx)));
  2654. buildStmt(subctx, fail);
  2655. }
  2656. return cursor;
  2657. }
  2658. BoundRow * HqlCppTranslator::buildDatasetIterateProject(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2659. {
  2660. IHqlExpression * dataset = expr->queryChild(0);
  2661. OwnedHqlExpr counterVar;
  2662. IHqlExpression * counter = queryPropertyChild(expr, _countProject_Atom, 0);
  2663. if (counter)
  2664. {
  2665. counterVar.setown(ctx.getTempDeclare(unsignedType, queryZero()));
  2666. }
  2667. bool containsSkip = transformContainsSkip(expr->queryChild(1));
  2668. if (containsSkip)
  2669. needToBreak = true;
  2670. buildDatasetIterate(ctx, dataset, needToBreak);
  2671. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  2672. if (counter)
  2673. {
  2674. ctx.associateExpr(counter, counterVar);
  2675. OwnedHqlExpr inc = createValue(no_postinc, LINK(unsignedType), LINK(counterVar));
  2676. ctx.addExpr(inc);
  2677. }
  2678. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  2679. OwnedHqlExpr leftSelect = createSelector(no_left, dataset, querySelSeq(expr));
  2680. OwnedHqlExpr transform = replaceSelector(expr->queryChild(1), leftSelect, dataset->queryNormalizedSelector());
  2681. HqlExprAssociation * skipAssociation = NULL;
  2682. if (containsSkip)
  2683. {
  2684. OwnedHqlExpr callback = createUnknown(no_unknown, makeVoidType(), NULL, new InlineDatasetSkipCallback);
  2685. skipAssociation = ctx.associateExpr(skipActionMarker, callback);
  2686. }
  2687. doTransform(ctx, transform, rowBuilder);
  2688. ctx.removeAssociation(skipAssociation); //remove it in case keeping hold of it causes issues.
  2689. finalizeTempRow(ctx, tempRow, rowBuilder);
  2690. return bindTableCursor(ctx, expr, tempRow->queryBound());
  2691. }
  2692. BoundRow * HqlCppTranslator::buildDatasetIterateUserTable(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2693. {
  2694. IHqlExpression * dataset = expr->queryChild(0);
  2695. buildDatasetIterate(ctx, dataset, needToBreak);
  2696. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  2697. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  2698. doTransform(ctx, expr->queryChild(2), rowBuilder);
  2699. finalizeTempRow(ctx, tempRow, rowBuilder);
  2700. return bindTableCursor(ctx, expr, tempRow->queryBound());
  2701. }
  2702. BoundRow * HqlCppTranslator::buildDatasetIterateSpecialTempTable(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2703. {
  2704. IHqlExpression * values = expr->queryChild(0);
  2705. bool requiresTempRow = false;
  2706. ITypeInfo * type = values->queryType()->queryChildType();
  2707. switch (type->getTypeCode())
  2708. {
  2709. case type_alien:
  2710. case type_bitfield:
  2711. requiresTempRow = true;
  2712. break;
  2713. default:
  2714. if (type->getSize() == UNKNOWN_LENGTH)
  2715. requiresTempRow = true;
  2716. break;
  2717. }
  2718. Owned<IHqlCppSetCursor> cursor = createSetSelector(ctx, values);
  2719. CHqlBoundExpr boundCurElement;
  2720. cursor->buildIterateLoop(ctx, boundCurElement, false);
  2721. OwnedHqlExpr address = getPointer(boundCurElement.expr);
  2722. if (requiresTempRow)
  2723. {
  2724. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  2725. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  2726. IHqlExpression * record = expr->queryRecord();
  2727. OwnedHqlExpr target = createSelectExpr(LINK(rowBuilder->querySelector()), LINK(record->queryChild(0)));
  2728. OwnedHqlExpr curValue = boundCurElement.getTranslatedExpr();
  2729. buildAssign(ctx, target, curValue);
  2730. finalizeTempRow(ctx, tempRow, rowBuilder);
  2731. return bindTableCursor(ctx, expr, tempRow->queryBound());
  2732. }
  2733. else
  2734. {
  2735. assertex(!boundCurElement.length && !boundCurElement.count);
  2736. address.setown(createValue(no_implicitcast, makeRowReferenceType(expr), LINK(address)));
  2737. return bindTableCursor(ctx, expr, address);
  2738. }
  2739. }
  2740. BoundRow * HqlCppTranslator::buildDatasetIterateStreamedCall(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2741. {
  2742. CHqlBoundExpr bound;
  2743. doBuildExprCall(ctx, expr, bound);
  2744. ITypeInfo * exprType = expr->queryType();
  2745. Owned<ITypeInfo> wrappedType = makeWrapperModifier(LINK(exprType));
  2746. OwnedHqlExpr temp = ctx.getTempDeclare(wrappedType, bound.expr);
  2747. ctx.addLoop(NULL, NULL, false);
  2748. Owned<ITypeInfo> wrappedRowType = makeWrapperModifier(LINK(queryRowType(exprType)));
  2749. OwnedHqlExpr tempRow = ctx.getTempDeclare(wrappedRowType, NULL);
  2750. StringBuffer s;
  2751. generateExprCpp(s, tempRow).append(".setown(");
  2752. generateExprCpp(s, temp).append("->nextRow());");
  2753. ctx.addQuoted(s);
  2754. s.clear().append("if (!");generateExprCpp(s, tempRow).append(".getbytes()) break;");
  2755. ctx.addQuoted(s);
  2756. return bindTableCursor(ctx, expr, tempRow);
  2757. }
  2758. BoundRow * HqlCppTranslator::buildDatasetIterate(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  2759. {
  2760. if (!canProcessInline(&ctx, expr))
  2761. {
  2762. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  2763. return cursor->buildIterateLoop(ctx, needToBreak);
  2764. }
  2765. switch (expr->getOperator())
  2766. {
  2767. case no_dataset_alias:
  2768. if (!expr->hasProperty(_normalized_Atom))
  2769. {
  2770. OwnedHqlExpr uniqueChild = normalizeDatasetAlias(expr);
  2771. BoundRow * childCursor = buildDatasetIterate(ctx, uniqueChild, needToBreak);
  2772. return rebindTableCursor(ctx, expr, childCursor, no_none, NULL);
  2773. }
  2774. else
  2775. {
  2776. throwUnexpected();
  2777. //The following would only be triggered for a splitter (not yet generated), and that would require
  2778. //disambiguation when that was built.
  2779. BoundRow * childCursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2780. return rebindTableCursor(ctx, expr, childCursor, no_none, NULL);
  2781. }
  2782. case no_null:
  2783. buildFilter(ctx, queryBoolExpr(false));
  2784. return NULL;
  2785. case no_filter:
  2786. {
  2787. IHqlExpression * dataset = expr->queryChild(0);
  2788. #ifdef _OPTIMZE_INLINE_FILTERS_
  2789. //Good code, but messes up accidental cse in some createSegmentMonitor calls.
  2790. HqlExprAttr invariant;
  2791. OwnedHqlExpr cond = extractFilterConditions(invariant, expr, dataset);
  2792. if (invariant)
  2793. buildFilter(ctx, invariant);
  2794. //MORE: if (canAssignInline(ctx, ds) && !canIterateInline(ctx, ds)) break;
  2795. BoundRow * cursor = buildDatasetIterate(ctx, dataset, needToBreak);
  2796. if (cond)
  2797. buildFilter(ctx, cond);
  2798. #else
  2799. //MORE: if (canAssignInline(ctx, ds) && !canIterateInline(ctx, ds)) break;
  2800. BoundRow * cursor = buildDatasetIterate(ctx, dataset, needToBreak);
  2801. unsigned max = expr->numChildren();
  2802. for (unsigned i=1; i < max; i++)
  2803. buildFilter(ctx, expr->queryChild(i));
  2804. #endif
  2805. return cursor;
  2806. }
  2807. case no_id2blob:
  2808. case no_select:
  2809. case no_translated:
  2810. {
  2811. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  2812. return cursor->buildIterateLoop(ctx, needToBreak);
  2813. }
  2814. case no_choosen:
  2815. return buildDatasetIterateChoosen(ctx, expr, needToBreak);
  2816. case no_limit:
  2817. return buildDatasetIterateLimit(ctx, expr, needToBreak);
  2818. case no_index:
  2819. case no_selectnth:
  2820. return buildDatasetIterateSelectN(ctx, expr, needToBreak);
  2821. case no_hqlproject:
  2822. return buildDatasetIterateProject(ctx, expr, needToBreak);
  2823. case no_newusertable:
  2824. return buildDatasetIterateUserTable(ctx, expr, needToBreak);
  2825. case no_compound_childread:
  2826. case no_compound_childnormalize:
  2827. case no_compound_childaggregate:
  2828. case no_compound_selectnew:
  2829. case no_compound_inline:
  2830. case no_distributed:
  2831. case no_preservemeta:
  2832. case no_sorted:
  2833. case no_nofold:
  2834. case no_nohoist:
  2835. return buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2836. case no_sectioninput:
  2837. case no_section:
  2838. {
  2839. BoundRow * row = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2840. #ifdef _DEBUG
  2841. StringBuffer s;
  2842. if (expr->getOperator() == no_section)
  2843. s.append("//---- section ");
  2844. else
  2845. s.append("//---- end section ");
  2846. getStringValue(s, expr->queryChild(1), "<?>").append(" ");
  2847. getStringValue(s, expr->queryChild(2)).append("----");
  2848. ctx.addQuoted(s);
  2849. #endif
  2850. return row;
  2851. }
  2852. case no_alias_scope:
  2853. // expandAliasScope(ctx, expr);
  2854. return buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  2855. case no_temptable:
  2856. {
  2857. IHqlExpression * values = expr->queryChild(0);
  2858. if (values->queryType()->getTypeCode() == type_set)
  2859. {
  2860. if (values->getOperator() == no_alias)
  2861. values = values->queryChild(0);
  2862. bool special = false;
  2863. switch (values->getOperator())
  2864. {
  2865. case no_getresult:
  2866. case no_null:
  2867. special = true;
  2868. break;
  2869. }
  2870. if (special)
  2871. return buildDatasetIterateSpecialTempTable(ctx, expr, needToBreak);
  2872. }
  2873. break;
  2874. }
  2875. case no_call:
  2876. case no_externalcall:
  2877. if (hasStreamedModifier(expr->queryType()))
  2878. return buildDatasetIterateStreamedCall(ctx, expr, needToBreak);
  2879. break;
  2880. #if 0
  2881. //Following should improve the code, but I'm not sure how to correctly convert a referenceSelector to a boundExpr (since it may be with an existing row)
  2882. case no_datasetfromrow:
  2883. if (!needToBreak)
  2884. {
  2885. BoundRow * row = buildNewRow(ctx, expr->queryChild(0));
  2886. bindTableCursor(ctx, expr, tempRow->queryBound(), no_none, NULL);
  2887. return row;
  2888. }
  2889. break;
  2890. #endif
  2891. }
  2892. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  2893. return cursor->buildIterateLoop(ctx, needToBreak);
  2894. }
  2895. //---------------------------------------------------------------------------
  2896. // Row Assignment
  2897. void HqlCppTranslator::buildCompoundAssign(BuildCtx & ctx, IHqlExpression * left, IReferenceSelector * leftSelector, IHqlExpression * rightScope, IHqlExpression * rightSelector)
  2898. {
  2899. switch (left->getOperator())
  2900. {
  2901. case no_ifblock:
  2902. {
  2903. BuildCtx subctx(ctx);
  2904. OwnedHqlExpr test = replaceSelector(left->queryChild(0), querySelfReference(), leftSelector->queryExpr());
  2905. buildFilter(subctx, test);
  2906. buildCompoundAssign(subctx, left->queryChild(1), leftSelector, rightScope, rightSelector);
  2907. //This calculates the size of the previous block. It means that subsequent uses of the
  2908. //offsets are cached - even if they are inside another ifblock().
  2909. CHqlBoundExpr bound;
  2910. IHqlExpression * mapexpr = createSelectExpr(LINK(leftSelector->queryExpr()), LINK(left));
  2911. OwnedHqlExpr size = createValue(no_sizeof, makeIntType(4,false), mapexpr);
  2912. buildCachedExpr(ctx, size, bound);
  2913. }
  2914. break;
  2915. case no_field:
  2916. {
  2917. Owned<IReferenceSelector> selectedLeft = leftSelector->select(ctx, left);
  2918. OwnedHqlExpr selectedRight;
  2919. IHqlExpression * leftRecord = ::queryRecord(leftSelector->queryType());
  2920. if (!rightScope || (leftRecord==rightScope))
  2921. {
  2922. selectedRight.setown(createSelectExpr(LINK(rightSelector), LINK(left)));
  2923. }
  2924. else
  2925. {
  2926. IHqlSimpleScope * scope = rightScope->querySimpleScope();
  2927. IHqlExpression * resolved = scope->lookupSymbol(left->queryName());
  2928. assertex(resolved);
  2929. selectedRight.setown(createSelectExpr(LINK(rightSelector), resolved));
  2930. }
  2931. if (left->queryType()->getTypeCode() == type_row)
  2932. buildCompoundAssign(ctx, left->queryRecord(), selectedLeft, selectedRight->queryRecord(), selectedRight);
  2933. else
  2934. selectedLeft->set(ctx, selectedRight);
  2935. break;
  2936. }
  2937. break;
  2938. case no_record:
  2939. {
  2940. ForEachChild(i, left)
  2941. buildCompoundAssign(ctx, left->queryChild(i), leftSelector, rightScope, rightSelector);
  2942. break;
  2943. }
  2944. case no_attr:
  2945. case no_attr_expr:
  2946. case no_attr_link:
  2947. break;
  2948. default:
  2949. UNIMPLEMENTED;
  2950. }
  2951. }
  2952. void HqlCppTranslator::buildCompoundAssign(BuildCtx & ctx, IHqlExpression * left, IHqlExpression * right)
  2953. {
  2954. //MORE: May need to resolve lhs and rhs in scope to find out the record type.
  2955. // buildCompoundAssign(ctx, column->queryRecord(), selector->queryExpr(), value->queryRecord(), value);
  2956. UNIMPLEMENTED;
  2957. }
  2958. void HqlCppTranslator::doBuildRowAssignAggregateClear(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  2959. {
  2960. IHqlExpression * transform = expr->queryChild(2);
  2961. unsigned numAggregates = transform->numChildren();
  2962. unsigned idx;
  2963. OwnedHqlExpr self = getSelf(expr);
  2964. for (idx = 0; idx < numAggregates; idx++)
  2965. {
  2966. IHqlExpression * cur = transform->queryChild(idx);
  2967. Owned<IReferenceSelector> curTarget = createSelfSelect(ctx, target, cur->queryChild(0), self);
  2968. IHqlExpression * src = cur->queryChild(1);
  2969. switch (src->getOperator())
  2970. {
  2971. case no_countgroup:
  2972. case no_maxgroup:
  2973. case no_mingroup:
  2974. case no_sumgroup:
  2975. case no_existsgroup:
  2976. curTarget->buildClear(ctx, 0);
  2977. break;
  2978. default:
  2979. if (src->isConstant())
  2980. curTarget->set(ctx, src);
  2981. else
  2982. curTarget->buildClear(ctx, 0);
  2983. break;
  2984. }
  2985. }
  2986. }
  2987. void HqlCppTranslator::doBuildRowAssignAggregateNext(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr, bool isSingleExists, IHqlExpression * alreadyDoneExpr)
  2988. {
  2989. IHqlExpression * transform = expr->queryChild(2);
  2990. unsigned numAggregates = transform->numChildren();
  2991. OwnedHqlExpr self = getSelf(expr);
  2992. OwnedHqlExpr notAlreadyDone = alreadyDoneExpr ? getInverse(alreadyDoneExpr) : NULL;
  2993. bool isVariableOffset = false;
  2994. for (unsigned idx = 0; idx < numAggregates; idx++)
  2995. {
  2996. IHqlExpression * cur = transform->queryChild(idx);
  2997. if (cur->isAttribute())
  2998. continue;
  2999. IHqlExpression * targetSelect = cur->queryChild(0);
  3000. Owned<IReferenceSelector> curTarget = createSelfSelect(ctx, target, targetSelect, self);
  3001. IHqlExpression * src = cur->queryChild(1);
  3002. IHqlExpression * arg = src->queryChild(0);
  3003. IHqlExpression * cond = src->queryChild(1);
  3004. BuildCtx condctx(ctx);
  3005. node_operator srcOp = src->getOperator();
  3006. switch (srcOp)
  3007. {
  3008. case no_countgroup:
  3009. {
  3010. assertex(!(arg && isVariableOffset));
  3011. if (arg)
  3012. buildFilter(condctx, arg);
  3013. OwnedHqlExpr one = getSizetConstant(1);
  3014. if (isVariableOffset)
  3015. {
  3016. IHqlStmt * ifStmt = condctx.addFilter(notAlreadyDone);
  3017. curTarget->set(condctx, one);
  3018. condctx.selectElse(ifStmt);
  3019. }
  3020. buildIncrementAssign(condctx, curTarget, one);
  3021. }
  3022. break;
  3023. case no_sumgroup:
  3024. {
  3025. assertex(!(cond && isVariableOffset));
  3026. if (cond)
  3027. buildFilter(condctx, cond);
  3028. if (isVariableOffset)
  3029. {
  3030. IHqlStmt * ifStmt = condctx.addFilter(notAlreadyDone);
  3031. curTarget->set(condctx, arg);
  3032. condctx.selectElse(ifStmt);
  3033. }
  3034. buildIncrementAssign(condctx, curTarget, arg);
  3035. }
  3036. break;
  3037. case no_maxgroup:
  3038. case no_mingroup:
  3039. {
  3040. node_operator op = (srcOp == no_maxgroup) ? no_gt : no_lt;
  3041. assertex(!cond);
  3042. OwnedHqlExpr castArg = ensureExprType(arg, targetSelect->queryType()); // cast to correct type, assume it can fit in the target type.
  3043. OwnedHqlExpr temp = buildSimplifyExpr(condctx, castArg);
  3044. OwnedHqlExpr compare = createBoolExpr (op, LINK(temp), LINK(curTarget->queryExpr()));
  3045. if (notAlreadyDone)
  3046. compare.setown(createBoolExpr(no_or, LINK(notAlreadyDone), compare.getClear()));
  3047. buildFilter(condctx, compare);
  3048. curTarget->set(condctx, temp);
  3049. }
  3050. break;
  3051. case no_existsgroup:
  3052. assertex(!(arg && isVariableOffset));
  3053. if (arg)
  3054. buildFilter(condctx, arg);
  3055. curTarget->set(condctx, queryBoolExpr(true));
  3056. if (isSingleExists)
  3057. condctx.addBreak();
  3058. break;
  3059. default:
  3060. if (!src->isConstant() || isVariableOffset)
  3061. {
  3062. condctx.addFilter(notAlreadyDone);
  3063. curTarget->set(condctx, src);
  3064. }
  3065. break;
  3066. }
  3067. if (targetSelect->queryType()->getSize() == UNKNOWN_LENGTH)
  3068. isVariableOffset = true;
  3069. }
  3070. if (alreadyDoneExpr)
  3071. buildAssignToTemp(ctx, alreadyDoneExpr, queryBoolExpr(true));
  3072. }
  3073. void HqlCppTranslator::doBuildRowAssignAggregate(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3074. {
  3075. IHqlExpression * dataset = expr->queryChild(0);
  3076. IHqlExpression * transform = expr->queryChild(2);
  3077. unsigned numAggregates = transform->numChildren();
  3078. if (isKeyedCountAggregate(expr))
  3079. throwError(HQLERR_KeyedCountNonKeyable);
  3080. bool needGuard = false;
  3081. bool isSingleExists = true;
  3082. unsigned idx;
  3083. for (idx = 0; idx < numAggregates; idx++)
  3084. {
  3085. IHqlExpression * cur = transform->queryChild(idx);
  3086. if (cur->isAttribute())
  3087. continue;
  3088. IHqlExpression * tgt = cur->queryChild(0);
  3089. IHqlExpression * src = cur->queryChild(1);
  3090. switch (src->getOperator())
  3091. {
  3092. case no_countgroup:
  3093. case no_sumgroup:
  3094. isSingleExists = false;
  3095. break;
  3096. case no_existsgroup:
  3097. break;
  3098. case no_mingroup:
  3099. isSingleExists = false;
  3100. needGuard = true;
  3101. break;
  3102. case no_maxgroup:
  3103. isSingleExists = false;
  3104. if (!isNullValueMinimumValue(src->queryType()))
  3105. needGuard = true;
  3106. break;
  3107. default:
  3108. isSingleExists = false;
  3109. if (!src->isConstant())
  3110. needGuard = true;
  3111. break;
  3112. }
  3113. if ((tgt->queryType()->getSize() == UNKNOWN_LENGTH) && (idx+1 != numAggregates))
  3114. needGuard = true;
  3115. }
  3116. OwnedHqlExpr guard;
  3117. if (needGuard)
  3118. {
  3119. Owned<ITypeInfo> boolType = makeBoolType();
  3120. guard.setown(ctx.getTempDeclare(boolType, queryBoolExpr(false)));
  3121. }
  3122. doBuildRowAssignAggregateClear(ctx, target, expr);
  3123. BuildCtx condctx(ctx);
  3124. BoundRow * cursor = buildDatasetIterate(condctx, dataset, isSingleExists);
  3125. doBuildRowAssignAggregateNext(condctx, target, expr, isSingleExists, guard);
  3126. }
  3127. void HqlCppTranslator::doBuildRowAssignProject(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3128. {
  3129. IHqlExpression * dataset = expr->queryChild(0);
  3130. IHqlExpression * counter = queryPropertyChild(expr, _countProject_Atom, 0);
  3131. if (counter && !ctx.queryMatchExpr(counter))
  3132. throwError(HQLERR_CounterNotFound);
  3133. BuildCtx subctx(ctx);
  3134. assertex(target->isRoot());
  3135. IHqlExpression * selSeq = querySelSeq(expr);
  3136. OwnedHqlExpr leftSelect = createSelector(no_left, dataset, selSeq);
  3137. OwnedHqlExpr activeDataset = ensureActiveRow(dataset->queryNormalizedSelector());
  3138. OwnedHqlExpr transform = queryNewReplaceSelector(expr->queryChild(1), leftSelect, activeDataset);
  3139. Owned<BoundRow> selfCursor;
  3140. if (!transform)
  3141. {
  3142. subctx.addGroup();
  3143. selfCursor.set(bindSelectorAsSelf(subctx, target, expr));
  3144. //Mapping may potentially be ambiguous, so do things correctly (see hqlsource for details)
  3145. BoundRow * prevCursor = resolveSelectorDataset(subctx, dataset->queryNormalizedSelector());
  3146. transform.set(expr->queryChild(1));
  3147. bindTableCursor(subctx, dataset, prevCursor->queryBound(), no_left, selSeq);
  3148. }
  3149. else
  3150. {
  3151. //Not introducing any new left rows => no problem assigning to target selector
  3152. selfCursor.setown(target->getRow(subctx));
  3153. }
  3154. doTransform(subctx, transform, selfCursor);
  3155. }
  3156. void HqlCppTranslator::doBuildRowAssignCreateRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3157. {
  3158. IHqlExpression * transform = expr->queryChild(0);
  3159. if (transform->isConstant())
  3160. {
  3161. #ifdef USE_CONSTANT_ROW_FOR_ASSIGN
  3162. //Generally not worthwhile - unless maybe it has a large number of fields....
  3163. CHqlBoundExpr bound;
  3164. if (doBuildRowConstantTransform(transform, bound))
  3165. {
  3166. OwnedHqlExpr raw = bound.getTranslatedExpr();
  3167. buildRowAssign(ctx, target, raw);
  3168. return;
  3169. }
  3170. #endif
  3171. }
  3172. Owned<BoundRow> selfCursor = target->getRow(ctx);
  3173. doTransform(ctx, transform, selfCursor);
  3174. }
  3175. void HqlCppTranslator::doBuildRowAssignNullRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3176. {
  3177. target->buildClear(ctx, 0);
  3178. }
  3179. void HqlCppTranslator::doBuildRowAssignProjectRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3180. {
  3181. IHqlExpression * srcRow = expr->queryChild(0);
  3182. IHqlExpression * transform = expr->queryChild(1);
  3183. Owned<IReferenceSelector> source = buildNewRow(ctx, srcRow);
  3184. BuildCtx subctx(ctx);
  3185. OwnedHqlExpr leftSelect = createSelector(no_left, srcRow, querySelSeq(expr));
  3186. OwnedHqlExpr newTransform = replaceSelector(transform, leftSelect, srcRow);
  3187. Owned<BoundRow> selfCursor = target->getRow(subctx);
  3188. doTransform(subctx, newTransform, selfCursor);
  3189. }
  3190. void HqlCppTranslator::doBuildRowAssignSerializeRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3191. {
  3192. IHqlExpression * srcRow = expr->queryChild(0);
  3193. Owned<IReferenceSelector> source = buildNewRow(ctx, srcRow);
  3194. BuildCtx subctx(ctx);
  3195. Owned<BoundRow> leftCursor = source->getRow(subctx);
  3196. BoundRow * selfCursor = bindSelectorAsSelf(subctx, target, expr);
  3197. IHqlExpression * unserializedRecord = srcRow->queryRecord();
  3198. //If builder isn't provided then the target must be a fixed size record that doesn't require serialization
  3199. //Therefore this should never be called.
  3200. assertex(selfCursor->queryBuilder());
  3201. {
  3202. HqlExprArray args;
  3203. args.append(*createRowSerializer(ctx, unserializedRecord, serializerAtom));
  3204. args.append(*LINK(srcRow));
  3205. Owned<ITypeInfo> type = makeTransformType(expr->queryRecord()->getType());
  3206. OwnedHqlExpr call = bindFunctionCall(rtlSerializeToBuilderAtom, args, type);
  3207. doTransform(subctx, call, selfCursor);
  3208. //MORE: This doesn't associated the returned size with the target if assigned to a child field.
  3209. //very unusual code, so not too concerned.
  3210. }
  3211. subctx.removeAssociation(selfCursor);
  3212. }
  3213. void HqlCppTranslator::doBuildRowAssignUserTable(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3214. {
  3215. Owned<BoundRow> selfCursor = target->getRow(ctx);
  3216. doTransform(ctx, expr->queryChild(2), selfCursor);
  3217. }
  3218. void HqlCppTranslator::buildRowAssign(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3219. {
  3220. switch (expr->getOperator())
  3221. {
  3222. case no_temprow:
  3223. throwUnexpected();
  3224. case no_projectrow:
  3225. doBuildRowAssignProjectRow(ctx, target, expr);
  3226. return;
  3227. case no_createrow:
  3228. doBuildRowAssignCreateRow(ctx, target, expr);
  3229. return;
  3230. case no_null:
  3231. doBuildRowAssignNullRow(ctx, target, expr);
  3232. return;
  3233. case no_serialize:
  3234. if (isDummySerializeDeserialize(expr))
  3235. buildRowAssign(ctx, target, expr->queryChild(0)->queryChild(0));
  3236. else
  3237. doBuildRowAssignSerializeRow(ctx, target, expr);
  3238. return;
  3239. case no_if:
  3240. {
  3241. OwnedHqlExpr foldedCond = foldHqlExpression(expr->queryChild(0));
  3242. if (foldedCond->queryValue())
  3243. {
  3244. unsigned branch = (foldedCond->queryValue()->getBoolValue()) ? 1 : 2;
  3245. buildRowAssign(ctx, target, expr->queryChild(branch));
  3246. return;
  3247. }
  3248. //Assigning a variable size record can mean that references to self need recalculating outside of the condition,
  3249. //producing poor code.
  3250. if (!isVariableSizeRecord(expr->queryRecord()))
  3251. {
  3252. BuildCtx condctx(ctx);
  3253. IHqlStmt * cond = buildFilterViaExpr(condctx, foldedCond);
  3254. buildRowAssign(condctx, target, expr->queryChild(1));
  3255. condctx.selectElse(cond);
  3256. buildRowAssign(condctx, target, expr->queryChild(2));
  3257. return;
  3258. }
  3259. }
  3260. break;
  3261. /*
  3262. case no_externalcall:
  3263. //MORE: Should assign directly to the target, but may not be very easy....
  3264. if (target->isBinary() && queryRecord(source->queryType()) == expr->queryRecord())
  3265. {
  3266. CHqlBoundExpr address;
  3267. target->buildAddress(ctx, address);
  3268. row.setown(createValue(no_typetransfer, makeReferenceModifier(LINK(selector->queryType())), LINK(address.expr)));
  3269. doBuildCall(ctx, &target, expr, NULL);
  3270. }
  3271. break;
  3272. */
  3273. case no_comma:
  3274. case no_compound:
  3275. buildStmt(ctx, expr->queryChild(0));
  3276. buildRowAssign(ctx, target, expr->queryChild(1));
  3277. return;
  3278. }
  3279. Owned<IReferenceSelector> src = buildNewRow(ctx, expr);
  3280. buildRowAssign(ctx, target, src);
  3281. }
  3282. void HqlCppTranslator::buildRowAssign(BuildCtx & ctx, IReferenceSelector * target, IReferenceSelector * source)
  3283. {
  3284. BuildCtx subctx(ctx);
  3285. IHqlExpression * sourceRecord = ::queryRecord(source->queryType());
  3286. IHqlExpression * targetRecord = ::queryRecord(target->queryType());
  3287. //if record structures are identical, then we must just be able to block copy the information across.
  3288. bool useMemcpy = (sourceRecord == targetRecord) && source->isBinary() && !source->isConditional() &&
  3289. !recordRequiresSerialization(sourceRecord);
  3290. if (useMemcpy)
  3291. {
  3292. if (source->queryRootRow()->isConditional())
  3293. {
  3294. IHqlStmt * ifStmt = subctx.addFilter(source->queryRootRow()->queryBound());
  3295. target->setRow(subctx, source);
  3296. subctx.selectElse(ifStmt);
  3297. target->buildClear(subctx, 0);
  3298. }
  3299. else
  3300. target->setRow(subctx, source);
  3301. }
  3302. else
  3303. buildCompoundAssign(subctx, targetRecord, target, sourceRecord, source->queryExpr());
  3304. }
  3305. //---------------------------------------------------------------------------
  3306. // Dataset selection
  3307. IReferenceSelector * HqlCppTranslator::doBuildRowSelectTop(BuildCtx & ctx, IHqlExpression * expr)
  3308. {
  3309. //create a temporary
  3310. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  3311. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  3312. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  3313. ctx.associate(*row); // associate here because it is compared inside the loop
  3314. CHqlBoundExpr boundCleared;
  3315. #ifdef CREATE_DEAULT_ROW_IF_NULL
  3316. buildDefaultRow(ctx, expr, boundCleared);
  3317. #else
  3318. buildNullRow(ctx, expr, boundCleared);
  3319. #endif
  3320. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  3321. //Declare row for final level, iterate the appropriate number of times, and then assign and break.
  3322. BuildCtx initctx(ctx);
  3323. initctx.addGroup(); // add a group to allow a temporary to be declared later.
  3324. initctx.addAssign(rowExpr, defaultRowPtr);
  3325. HqlExprAssociation * savedMarker = ctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  3326. BuildCtx iterctx(ctx);
  3327. IHqlExpression * sort = expr->queryChild(0);
  3328. IHqlExpression * dataset = sort->queryChild(0);
  3329. IHqlExpression * sortList = sort->queryChild(1);
  3330. BoundRow * chooseCursor = buildDatasetIterate(iterctx, dataset, false);
  3331. //if (!best) { best=row; } else { if (next < best) best = row; } Must short-circuit the test of best
  3332. OwnedHqlExpr testBest = createBoolExpr(no_eq, LINK(rowExpr), LINK(defaultRowPtr));
  3333. IHqlStmt * ifStmt = iterctx.addFilter(testBest);
  3334. {
  3335. OwnedHqlExpr source = ensureIteratedRowIsLive(initctx, ctx, iterctx, chooseCursor, dataset, expr);
  3336. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));//chooseCursor->queryBound()));
  3337. iterctx.addAssign(rowExpr, castLeftRow);
  3338. }
  3339. iterctx.selectElse(ifStmt);
  3340. CHqlBoundExpr bound;
  3341. buildOrderedCompare(iterctx, dataset, sortList, bound, dataset, expr);
  3342. OwnedHqlExpr compare = createBoolExpr(no_lt, LINK(bound.expr), getZero());
  3343. iterctx.addFilter(compare);
  3344. {
  3345. OwnedHqlExpr source = ensureIteratedRowIsLive(initctx, ctx, iterctx, chooseCursor, dataset, expr);
  3346. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));//chooseCursor->queryBound()));
  3347. iterctx.addAssign(rowExpr, castLeftRow);
  3348. }
  3349. ctx.removeAssociation(savedMarker);
  3350. //Set conditional later on, so test in main loop is explicit
  3351. #ifndef CREATE_DEAULT_ROW_IF_NULL
  3352. row->setConditional(true);
  3353. #endif
  3354. return createReferenceSelector(row);
  3355. }
  3356. BoundRow * HqlCppTranslator::buildOptimizeSelectFirstRow(BuildCtx & ctx, IHqlExpression * expr)
  3357. {
  3358. BoundRow * parentRow = NULL;
  3359. node_operator op = expr->getOperator();
  3360. switch (op)
  3361. {
  3362. case no_compound_childaggregate:
  3363. return buildOptimizeSelectFirstRow(ctx, expr->queryChild(0));
  3364. case no_hqlproject:
  3365. case no_newusertable:
  3366. {
  3367. parentRow = buildOptimizeSelectFirstRow(ctx, expr->queryChild(0));
  3368. if (!parentRow)
  3369. return NULL;
  3370. }
  3371. //fall through
  3372. case no_newaggregate:
  3373. {
  3374. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  3375. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  3376. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  3377. BuildCtx subctx(ctx);
  3378. subctx.addGroup();
  3379. if (parentRow)
  3380. {
  3381. if (op == no_hqlproject)
  3382. bindTableCursor(ctx, expr->queryChild(0), tempRow->queryBound(), no_left, querySelSeq(expr));
  3383. else
  3384. bindTableCursor(ctx, expr->queryChild(0), tempRow->queryBound(), no_none, NULL);
  3385. }
  3386. doBuildRowAssignAggregate(subctx, createdRef, expr);
  3387. finalizeTempRow(ctx, tempRow, rowBuilder);
  3388. return tempRow;
  3389. }
  3390. //
  3391. default:
  3392. return NULL;
  3393. }
  3394. }
  3395. void HqlCppTranslator::convertBoundDatasetToFirstRow(IHqlExpression * expr, CHqlBoundExpr & bound)
  3396. {
  3397. Owned<ITypeInfo> type = makeReferenceModifier(expr->getType());
  3398. ITypeInfo * boundType = bound.queryType();
  3399. if (isArrayRowset(boundType))
  3400. {
  3401. Linked<ITypeInfo> rowType = queryUnqualifiedType(queryRowType(boundType));
  3402. rowType.setown(makeReferenceModifier(LINK(rowType)));
  3403. if (hasLinkedRow(boundType))
  3404. type.setown(setLinkCountedAttr(type, true));
  3405. bound.expr.setown(createValue(no_deref, LINK(rowType), LINK(bound.expr)));
  3406. }
  3407. else if (bound.queryType()->isReference())
  3408. bound.expr.setown(createValue(no_typetransfer, LINK(type), bound.expr.getClear()));
  3409. else
  3410. bound.expr.setown(createValue(no_implicitcast, LINK(type), bound.expr.getClear()));
  3411. }
  3412. void HqlCppTranslator::convertBoundRowToDataset(BuildCtx & ctx, CHqlBoundExpr & bound, const BoundRow * row, ExpressionFormat preferredFormat)
  3413. {
  3414. IHqlExpression * boundRow = row->queryBound();
  3415. IHqlExpression * record = row->queryDataset()->queryRecord();
  3416. Owned<ITypeInfo> type = makeTableType(makeRowType(LINK(record->queryType())), NULL, NULL, NULL);
  3417. Owned<ITypeInfo> refType = makeReferenceModifier(LINK(type));
  3418. if (hasLinkCountedModifier(boundRow->queryType()) && (preferredFormat != FormatBlockedDataset))
  3419. {
  3420. OwnedHqlExpr curActivityId = getCurrentActivityId(ctx);
  3421. StringBuffer allocatorName;
  3422. ensureRowAllocator(allocatorName, ctx, record, curActivityId);
  3423. OwnedHqlExpr src = getPointer(boundRow);
  3424. //We can't just take the address of the link counted row, have to create a temporary dataset
  3425. //could be fixed once the link counting is tracked on rows and datasets
  3426. CHqlBoundTarget target;
  3427. createTempFor(ctx, type, target, typemod_none, FormatLinkedDataset);
  3428. StringBuffer s;
  3429. generateExprCpp(s, target.expr).append(".setRow(").append(allocatorName).append(",");
  3430. generateExprCpp(s, src).append(");");
  3431. ctx.addQuoted(s);
  3432. bound.setFromTarget(target);
  3433. }
  3434. else if (boundRow->queryType()->isReference())
  3435. bound.expr.setown(createValue(no_typetransfer, LINK(refType), LINK(boundRow)));
  3436. else
  3437. bound.expr.setown(createValue(no_implicitcast, LINK(refType), LINK(boundRow)));
  3438. bound.count.setown(getSizetConstant(1));
  3439. }
  3440. IHqlExpression * HqlCppTranslator::ensureIteratedRowIsLive(BuildCtx & initctx, BuildCtx & searchctx, BuildCtx & iterctx, BoundRow * row, IHqlExpression * dataset, IHqlExpression * rowExpr)
  3441. {
  3442. //The problem is that we are iterating through the rows in a dataset, and we need to access the "best" row outside of the loop
  3443. //However subsequent iterations of the loop might invalidate the current row, so we need to ensure the best row is retained.
  3444. //There should really be a better way, but it isn't too bad with link counted rows.
  3445. bool needToPreserve = false;
  3446. IHqlExpression * ds = dataset;
  3447. while (ds && !needToPreserve)
  3448. {
  3449. if (ds->isDatarow())
  3450. {
  3451. if (initctx.queryAssociation(ds, AssocRow, NULL))
  3452. break;
  3453. }
  3454. else
  3455. {
  3456. if (initctx.queryMatchExpr(ds))
  3457. break;
  3458. }
  3459. switch (ds->getOperator())
  3460. {
  3461. case no_filter:
  3462. case no_grouped:
  3463. case no_stepped:
  3464. case no_sorted:
  3465. case no_distributed:
  3466. case no_preservemeta:
  3467. case no_choosen:
  3468. case no_selectnth: // can occur as the lhs of no_select
  3469. case no_compound_childnormalize:
  3470. case no_compound_selectnew:
  3471. case no_compound_childread:
  3472. case no_dataset_alias:
  3473. ds = ds->queryChild(0);
  3474. break;
  3475. case no_select:
  3476. if (ds->isDataset())
  3477. {
  3478. if (ds->hasProperty(newAtom))
  3479. {
  3480. ds = ds->queryChild(0);
  3481. //don't walk complexds[1].childDataset<new> since the [1] will be generated as a temporary
  3482. // if (!ds->isDataset() && (ds->getOperator() != no_select))
  3483. // ds = NULL;
  3484. }
  3485. else
  3486. ds = NULL;
  3487. }
  3488. else
  3489. {
  3490. //ds.x.y, always walk to to ds.x
  3491. ds = ds->queryChild(0);
  3492. }
  3493. break;
  3494. case no_rows:
  3495. case no_call:
  3496. case no_externalcall:
  3497. case no_getresult:
  3498. case no_getgraphresult:
  3499. case no_alias:
  3500. ds = NULL;
  3501. break;
  3502. default:
  3503. needToPreserve = true;
  3504. break;
  3505. }
  3506. }
  3507. OwnedHqlExpr source = getPointer(row->queryBound());
  3508. if (!needToPreserve || initctx.hasAssociation(*row, false))
  3509. return source.getClear();
  3510. //If link counted, then declare a member that is a link counted row to ensure this row remains linked.
  3511. ITypeInfo * rowType = rowExpr->queryType();
  3512. if (hasLinkCountedModifier(row->queryBound()))
  3513. {
  3514. CHqlBoundTarget saveTarget;
  3515. createTempFor(initctx, rowType, saveTarget, typemod_wrapper, FormatLinkedDataset);
  3516. StringBuffer s;
  3517. generateExprCpp(s, saveTarget.expr);
  3518. s.append(".set(");
  3519. generateExprCpp(s, source).append(");");
  3520. iterctx.addQuoted(s);
  3521. return getPointer(saveTarget.expr);
  3522. }
  3523. BuildCtx childctx(iterctx);
  3524. childctx.addGroup();
  3525. Owned<BoundRow> tempRow = declareTempRow(childctx, childctx, rowExpr);
  3526. Owned<BoundRow> rowBuilder = createRowBuilder(childctx, tempRow);
  3527. OwnedHqlExpr sourceSelector = ensureActiveRow(row->querySelector());
  3528. buildAssign(childctx, rowBuilder->querySelector(), sourceSelector);
  3529. finalizeTempRow(childctx, tempRow, rowBuilder);
  3530. return getPointer(tempRow->queryBound());
  3531. }
  3532. IReferenceSelector * HqlCppTranslator::buildDatasetIndexViaIterator(BuildCtx & ctx, IHqlExpression * expr)
  3533. {
  3534. OwnedHqlExpr dataset = normalizeAnyDatasetAliases(querySkipDatasetMeta(expr->queryChild(0)));
  3535. IHqlExpression * index = expr->queryChild(1);
  3536. IHqlExpression * childDataset = dataset;
  3537. switch (dataset->getOperator())
  3538. {
  3539. case no_hqlproject:
  3540. //optimize selectnth(project(rows, t), n) to projectrow(selectnth(rows, n), t)
  3541. if (dataset->queryChild(1)->isPure() && !expr->hasProperty(_countProject_Atom))
  3542. childDataset = dataset->queryChild(0);
  3543. break;
  3544. }
  3545. //create a temporary
  3546. //Following works because rows are created as temporaries in the class, so still in scope outside the iterate loop.
  3547. //Not a strictly correct assumption - e.g., if ever done in the main process() code.
  3548. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  3549. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  3550. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  3551. CHqlBoundExpr boundCleared;
  3552. #ifdef CREATE_DEAULT_ROW_IF_NULL
  3553. buildDefaultRow(ctx, expr, boundCleared);
  3554. #else
  3555. buildNullRow(ctx, expr, boundCleared);
  3556. row->setConditional(true);
  3557. #endif
  3558. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  3559. //Declare row for final level, iterate the appropriate number of times, and then assign and break.
  3560. BuildCtx initctx(ctx);
  3561. initctx.addGroup(); // add a group to allow a temporary to be declared later.
  3562. initctx.addAssign(rowExpr, defaultRowPtr);
  3563. HqlExprAssociation * savedMarker = ctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  3564. BuildCtx iterctx(ctx);
  3565. bool done = false;
  3566. if (childDataset->getOperator() == no_rows) //hasOutOfLineModifier(dataset->queryType()))
  3567. {
  3568. CHqlBoundExpr boundDs;
  3569. buildDataset(ctx, childDataset, boundDs, FormatNatural);
  3570. if (boundDs.count && isArrayRowset(boundDs.expr->queryType()))
  3571. {
  3572. OwnedHqlExpr castIndex = ensureExprType(index, unsignedType);
  3573. OwnedHqlExpr adjustedIndex = adjustValue(castIndex, -1);
  3574. CHqlBoundExpr boundIndex;
  3575. buildExpr(ctx, adjustedIndex, boundIndex);
  3576. OwnedHqlExpr count = getBoundCount(boundDs); // could be serialized, so can't assume bound.count is set
  3577. OwnedHqlExpr test = createValue(no_gt, makeBoolType(), LINK(count), LINK(boundIndex.expr));
  3578. iterctx.addFilter(test);
  3579. if (dataset != childDataset)
  3580. {
  3581. Owned<ITypeInfo> datasetRowType = makeRowReferenceType(boundDs);
  3582. OwnedHqlExpr selectedRow = createValue(no_index, LINK(datasetRowType), LINK(boundDs.expr), LINK(boundIndex.expr));
  3583. OwnedHqlExpr projected = createRow(no_projectrow, createTranslated(selectedRow), createComma(LINK(dataset->queryChild(1)), LINK(querySelSeq(dataset))));
  3584. Owned<IReferenceSelector> newRow = buildNewRow(iterctx, projected);
  3585. OwnedHqlExpr newPtr = getPointer(newRow->queryRootRow()->queryBound());
  3586. iterctx.addAssign(rowExpr, newPtr);
  3587. }
  3588. else
  3589. {
  3590. OwnedHqlExpr selectedRow = createValue(no_index, LINK(rowType), LINK(boundDs.expr), LINK(boundIndex.expr));
  3591. iterctx.addAssign(rowExpr, selectedRow);
  3592. }
  3593. done = true;
  3594. }
  3595. }
  3596. if (!done)
  3597. {
  3598. BoundRow * chooseCursor;
  3599. //If choosing the first element, then no need to maintain a counter...
  3600. IValue * indexValue = index->queryValue();
  3601. if (indexValue && (indexValue->getIntValue() == 1))
  3602. chooseCursor = buildDatasetIterate(iterctx, dataset, true);
  3603. else
  3604. chooseCursor = buildDatasetIterate(iterctx, expr, true);
  3605. if (chooseCursor)
  3606. {
  3607. OwnedHqlExpr source = getPointer(chooseCursor->queryBound());
  3608. //MORE: Need casts because cursor may be (probably are) constant, but temporary isn't
  3609. //should somehow fnd out by looking at the cursors.
  3610. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));
  3611. iterctx.addAssign(rowExpr, castLeftRow);
  3612. iterctx.addBreak();
  3613. }
  3614. }
  3615. ctx.removeAssociation(savedMarker);
  3616. ctx.associate(*row);
  3617. return createReferenceSelector(row);
  3618. }
  3619. IReferenceSelector * HqlCppTranslator::buildDatasetIndex(BuildCtx & ctx, IHqlExpression * expr)
  3620. {
  3621. HqlExprAssociation * match = ctx.queryAssociation(expr, AssocRow, NULL);
  3622. if (match)
  3623. return createReferenceSelector(static_cast<BoundRow *>(match));
  3624. #if 0
  3625. //Causes some queries (ncf10) to run out of memory, so disable for the moment.
  3626. OwnedHqlExpr optimized = optimizeHqlExpression(expr, getOptimizeFlags()|HOOcompoundproject);
  3627. if (optimized != expr)
  3628. return buildNewRow(ctx, optimized);
  3629. #endif
  3630. OwnedHqlExpr dataset = normalizeAnyDatasetAliases(expr->queryChild(0));
  3631. //Special cases:
  3632. //i) selecting row [1] from something that only has a single row
  3633. //ii) selecting row [n] from something that can be iterated.
  3634. //iii) row[1] from something sorted that can be iterated.
  3635. BoundRow * row = NULL;
  3636. if (isTrivialSelectN(expr))
  3637. {
  3638. BoundRow * row = NULL;
  3639. #if 0
  3640. //This could be a good idea - but again it can mess up cse since dataset never gets bound.
  3641. //Could enable if I implement cse on datasets within transforms.
  3642. // if (canIterateInline(&ctx, dataset))
  3643. // row = buildOptimizeSelectFirstRow(ctx, dataset);
  3644. #endif
  3645. if (!row)
  3646. {
  3647. CHqlBoundExpr bound;
  3648. buildDataset(ctx, dataset, bound, FormatNatural);
  3649. convertBoundDatasetToFirstRow(expr, bound);
  3650. row = bindRow(ctx, expr, bound.expr);
  3651. }
  3652. return createReferenceSelector(row);
  3653. }
  3654. else if (canIterateInline(&ctx, dataset))
  3655. {
  3656. //MORE? Following doesn't work for implicit normalize which iterates multiple levels
  3657. bool specialCase = false;
  3658. dataset.set(querySkipDatasetMeta(dataset));
  3659. switch (dataset->getOperator())
  3660. {
  3661. case no_select:
  3662. specialCase = !isMultiLevelDatasetSelector(expr, false);
  3663. break;
  3664. case no_if:
  3665. case no_inlinetable:
  3666. case no_join:
  3667. //Always creates a temporary, so don't use an iterator
  3668. specialCase = true;
  3669. break;
  3670. default:
  3671. specialCase = alwaysEvaluatesToBound(dataset);
  3672. break;
  3673. }
  3674. if (!specialCase)
  3675. return buildDatasetIndexViaIterator(ctx, expr);
  3676. }
  3677. else if (isSelectSortedTop(expr) && canIterateInline(&ctx, dataset->queryChild(0)))
  3678. {
  3679. return doBuildRowSelectTop(ctx, expr);
  3680. }
  3681. //MORE: Is this a good idea???
  3682. else if (!canProcessInline(&ctx, expr))
  3683. {
  3684. CHqlBoundExpr bound;
  3685. OwnedHqlExpr dsExpr = expr->isDatarow() ? createDatasetFromRow(LINK(expr)) : LINK(expr);
  3686. buildDataset(ctx, dsExpr, bound, FormatNatural);
  3687. convertBoundDatasetToFirstRow(expr, bound);
  3688. row = bindRow(ctx, expr, bound.expr);
  3689. }
  3690. if (!row)
  3691. {
  3692. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, dataset);
  3693. row = cursor->buildSelect(ctx, expr);
  3694. if (!row)
  3695. {
  3696. CHqlBoundExpr boundCleared;
  3697. buildDefaultRow(ctx, dataset, boundCleared);
  3698. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  3699. row = bindRow(ctx, expr, defaultRowPtr);
  3700. }
  3701. }
  3702. return createReferenceSelector(row);
  3703. }
  3704. //---------------------------------------------------------------------------
  3705. IHqlExpression * HqlCppTranslator::buildGetLocalResult(BuildCtx & ctx, IHqlExpression * expr, bool preferLinkedRows)
  3706. {
  3707. IHqlExpression * graphId = expr->queryChild(1);
  3708. IHqlExpression * resultNum = expr->queryChild(2);
  3709. Linked<ITypeInfo> exprType = queryUnqualifiedType(expr->queryType());
  3710. if (preferLinkedRows && !hasLinkCountedModifier(exprType))
  3711. exprType.setown(makeAttributeModifier(LINK(exprType), getLinkCountedAttr()));
  3712. if (expr->hasProperty(externalAtom))
  3713. {
  3714. IHqlExpression * resultInstance = queryPropertyChild(expr, externalAtom, 0);
  3715. HqlExprAssociation * matchedResults = ctx.queryMatchExpr(resultInstance);
  3716. if (!matchedResults)
  3717. {
  3718. //Very unusual - a result is required from a child query, but that child query is actually in
  3719. //the parent/grandparent. We need to evaluate in the parent instead.
  3720. CHqlBoundExpr match;
  3721. if (!buildExprInCorrectContext(ctx, expr, match, false))
  3722. throwUnexpected();
  3723. return match.getTranslatedExpr();
  3724. }
  3725. HqlExprArray args;
  3726. args.append(*LINK(matchedResults->queryExpr()));
  3727. args.append(*LINK(resultNum));
  3728. if (preferLinkedRows)
  3729. return bindFunctionCall(getChildQueryLinkedResultAtom, args, exprType);
  3730. return bindFunctionCall(getChildQueryResultAtom, args, exprType);
  3731. }
  3732. assertex(activeActivities.ordinality());
  3733. queryAddResultDependancy(activeActivities.tos(), graphId, resultNum);
  3734. SubGraphInfo * activeSubgraph = queryActiveSubGraph(ctx);
  3735. assertex(activeSubgraph && graphId == activeSubgraph->graphTag);
  3736. unique_id_t id = activeSubgraph->graphId;
  3737. EvalContext * instance = queryEvalContext(ctx);
  3738. OwnedHqlExpr retInstanceExpr;
  3739. if (instance && !insideOnCreate(ctx))
  3740. retInstanceExpr.setown(instance->createGraphLookup(id, false));
  3741. else
  3742. retInstanceExpr.setown(doCreateGraphLookup(ctx, ctx, id, "this", true));
  3743. HqlExprArray args;
  3744. args.append(*LINK(retInstanceExpr));
  3745. args.append(*LINK(resultNum));
  3746. if (preferLinkedRows)
  3747. return bindFunctionCall(getLocalLinkedResultAtom, args, exprType);
  3748. return bindFunctionCall(getLocalResultAtom, args, exprType);
  3749. }
  3750. void HqlCppTranslator::doBuildAssignGetGraphResult(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  3751. {
  3752. if (expr->hasProperty(_streaming_Atom))
  3753. throwError(HQLERR_LoopTooComplexForParallel);
  3754. bool isTargetLinkCounted = hasLinkCountedModifier(target.queryType());
  3755. if (expr->hasProperty(externalAtom))
  3756. {
  3757. OwnedHqlExpr call = buildGetLocalResult(ctx, expr, isTargetLinkCounted);
  3758. buildExprAssign(ctx, target, call);
  3759. return;
  3760. }
  3761. if (!isCurrentActiveGraph(ctx, expr->queryChild(1)))
  3762. {
  3763. CHqlBoundExpr match;
  3764. if (!buildExprInCorrectContext(ctx, expr, match, false))
  3765. throwError(HQLERR_GraphContextNotFound);
  3766. assign(ctx, target, match);
  3767. return;
  3768. }
  3769. OwnedHqlExpr call = buildGetLocalResult(ctx, expr, isTargetLinkCounted);
  3770. buildExprAssign(ctx, target, call);
  3771. }
  3772. void HqlCppTranslator::doBuildExprGetGraphResult(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  3773. {
  3774. if (!expr->hasProperty(externalAtom))
  3775. {
  3776. doBuildAliasValue(ctx, expr, tgt);
  3777. return;
  3778. if (!isCurrentActiveGraph(ctx, expr->queryChild(1)))
  3779. {
  3780. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  3781. throwError(HQLERR_GraphContextNotFound);
  3782. return;
  3783. }
  3784. }
  3785. bool useLinkCounted = recordRequiresSerialization(expr->queryRecord()) || options.tempDatasetsUseLinkedRows;
  3786. OwnedHqlExpr call = buildGetLocalResult(ctx, expr, useLinkCounted);
  3787. switch (expr->queryType()->getTypeCode())
  3788. {
  3789. case type_row:
  3790. throwUnexpected();
  3791. case type_table:
  3792. case type_groupedtable:
  3793. buildTempExpr(ctx, call, tgt);
  3794. break;
  3795. default:
  3796. buildExpr(ctx, call, tgt);
  3797. break;
  3798. }
  3799. }
  3800. ABoundActivity * HqlCppTranslator::doBuildActivityGetGraphResult(BuildCtx & ctx, IHqlExpression * expr)
  3801. {
  3802. IHqlExpression * graphId = expr->queryChild(1);
  3803. IHqlExpression * resultNum = expr->queryChild(2);
  3804. ThorActivityKind activityKind = (expr->hasProperty(_streaming_Atom) ? TAKlocalstreamread : TAKlocalresultread);
  3805. bool useImplementationClass = options.minimizeActivityClasses && (resultNum->getOperator() == no_constant);
  3806. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, activityKind, expr, "LocalResultRead");
  3807. if (useImplementationClass)
  3808. instance->setImplementationClass(newLocalResultReadArgAtom);
  3809. if (expr->hasProperty(_loop_Atom))
  3810. {
  3811. if (isCurrentActiveGraph(ctx, graphId))
  3812. instance->graphLabel.set("Begin Loop");
  3813. else
  3814. instance->graphLabel.set("Outer Loop Input");
  3815. }
  3816. buildActivityFramework(instance);
  3817. buildInstancePrefix(instance);
  3818. if (!useImplementationClass)
  3819. doBuildUnsignedFunction(instance->classctx, "querySequence", resultNum);
  3820. else
  3821. instance->addConstructorParameter(resultNum);
  3822. addGraphIdAttribute(instance, ctx, graphId);
  3823. buildInstanceSuffix(instance);
  3824. queryAddResultDependancy(*instance->queryBoundActivity(), graphId, resultNum);
  3825. return instance->getBoundActivity();
  3826. }
  3827. ABoundActivity * HqlCppTranslator::doBuildActivitySetGraphResult(BuildCtx & ctx, IHqlExpression * expr, bool isRoot)
  3828. {
  3829. IHqlExpression * dataset = expr->queryChild(0);
  3830. IHqlExpression * graphId = expr->queryChild(1);
  3831. IHqlExpression * resultNum = expr->queryChild(2);
  3832. bool isSpill = expr->hasProperty(_spill_Atom);
  3833. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  3834. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  3835. bool useImplementationClass = options.minimizeActivityClasses;
  3836. Owned<ActivityInstance> instance;
  3837. if (expr->getOperator() == no_spillgraphresult)
  3838. {
  3839. instance.setown(new ActivityInstance(*this, ctx, TAKlocalresultspill, expr, "LocalResultSpill"));
  3840. }
  3841. else
  3842. {
  3843. instance.setown(new ActivityInstance(*this, ctx, TAKlocalresultwrite, expr, "LocalResultWrite"));
  3844. }
  3845. if (useImplementationClass)
  3846. instance->setImplementationClass(newLocalResultSpillArgAtom);
  3847. if (expr->hasProperty(_loop_Atom))
  3848. instance->graphLabel.set("End Loop");
  3849. buildActivityFramework(instance, isRoot && !isSpill);
  3850. buildInstancePrefix(instance);
  3851. if (!useImplementationClass)
  3852. {
  3853. doBuildUnsignedFunction(instance->classctx, "querySequence", resultNum);
  3854. doBuildBoolFunction(instance->classctx, "usedOutsideGraph", !isSpill);
  3855. }
  3856. else
  3857. {
  3858. instance->addConstructorParameter(resultNum);
  3859. instance->addConstructorParameter(queryBoolExpr(!isSpill));
  3860. }
  3861. if (parentActivity && !insideRemoteGraph(ctx) && !isSpill)
  3862. {
  3863. const char * relationship;
  3864. if (expr->hasProperty(_loop_Atom))
  3865. relationship = "Body";
  3866. else if (insideRemoteGraph(ctx))
  3867. relationship = "Remote";
  3868. else
  3869. relationship = "Child";
  3870. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, relationship);
  3871. }
  3872. instance->addAttributeBool("_isSpill", isSpill);
  3873. if (targetRoxie())
  3874. addGraphIdAttribute(instance, ctx, graphId);
  3875. buildInstanceSuffix(instance);
  3876. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  3877. associateRemoteResult(*instance, graphId, resultNum);
  3878. return instance->getBoundActivity();
  3879. }
  3880. ABoundActivity * HqlCppTranslator::doBuildActivityReturnResult(BuildCtx & ctx, IHqlExpression * expr, bool isRoot)
  3881. {
  3882. IHqlExpression * dataset = expr->queryChild(0);
  3883. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  3884. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  3885. ThorActivityKind kind;
  3886. const char * helper;
  3887. if (dataset->isDataset())
  3888. {
  3889. kind = TAKdatasetresult;
  3890. helper = "DatasetResult";
  3891. }
  3892. else
  3893. {
  3894. kind = TAKrowresult;
  3895. helper = "RowResult";
  3896. }
  3897. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, kind, expr, helper);
  3898. buildActivityFramework(instance, isRoot);
  3899. buildInstancePrefix(instance);
  3900. if (parentActivity && !insideRemoteGraph(ctx))
  3901. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, "Child");
  3902. buildInstanceSuffix(instance);
  3903. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  3904. return instance->getBoundActivity();
  3905. }
  3906. void HqlCppTranslator::doBuildAssignLoopCounter(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  3907. {
  3908. if (!isCurrentActiveGraph(ctx, expr->queryChild(0)))
  3909. {
  3910. CHqlBoundExpr match;
  3911. if (!buildExprInCorrectContext(ctx, expr, match, false))
  3912. throwError(HQLERR_GraphContextNotFound);
  3913. assign(ctx, target, match);
  3914. return;
  3915. }
  3916. HqlExprArray args;
  3917. OwnedHqlExpr call = bindFunctionCall(getGraphLoopCounterAtom, args);
  3918. buildExprAssign(ctx, target, call);
  3919. }
  3920. //---------------------------------------------------------------------------
  3921. ABoundActivity * HqlCppTranslator::doBuildActivityGetGraphLoopResult(BuildCtx & ctx, IHqlExpression * expr)
  3922. {
  3923. IHqlExpression * graphId = expr->queryChild(1);
  3924. IHqlExpression * resultNum = expr->queryChild(2);
  3925. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKgraphloopresultread, expr, "GraphLoopResultRead");
  3926. buildActivityFramework(instance);
  3927. buildInstancePrefix(instance);
  3928. doBuildUnsignedFunction(instance->startctx, "querySequence", resultNum);
  3929. addGraphIdAttribute(instance, ctx, graphId);
  3930. buildInstanceSuffix(instance);
  3931. return instance->getBoundActivity();
  3932. }
  3933. ABoundActivity * HqlCppTranslator::doBuildActivitySetGraphLoopResult(BuildCtx & ctx, IHqlExpression * expr)
  3934. {
  3935. IHqlExpression * dataset = expr->queryChild(0);
  3936. IHqlExpression * graphId = expr->queryChild(1);
  3937. bool isSpill = expr->hasProperty(_spill_Atom);
  3938. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  3939. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  3940. bool useImplementationClass = options.minimizeActivityClasses;
  3941. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKgraphloopresultwrite, expr, "GraphLoopResultWrite");
  3942. if (useImplementationClass)
  3943. instance->setImplementationClass(newGraphLoopResultWriteArgAtom);
  3944. buildActivityFramework(instance, true);
  3945. buildInstancePrefix(instance);
  3946. if (parentActivity && !insideRemoteGraph(ctx) && !isSpill)
  3947. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, "Body");
  3948. if (targetRoxie())
  3949. addGraphIdAttribute(instance, ctx, graphId);
  3950. buildInstanceSuffix(instance);
  3951. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  3952. return instance->getBoundActivity();
  3953. }
  3954. //---------------------------------------------------------------------------
  3955. static IHqlExpression * queryResultExpr(IHqlExpression * expr)
  3956. {
  3957. loop
  3958. {
  3959. switch (expr->getOperator())
  3960. {
  3961. case no_compound:
  3962. expr = expr->queryChild(1);
  3963. break;
  3964. case no_subgraph:
  3965. expr = expr->queryChild(0);
  3966. break;
  3967. case no_returnresult:
  3968. return expr;
  3969. default:
  3970. throwUnexpectedOp(expr->getOperator());
  3971. }
  3972. }
  3973. }
  3974. ABoundActivity * HqlCppTranslator::doBuildActivityForceLocal(BuildCtx & ctx, IHqlExpression * expr)
  3975. {
  3976. IHqlExpression * child = expr->queryChild(0);
  3977. if (targetHThor() || (targetThor() && !insideChildQuery(ctx)))
  3978. {
  3979. WARNING(HQLWRN_LocalHasNoEffect);
  3980. return buildCachedActivity(ctx, child);
  3981. }
  3982. OwnedHqlExpr result = createValue(no_returnresult, makeVoidType(), LINK(child));
  3983. OwnedHqlExpr remote = resourceThorGraph(*this, result, RoxieCluster, 1, NULL);
  3984. unique_id_t localId = doBuildThorSubGraph(ctx, remote, SubGraphRemote);
  3985. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKlocalgraph, expr, "Null");
  3986. buildActivityFramework(instance);
  3987. buildInstancePrefix(instance);
  3988. instance->addAttributeInt("_subgraph", localId);
  3989. ActivityAssociation * match = static_cast<ActivityAssociation *>(ctx.queryAssociation(queryResultExpr(remote), AssocActivity, NULL));
  3990. assertex(match);
  3991. addDependency(ctx, match->activity, instance->queryBoundActivity(), childAtom);
  3992. buildInstanceSuffix(instance);
  3993. return instance->getBoundActivity();
  3994. }
  3995. void HqlCppTranslator::doBuildStmtApply(BuildCtx & ctx, IHqlExpression * expr)
  3996. {
  3997. IHqlExpression * dataset = expr->queryChild(0);
  3998. IHqlExpression * start = expr->queryProperty(beforeAtom);
  3999. IHqlExpression * end = expr->queryProperty(afterAtom);
  4000. if (start)
  4001. buildStmt(ctx, start->queryChild(0));
  4002. BuildCtx condctx(ctx);
  4003. BoundRow * cursor = buildDatasetIterate(condctx, dataset, false);
  4004. unsigned max = expr->numChildren();
  4005. for (unsigned i=1; i < max; i++)
  4006. {
  4007. IHqlExpression * cur = expr->queryChild(i);
  4008. if (!cur->isAttribute())
  4009. buildStmt(condctx, cur);
  4010. }
  4011. if (end)
  4012. buildStmt(ctx, end->queryChild(0));
  4013. }