node.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522
  1. #include "node.h"
  2. #include "source.h"
  3. #include "context.h"
  4. #include <yql/essentials/ast/yql_ast_escaping.h>
  5. #include <yql/essentials/ast/yql_expr.h>
  6. #include <yql/essentials/core/sql_types/simple_types.h>
  7. #include <yql/essentials/minikql/mkql_type_ops.h>
  8. #include <yql/essentials/parser/pg_catalog/catalog.h>
  9. #include <yql/essentials/utils/yql_panic.h>
  10. #include <library/cpp/containers/stack_vector/stack_vec.h>
  11. #include <library/cpp/charset/ci_string.h>
  12. #include <util/generic/hash_set.h>
  13. #include <util/stream/str.h>
  14. #include <util/string/cast.h>
  15. #include <util/string/escape.h>
  16. #include <util/string/subst.h>
  17. using namespace NYql;
  18. namespace NSQLTranslationV1 {
  19. TString ErrorDistinctWithoutCorrelation(const TString& column) {
  20. return TStringBuilder() << "DISTINCT columns for JOIN in SELECT should have table aliases (correlation name),"
  21. " add it if necessary to FROM section over 'AS <alias>' keyword and put it like '<alias>." << column << "'";
  22. }
  23. TString ErrorDistinctByGroupKey(const TString& column) {
  24. return TStringBuilder() << "Unable to use DISTINCT by grouping column: " << column << ". You should leave one of them.";
  25. }
  26. TTopicRef::TTopicRef(const TString& refName, const TDeferredAtom& cluster, TNodePtr keys)
  27. : RefName(refName)
  28. , Cluster(cluster)
  29. , Keys(keys)
  30. {
  31. }
  32. TColumnConstraints::TColumnConstraints(TNodePtr defaultExpr, bool nullable)
  33. : DefaultExpr(defaultExpr)
  34. , Nullable(nullable)
  35. {
  36. }
  37. TColumnSchema::TColumnSchema(TPosition pos, const TString& name, const TNodePtr& type, bool nullable,
  38. TVector<TIdentifier> families, bool serial, TNodePtr defaultExpr, ETypeOfChange typeOfChange)
  39. : Pos(pos)
  40. , Name(name)
  41. , Type(type)
  42. , Nullable(nullable)
  43. , Families(families)
  44. , Serial(serial)
  45. , DefaultExpr(defaultExpr)
  46. , TypeOfChange(typeOfChange)
  47. {
  48. }
  49. INode::INode(TPosition pos)
  50. : Pos(pos)
  51. {
  52. }
  53. INode::~INode()
  54. {
  55. }
  56. TPosition INode::GetPos() const {
  57. return Pos;
  58. }
  59. const TString& INode::GetLabel() const {
  60. return Label;
  61. }
  62. TMaybe<TPosition> INode::GetLabelPos() const {
  63. return LabelPos;
  64. }
  65. void INode::SetLabel(const TString& label, TMaybe<TPosition> pos) {
  66. Label = label;
  67. LabelPos = pos;
  68. }
  69. bool INode::IsImplicitLabel() const {
  70. return ImplicitLabel;
  71. }
  72. void INode::MarkImplicitLabel(bool isImplicitLabel) {
  73. ImplicitLabel = isImplicitLabel;
  74. }
  75. void INode::SetRefPos(TPosition pos) {
  76. RefPos = pos;
  77. }
  78. TMaybe<TPosition> INode::GetRefPos() const {
  79. return RefPos;
  80. }
  81. void INode::SetCountHint(bool isCount) {
  82. State.Set(ENodeState::CountHint, isCount);
  83. }
  84. bool INode::GetCountHint() const {
  85. return State.Test(ENodeState::CountHint);
  86. }
  87. bool INode::IsConstant() const {
  88. return HasState(ENodeState::Const);
  89. }
  90. bool INode::MaybeConstant() const {
  91. return HasState(ENodeState::MaybeConst);
  92. }
  93. bool INode::IsAggregated() const {
  94. return HasState(ENodeState::Aggregated);
  95. }
  96. bool INode::IsAggregationKey() const {
  97. return HasState(ENodeState::AggregationKey);
  98. }
  99. bool INode::IsOverWindow() const {
  100. return HasState(ENodeState::OverWindow);
  101. }
  102. bool INode::IsOverWindowDistinct() const {
  103. return HasState(ENodeState::OverWindowDistinct);
  104. }
  105. bool INode::IsNull() const {
  106. return false;
  107. }
  108. bool INode::IsLiteral() const {
  109. return false;
  110. }
  111. TString INode::GetLiteralType() const {
  112. return "";
  113. }
  114. TString INode::GetLiteralValue() const {
  115. return "";
  116. }
  117. bool INode::IsIntegerLiteral() const {
  118. return false;
  119. }
  120. INode::TPtr INode::ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const {
  121. Y_UNUSED(ctx);
  122. if (IsNull()) {
  123. return BuildLiteralNull(pos);
  124. }
  125. return new TCallNodeImpl(pos, opName, { Clone() });
  126. }
  127. bool INode::IsAsterisk() const {
  128. return false;
  129. }
  130. const TString* INode::SubqueryAlias() const {
  131. return nullptr;
  132. }
  133. TString INode::GetOpName() const {
  134. return TString();
  135. }
  136. const TString* INode::GetLiteral(const TString& type) const {
  137. Y_UNUSED(type);
  138. return nullptr;
  139. }
  140. const TString* INode::GetColumnName() const {
  141. return nullptr;
  142. }
  143. bool INode::IsPlainColumn() const {
  144. return GetColumnName() != nullptr;
  145. }
  146. bool INode::IsTableRow() const {
  147. return false;
  148. }
  149. void INode::AssumeColumn() {
  150. }
  151. const TString* INode::GetSourceName() const {
  152. return nullptr;
  153. }
  154. const TString* INode::GetAtomContent() const {
  155. return nullptr;
  156. }
  157. bool INode::IsOptionalArg() const {
  158. return false;
  159. }
  160. size_t INode::GetTupleSize() const {
  161. return 0;
  162. }
  163. INode::TPtr INode::GetTupleElement(size_t index) const {
  164. Y_UNUSED(index);
  165. return nullptr;
  166. }
  167. ITableKeys* INode::GetTableKeys() {
  168. return nullptr;
  169. }
  170. ISource* INode::GetSource() {
  171. return nullptr;
  172. }
  173. TVector<TNodePtr>* INode::ContentListPtr() {
  174. return nullptr;
  175. }
  176. bool INode::Init(TContext& ctx, ISource* src) {
  177. if (State.Test(ENodeState::Failed)) {
  178. return false;
  179. }
  180. if (!State.Test(ENodeState::Initialized)) {
  181. if (!DoInit(ctx, src)) {
  182. State.Set(ENodeState::Failed);
  183. return false;
  184. }
  185. State.Set(ENodeState::Initialized);
  186. }
  187. return true;
  188. }
  189. bool INode::InitReference(TContext& ctx) {
  190. Y_UNUSED(ctx);
  191. return true;
  192. }
  193. bool INode::DoInit(TContext& ctx, ISource* src) {
  194. Y_UNUSED(ctx);
  195. Y_UNUSED(src);
  196. return true;
  197. }
  198. TNodePtr INode::AstNode() const {
  199. return new TAstListNodeImpl(Pos);
  200. }
  201. TNodePtr INode::AstNode(TNodePtr node) const {
  202. return node;
  203. }
  204. TNodePtr INode::AstNode(const TString& str) const {
  205. return new TAstAtomNodeImpl(Pos, str, TNodeFlags::Default);
  206. }
  207. TNodePtr INode::AstNode(TAstNode* node) const {
  208. return new TAstDirectNode(node);
  209. }
  210. TNodePtr INode::Clone() const {
  211. TNodePtr clone = DoClone();
  212. if (!clone) {
  213. clone = const_cast<INode*>(this);
  214. } else {
  215. YQL_ENSURE(!State.Test(ENodeState::Initialized), "Clone should be for uninitialized or persistent node");
  216. clone->SetLabel(Label, LabelPos);
  217. clone->MarkImplicitLabel(ImplicitLabel);
  218. }
  219. return clone;
  220. }
  221. TAggregationPtr INode::GetAggregation() const {
  222. return {};
  223. }
  224. void INode::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  225. Y_UNUSED(ctx);
  226. Y_UNUSED(src);
  227. Y_UNUSED(exprs);
  228. }
  229. INode::TPtr INode::WindowSpecFunc(const TPtr& type) const {
  230. Y_UNUSED(type);
  231. return {};
  232. }
  233. bool INode::SetViewName(TContext& ctx, TPosition pos, const TString& view) {
  234. Y_UNUSED(pos);
  235. Y_UNUSED(view);
  236. ctx.Error() << "Node not support views";
  237. return false;
  238. }
  239. bool INode::SetPrimaryView(TContext& ctx, TPosition pos) {
  240. Y_UNUSED(pos);
  241. ctx.Error() << "Node not support primary views";
  242. return false;
  243. }
  244. void INode::UseAsInner() {
  245. AsInner = true;
  246. }
  247. void INode::DisableSort() {
  248. DisableSort_ = true;
  249. }
  250. bool INode::UsedSubquery() const {
  251. return false;
  252. }
  253. bool INode::IsSelect() const {
  254. return false;
  255. }
  256. bool INode::HasSelectResult() const {
  257. return false;
  258. }
  259. const TString* INode::FuncName() const {
  260. return nullptr;
  261. }
  262. const TString* INode::ModuleName() const {
  263. return nullptr;
  264. }
  265. bool INode::HasSkip() const {
  266. return false;
  267. }
  268. TColumnNode* INode::GetColumnNode() {
  269. return nullptr;
  270. }
  271. const TColumnNode* INode::GetColumnNode() const {
  272. return nullptr;
  273. }
  274. TTupleNode* INode::GetTupleNode() {
  275. return nullptr;
  276. }
  277. const TTupleNode* INode::GetTupleNode() const {
  278. return nullptr;
  279. }
  280. TCallNode* INode::GetCallNode() {
  281. return nullptr;
  282. }
  283. const TCallNode* INode::GetCallNode() const {
  284. return nullptr;
  285. }
  286. TStructNode* INode::GetStructNode() {
  287. return nullptr;
  288. }
  289. const TStructNode* INode::GetStructNode() const {
  290. return nullptr;
  291. }
  292. TAccessNode* INode::GetAccessNode() {
  293. return nullptr;
  294. }
  295. const TAccessNode* INode::GetAccessNode() const {
  296. return nullptr;
  297. }
  298. TLambdaNode* INode::GetLambdaNode() {
  299. return nullptr;
  300. }
  301. const TLambdaNode* INode::GetLambdaNode() const {
  302. return nullptr;
  303. }
  304. TUdfNode* INode::GetUdfNode() {
  305. return nullptr;
  306. }
  307. const TUdfNode* INode::GetUdfNode() const {
  308. return nullptr;
  309. }
  310. void INode::VisitTree(const TVisitFunc& func) const {
  311. TVisitNodeSet visited;
  312. VisitTree(func, visited);
  313. }
  314. void INode::VisitTree(const TVisitFunc& func, TVisitNodeSet& visited) const {
  315. if (visited.emplace(this).second && HasState(ENodeState::Initialized) && func(*this)) {
  316. DoVisitChildren(func, visited);
  317. }
  318. }
  319. TNodePtr INode::ShallowCopy() const {
  320. Y_DEBUG_ABORT_UNLESS(false, "Node is not copyable");
  321. return nullptr;
  322. }
  323. void INode::DoUpdateState() const {
  324. }
  325. void INode::PrecacheState() const {
  326. if (State.Test(ENodeState::Failed)) {
  327. return;
  328. }
  329. /// Not work right now! It's better use Init at first, because some kind of update depend on it
  330. /// \todo turn on and remove all issues
  331. //Y_DEBUG_ABORT_UNLESS(State.Test(ENodeState::Initialized));
  332. if (State.Test(ENodeState::Precached)) {
  333. return;
  334. }
  335. DoUpdateState();
  336. State.Set(ENodeState::Precached);
  337. }
  338. void INode::DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const {
  339. Y_UNUSED(func);
  340. Y_UNUSED(visited);
  341. }
  342. void INode::DoAdd(TNodePtr node) {
  343. Y_UNUSED(node);
  344. Y_DEBUG_ABORT_UNLESS(false, "Node is not expandable");
  345. }
  346. bool IProxyNode::IsNull() const {
  347. return Inner->IsNull();
  348. }
  349. bool IProxyNode::IsLiteral() const {
  350. return Inner->IsNull();
  351. }
  352. TString IProxyNode::GetLiteralType() const {
  353. return Inner->GetLiteralType();
  354. }
  355. TString IProxyNode::GetLiteralValue() const {
  356. return Inner->GetLiteralValue();
  357. }
  358. bool IProxyNode::IsIntegerLiteral() const {
  359. return Inner->IsIntegerLiteral();
  360. }
  361. INode::TPtr IProxyNode::ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const {
  362. return Inner->ApplyUnaryOp(ctx, pos, opName);
  363. }
  364. bool IProxyNode::IsAsterisk() const {
  365. return Inner->IsAsterisk();
  366. }
  367. const TString* IProxyNode::SubqueryAlias() const {
  368. return Inner->SubqueryAlias();
  369. }
  370. TString IProxyNode::GetOpName() const {
  371. return Inner->GetOpName();
  372. }
  373. const TString* IProxyNode::GetLiteral(const TString& type) const {
  374. return Inner->GetLiteral(type);
  375. }
  376. const TString* IProxyNode::GetColumnName() const {
  377. return Inner->GetColumnName();
  378. }
  379. bool IProxyNode::IsPlainColumn() const {
  380. return Inner->IsPlainColumn();
  381. }
  382. bool IProxyNode::IsTableRow() const {
  383. return Inner->IsTableRow();
  384. }
  385. void IProxyNode::AssumeColumn() {
  386. Inner->AssumeColumn();
  387. }
  388. const TString* IProxyNode::GetSourceName() const {
  389. return Inner->GetSourceName();
  390. }
  391. const TString* IProxyNode::GetAtomContent() const {
  392. return Inner->GetAtomContent();
  393. }
  394. bool IProxyNode::IsOptionalArg() const {
  395. return Inner->IsOptionalArg();
  396. }
  397. size_t IProxyNode::GetTupleSize() const {
  398. return Inner->GetTupleSize();
  399. }
  400. INode::TPtr IProxyNode::GetTupleElement(size_t index) const {
  401. return Inner->GetTupleElement(index);
  402. }
  403. ITableKeys* IProxyNode::GetTableKeys() {
  404. return Inner->GetTableKeys();
  405. }
  406. ISource* IProxyNode::GetSource() {
  407. return Inner->GetSource();
  408. }
  409. TVector<INode::TPtr>* IProxyNode::ContentListPtr() {
  410. return Inner->ContentListPtr();
  411. }
  412. TAggregationPtr IProxyNode::GetAggregation() const {
  413. return Inner->GetAggregation();
  414. }
  415. void IProxyNode::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  416. Inner->CollectPreaggregateExprs(ctx, src, exprs);
  417. }
  418. INode::TPtr IProxyNode::WindowSpecFunc(const TPtr& type) const {
  419. return Inner->WindowSpecFunc(type);
  420. }
  421. bool IProxyNode::SetViewName(TContext& ctx, TPosition pos, const TString& view) {
  422. return Inner->SetViewName(ctx, pos, view);
  423. }
  424. bool IProxyNode::SetPrimaryView(TContext& ctx, TPosition pos) {
  425. return Inner->SetPrimaryView(ctx, pos);
  426. }
  427. bool IProxyNode::UsedSubquery() const {
  428. return Inner->UsedSubquery();
  429. }
  430. bool IProxyNode::IsSelect() const {
  431. return Inner->IsSelect();
  432. }
  433. bool IProxyNode::HasSelectResult() const {
  434. return Inner->HasSelectResult();
  435. }
  436. const TString* IProxyNode::FuncName() const {
  437. return Inner->FuncName();
  438. }
  439. const TString* IProxyNode::ModuleName() const {
  440. return Inner->ModuleName();
  441. }
  442. bool IProxyNode::HasSkip() const {
  443. return Inner->HasSkip();
  444. }
  445. TColumnNode* IProxyNode::GetColumnNode() {
  446. return Inner->GetColumnNode();
  447. }
  448. const TColumnNode* IProxyNode::GetColumnNode() const {
  449. return static_cast<const INode*>(Inner.Get())->GetColumnNode();
  450. }
  451. TTupleNode* IProxyNode::GetTupleNode() {
  452. return Inner->GetTupleNode();
  453. }
  454. const TTupleNode* IProxyNode::GetTupleNode() const {
  455. return static_cast<const INode*>(Inner.Get())->GetTupleNode();
  456. }
  457. TCallNode* IProxyNode::GetCallNode() {
  458. return Inner->GetCallNode();
  459. }
  460. const TCallNode* IProxyNode::GetCallNode() const {
  461. return static_cast<const INode*>(Inner.Get())->GetCallNode();
  462. }
  463. TStructNode* IProxyNode::GetStructNode() {
  464. return Inner->GetStructNode();
  465. }
  466. const TStructNode* IProxyNode::GetStructNode() const {
  467. return static_cast<const INode*>(Inner.Get())->GetStructNode();
  468. }
  469. TAccessNode* IProxyNode::GetAccessNode() {
  470. return Inner->GetAccessNode();
  471. }
  472. const TAccessNode* IProxyNode::GetAccessNode() const {
  473. return static_cast<const INode*>(Inner.Get())->GetAccessNode();
  474. }
  475. TLambdaNode* IProxyNode::GetLambdaNode() {
  476. return Inner->GetLambdaNode();
  477. }
  478. const TLambdaNode* IProxyNode::GetLambdaNode() const {
  479. return static_cast<const INode*>(Inner.Get())->GetLambdaNode();
  480. }
  481. TUdfNode* IProxyNode::GetUdfNode() {
  482. return Inner->GetUdfNode();
  483. }
  484. const TUdfNode* IProxyNode::GetUdfNode() const {
  485. return static_cast<const INode*>(Inner.Get())->GetUdfNode();
  486. }
  487. void IProxyNode::DoUpdateState() const {
  488. static_assert(static_cast<int>(ENodeState::End) == 10, "Need to support new states here");
  489. State.Set(ENodeState::CountHint, Inner->GetCountHint());
  490. State.Set(ENodeState::Const, Inner->IsConstant());
  491. State.Set(ENodeState::MaybeConst, Inner->MaybeConstant());
  492. State.Set(ENodeState::Aggregated, Inner->IsAggregated());
  493. State.Set(ENodeState::AggregationKey, Inner->IsAggregationKey());
  494. State.Set(ENodeState::OverWindow, Inner->IsOverWindow());
  495. State.Set(ENodeState::OverWindowDistinct, Inner->IsOverWindowDistinct());
  496. }
  497. void IProxyNode::DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const {
  498. Inner->VisitTree(func, visited);
  499. }
  500. bool IProxyNode::InitReference(TContext& ctx) {
  501. return Inner->InitReference(ctx);
  502. }
  503. bool IProxyNode::DoInit(TContext& ctx, ISource* src) {
  504. return Inner->Init(ctx, src);
  505. }
  506. void IProxyNode::DoAdd(TPtr node) {
  507. Inner->Add(node);
  508. }
  509. void MergeHints(TTableHints& base, const TTableHints& overrides) {
  510. for (auto& i : overrides) {
  511. base[i.first] = i.second;
  512. }
  513. }
  514. TTableHints CloneContainer(const TTableHints& hints) {
  515. TTableHints result;
  516. for (auto& [name, nodes] : hints) {
  517. result.emplace(std::make_pair(name, CloneContainer(nodes)));
  518. }
  519. return result;
  520. }
  521. TAstAtomNode::TAstAtomNode(TPosition pos, const TString& content, ui32 flags, bool isOptionalArg)
  522. : INode(pos)
  523. , Content(content)
  524. , Flags(flags)
  525. , IsOptionalArg_(isOptionalArg)
  526. {
  527. }
  528. TAstAtomNode::~TAstAtomNode()
  529. {
  530. }
  531. void TAstAtomNode::DoUpdateState() const {
  532. State.Set(ENodeState::Const);
  533. }
  534. TAstNode* TAstAtomNode::Translate(TContext& ctx) const {
  535. return TAstNode::NewAtom(Pos, Content, *ctx.Pool, Flags);
  536. }
  537. const TString* TAstAtomNode::GetAtomContent() const {
  538. return &Content;
  539. }
  540. bool TAstAtomNode::IsOptionalArg() const {
  541. return IsOptionalArg_;
  542. }
  543. TAstDirectNode::TAstDirectNode(TAstNode* node)
  544. : INode(node->GetPosition())
  545. , Node(node)
  546. {
  547. }
  548. TAstNode* TAstDirectNode::Translate(TContext& ctx) const {
  549. Y_UNUSED(ctx);
  550. return Node;
  551. }
  552. TNodePtr BuildList(TPosition pos, TVector<TNodePtr> nodes) {
  553. return new TAstListNodeImpl(pos, std::move(nodes));
  554. }
  555. TNodePtr BuildQuote(TPosition pos, TNodePtr expr) {
  556. return BuildList(pos, {BuildAtom(pos, "quote", TNodeFlags::Default), expr});
  557. }
  558. TNodePtr BuildAtom(TPosition pos, const TString& content, ui32 flags, bool isOptionalArg) {
  559. return new TAstAtomNodeImpl(pos, content, flags, isOptionalArg);
  560. }
  561. TAstListNode::TAstListNode(TPosition pos)
  562. : INode(pos)
  563. {
  564. }
  565. TAstListNode::~TAstListNode()
  566. {
  567. }
  568. bool TAstListNode::DoInit(TContext& ctx, ISource* src) {
  569. for (auto& node: Nodes) {
  570. if (!node->Init(ctx, src)) {
  571. return false;
  572. }
  573. }
  574. return true;
  575. }
  576. TAstNode* TAstListNode::Translate(TContext& ctx) const {
  577. TSmallVec<TAstNode*> children;
  578. children.reserve(Nodes.size());
  579. auto listPos = Pos;
  580. for (auto& node: Nodes) {
  581. if (node) {
  582. auto astNode = node->Translate(ctx);
  583. if (!astNode) {
  584. return nullptr;
  585. }
  586. children.push_back(astNode);
  587. } else {
  588. ctx.Error(Pos) << "Translation error: encountered empty TNodePtr";
  589. return nullptr;
  590. }
  591. }
  592. return TAstNode::NewList(listPos, children.data(), children.size(), *ctx.Pool);
  593. }
  594. void TAstListNode::UpdateStateByListNodes(const TVector<TNodePtr>& nodes) const {
  595. bool isConst = true;
  596. struct TAttributesFlags {
  597. bool has = false;
  598. bool all = true;
  599. };
  600. std::array<ENodeState, 3> checkStates = {{ENodeState::Aggregated, ENodeState::AggregationKey, ENodeState::OverWindow}};
  601. std::map<ENodeState, TAttributesFlags> flags;
  602. for (auto& node: nodes) {
  603. const bool isNodeConst = node->IsConstant();
  604. const bool isNodeMaybeConst = node->MaybeConstant();
  605. for (auto state: checkStates) {
  606. if (node->HasState(state)) {
  607. flags[state].has = true;
  608. } else if (!isNodeConst && !isNodeMaybeConst) {
  609. flags[state].all = false;
  610. }
  611. if (!isNodeConst) {
  612. isConst = false;
  613. }
  614. }
  615. }
  616. State.Set(ENodeState::Const, isConst);
  617. for (auto& flag: flags) {
  618. State.Set(flag.first, flag.second.has && flag.second.all);
  619. }
  620. State.Set(ENodeState::MaybeConst, !isConst && AllOf(nodes, [](const auto& node) { return node->IsConstant() || node->MaybeConstant(); }));
  621. }
  622. void TAstListNode::DoUpdateState() const {
  623. UpdateStateByListNodes(Nodes);
  624. }
  625. void TAstListNode::DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const {
  626. for (auto& node : Nodes) {
  627. node->VisitTree(func, visited);
  628. }
  629. }
  630. TAstListNode::TAstListNode(const TAstListNode& node)
  631. : INode(node.Pos)
  632. , Nodes(node.Nodes)
  633. {
  634. Label = node.Label;
  635. State = node.State;
  636. }
  637. TAstListNode::TAstListNode(TPosition pos, TVector<TNodePtr>&& nodes)
  638. : INode(pos)
  639. , Nodes(std::move(nodes))
  640. {
  641. for (const auto& node: Nodes) {
  642. YQL_ENSURE(node, "Null ptr passed as list element");
  643. }
  644. }
  645. TNodePtr TAstListNode::ShallowCopy() const {
  646. return new TAstListNodeImpl(Pos, Nodes);
  647. }
  648. void TAstListNode::DoAdd(TNodePtr node) {
  649. Y_DEBUG_ABORT_UNLESS(node);
  650. Y_DEBUG_ABORT_UNLESS(node.Get() != this);
  651. Nodes.push_back(node);
  652. }
  653. TAstListNodeImpl::TAstListNodeImpl(TPosition pos)
  654. : TAstListNode(pos)
  655. {}
  656. TAstListNodeImpl::TAstListNodeImpl(TPosition pos, TVector<TNodePtr> nodes)
  657. : TAstListNode(pos)
  658. {
  659. for (const auto& node: nodes) {
  660. YQL_ENSURE(node, "Null ptr passed as list element");
  661. }
  662. Nodes.swap(nodes);
  663. }
  664. void TAstListNodeImpl::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  665. for (auto& node : Nodes) {
  666. node->CollectPreaggregateExprs(ctx, src, exprs);
  667. }
  668. }
  669. TNodePtr TAstListNodeImpl::DoClone() const {
  670. return new TAstListNodeImpl(Pos, CloneContainer(Nodes));
  671. }
  672. TCallNode::TCallNode(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  673. : TAstListNode(pos)
  674. , OpName(opName)
  675. , MinArgs(minArgs)
  676. , MaxArgs(maxArgs)
  677. , Args(args)
  678. {
  679. for (const auto& arg: Args) {
  680. YQL_ENSURE(arg, "Null ptr passed as call argument");
  681. }
  682. }
  683. TString TCallNode::GetOpName() const {
  684. return OpName;
  685. }
  686. const TString* DeriveCommonSourceName(const TVector<TNodePtr> &nodes) {
  687. const TString* name = nullptr;
  688. for (auto& node: nodes) {
  689. auto n = node->GetSourceName();
  690. if (!n) {
  691. continue;
  692. }
  693. if (name && *n != *name) {
  694. return nullptr;
  695. }
  696. name = n;
  697. }
  698. return name;
  699. }
  700. const TString* TCallNode::GetSourceName() const {
  701. return DeriveCommonSourceName(Args);
  702. }
  703. const TVector<TNodePtr>& TCallNode::GetArgs() const {
  704. return Args;
  705. }
  706. void TCallNode::DoUpdateState() const {
  707. UpdateStateByListNodes(Args);
  708. }
  709. TString TCallNode::GetCallExplain() const {
  710. auto derivedName = GetOpName();
  711. TStringBuilder sb;
  712. sb << derivedName << "()";
  713. if (derivedName != OpName) {
  714. sb << ", converted to " << OpName << "()";
  715. }
  716. return std::move(sb);
  717. }
  718. void TCallNode::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  719. for (auto& arg : Args) {
  720. arg->CollectPreaggregateExprs(ctx, src, exprs);
  721. }
  722. }
  723. bool TCallNode::ValidateArguments(TContext& ctx) const {
  724. const auto argsCount = static_cast<i32>(Args.size());
  725. if (MinArgs >= 0 && MaxArgs == MinArgs && argsCount != MinArgs) {
  726. ctx.Error(Pos) << GetCallExplain() << " requires exactly " << MinArgs << " arguments, given: " << Args.size();
  727. return false;
  728. }
  729. if (MinArgs >= 0 && argsCount < MinArgs) {
  730. ctx.Error(Pos) << GetCallExplain() << " requires at least " << MinArgs << " arguments, given: " << Args.size();
  731. return false;
  732. }
  733. if (MaxArgs >= 0 && argsCount > MaxArgs) {
  734. ctx.Error(Pos) << GetCallExplain() << " requires at most " << MaxArgs << " arguments, given: " << Args.size();
  735. return false;
  736. }
  737. return true;
  738. }
  739. bool TCallNode::DoInit(TContext& ctx, ISource* src) {
  740. if (!ValidateArguments(ctx)) {
  741. return false;
  742. }
  743. bool hasError = false;
  744. for (auto& arg: Args) {
  745. if (!arg->Init(ctx, src)) {
  746. hasError = true;
  747. continue;
  748. }
  749. }
  750. if (hasError) {
  751. return false;
  752. }
  753. Nodes.push_back(BuildAtom(Pos, OpName,
  754. OpName.cend() == std::find_if_not(OpName.cbegin(), OpName.cend(), [](char c) { return bool(std::isalnum(c)); }) ? TNodeFlags::Default : TNodeFlags::ArbitraryContent));
  755. Nodes.insert(Nodes.end(), Args.begin(), Args.end());
  756. return true;
  757. }
  758. TCallNode* TCallNode::GetCallNode() {
  759. return this;
  760. }
  761. const TCallNode* TCallNode::GetCallNode() const {
  762. return this;
  763. }
  764. TCallNodeImpl::TCallNodeImpl(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  765. : TCallNode(pos, opName, minArgs, maxArgs, args)
  766. {}
  767. TCallNodeImpl::TCallNodeImpl(TPosition pos, const TString& opName, const TVector<TNodePtr>& args)
  768. : TCallNode(pos, opName, args.size(), args.size(), args)
  769. {}
  770. TCallNode::TPtr TCallNodeImpl::DoClone() const {
  771. return new TCallNodeImpl(GetPos(), OpName, MinArgs, MaxArgs, CloneContainer(Args));
  772. }
  773. TFuncNodeImpl::TFuncNodeImpl(TPosition pos, const TString& opName)
  774. : TCallNode(pos, opName, 0, 0, {})
  775. {}
  776. TCallNode::TPtr TFuncNodeImpl::DoClone() const {
  777. return new TFuncNodeImpl(GetPos(), OpName);
  778. }
  779. const TString* TFuncNodeImpl::FuncName() const {
  780. return &OpName;
  781. }
  782. TCallNodeDepArgs::TCallNodeDepArgs(ui32 reqArgsCount, TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  783. : TCallNode(pos, opName, minArgs, maxArgs, args)
  784. , ReqArgsCount(reqArgsCount)
  785. {}
  786. TCallNodeDepArgs::TCallNodeDepArgs(ui32 reqArgsCount, TPosition pos, const TString& opName, const TVector<TNodePtr>& args)
  787. : TCallNode(pos, opName, args.size(), args.size(), args)
  788. , ReqArgsCount(reqArgsCount)
  789. {}
  790. TCallNode::TPtr TCallNodeDepArgs::DoClone() const {
  791. return new TCallNodeDepArgs(ReqArgsCount, GetPos(), OpName, MinArgs, MaxArgs, CloneContainer(Args));
  792. }
  793. bool TCallNodeDepArgs::DoInit(TContext& ctx, ISource* src) {
  794. if (!TCallNode::DoInit(ctx, src)) {
  795. return false;
  796. }
  797. for (ui32 i = 1 + ReqArgsCount; i < Nodes.size(); ++i) {
  798. Nodes[i] = Y("DependsOn", Nodes[i]);
  799. }
  800. return true;
  801. }
  802. TCallDirectRow::TPtr TCallDirectRow::DoClone() const {
  803. return new TCallDirectRow(Pos, OpName, CloneContainer(Args));
  804. }
  805. TCallDirectRow::TCallDirectRow(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  806. : TCallNode(pos, opName, minArgs, maxArgs, args)
  807. {}
  808. TCallDirectRow::TCallDirectRow(TPosition pos, const TString& opName, const TVector<TNodePtr>& args)
  809. : TCallNode(pos, opName, 0, 0, args)
  810. {}
  811. bool TCallDirectRow::DoInit(TContext& ctx, ISource* src) {
  812. if (!src || (ctx.CompactNamedExprs && src->IsFake())) {
  813. ctx.Error(Pos) << "Unable to use function: " << OpName << " without source";
  814. return false;
  815. }
  816. if (src->IsCompositeSource() || src->GetJoin() || src->HasAggregations() || src->IsFlattenByColumns() || src->IsOverWindowSource()) {
  817. ctx.Error(Pos) << "Failed to use function: " << OpName << " with aggregation, join, flatten by or window functions";
  818. return false;
  819. }
  820. if (!TCallNode::DoInit(ctx, src)) {
  821. return false;
  822. }
  823. Nodes.push_back(Y("DependsOn", "row"));
  824. return true;
  825. }
  826. void TCallDirectRow::DoUpdateState() const {
  827. State.Set(ENodeState::Const, false);
  828. }
  829. void TWinAggrEmulation::DoUpdateState() const {
  830. State.Set(ENodeState::OverWindow, true);
  831. }
  832. bool TWinAggrEmulation::DoInit(TContext& ctx, ISource* src) {
  833. if (!src) {
  834. ctx.Error(Pos) << "Unable to use window function " << OpName << " without source";
  835. return false;
  836. }
  837. if (!src->IsOverWindowSource()) {
  838. ctx.Error(Pos) << "Failed to use window function " << OpName << " without window specification";
  839. return false;
  840. }
  841. if (!src->AddFuncOverWindow(ctx, this)) {
  842. ctx.Error(Pos) << "Failed to use window function " << OpName << " without window specification or in wrong place";
  843. return false;
  844. }
  845. FuncAlias = "_yql_" + src->MakeLocalName(OpName);
  846. src->AddTmpWindowColumn(FuncAlias);
  847. if (!TCallNode::DoInit(ctx, src)) {
  848. return false;
  849. }
  850. Nodes.clear();
  851. Add("Member", "row", Q(FuncAlias));
  852. return true;
  853. }
  854. INode::TPtr TWinAggrEmulation::WindowSpecFunc(const TPtr& type) const {
  855. auto result = Y(OpName, type);
  856. for (const auto& arg: Args) {
  857. result = L(result, arg);
  858. }
  859. return Q(Y(Q(FuncAlias), result));
  860. }
  861. TWinAggrEmulation::TWinAggrEmulation(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  862. : TCallNode(pos, opName, minArgs, maxArgs, args)
  863. , FuncAlias(opName)
  864. {}
  865. TWinRowNumber::TWinRowNumber(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  866. : TWinAggrEmulation(pos, opName, minArgs, maxArgs, args)
  867. {}
  868. TWinCumeDist::TWinCumeDist(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  869. : TWinAggrEmulation(pos, opName, minArgs, maxArgs, args)
  870. {}
  871. bool TWinCumeDist::DoInit(TContext& ctx, ISource* src) {
  872. if (!ValidateArguments(ctx)) {
  873. return false;
  874. }
  875. YQL_ENSURE(Args.size() == 0);
  876. TVector<TNodePtr> optionsElements;
  877. if (ctx.AnsiCurrentRow) {
  878. optionsElements.push_back(BuildTuple(Pos, { BuildQuotedAtom(Pos, "ansi", NYql::TNodeFlags::Default) }));
  879. }
  880. Args.push_back(BuildTuple(Pos, optionsElements));
  881. MinArgs = MaxArgs = 1;
  882. if (!TWinAggrEmulation::DoInit(ctx, src)) {
  883. return false;
  884. }
  885. YQL_ENSURE(Args.size() == 1);
  886. return true;
  887. }
  888. TWinNTile::TWinNTile(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  889. : TWinAggrEmulation(pos, opName, minArgs, maxArgs, args)
  890. {
  891. FakeSource = BuildFakeSource(pos);
  892. }
  893. bool TWinNTile::DoInit(TContext& ctx, ISource* src) {
  894. if (Args.size() >= 1 && !Args[0]->Init(ctx, FakeSource.Get())) {
  895. return false;
  896. }
  897. if (!TWinAggrEmulation::DoInit(ctx, src)) {
  898. return false;
  899. }
  900. return true;
  901. }
  902. TWinLeadLag::TWinLeadLag(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  903. : TWinAggrEmulation(pos, opName, minArgs, maxArgs, args)
  904. {}
  905. bool TWinLeadLag::DoInit(TContext& ctx, ISource* src) {
  906. if (Args.size() >= 2) {
  907. if (!Args[1]->IsIntegerLiteral()) {
  908. ctx.Error(Args[1]->GetPos()) << "Expected integer literal as second parameter of " << OpName << "( ) function";
  909. return false;
  910. }
  911. }
  912. if (!TWinAggrEmulation::DoInit(ctx, src)) {
  913. return false;
  914. }
  915. if (Args.size() >= 1) {
  916. Args[0] = BuildLambda(Pos, Y("row"), Args[0]);
  917. }
  918. return true;
  919. }
  920. TWinRank::TWinRank(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args)
  921. : TWinAggrEmulation(pos, opName, minArgs, maxArgs, args)
  922. {
  923. }
  924. bool TExternalFunctionConfig::DoInit(TContext& ctx, ISource* src) {
  925. for (auto& param: Config) {
  926. auto paramName = Y(BuildQuotedAtom(Pos, param.first));
  927. if (!param.second->Init(ctx, src)) {
  928. return false;
  929. }
  930. Nodes.push_back(Q(L(paramName, param.second)));
  931. }
  932. return true;
  933. }
  934. INode::TPtr TExternalFunctionConfig::DoClone() const {
  935. TFunctionConfig cloned;
  936. for (auto& [name, node] : Config) {
  937. cloned[name] = SafeClone(node);
  938. }
  939. return new TExternalFunctionConfig(GetPos(), cloned);
  940. }
  941. bool TWinRank::DoInit(TContext& ctx, ISource* src) {
  942. if (!ValidateArguments(ctx)) {
  943. return false;
  944. }
  945. if (!src) {
  946. ctx.Error(Pos) << "Unable to use window function: " << OpName << " without source";
  947. return false;
  948. }
  949. auto winNamePtr = src->GetWindowName();
  950. if (!winNamePtr) {
  951. ctx.Error(Pos) << "Failed to use window function: " << OpName << " without window";
  952. return false;
  953. }
  954. auto winSpecPtr = src->FindWindowSpecification(ctx, *winNamePtr);
  955. if (!winSpecPtr) {
  956. return false;
  957. }
  958. const auto& orderSpec = winSpecPtr->OrderBy;
  959. if (orderSpec.empty()) {
  960. if (Args.empty()) {
  961. ctx.Warning(GetPos(), TIssuesIds::YQL_RANK_WITHOUT_ORDER_BY) <<
  962. OpName << "() is used with unordered window - all rows will be considered equal to each other";
  963. } else {
  964. ctx.Warning(GetPos(), TIssuesIds::YQL_RANK_WITHOUT_ORDER_BY) <<
  965. OpName << "(<expression>) is used with unordered window - the result is likely to be undefined";
  966. }
  967. }
  968. if (Args.empty()) {
  969. for (const auto& spec: orderSpec) {
  970. Args.push_back(spec->Clone()->OrderExpr);
  971. }
  972. if (Args.size() != 1) {
  973. Args = {BuildTuple(GetPos(), Args)};
  974. }
  975. }
  976. YQL_ENSURE(Args.size() == 1);
  977. TVector<TNodePtr> optionsElements;
  978. if (!ctx.AnsiRankForNullableKeys.Defined()) {
  979. optionsElements.push_back(BuildTuple(Pos, { BuildQuotedAtom(Pos, "warnNoAnsi", NYql::TNodeFlags::Default) }));
  980. } else if (*ctx.AnsiRankForNullableKeys) {
  981. optionsElements.push_back(BuildTuple(Pos, { BuildQuotedAtom(Pos, "ansi", NYql::TNodeFlags::Default) }));
  982. }
  983. Args.push_back(BuildTuple(Pos, optionsElements));
  984. MinArgs = MaxArgs = 2;
  985. if (!TWinAggrEmulation::DoInit(ctx, src)) {
  986. return false;
  987. }
  988. YQL_ENSURE(Args.size() == 2);
  989. Args[0] = BuildLambda(Pos, Y("row"), Args[0]);
  990. return true;
  991. }
  992. class TQuotedAtomNode: public TAstListNode {
  993. public:
  994. TQuotedAtomNode(TPosition pos, const TString& content, ui32 flags)
  995. : TAstListNode(pos)
  996. {
  997. Add("quote", BuildAtom(pos, content, flags));
  998. }
  999. protected:
  1000. TQuotedAtomNode(const TQuotedAtomNode& other)
  1001. : TAstListNode(other.Pos)
  1002. {
  1003. Nodes = CloneContainer(other.Nodes);
  1004. }
  1005. TPtr DoClone() const final {
  1006. return new TQuotedAtomNode(*this);
  1007. }
  1008. };
  1009. TNodePtr BuildQuotedAtom(TPosition pos, const TString& content, ui32 flags) {
  1010. return new TQuotedAtomNode(pos, content, flags);
  1011. }
  1012. TNodePtr ITableKeys::AddView(TNodePtr key, const TViewDescription& view) {
  1013. if (view.PrimaryFlag) {
  1014. return L(key, Q(Y(Q("primary_view"))));
  1015. } else if (!view.empty()) {
  1016. return L(key, Q(Y(Q("view"), Y("String", BuildQuotedAtom(Pos, view.ViewName)))));
  1017. } else {
  1018. return key;
  1019. }
  1020. }
  1021. TString TColumns::AddUnnamed() {
  1022. TString desiredResult = TStringBuilder() << "column" << List.size();
  1023. if (!All) {
  1024. HasUnnamed = true;
  1025. List.emplace_back();
  1026. NamedColumns.push_back(false);
  1027. }
  1028. return desiredResult;
  1029. }
  1030. bool TColumns::Add(const TString* column, bool countHint, bool isArtificial, bool isReliable) {
  1031. if (!column || *column == "*") {
  1032. if (!countHint) {
  1033. SetAll();
  1034. }
  1035. } else if (!All) {
  1036. if (column->EndsWith('*')) {
  1037. QualifiedAll = true;
  1038. }
  1039. bool inserted = false;
  1040. if (isArtificial) {
  1041. inserted = Artificial.insert(*column).second;
  1042. } else {
  1043. inserted = Real.insert(*column).second;
  1044. }
  1045. if (!isReliable) {
  1046. HasUnreliable = true;
  1047. }
  1048. if (std::find(List.begin(), List.end(), *column) == List.end()) {
  1049. List.push_back(*column);
  1050. NamedColumns.push_back(true);
  1051. }
  1052. return inserted;
  1053. }
  1054. return All;
  1055. }
  1056. void TColumns::Merge(const TColumns& columns) {
  1057. if (columns.All) {
  1058. SetAll();
  1059. } else {
  1060. YQL_ENSURE(columns.List.size() == columns.NamedColumns.size());
  1061. size_t myUnnamed = NamedColumns.size() - std::accumulate(NamedColumns.begin(), NamedColumns.end(), 0);
  1062. size_t otherUnnamed = 0;
  1063. for (size_t i = 0; i < columns.List.size(); ++i) {
  1064. auto& c = columns.List[i];
  1065. if (!columns.NamedColumns[i]) {
  1066. if (++otherUnnamed > myUnnamed) {
  1067. AddUnnamed();
  1068. ++myUnnamed;
  1069. }
  1070. continue;
  1071. }
  1072. if (columns.Real.contains(c)) {
  1073. Add(&c, false, false);
  1074. }
  1075. if (columns.Artificial.contains(c)) {
  1076. Add(&c, false, true);
  1077. }
  1078. }
  1079. HasUnreliable |= columns.HasUnreliable;
  1080. HasUnnamed |= columns.HasUnnamed;
  1081. }
  1082. }
  1083. void TColumns::SetPrefix(const TString& prefix) {
  1084. Y_DEBUG_ABORT_UNLESS(!prefix.empty());
  1085. auto addPrefixFunc = [&prefix](const TString& str) {
  1086. return prefix + "." + str;
  1087. };
  1088. TSet<TString> newReal;
  1089. TSet<TString> newArtificial;
  1090. TVector<TString> newList;
  1091. std::transform(Real.begin(), Real.end(), std::inserter(newReal, newReal.begin()), addPrefixFunc);
  1092. std::transform(Artificial.begin(), Artificial.end(), std::inserter(newArtificial, newArtificial.begin()), addPrefixFunc);
  1093. std::transform(List.begin(), List.end(), std::back_inserter(newList), addPrefixFunc);
  1094. newReal.swap(Real);
  1095. newArtificial.swap(Artificial);
  1096. newList.swap(List);
  1097. }
  1098. void TColumns::SetAll() {
  1099. All = true;
  1100. QualifiedAll = false;
  1101. Real.clear();
  1102. List.clear();
  1103. Artificial.clear();
  1104. NamedColumns.clear();
  1105. HasUnnamed = HasUnreliable = false;
  1106. }
  1107. namespace {
  1108. bool MaybeAutogenerated(const TString& name) {
  1109. TStringBuf prefix = "column";
  1110. if (!name.StartsWith(prefix)) {
  1111. return false;
  1112. }
  1113. TString suffix = name.substr(prefix.size());
  1114. return !suffix.empty() && AllOf(suffix, [](const auto c) { return std::isdigit(c); });
  1115. }
  1116. bool MatchDotSuffix(const TSet<TString>& columns, const TString& column) {
  1117. for (const auto& col: columns) {
  1118. const auto pos = col.find_first_of(".");
  1119. if (pos == TString::npos) {
  1120. continue;
  1121. }
  1122. if (column == col.substr(pos + 1)) {
  1123. return true;
  1124. }
  1125. }
  1126. return false;
  1127. }
  1128. }
  1129. bool TColumns::IsColumnPossible(TContext& ctx, const TString& name) const {
  1130. if (All || Real.contains(name) || Artificial.contains(name)) {
  1131. return true;
  1132. }
  1133. if (ctx.SimpleColumns && !name.Contains('.') && (MatchDotSuffix(Real, name) || MatchDotSuffix(Artificial, name))) {
  1134. return true;
  1135. }
  1136. if (QualifiedAll) {
  1137. if (ctx.SimpleColumns) {
  1138. return true;
  1139. }
  1140. if (HasUnnamed) {
  1141. const auto dotPos = name.find_first_of(".");
  1142. TString suffix = (dotPos == TString::npos) ? name : name.substr(dotPos + 1);
  1143. if (MaybeAutogenerated(suffix)) {
  1144. return true;
  1145. }
  1146. }
  1147. for (const auto& real: Real) {
  1148. const auto pos = real.find_first_of("*");
  1149. if (pos == TString::npos) {
  1150. continue;
  1151. }
  1152. if (name.StartsWith(real.substr(0, pos))) {
  1153. return true;
  1154. }
  1155. }
  1156. } else if (HasUnnamed && MaybeAutogenerated(name)) {
  1157. return true;
  1158. }
  1159. return false;
  1160. }
  1161. TSortSpecification::TSortSpecification(const TNodePtr& orderExpr, bool ascending)
  1162. : OrderExpr(orderExpr->Clone())
  1163. , Ascending(ascending)
  1164. , CleanOrderExpr(orderExpr->Clone())
  1165. {
  1166. }
  1167. TSortSpecificationPtr TSortSpecification::Clone() const {
  1168. return MakeIntrusive<TSortSpecification>(CleanOrderExpr, Ascending);
  1169. }
  1170. TFrameBoundPtr TFrameBound::Clone() const {
  1171. auto res = MakeIntrusive<TFrameBound>();
  1172. res->Pos = Pos;
  1173. res->Bound = SafeClone(Bound);
  1174. res->Settings = Settings;
  1175. return res;
  1176. }
  1177. TFrameSpecificationPtr TFrameSpecification::Clone() const {
  1178. YQL_ENSURE(FrameBegin);
  1179. YQL_ENSURE(FrameEnd);
  1180. auto res = MakeIntrusive<TFrameSpecification>();
  1181. res->FrameType = FrameType;
  1182. res->FrameBegin = FrameBegin->Clone();
  1183. res->FrameEnd = FrameEnd->Clone();
  1184. res->FrameExclusion = FrameExclusion;
  1185. return res;
  1186. }
  1187. TWindowSpecificationPtr TWindowSpecification::Clone() const {
  1188. YQL_ENSURE(Frame);
  1189. auto res = MakeIntrusive<TWindowSpecification>();
  1190. res->ExistingWindowName = ExistingWindowName;
  1191. res->Partitions = CloneContainer(Partitions);
  1192. res->IsCompact = IsCompact;
  1193. res->OrderBy = CloneContainer(OrderBy);
  1194. res->Session = SafeClone(Session);
  1195. res->Frame = Frame->Clone();
  1196. return res;
  1197. }
  1198. TWinSpecs CloneContainer(const TWinSpecs& specs) {
  1199. TWinSpecs newSpecs;
  1200. for (auto cur: specs) {
  1201. newSpecs.emplace(cur.first, cur.second->Clone());
  1202. }
  1203. return newSpecs;
  1204. }
  1205. TLegacyHoppingWindowSpecPtr TLegacyHoppingWindowSpec::Clone() const {
  1206. auto res = MakeIntrusive<TLegacyHoppingWindowSpec>();
  1207. res->TimeExtractor = TimeExtractor->Clone();
  1208. res->Hop = Hop->Clone();
  1209. res->Interval = Interval->Clone();
  1210. res->Delay = Delay->Clone();
  1211. res->DataWatermarks = DataWatermarks;
  1212. return res;
  1213. }
  1214. TColumnNode::TColumnNode(TPosition pos, const TString& column, const TString& source, bool maybeType)
  1215. : INode(pos)
  1216. , ColumnName(column)
  1217. , Source(source)
  1218. , MaybeType(maybeType)
  1219. {
  1220. }
  1221. TColumnNode::TColumnNode(TPosition pos, const TNodePtr& column, const TString& source)
  1222. : INode(pos)
  1223. , ColumnExpr(column)
  1224. , Source(source)
  1225. {
  1226. }
  1227. TColumnNode::~TColumnNode()
  1228. {
  1229. }
  1230. bool TColumnNode::IsAsterisk() const {
  1231. return ColumnName == "*";
  1232. }
  1233. bool TColumnNode::IsArtificial() const {
  1234. return Artificial;
  1235. }
  1236. const TString* TColumnNode::GetColumnName() const {
  1237. return UseSourceAsColumn ? &Source : (ColumnExpr ? nullptr : &ColumnName);
  1238. }
  1239. const TString* TColumnNode::GetSourceName() const {
  1240. return UseSourceAsColumn ? &Empty : &Source;
  1241. }
  1242. TColumnNode* TColumnNode::GetColumnNode() {
  1243. return this;
  1244. }
  1245. const TColumnNode* TColumnNode::GetColumnNode () const {
  1246. return this;
  1247. }
  1248. bool TColumnNode::DoInit(TContext& ctx, ISource* src) {
  1249. if (src) {
  1250. YQL_ENSURE(!State.Test(ENodeState::Initialized)); /// should be not initialized or Aggregated already invalid
  1251. if (src->ShouldUseSourceAsColumn(*GetSourceName())) {
  1252. if (!IsAsterisk() && IsReliable()) {
  1253. SetUseSourceAsColumn();
  1254. }
  1255. }
  1256. if (GetColumnName()) {
  1257. auto fullName = Source ? DotJoin(Source, *GetColumnName()) : *GetColumnName();
  1258. auto alias = src->GetGroupByColumnAlias(fullName);
  1259. if (alias) {
  1260. ResetColumn(alias, {});
  1261. }
  1262. Artificial = !Source && src->IsExprAlias(*GetColumnName());
  1263. }
  1264. if (!src->AddColumn(ctx, *this)) {
  1265. return false;
  1266. }
  1267. if (GetColumnName()) {
  1268. if (src->GetJoin() && Source) {
  1269. GroupKey = src->IsGroupByColumn(DotJoin(Source, *GetColumnName()));
  1270. } else {
  1271. GroupKey = src->IsGroupByColumn(*GetColumnName()) || src->IsAlias(EExprSeat::GroupBy, *GetColumnName());
  1272. }
  1273. }
  1274. }
  1275. if (IsAsterisk()) {
  1276. Node = AstNode("row");
  1277. } else {
  1278. TString callable;
  1279. if (MaybeType) {
  1280. callable = Reliable && !UseSource ? "SqlPlainColumnOrType" : "SqlColumnOrType";
  1281. } else {
  1282. // TODO: consider replacing Member -> SqlPlainColumn
  1283. callable = Reliable && !UseSource ? "Member" : "SqlColumn";
  1284. }
  1285. Node = Y(callable, "row", ColumnExpr ? Y("EvaluateAtom", ColumnExpr) : BuildQuotedAtom(Pos, *GetColumnName()));
  1286. if (UseSource) {
  1287. YQL_ENSURE(Source);
  1288. Node = L(Node, BuildQuotedAtom(Pos, Source));
  1289. }
  1290. }
  1291. return Node->Init(ctx, src);
  1292. }
  1293. void TColumnNode::SetUseSourceAsColumn() {
  1294. YQL_ENSURE(!State.Test(ENodeState::Initialized)); /// should be not initialized or Aggregated already invalid
  1295. YQL_ENSURE(!IsAsterisk());
  1296. UseSourceAsColumn = true;
  1297. }
  1298. void TColumnNode::ResetAsReliable() {
  1299. Reliable = true;
  1300. }
  1301. void TColumnNode::SetAsNotReliable() {
  1302. Reliable = false;
  1303. }
  1304. void TColumnNode::SetUseSource() {
  1305. UseSource = true;
  1306. }
  1307. bool TColumnNode::IsUseSourceAsColumn() const {
  1308. return UseSourceAsColumn;
  1309. }
  1310. bool TColumnNode::IsUseSource() const {
  1311. return UseSource;
  1312. }
  1313. bool TColumnNode::IsReliable() const {
  1314. return Reliable;
  1315. }
  1316. bool TColumnNode::CanBeType() const {
  1317. return MaybeType;
  1318. }
  1319. TNodePtr TColumnNode::DoClone() const {
  1320. YQL_ENSURE(!Node, "TColumnNode::Clone: Node should not be initialized");
  1321. auto copy = ColumnExpr ? new TColumnNode(Pos, ColumnExpr, Source) : new TColumnNode(Pos, ColumnName, Source, MaybeType);
  1322. copy->GroupKey = GroupKey;
  1323. copy->Artificial = Artificial;
  1324. copy->Reliable = Reliable;
  1325. copy->UseSource = UseSource;
  1326. copy->UseSourceAsColumn = UseSourceAsColumn;
  1327. return copy;
  1328. }
  1329. void TColumnNode::DoUpdateState() const {
  1330. State.Set(ENodeState::Const, false);
  1331. State.Set(ENodeState::MaybeConst, MaybeType);
  1332. State.Set(ENodeState::Aggregated, GroupKey);
  1333. State.Set(ENodeState::AggregationKey, GroupKey);
  1334. }
  1335. TAstNode* TColumnNode::Translate(TContext& ctx) const {
  1336. return Node->Translate(ctx);
  1337. }
  1338. void TColumnNode::ResetColumn(const TString& column, const TString& source) {
  1339. YQL_ENSURE(!State.Test(ENodeState::Initialized)); /// should be not initialized
  1340. Reliable = true;
  1341. UseSource = false;
  1342. UseSourceAsColumn = false;
  1343. ColumnName = column;
  1344. ColumnExpr = nullptr;
  1345. Source = source;
  1346. }
  1347. void TColumnNode::ResetColumn(const TNodePtr& column, const TString& source) {
  1348. YQL_ENSURE(!State.Test(ENodeState::Initialized)); /// should be not initialized
  1349. Reliable = true;
  1350. UseSource = false;
  1351. UseSourceAsColumn = false;
  1352. ColumnName = "";
  1353. ColumnExpr = column;
  1354. Source = source;
  1355. }
  1356. const TString TColumnNode::Empty;
  1357. TNodePtr BuildColumn(TPosition pos, const TString& column, const TString& source) {
  1358. bool maybeType = false;
  1359. return new TColumnNode(pos, column, source, maybeType);
  1360. }
  1361. TNodePtr BuildColumn(TPosition pos, const TNodePtr& column, const TString& source) {
  1362. return new TColumnNode(pos, column, source);
  1363. }
  1364. TNodePtr BuildColumn(TPosition pos, const TDeferredAtom& column, const TString& source) {
  1365. return column.GetLiteral() ? BuildColumn(pos, *column.GetLiteral(), source) : BuildColumn(pos, column.Build(), source);
  1366. }
  1367. TNodePtr BuildColumnOrType(TPosition pos, const TString& column) {
  1368. TString source = "";
  1369. bool maybeType = true;
  1370. return new TColumnNode(pos, column, source, maybeType);
  1371. }
  1372. ITableKeys::ITableKeys(TPosition pos)
  1373. : INode(pos)
  1374. {
  1375. }
  1376. const TString* ITableKeys::GetTableName() const {
  1377. return nullptr;
  1378. }
  1379. ITableKeys* ITableKeys::GetTableKeys() {
  1380. return this;
  1381. }
  1382. TAstNode* ITableKeys::Translate(TContext& ctx) const {
  1383. Y_DEBUG_ABORT_UNLESS(false);
  1384. Y_UNUSED(ctx);
  1385. return nullptr;
  1386. }
  1387. bool IAggregation::IsDistinct() const {
  1388. return !DistinctKey.empty();
  1389. }
  1390. void IAggregation::DoUpdateState() const {
  1391. State.Set(ENodeState::Aggregated, AggMode == EAggregateMode::Normal);
  1392. State.Set(ENodeState::OverWindow, AggMode == EAggregateMode::OverWindow);
  1393. State.Set(ENodeState::OverWindowDistinct, AggMode == EAggregateMode::OverWindowDistinct);
  1394. }
  1395. const TString* IAggregation::GetGenericKey() const {
  1396. return nullptr;
  1397. }
  1398. void IAggregation::Join(IAggregation*) {
  1399. YQL_ENSURE(false, "Should not be called");
  1400. }
  1401. const TString& IAggregation::GetName() const {
  1402. return Name;
  1403. }
  1404. EAggregateMode IAggregation::GetAggregationMode() const {
  1405. return AggMode;
  1406. }
  1407. void IAggregation::MarkKeyColumnAsGenerated() {
  1408. IsGeneratedKeyColumn = true;
  1409. }
  1410. IAggregation::IAggregation(TPosition pos, const TString& name, const TString& func, EAggregateMode aggMode)
  1411. : INode(pos), Name(name), Func(func), AggMode(aggMode)
  1412. {}
  1413. TAstNode* IAggregation::Translate(TContext& ctx) const {
  1414. Y_DEBUG_ABORT_UNLESS(false);
  1415. Y_UNUSED(ctx);
  1416. return nullptr;
  1417. }
  1418. std::pair<TNodePtr, bool> IAggregation::AggregationTraits(const TNodePtr& type, bool overState, bool many, bool allowAggApply, TContext& ctx) const {
  1419. const bool distinct = AggMode == EAggregateMode::Distinct;
  1420. const auto listType = distinct ? Y("ListType", Y("StructMemberType", Y("ListItemType", type), BuildQuotedAtom(Pos, DistinctKey))) : type;
  1421. auto apply = GetApply(listType, many, allowAggApply, ctx);
  1422. if (!apply) {
  1423. return { nullptr, false };
  1424. }
  1425. auto wrapped = WrapIfOverState(apply, overState, many, ctx);
  1426. if (!wrapped) {
  1427. return { nullptr, false };
  1428. }
  1429. return { distinct ?
  1430. Q(Y(Q(Name), wrapped, BuildQuotedAtom(Pos, DistinctKey))) :
  1431. Q(Y(Q(Name), wrapped)), true };
  1432. }
  1433. TNodePtr IAggregation::WrapIfOverState(const TNodePtr& input, bool overState, bool many, TContext& ctx) const {
  1434. if (!overState) {
  1435. return input;
  1436. }
  1437. auto extractor = GetExtractor(many, ctx);
  1438. if (!extractor) {
  1439. return nullptr;
  1440. }
  1441. return Y(ToString("AggOverState"), extractor, BuildLambda(Pos, Y(), input));
  1442. }
  1443. void IAggregation::AddFactoryArguments(TNodePtr& apply) const {
  1444. Y_UNUSED(apply);
  1445. }
  1446. std::vector<ui32> IAggregation::GetFactoryColumnIndices() const {
  1447. return {0u};
  1448. }
  1449. TNodePtr IAggregation::WindowTraits(const TNodePtr& type, TContext& ctx) const {
  1450. YQL_ENSURE(AggMode == EAggregateMode::OverWindow || AggMode == EAggregateMode::OverWindowDistinct, "Windows traits is unavailable");
  1451. const bool distinct = AggMode == EAggregateMode::OverWindowDistinct;
  1452. const auto listType = distinct ? Y("ListType", Y("StructMemberType", Y("ListItemType", type), BuildQuotedAtom(Pos, DistinctKey))) : type;
  1453. auto traits = Y(Q(Name), GetApply(listType, false, false, ctx));
  1454. if (AggMode == EAggregateMode::OverWindowDistinct) {
  1455. traits->Add(BuildQuotedAtom(Pos, DistinctKey));
  1456. }
  1457. return Q(traits);
  1458. }
  1459. namespace {
  1460. bool UnescapeQuoted(const TString& str, TPosition& pos, char quoteChar, TString& result, TString& error, bool utf8Aware) {
  1461. result = error = {};
  1462. size_t readBytes = 0;
  1463. TStringBuf atom(str);
  1464. TStringOutput sout(result);
  1465. atom.Skip(1);
  1466. result.reserve(str.size());
  1467. auto unescapeResult = UnescapeArbitraryAtom(atom, quoteChar, &sout, &readBytes);
  1468. if (unescapeResult != EUnescapeResult::OK) {
  1469. TTextWalker walker(pos, utf8Aware);
  1470. walker.Advance(atom.Trunc(readBytes));
  1471. error = UnescapeResultToString(unescapeResult);
  1472. return false;
  1473. }
  1474. return true;
  1475. }
  1476. TString UnescapeAnsiQuoted(const TString& str) {
  1477. YQL_ENSURE(str.length() >= 2);
  1478. YQL_ENSURE(str[0] == str[str.length() - 1]);
  1479. YQL_ENSURE(str[0] == '\'' || str[0] == '"');
  1480. TString quote(1, str[0]);
  1481. TString replace(2, str[0]);
  1482. TString result = str.substr(1, str.length() - 2);
  1483. SubstGlobal(result, replace, quote);
  1484. return result;
  1485. }
  1486. enum class EStringContentMode : int {
  1487. Default = 0,
  1488. AnsiIdent,
  1489. TypedStringLiteral,
  1490. };
  1491. TMaybe<TStringContent>
  1492. StringContentInternal(TContext& ctx, TPosition pos, const TString& input, EStringContentMode mode) {
  1493. TStringContent result;
  1494. if (mode == EStringContentMode::AnsiIdent) {
  1495. if (!(input.size() >= 2 && input.StartsWith('"') && input.EndsWith('"'))) {
  1496. ctx.Error(pos) << "Expected double quoted identifier, got string literal";
  1497. return {};
  1498. }
  1499. result.Flags = NYql::TNodeFlags::ArbitraryContent;
  1500. result.Content = UnescapeAnsiQuoted(input);
  1501. return result;
  1502. }
  1503. TString str = input;
  1504. if (mode == EStringContentMode::TypedStringLiteral) {
  1505. auto lower = to_lower(str);
  1506. if (lower.EndsWith("y")) {
  1507. str = str.substr(0, str.size() - 1);
  1508. result.Type = NKikimr::NUdf::EDataSlot::Yson;
  1509. } else if (lower.EndsWith("j")) {
  1510. str = str.substr(0, str.size() - 1);
  1511. result.Type = NKikimr::NUdf::EDataSlot::Json;
  1512. } else if (lower.EndsWith("p")) {
  1513. str = str.substr(0, str.size() - 1);
  1514. result.PgType = "PgText";
  1515. } else if (lower.EndsWith("pt")) {
  1516. str = str.substr(0, str.size() - 2);
  1517. result.PgType = "PgText";
  1518. } else if (lower.EndsWith("pb")) {
  1519. str = str.substr(0, str.size() - 2);
  1520. result.PgType = "PgBytea";
  1521. } else if (lower.EndsWith("pv")) {
  1522. str = str.substr(0, str.size() - 2);
  1523. result.PgType = "PgVarchar";
  1524. } else if (lower.EndsWith("s")) {
  1525. str = str.substr(0, str.size() - 1);
  1526. result.Type = NKikimr::NUdf::EDataSlot::String;
  1527. } else if (lower.EndsWith("u")) {
  1528. str = str.substr(0, str.size() - 1);
  1529. result.Type = NKikimr::NUdf::EDataSlot::Utf8;
  1530. } else {
  1531. if (ctx.Scoped->WarnUntypedStringLiterals) {
  1532. ctx.Warning(pos, TIssuesIds::YQL_UNTYPED_STRING_LITERALS)
  1533. << "Please add suffix u for Utf8 strings or s for arbitrary binary strings";
  1534. }
  1535. if (ctx.Scoped->UnicodeLiterals) {
  1536. result.Type = NKikimr::NUdf::EDataSlot::Utf8;
  1537. }
  1538. }
  1539. }
  1540. if (mode == EStringContentMode::Default && (result.Type != NKikimr::NUdf::EDataSlot::String || result.PgType)) {
  1541. ctx.Error(pos) << "Type suffix is not allowed here";
  1542. return {};
  1543. }
  1544. bool doubleQuoted = (str.StartsWith('"') && str.EndsWith('"'));
  1545. bool singleQuoted = !doubleQuoted && (str.StartsWith('\'') && str.EndsWith('\''));
  1546. if (str.size() >= 2 && (doubleQuoted || singleQuoted)) {
  1547. result.Flags = NYql::TNodeFlags::ArbitraryContent;
  1548. if (ctx.Settings.AnsiLexer) {
  1549. YQL_ENSURE(singleQuoted);
  1550. result.Content = UnescapeAnsiQuoted(str);
  1551. } else {
  1552. TString error;
  1553. if (!UnescapeQuoted(str, pos, str[0], result.Content, error, ctx.Settings.Antlr4Parser)) {
  1554. ctx.Error(pos) << "Failed to parse string literal: " << error;
  1555. return {};
  1556. }
  1557. }
  1558. } else if (str.size() >= 4 && str.StartsWith("@@") && str.EndsWith("@@")) {
  1559. result.Flags = TNodeFlags::MultilineContent;
  1560. TString s = str.substr(2, str.length() - 4);
  1561. SubstGlobal(s, "@@@@", "@@");
  1562. result.Content.swap(s);
  1563. } else {
  1564. ctx.Error(pos) << "Invalid string literal: " << EscapeC(str);
  1565. return {};
  1566. }
  1567. if (!result.PgType.Defined() && !NKikimr::NMiniKQL::IsValidStringValue(result.Type, result.Content)) {
  1568. ctx.Error() << "Invalid value " << result.Content.Quote() << " for type " << result.Type;
  1569. return {};
  1570. }
  1571. return result;
  1572. }
  1573. } // namespace
  1574. TMaybe<TStringContent> StringContent(TContext& ctx, TPosition pos, const TString& input) {
  1575. if (ctx.AnsiQuotedIdentifiers && input.StartsWith('"')) {
  1576. ctx.Error() << "Expected string literal, got quoted identifier";
  1577. return {};
  1578. }
  1579. return StringContentInternal(ctx, pos, input, EStringContentMode::Default);
  1580. }
  1581. TMaybe<TStringContent> StringContentOrIdContent(TContext& ctx, TPosition pos, const TString& input) {
  1582. return StringContentInternal(ctx, pos, input,
  1583. (ctx.AnsiQuotedIdentifiers && input.StartsWith('"'))? EStringContentMode::AnsiIdent : EStringContentMode::Default);
  1584. }
  1585. TTtlSettings::TTierSettings::TTierSettings(const TNodePtr& evictionDelay, const std::optional<TIdentifier>& storageName)
  1586. : EvictionDelay(evictionDelay)
  1587. , StorageName(storageName) {
  1588. }
  1589. TTtlSettings::TTtlSettings(const TIdentifier& columnName, const std::vector<TTierSettings>& tiers, const TMaybe<EUnit>& columnUnit)
  1590. : ColumnName(columnName)
  1591. , Tiers(tiers)
  1592. , ColumnUnit(columnUnit)
  1593. {
  1594. }
  1595. TString IdContent(TContext& ctx, const TString& s) {
  1596. YQL_ENSURE(!s.empty(), "Empty identifier not expected");
  1597. if (!s.StartsWith('`')) {
  1598. return s;
  1599. }
  1600. auto endSym = '`';
  1601. if (s.size() < 2 || !s.EndsWith(endSym)) {
  1602. ctx.Error() << "The identifier that starts with: '" << s[0] << "' should ends with: '" << endSym << "'";
  1603. return {};
  1604. }
  1605. size_t skipSymbols = 1;
  1606. TStringBuf atom(s.data() + skipSymbols, s.size() - 2 * skipSymbols + 1);
  1607. TString unescapedStr;
  1608. TStringOutput sout(unescapedStr);
  1609. unescapedStr.reserve(s.size());
  1610. size_t readBytes = 0;
  1611. TPosition pos = ctx.Pos();
  1612. pos.Column += skipSymbols - 1;
  1613. auto unescapeResult = UnescapeArbitraryAtom(atom, endSym, &sout, &readBytes);
  1614. if (unescapeResult != EUnescapeResult::OK) {
  1615. TTextWalker walker(pos, ctx.Settings.Antlr4Parser);
  1616. walker.Advance(atom.Trunc(readBytes));
  1617. ctx.Error(pos) << "Cannot parse broken identifier: " << UnescapeResultToString(unescapeResult);
  1618. return {};
  1619. }
  1620. if (readBytes != atom.size()) {
  1621. ctx.Error() << "The identifier not parsed completely";
  1622. return {};
  1623. }
  1624. return unescapedStr;
  1625. }
  1626. TString IdContentFromString(TContext& ctx, const TString& str) {
  1627. if (!ctx.AnsiQuotedIdentifiers) {
  1628. ctx.Error() << "String literal can not be used here";
  1629. return {};
  1630. }
  1631. auto parsed = StringContentInternal(ctx, ctx.Pos(), str, EStringContentMode::AnsiIdent);
  1632. if (!parsed) {
  1633. return {};
  1634. }
  1635. return parsed->Content;
  1636. }
  1637. namespace {
  1638. class TInvalidLiteralNode final: public INode {
  1639. public:
  1640. TInvalidLiteralNode(TPosition pos)
  1641. : INode(pos)
  1642. {
  1643. }
  1644. bool DoInit(TContext& ctx, ISource* source) override {
  1645. Y_UNUSED(ctx);
  1646. Y_UNUSED(source);
  1647. return false;
  1648. }
  1649. TAstNode* Translate(TContext& ctx) const override {
  1650. Y_UNUSED(ctx);
  1651. return nullptr;
  1652. }
  1653. TPtr DoClone() const override {
  1654. return new TInvalidLiteralNode(GetPos());
  1655. }
  1656. };
  1657. }
  1658. TLiteralNode::TLiteralNode(TPosition pos, bool isNull)
  1659. : TAstListNode(pos)
  1660. , Null(isNull)
  1661. , Void(!isNull)
  1662. {
  1663. Add(isNull ? "Null" : "Void");
  1664. }
  1665. TLiteralNode::TLiteralNode(TPosition pos, const TString& type, const TString& value)
  1666. : TAstListNode(pos)
  1667. , Null(false)
  1668. , Void(false)
  1669. , Type(type)
  1670. , Value(value)
  1671. {
  1672. if (Type.StartsWith("Pg")) {
  1673. Add("PgConst", BuildQuotedAtom(Pos, Value), Y("PgType", Q(to_lower(Type.substr(2)))));
  1674. } else {
  1675. Add(Type, BuildQuotedAtom(Pos, Value));
  1676. }
  1677. }
  1678. TLiteralNode::TLiteralNode(TPosition pos, const TString& value, ui32 nodeFlags)
  1679. : TAstListNode(pos)
  1680. , Null(false)
  1681. , Void(false)
  1682. , Type("String")
  1683. , Value(value)
  1684. {
  1685. Add(Type, BuildQuotedAtom(pos, Value, nodeFlags));
  1686. }
  1687. TLiteralNode::TLiteralNode(TPosition pos, const TString& value, ui32 nodeFlags, const TString& type)
  1688. : TAstListNode(pos)
  1689. , Null(false)
  1690. , Void(false)
  1691. , Type(type)
  1692. , Value(value)
  1693. {
  1694. if (Type.StartsWith("Pg")) {
  1695. Add("PgConst", BuildQuotedAtom(Pos, Value, nodeFlags), Y("PgType", Q(to_lower(Type.substr(2)))));
  1696. } else {
  1697. Add(Type, BuildQuotedAtom(pos, Value, nodeFlags));
  1698. }
  1699. }
  1700. bool TLiteralNode::IsNull() const {
  1701. return Null;
  1702. }
  1703. const TString* TLiteralNode::GetLiteral(const TString& type) const {
  1704. return type == Type ? &Value : nullptr;
  1705. }
  1706. bool TLiteralNode::IsLiteral() const {
  1707. return true;
  1708. }
  1709. TString TLiteralNode::GetLiteralType() const {
  1710. return Type;
  1711. }
  1712. TString TLiteralNode::GetLiteralValue() const {
  1713. return Value;
  1714. }
  1715. void TLiteralNode::DoUpdateState() const {
  1716. State.Set(ENodeState::Const);
  1717. }
  1718. TNodePtr TLiteralNode::DoClone() const {
  1719. auto res = (Null || Void) ? MakeIntrusive<TLiteralNode>(Pos, Null) : MakeIntrusive<TLiteralNode>(Pos, Type, Value);
  1720. res->Nodes = Nodes;
  1721. return res;
  1722. }
  1723. template<typename T>
  1724. TLiteralNumberNode<T>::TLiteralNumberNode(TPosition pos, const TString& type, const TString& value, bool implicitType)
  1725. : TLiteralNode(pos, type, value)
  1726. , ImplicitType(implicitType)
  1727. {}
  1728. template<typename T>
  1729. TNodePtr TLiteralNumberNode<T>::DoClone() const {
  1730. return new TLiteralNumberNode<T>(Pos, Type, Value, ImplicitType);
  1731. }
  1732. template<typename T>
  1733. bool TLiteralNumberNode<T>::DoInit(TContext& ctx, ISource* src) {
  1734. Y_UNUSED(src);
  1735. T val;
  1736. if (!TryFromString(Value, val)) {
  1737. ctx.Error(Pos) << "Failed to parse " << Value << " as integer literal of " << Type << " type: value out of range for " << Type;
  1738. return false;
  1739. }
  1740. return true;
  1741. }
  1742. template<typename T>
  1743. bool TLiteralNumberNode<T>::IsIntegerLiteral() const {
  1744. return std::numeric_limits<T>::is_integer;
  1745. }
  1746. template<typename T>
  1747. TNodePtr TLiteralNumberNode<T>::ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const {
  1748. YQL_ENSURE(!Value.empty());
  1749. if (opName == "Minus" && IsIntegerLiteral() && Value[0] != '-') {
  1750. if (ImplicitType) {
  1751. ui64 val = FromString<ui64>(Value);
  1752. TString negated = "-" + Value;
  1753. if (val <= ui64(std::numeric_limits<i32>::max()) + 1) {
  1754. // negated value fits in Int32
  1755. i32 v;
  1756. YQL_ENSURE(TryFromString(negated, v));
  1757. return new TLiteralNumberNode<i32>(pos, Type.StartsWith("Pg") ? "PgInt4" : "Int32", negated);
  1758. }
  1759. if (val <= ui64(std::numeric_limits<i64>::max()) + 1) {
  1760. // negated value fits in Int64
  1761. i64 v;
  1762. YQL_ENSURE(TryFromString(negated, v));
  1763. return new TLiteralNumberNode<i64>(pos, Type.StartsWith("Pg") ? "PgInt8" : "Int64", negated);
  1764. }
  1765. ctx.Error(pos) << "Failed to parse negative integer: " << negated << ", number limit overflow";
  1766. return {};
  1767. }
  1768. if (std::numeric_limits<T>::is_signed) {
  1769. return new TLiteralNumberNode<T>(pos, Type, "-" + Value);
  1770. }
  1771. }
  1772. return INode::ApplyUnaryOp(ctx, pos, opName);
  1773. }
  1774. template class TLiteralNumberNode<i32>;
  1775. template class TLiteralNumberNode<i64>;
  1776. template class TLiteralNumberNode<ui32>;
  1777. template class TLiteralNumberNode<ui64>;
  1778. template class TLiteralNumberNode<float>;
  1779. template class TLiteralNumberNode<double>;
  1780. template class TLiteralNumberNode<ui8>;
  1781. template class TLiteralNumberNode<i8>;
  1782. template class TLiteralNumberNode<ui16>;
  1783. template class TLiteralNumberNode<i16>;
  1784. TNodePtr BuildLiteralNull(TPosition pos) {
  1785. return new TLiteralNode(pos, true);
  1786. }
  1787. TNodePtr BuildLiteralVoid(TPosition pos) {
  1788. return new TLiteralNode(pos, false);
  1789. }
  1790. TNodePtr BuildLiteralSmartString(TContext& ctx, const TString& value) {
  1791. auto unescaped = StringContent(ctx, ctx.Pos(), value);
  1792. if (!unescaped) {
  1793. return new TInvalidLiteralNode(ctx.Pos());
  1794. }
  1795. YQL_ENSURE(unescaped->Type == NKikimr::NUdf::EDataSlot::String);
  1796. return new TLiteralNode(ctx.Pos(), unescaped->Content, unescaped->Flags, "String");
  1797. }
  1798. TMaybe<TExprOrIdent> BuildLiteralTypedSmartStringOrId(TContext& ctx, const TString& value) {
  1799. TExprOrIdent result;
  1800. if (ctx.AnsiQuotedIdentifiers && value.StartsWith('"')) {
  1801. auto unescaped = StringContentInternal(ctx, ctx.Pos(), value, EStringContentMode::AnsiIdent);
  1802. if (!unescaped) {
  1803. return {};
  1804. }
  1805. result.Ident = unescaped->Content;
  1806. return result;
  1807. }
  1808. auto unescaped = StringContentInternal(ctx, ctx.Pos(), value, EStringContentMode::TypedStringLiteral);
  1809. if (!unescaped) {
  1810. return {};
  1811. }
  1812. TString type = unescaped->PgType ? *unescaped->PgType : ToString(unescaped->Type);
  1813. result.Expr = new TLiteralNode(ctx.Pos(), unescaped->Content, unescaped->Flags, type);
  1814. return result;
  1815. }
  1816. TNodePtr BuildLiteralRawString(TPosition pos, const TString& value, bool isUtf8) {
  1817. return new TLiteralNode(pos, isUtf8 ? "Utf8" : "String", value);
  1818. }
  1819. TNodePtr BuildLiteralBool(TPosition pos, bool value) {
  1820. return new TLiteralNode(pos, "Bool", value ? "true" : "false");
  1821. }
  1822. TAsteriskNode::TAsteriskNode(TPosition pos)
  1823. : INode(pos)
  1824. {}
  1825. bool TAsteriskNode::IsAsterisk() const {
  1826. return true;
  1827. };
  1828. TNodePtr TAsteriskNode::DoClone() const {
  1829. return new TAsteriskNode(Pos);
  1830. }
  1831. TAstNode* TAsteriskNode::Translate(TContext& ctx) const {
  1832. ctx.Error(Pos) << "* is not allowed here";
  1833. return nullptr;
  1834. }
  1835. TNodePtr BuildEmptyAction(TPosition pos) {
  1836. TNodePtr params = new TAstListNodeImpl(pos);
  1837. TNodePtr arg = new TAstAtomNodeImpl(pos, "x", TNodeFlags::Default);
  1838. params->Add(arg);
  1839. return BuildLambda(pos, params, arg);
  1840. }
  1841. TDeferredAtom::TDeferredAtom()
  1842. {}
  1843. TDeferredAtom::TDeferredAtom(TPosition pos, const TString& str)
  1844. {
  1845. Node = BuildQuotedAtom(pos, str);
  1846. Explicit = str;
  1847. Repr = str;
  1848. }
  1849. TDeferredAtom::TDeferredAtom(TNodePtr node, TContext& ctx)
  1850. {
  1851. Node = node;
  1852. Repr = ctx.MakeName("DeferredAtom");
  1853. }
  1854. const TString* TDeferredAtom::GetLiteral() const {
  1855. return Explicit.Get();
  1856. }
  1857. bool TDeferredAtom::GetLiteral(TString& value, TContext& ctx) const {
  1858. if (Explicit) {
  1859. value = *Explicit;
  1860. return true;
  1861. }
  1862. ctx.Error(Node ? Node->GetPos() : ctx.Pos()) << "Expected literal value";
  1863. return false;
  1864. }
  1865. TNodePtr TDeferredAtom::Build() const {
  1866. return Node;
  1867. }
  1868. TString TDeferredAtom::GetRepr() const {
  1869. return Repr;
  1870. }
  1871. bool TDeferredAtom::Empty() const {
  1872. return !Node || Repr.empty();
  1873. }
  1874. bool TDeferredAtom::HasNode() const {
  1875. return !!Node;
  1876. }
  1877. TTupleNode::TTupleNode(TPosition pos, const TVector<TNodePtr>& exprs)
  1878. : TAstListNode(pos)
  1879. , Exprs(exprs)
  1880. {}
  1881. bool TTupleNode::IsEmpty() const {
  1882. return Exprs.empty();
  1883. }
  1884. const TVector<TNodePtr>& TTupleNode::Elements() const {
  1885. return Exprs;
  1886. }
  1887. TTupleNode* TTupleNode::GetTupleNode() {
  1888. return this;
  1889. }
  1890. const TTupleNode* TTupleNode::GetTupleNode() const {
  1891. return this;
  1892. }
  1893. bool TTupleNode::DoInit(TContext& ctx, ISource* src) {
  1894. auto node(Y());
  1895. for (auto& expr: Exprs) {
  1896. if (expr->GetLabel()) {
  1897. ctx.Error(expr->GetPos()) << "Tuple does not allow named members";
  1898. return false;
  1899. }
  1900. node = L(node, expr);
  1901. }
  1902. Add("quote", node);
  1903. return TAstListNode::DoInit(ctx, src);
  1904. }
  1905. size_t TTupleNode::GetTupleSize() const {
  1906. return Exprs.size();
  1907. }
  1908. TNodePtr TTupleNode::GetTupleElement(size_t index) const {
  1909. return Exprs[index];
  1910. }
  1911. TNodePtr TTupleNode::DoClone() const {
  1912. return new TTupleNode(Pos, CloneContainer(Exprs));
  1913. }
  1914. void TTupleNode::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  1915. for (auto& expr : Exprs) {
  1916. expr->CollectPreaggregateExprs(ctx, src, exprs);
  1917. }
  1918. }
  1919. const TString* TTupleNode::GetSourceName() const {
  1920. return DeriveCommonSourceName(Exprs);
  1921. }
  1922. TNodePtr BuildTuple(TPosition pos, const TVector<TNodePtr>& exprs) {
  1923. return new TTupleNode(pos, exprs);
  1924. }
  1925. TStructNode::TStructNode(TPosition pos, const TVector<TNodePtr>& exprs, const TVector<TNodePtr>& labels, bool ordered)
  1926. : TAstListNode(pos)
  1927. , Exprs(exprs)
  1928. , Labels(labels)
  1929. , Ordered(ordered)
  1930. {
  1931. YQL_ENSURE(Labels.empty() || Labels.size() == Exprs.size());
  1932. }
  1933. bool TStructNode::DoInit(TContext& ctx, ISource* src) {
  1934. Nodes.push_back(BuildAtom(Pos, (Ordered || Exprs.size() < 2) ? "AsStruct" : "AsStructUnordered", TNodeFlags::Default));
  1935. size_t i = 0;
  1936. for (const auto& expr : Exprs) {
  1937. TNodePtr label;
  1938. if (Labels.empty()) {
  1939. if (!expr->GetLabel()) {
  1940. ctx.Error(expr->GetPos()) << "Structure does not allow anonymous members";
  1941. return false;
  1942. }
  1943. label = BuildQuotedAtom(expr->GetPos(), expr->GetLabel());
  1944. } else {
  1945. label = Labels[i++];
  1946. }
  1947. Nodes.push_back(Q(Y(label, expr)));
  1948. }
  1949. return TAstListNode::DoInit(ctx, src);
  1950. }
  1951. TNodePtr TStructNode::DoClone() const {
  1952. return new TStructNode(Pos, CloneContainer(Exprs), CloneContainer(Labels), Ordered);
  1953. }
  1954. TStructNode* TStructNode::GetStructNode() {
  1955. return this;
  1956. }
  1957. const TStructNode* TStructNode::GetStructNode() const {
  1958. return this;
  1959. }
  1960. void TStructNode::CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) {
  1961. for (auto& expr : Exprs) {
  1962. expr->CollectPreaggregateExprs(ctx, src, exprs);
  1963. }
  1964. }
  1965. const TString* TStructNode::GetSourceName() const {
  1966. return DeriveCommonSourceName(Exprs);
  1967. }
  1968. TNodePtr BuildStructure(TPosition pos, const TVector<TNodePtr>& exprs) {
  1969. bool ordered = false;
  1970. return new TStructNode(pos, exprs, {}, ordered);
  1971. }
  1972. TNodePtr BuildStructure(TPosition pos, const TVector<TNodePtr>& exprsUnlabeled, const TVector<TNodePtr>& labels) {
  1973. bool ordered = false;
  1974. return new TStructNode(pos, exprsUnlabeled, labels, ordered);
  1975. }
  1976. TNodePtr BuildOrderedStructure(TPosition pos, const TVector<TNodePtr>& exprsUnlabeled, const TVector<TNodePtr>& labels) {
  1977. bool ordered = true;
  1978. return new TStructNode(pos, exprsUnlabeled, labels, ordered);
  1979. }
  1980. TListOfNamedNodes::TListOfNamedNodes(TPosition pos, TVector<TNodePtr>&& exprs)
  1981. : INode(pos)
  1982. , Exprs(std::move(exprs))
  1983. {}
  1984. TVector<TNodePtr>* TListOfNamedNodes::ContentListPtr() {
  1985. return &Exprs;
  1986. }
  1987. TAstNode* TListOfNamedNodes::Translate(TContext& ctx) const {
  1988. YQL_ENSURE(!"Unexpected usage");
  1989. Y_UNUSED(ctx);
  1990. return nullptr;
  1991. }
  1992. TNodePtr TListOfNamedNodes::DoClone() const {
  1993. return new TListOfNamedNodes(GetPos(), CloneContainer(Exprs));
  1994. }
  1995. void TListOfNamedNodes::DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const {
  1996. for (auto& expr : Exprs) {
  1997. expr->VisitTree(func, visited);
  1998. }
  1999. }
  2000. TNodePtr BuildListOfNamedNodes(TPosition pos, TVector<TNodePtr>&& exprs) {
  2001. return new TListOfNamedNodes(pos, std::move(exprs));
  2002. }
  2003. TArgPlaceholderNode::TArgPlaceholderNode(TPosition pos, const TString &name) :
  2004. INode(pos),
  2005. Name(name)
  2006. {
  2007. }
  2008. bool TArgPlaceholderNode::DoInit(TContext& ctx, ISource* src) {
  2009. Y_UNUSED(src);
  2010. ctx.Error(Pos) << Name << " can't be used as a part of expression.";
  2011. return false;
  2012. }
  2013. TAstNode* TArgPlaceholderNode::Translate(TContext& ctx) const {
  2014. Y_UNUSED(ctx);
  2015. return nullptr;
  2016. }
  2017. TString TArgPlaceholderNode::GetName() const {
  2018. return Name;
  2019. }
  2020. TNodePtr TArgPlaceholderNode::DoClone() const {
  2021. return new TArgPlaceholderNode(GetPos(), Name);
  2022. }
  2023. TNodePtr BuildArgPlaceholder(TPosition pos, const TString& name) {
  2024. return new TArgPlaceholderNode(pos, name);
  2025. }
  2026. class TAccessNode: public INode {
  2027. public:
  2028. TAccessNode(TPosition pos, const TVector<TIdPart>& ids, bool isLookup)
  2029. : INode(pos)
  2030. , Ids(ids)
  2031. , IsLookup(isLookup)
  2032. , ColumnOnly(false)
  2033. , IsColumnRequired(false)
  2034. , AccessOpName("AccessNode")
  2035. {
  2036. Y_DEBUG_ABORT_UNLESS(Ids.size() > 1);
  2037. Y_DEBUG_ABORT_UNLESS(Ids[0].Expr);
  2038. auto column = Ids[0].Expr->GetColumnNode();
  2039. if (column) {
  2040. ui32 idx = 1;
  2041. TString source;
  2042. if (Ids.size() > 2) {
  2043. source = Ids[idx].Name;
  2044. ++idx;
  2045. }
  2046. ColumnOnly = !IsLookup && Ids.size() < 4;
  2047. if (ColumnOnly && Ids[idx].Expr) {
  2048. column->ResetColumn(Ids[idx].Expr, source);
  2049. } else {
  2050. column->ResetColumn(Ids[idx].Name, source);
  2051. }
  2052. }
  2053. }
  2054. void AssumeColumn() override {
  2055. IsColumnRequired = true;
  2056. }
  2057. TMaybe<TString> TryMakeTable() {
  2058. if (!ColumnOnly) {
  2059. return Nothing();
  2060. }
  2061. ui32 idx = 1;
  2062. if (Ids.size() > 2) {
  2063. return Nothing();
  2064. }
  2065. return Ids[idx].Name;
  2066. }
  2067. const TString* GetColumnName() const override {
  2068. return ColumnOnly ? Ids[0].Expr->GetColumnName() : nullptr;
  2069. }
  2070. bool IsPlainColumn() const override {
  2071. if (GetColumnName()) {
  2072. return true;
  2073. }
  2074. if (Ids[0].Expr->IsTableRow()) {
  2075. return true;
  2076. }
  2077. return false;
  2078. }
  2079. const TString* GetSourceName() const override {
  2080. return Ids[0].Expr->GetSourceName();
  2081. }
  2082. TAccessNode* GetAccessNode() override {
  2083. return this;
  2084. }
  2085. const TAccessNode* GetAccessNode() const override {
  2086. return this;
  2087. }
  2088. bool DoInit(TContext& ctx, ISource* src) override {
  2089. auto expr = Ids[0].Expr;
  2090. const TPosition pos(expr->GetPos());
  2091. if (expr->IsAsterisk()) {
  2092. ctx.Error(pos) << "Asterisk column does not allow any access";
  2093. return false;
  2094. }
  2095. if (!expr->Init(ctx, src)) {
  2096. return false;
  2097. }
  2098. for (auto& id: Ids) {
  2099. if (id.Expr && !id.Expr->Init(ctx, src)) {
  2100. return false;
  2101. }
  2102. }
  2103. ui32 idx = 1;
  2104. auto column = expr->GetColumnNode();
  2105. if (column) {
  2106. const bool useSourceAsColumn = column->IsUseSourceAsColumn();
  2107. ColumnOnly &= !useSourceAsColumn;
  2108. if (IsColumnRequired && !ColumnOnly) {
  2109. ctx.Error(pos) << "Please use a full form (corellation.struct.field) or an alias (struct.field as alias) to access struct's field in the GROUP BY";
  2110. return false;
  2111. }
  2112. if (Ids.size() > 2) {
  2113. if (!CheckColumnId(pos, ctx, Ids[idx], ColumnOnly ? "Correlation" : "Column", true)) {
  2114. return false;
  2115. }
  2116. ++idx;
  2117. }
  2118. if (!useSourceAsColumn) {
  2119. if (!IsLookup && !CheckColumnId(pos, ctx, Ids[idx], ColumnOnly ? "Column" : "Member", false)) {
  2120. return false;
  2121. }
  2122. ++idx;
  2123. }
  2124. }
  2125. for (; idx < Ids.size(); ++idx) {
  2126. const auto& id = Ids[idx];
  2127. if (!id.Name.empty()) {
  2128. expr = Y("SqlAccess", Q("struct"), expr, id.Expr ? Y("EvaluateAtom", id.Expr) : BuildQuotedAtom(Pos, id.Name));
  2129. AccessOpName = "AccessStructMember";
  2130. } else if (id.Expr) {
  2131. expr = Y("SqlAccess", Q("dict"), expr, id.Expr);
  2132. AccessOpName = "AccessDictMember";
  2133. } else {
  2134. continue;
  2135. }
  2136. if (ctx.PragmaYsonAutoConvert || ctx.PragmaYsonStrict || ctx.PragmaYsonFast) {
  2137. auto ysonOptions = Y();
  2138. if (ctx.PragmaYsonAutoConvert) {
  2139. ysonOptions->Add(BuildQuotedAtom(Pos, "yson_auto_convert"));
  2140. }
  2141. if (ctx.PragmaYsonStrict) {
  2142. ysonOptions->Add(BuildQuotedAtom(Pos, "yson_strict"));
  2143. }
  2144. if (ctx.PragmaYsonFast) {
  2145. ysonOptions->Add(BuildQuotedAtom(Pos, "yson_fast"));
  2146. }
  2147. expr->Add(Q(ysonOptions));
  2148. }
  2149. }
  2150. Node = expr;
  2151. return true;
  2152. }
  2153. TAstNode* Translate(TContext& ctx) const override {
  2154. Y_DEBUG_ABORT_UNLESS(Node);
  2155. return Node->Translate(ctx);
  2156. }
  2157. TPtr DoClone() const override {
  2158. YQL_ENSURE(!Node, "TAccessNode::Clone: Node should not be initialized");
  2159. TVector<TIdPart> cloneIds;
  2160. cloneIds.reserve(Ids.size());
  2161. for (const auto& id: Ids) {
  2162. cloneIds.emplace_back(id.Clone());
  2163. }
  2164. auto copy = new TAccessNode(Pos, cloneIds, IsLookup);
  2165. copy->ColumnOnly = ColumnOnly;
  2166. return copy;
  2167. }
  2168. const TVector<TIdPart>& GetParts() const {
  2169. return Ids;
  2170. }
  2171. protected:
  2172. void DoUpdateState() const override {
  2173. YQL_ENSURE(Node);
  2174. State.Set(ENodeState::Const, Node->IsConstant());
  2175. State.Set(ENodeState::MaybeConst, Node->MaybeConstant());
  2176. State.Set(ENodeState::Aggregated, Node->IsAggregated());
  2177. State.Set(ENodeState::AggregationKey, Node->HasState(ENodeState::AggregationKey));
  2178. State.Set(ENodeState::OverWindow, Node->IsOverWindow());
  2179. }
  2180. void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const final {
  2181. Y_DEBUG_ABORT_UNLESS(Node);
  2182. Node->VisitTree(func, visited);
  2183. }
  2184. bool CheckColumnId(TPosition pos, TContext& ctx, const TIdPart& id, const TString& where, bool checkLookup) {
  2185. if (id.Name.empty()) {
  2186. ctx.Error(pos) << where << " name can not be empty";
  2187. return false;
  2188. }
  2189. if (checkLookup && id.Expr) {
  2190. ctx.Error(pos) << where << " name does not allow dict lookup";
  2191. return false;
  2192. }
  2193. return true;
  2194. }
  2195. TString GetOpName() const override {
  2196. return AccessOpName;
  2197. }
  2198. void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override {
  2199. for (auto& id : Ids) {
  2200. if (id.Expr) {
  2201. id.Expr->CollectPreaggregateExprs(ctx, src, exprs);
  2202. }
  2203. }
  2204. }
  2205. private:
  2206. TNodePtr Node;
  2207. TVector<TIdPart> Ids;
  2208. bool IsLookup;
  2209. bool ColumnOnly;
  2210. bool IsColumnRequired;
  2211. TString AccessOpName;
  2212. };
  2213. TNodePtr BuildAccess(TPosition pos, const TVector<INode::TIdPart>& ids, bool isLookup) {
  2214. return new TAccessNode(pos, ids, isLookup);
  2215. }
  2216. void WarnIfAliasFromSelectIsUsedInGroupBy(TContext& ctx, const TVector<TNodePtr>& selectTerms, const TVector<TNodePtr>& groupByTerms,
  2217. const TVector<TNodePtr>& groupByExprTerms)
  2218. {
  2219. THashMap<TString, TNodePtr> termsByLabel;
  2220. for (auto& term : selectTerms) {
  2221. auto label = term->GetLabel();
  2222. if (!label || term->IsOverWindow()) {
  2223. continue;
  2224. }
  2225. auto column = term->GetColumnName();
  2226. // do not warn for trivial renaming such as '[X.]foo AS foo'
  2227. if (column && *column == label) {
  2228. continue;
  2229. }
  2230. // skip terms with aggregation functions inside
  2231. bool hasAggregationFunction = false;
  2232. auto visitor = [&](const INode& current) {
  2233. hasAggregationFunction = hasAggregationFunction || current.GetAggregation();
  2234. return !hasAggregationFunction;
  2235. };
  2236. term->VisitTree(visitor);
  2237. if (!hasAggregationFunction) {
  2238. termsByLabel[label] = term;
  2239. }
  2240. }
  2241. if (termsByLabel.empty()) {
  2242. return;
  2243. }
  2244. bool found = false;
  2245. auto visitor = [&](const INode& current) {
  2246. if (found) {
  2247. return false;
  2248. }
  2249. if (auto columnName = current.GetColumnName()) {
  2250. // do not warn if source name is set
  2251. auto src = current.GetSourceName();
  2252. if (src && *src) {
  2253. return true;
  2254. }
  2255. auto it = termsByLabel.find(*columnName);
  2256. if (it != termsByLabel.end()) {
  2257. found = true;
  2258. ctx.Warning(current.GetPos(), TIssuesIds::YQL_PROJECTION_ALIAS_IS_REFERENCED_IN_GROUP_BY)
  2259. << "GROUP BY will aggregate by column `" << *columnName << "` instead of aggregating by SELECT expression with same alias";
  2260. ctx.Warning(it->second->GetPos(), TIssuesIds::YQL_PROJECTION_ALIAS_IS_REFERENCED_IN_GROUP_BY)
  2261. << "You should probably use alias in GROUP BY instead of using it here. Please consult documentation for more details";
  2262. return false;
  2263. }
  2264. }
  2265. return true;
  2266. };
  2267. TVector<TNodePtr> originalGroupBy;
  2268. {
  2269. THashSet<TString> groupByExprLabels;
  2270. for (auto& expr : groupByExprTerms) {
  2271. auto label = expr->GetLabel();
  2272. YQL_ENSURE(label);
  2273. groupByExprLabels.insert(label);
  2274. }
  2275. originalGroupBy = groupByTerms;
  2276. EraseIf(originalGroupBy, [&](const TNodePtr& node) {
  2277. auto column = node->GetColumnName();
  2278. auto src = node->GetSourceName();
  2279. return (!src || src->empty()) && column && groupByExprLabels.contains(*column);
  2280. });
  2281. originalGroupBy.insert(originalGroupBy.end(), groupByExprTerms.begin(), groupByExprTerms.end());
  2282. }
  2283. for (auto& groupByTerm : originalGroupBy) {
  2284. groupByTerm->VisitTree(visitor);
  2285. if (found) {
  2286. return;
  2287. }
  2288. }
  2289. }
  2290. bool ValidateAllNodesForAggregation(TContext& ctx, const TVector<TNodePtr>& nodes) {
  2291. for (auto& node: nodes) {
  2292. if (!node->HasState(ENodeState::Initialized) || node->IsConstant() || node->MaybeConstant()) {
  2293. continue;
  2294. }
  2295. // TODO: "!node->IsOverWindow()" doesn't look right here
  2296. if (!node->IsAggregated() && !node->IsOverWindow() && !node->IsOverWindowDistinct()) {
  2297. // locate column which is not a key column and not aggregated
  2298. const INode* found = nullptr;
  2299. auto visitor = [&found](const INode& current) {
  2300. if (found || current.IsAggregated() || current.IsOverWindow() || current.IsOverWindowDistinct()) {
  2301. return false;
  2302. }
  2303. if (current.GetColumnNode() || current.GetAccessNode()) {
  2304. found = &current;
  2305. return false;
  2306. }
  2307. return true;
  2308. };
  2309. node->VisitTree(visitor);
  2310. if (found) {
  2311. TString columnName;
  2312. if (auto col = found->GetColumnName(); col && *col) {
  2313. columnName = "`";
  2314. if (auto src = found->GetSourceName(); src && *src) {
  2315. columnName += DotJoin(*src, *col);
  2316. } else {
  2317. columnName += *col;
  2318. }
  2319. columnName += "` ";
  2320. }
  2321. ctx.Error(found->GetPos()) << "Column " << columnName << "must either be a key column in GROUP BY or it should be used in aggregation function";
  2322. } else {
  2323. ctx.Error(node->GetPos()) << "Expression has to be an aggregation function or key column, because aggregation is used elsewhere in this subquery";
  2324. }
  2325. return false;
  2326. }
  2327. }
  2328. return true;
  2329. }
  2330. class TBindNode: public TAstListNode {
  2331. public:
  2332. TBindNode(TPosition pos, const TString& module, const TString& alias)
  2333. : TAstListNode(pos)
  2334. {
  2335. Add("bind", AstNode(module), BuildQuotedAtom(pos, alias));
  2336. }
  2337. private:
  2338. TBindNode(const TBindNode& other)
  2339. : TAstListNode(other.GetPos())
  2340. {
  2341. Nodes = CloneContainer(other.Nodes);
  2342. }
  2343. TPtr DoClone() const final {
  2344. return new TBindNode(*this);
  2345. }
  2346. };
  2347. TNodePtr BuildBind(TPosition pos, const TString& module, const TString& alias) {
  2348. return new TBindNode(pos, module, alias);
  2349. }
  2350. class TLambdaNode: public TAstListNode {
  2351. public:
  2352. TLambdaNode(TPosition pos, TNodePtr params, TNodePtr body, const TString& resName)
  2353. : TAstListNode(pos)
  2354. {
  2355. if (!resName.empty()) {
  2356. body = Y("block", Q(L(body, Y("return", resName))));
  2357. }
  2358. Add("lambda", Q(params), body);
  2359. }
  2360. TLambdaNode(TPosition pos, TNodePtr params, TVector<TNodePtr> bodies)
  2361. : TAstListNode(pos)
  2362. {
  2363. Add("lambda", Q(params));
  2364. for (const auto& b : bodies) {
  2365. Add(b);
  2366. }
  2367. }
  2368. TLambdaNode* GetLambdaNode() override {
  2369. return this;
  2370. }
  2371. const TLambdaNode* GetLambdaNode() const override {
  2372. return this;
  2373. }
  2374. private:
  2375. TLambdaNode(const TLambdaNode& other)
  2376. : TAstListNode(other.GetPos())
  2377. {
  2378. Nodes = CloneContainer(other.Nodes);
  2379. }
  2380. TPtr DoClone() const final {
  2381. return new TLambdaNode(*this);
  2382. }
  2383. void DoUpdateState() const final {
  2384. State.Set(ENodeState::Const);
  2385. }
  2386. };
  2387. TNodePtr BuildLambda(TPosition pos, TNodePtr params, TNodePtr body, const TString& resName) {
  2388. return new TLambdaNode(pos, params, body, resName);
  2389. }
  2390. TNodePtr BuildLambda(TPosition pos, TNodePtr params, const TVector<TNodePtr>& bodies) {
  2391. return new TLambdaNode(pos, params, bodies);
  2392. }
  2393. TNodePtr BuildDataType(TPosition pos, const TString& typeName) {
  2394. return new TCallNodeImpl(pos, "DataType", {BuildQuotedAtom(pos, typeName, TNodeFlags::Default)});
  2395. }
  2396. TMaybe<TString> LookupSimpleType(const TStringBuf& alias, bool flexibleTypes, bool isPgType) {
  2397. TString normalized = to_lower(TString(alias));
  2398. if (isPgType) {
  2399. // expecting original pg type (like _int4 or varchar) with optional pg suffix (i.e. _pgint4, pgvarchar)
  2400. if (normalized.StartsWith("pg")) {
  2401. normalized = normalized.substr(2);
  2402. } else if (normalized.StartsWith("_pg")) {
  2403. normalized = "_" + normalized.substr(3);
  2404. }
  2405. if (!NPg::HasType(normalized)) {
  2406. return {};
  2407. }
  2408. if (normalized.StartsWith("_")) {
  2409. return "_pg" + normalized.substr(1);
  2410. }
  2411. return "pg" + normalized;
  2412. }
  2413. if (auto sqlAlias = LookupSimpleTypeBySqlAlias(alias, flexibleTypes)) {
  2414. return TString(*sqlAlias);
  2415. }
  2416. TString pgType;
  2417. if (normalized.StartsWith("_pg")) {
  2418. pgType = normalized.substr(3);
  2419. } else if (normalized.StartsWith("pg")) {
  2420. pgType = normalized.substr(2);
  2421. } else {
  2422. return {};
  2423. }
  2424. if (NPg::HasType(pgType)) {
  2425. return normalized;
  2426. }
  2427. return {};
  2428. }
  2429. TNodePtr BuildSimpleType(TContext& ctx, TPosition pos, const TString& typeName, bool dataOnly) {
  2430. bool explicitPgType = ctx.GetColumnReferenceState() == EColumnRefState::AsPgType;
  2431. auto found = LookupSimpleType(typeName, ctx.FlexibleTypes, explicitPgType);
  2432. if (!found) {
  2433. ctx.Error(pos) << "Unknown " << (explicitPgType ? "pg" : "simple") << " type '" << typeName << "'";
  2434. return {};
  2435. }
  2436. auto type = *found;
  2437. if (type == "Void" || type == "Unit" || type == "Generic" || type == "EmptyList" || type == "EmptyDict") {
  2438. if (dataOnly) {
  2439. ctx.Error(pos) << "Only data types are allowed here, but got: '" << typeName << "'";
  2440. return {};
  2441. }
  2442. type += "Type";
  2443. return new TCallNodeImpl(pos, type, {});
  2444. }
  2445. if (type.StartsWith("_pg") || type.StartsWith("pg")) {
  2446. TString pgType;
  2447. if (type.StartsWith("_pg")) {
  2448. pgType = "_" + type.substr(3);
  2449. } else {
  2450. pgType = type.substr(2);
  2451. }
  2452. return new TCallNodeImpl(pos, "PgType", { BuildQuotedAtom(pos, pgType, TNodeFlags::Default) });
  2453. }
  2454. return new TCallNodeImpl(pos, "DataType", { BuildQuotedAtom(pos, type, TNodeFlags::Default) });
  2455. }
  2456. TString TypeByAlias(const TString& alias, bool normalize) {
  2457. TString type(alias);
  2458. TCiString typeAlias(alias);
  2459. if (typeAlias.StartsWith("varchar")) {
  2460. type = "String";
  2461. } else if (typeAlias == "tinyint") {
  2462. type = "Int8";
  2463. } else if (typeAlias == "byte") {
  2464. type = "Uint8";
  2465. } else if (typeAlias == "smallint") {
  2466. type = "Int16";
  2467. } else if (typeAlias == "int" || typeAlias == "integer") {
  2468. type = "Int32";
  2469. } else if (typeAlias == "bigint") {
  2470. type = "Int64";
  2471. }
  2472. return normalize ? NormalizeTypeString(type) : type;
  2473. }
  2474. TNodePtr BuildIsNullOp(TPosition pos, TNodePtr a) {
  2475. if (!a) {
  2476. return nullptr;
  2477. }
  2478. if (a->IsNull()) {
  2479. return BuildLiteralBool(pos, true);
  2480. }
  2481. return new TCallNodeImpl(pos, "Not", {new TCallNodeImpl(pos, "Exists", {a})});
  2482. }
  2483. TUdfNode::TUdfNode(TPosition pos, const TVector<TNodePtr>& args)
  2484. : INode(pos)
  2485. , Args(args)
  2486. {
  2487. if (Args.size()) {
  2488. // If there aren't any named args, args are passed as vector of positional args,
  2489. // else Args has length 2: tuple for positional args and struct for named args,
  2490. // so let's construct tuple of args there. Other type checks will within DoInit call.
  2491. if (!Args[0]->GetTupleNode()) {
  2492. Args = {BuildTuple(pos, args)};
  2493. }
  2494. }
  2495. }
  2496. bool TUdfNode::DoInit(TContext& ctx, ISource* src) {
  2497. Y_UNUSED(src);
  2498. if (Args.size() < 1) {
  2499. ctx.Error(Pos) << "Udf: expected at least one argument";
  2500. return false;
  2501. }
  2502. TTupleNode* as_tuple = Args[0]->GetTupleNode();
  2503. if (!as_tuple || as_tuple->GetTupleSize() < 1) {
  2504. ctx.Error(Pos) << "Udf: first argument must be a callable, like Foo::Bar";
  2505. return false;
  2506. }
  2507. TNodePtr function = as_tuple->GetTupleElement(0);
  2508. if (!function || !function->FuncName()) {
  2509. ctx.Error(Pos) << "Udf: first argument must be a callable, like Foo::Bar";
  2510. return false;
  2511. }
  2512. FunctionName = function->FuncName();
  2513. ModuleName = function->ModuleName();
  2514. TVector<TNodePtr> external;
  2515. external.reserve(as_tuple->GetTupleSize() - 1);
  2516. for (size_t i = 1; i < as_tuple->GetTupleSize(); ++i) {
  2517. // TODO(): support named args in GetFunctionArgColumnStatus
  2518. TNodePtr current = as_tuple->GetTupleElement(i);
  2519. if (TAccessNode* as_access = current->GetAccessNode(); as_access) {
  2520. external.push_back(Y("DataType", Q(as_access->GetParts()[1].Name)));
  2521. continue;
  2522. }
  2523. external.push_back(current);
  2524. }
  2525. ExternalTypesTuple = new TCallNodeImpl(Pos, "TupleType", external);
  2526. if (Args.size() == 1) {
  2527. return true;
  2528. }
  2529. if (TStructNode* named_args = Args[1]->GetStructNode(); named_args) {
  2530. for (const auto &arg: named_args->GetExprs()) {
  2531. if (arg->GetLabel() == "TypeConfig") {
  2532. TypeConfig = MakeAtomFromExpression(Pos, ctx, arg);
  2533. } else if (arg->GetLabel() == "RunConfig") {
  2534. RunConfig = arg;
  2535. }
  2536. }
  2537. }
  2538. return true;
  2539. }
  2540. const TNodePtr TUdfNode::GetExternalTypes() const {
  2541. return ExternalTypesTuple;
  2542. }
  2543. const TString& TUdfNode::GetFunction() const {
  2544. return *FunctionName;
  2545. }
  2546. const TString& TUdfNode::GetModule() const {
  2547. return *ModuleName;
  2548. }
  2549. TNodePtr TUdfNode::GetRunConfig() const {
  2550. return RunConfig;
  2551. }
  2552. const TDeferredAtom& TUdfNode::GetTypeConfig() const {
  2553. return TypeConfig;
  2554. }
  2555. TUdfNode* TUdfNode::GetUdfNode() {
  2556. return this;
  2557. }
  2558. const TUdfNode* TUdfNode::GetUdfNode() const {
  2559. return this;
  2560. }
  2561. TAstNode* TUdfNode::Translate(TContext& ctx) const {
  2562. ctx.Error(Pos) << "Abstract Udf Node can't be used as a part of expression.";
  2563. return nullptr;
  2564. }
  2565. TNodePtr TUdfNode::DoClone() const {
  2566. return new TUdfNode(Pos, CloneContainer(Args));
  2567. }
  2568. class TBinaryOpNode final: public TCallNode {
  2569. public:
  2570. TBinaryOpNode(TPosition pos, const TString& opName, TNodePtr a, TNodePtr b);
  2571. TNodePtr DoClone() const final {
  2572. YQL_ENSURE(Args.size() == 2);
  2573. return new TBinaryOpNode(Pos, OpName, Args[0]->Clone(), Args[1]->Clone());
  2574. }
  2575. };
  2576. TBinaryOpNode::TBinaryOpNode(TPosition pos, const TString& opName, TNodePtr a, TNodePtr b)
  2577. : TCallNode(pos, opName, 2, 2, { a, b })
  2578. {
  2579. }
  2580. TNodePtr BuildBinaryOp(TContext& ctx, TPosition pos, const TString& opName, TNodePtr a, TNodePtr b) {
  2581. if (!a || !b) {
  2582. return nullptr;
  2583. }
  2584. static const THashSet<TStringBuf> nullSafeOps = {"IsDistinctFrom", "IsNotDistinctFrom"};
  2585. if (!nullSafeOps.contains(opName)) {
  2586. const bool bothArgNull = a->IsNull() && b->IsNull();
  2587. const bool oneArgNull = a->IsNull() || b->IsNull();
  2588. if (bothArgNull || (oneArgNull && opName != "Or" && opName != "And")) {
  2589. ctx.Warning(pos, TIssuesIds::YQL_OPERATION_WILL_RETURN_NULL) << "Binary operation "
  2590. << opName.substr(0, opName.size() - 7 * opName.EndsWith("MayWarn"))
  2591. << " will return NULL here";
  2592. }
  2593. }
  2594. return new TBinaryOpNode(pos, opName, a, b);
  2595. }
  2596. TNodePtr BuildBinaryOpRaw(TPosition pos, const TString& opName, TNodePtr a, TNodePtr b) {
  2597. if (!a || !b) {
  2598. return nullptr;
  2599. }
  2600. return new TBinaryOpNode(pos, opName, a, b);
  2601. }
  2602. class TCalcOverWindow final: public INode {
  2603. public:
  2604. TCalcOverWindow(TPosition pos, const TString& windowName, TNodePtr node)
  2605. : INode(pos)
  2606. , WindowName(windowName)
  2607. , FuncNode(node)
  2608. {}
  2609. TAstNode* Translate(TContext& ctx) const override {
  2610. return FuncNode->Translate(ctx);
  2611. }
  2612. bool DoInit(TContext& ctx, ISource* src) override {
  2613. YQL_ENSURE(src);
  2614. TSourcePtr overWindowSource = BuildOverWindowSource(ctx.Pos(), WindowName, src);
  2615. if (!FuncNode->Init(ctx, overWindowSource.Get())) {
  2616. return false;
  2617. }
  2618. return true;
  2619. }
  2620. TPtr DoClone() const final {
  2621. return new TCalcOverWindow(Pos, WindowName, SafeClone(FuncNode));
  2622. }
  2623. void DoUpdateState() const override {
  2624. State.Set(ENodeState::Const, FuncNode->IsConstant());
  2625. State.Set(ENodeState::MaybeConst, FuncNode->MaybeConstant());
  2626. State.Set(ENodeState::Aggregated, FuncNode->IsAggregated());
  2627. State.Set(ENodeState::OverWindow, true);
  2628. }
  2629. void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const final {
  2630. Y_DEBUG_ABORT_UNLESS(FuncNode);
  2631. FuncNode->VisitTree(func, visited);
  2632. }
  2633. void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override {
  2634. if (ctx.DistinctOverWindow) {
  2635. FuncNode->CollectPreaggregateExprs(ctx, src, exprs);
  2636. } else {
  2637. INode::CollectPreaggregateExprs(ctx, src, exprs);
  2638. }
  2639. }
  2640. protected:
  2641. const TString WindowName;
  2642. TNodePtr FuncNode;
  2643. };
  2644. TNodePtr BuildCalcOverWindow(TPosition pos, const TString& windowName, TNodePtr call) {
  2645. return new TCalcOverWindow(pos, windowName, call);
  2646. }
  2647. template<bool Fast>
  2648. class TYsonOptionsNode final: public INode {
  2649. public:
  2650. TYsonOptionsNode(TPosition pos, bool autoConvert, bool strict)
  2651. : INode(pos)
  2652. , AutoConvert(autoConvert)
  2653. , Strict(strict)
  2654. {
  2655. auto udf = Y("Udf", Q(Fast ? "Yson2.Options" : "Yson.Options"));
  2656. auto autoConvertNode = BuildLiteralBool(pos, autoConvert);
  2657. autoConvertNode->SetLabel("AutoConvert");
  2658. auto strictNode = BuildLiteralBool(pos, strict);
  2659. strictNode->SetLabel("Strict");
  2660. Node = Y("NamedApply", udf, Q(Y()), BuildStructure(pos, { autoConvertNode, strictNode }));
  2661. }
  2662. TAstNode* Translate(TContext& ctx) const override {
  2663. return Node->Translate(ctx);
  2664. }
  2665. bool DoInit(TContext& ctx, ISource* src) override {
  2666. if (!Node->Init(ctx, src)) {
  2667. return false;
  2668. }
  2669. return true;
  2670. }
  2671. TPtr DoClone() const final {
  2672. return new TYsonOptionsNode(Pos, AutoConvert, Strict);
  2673. }
  2674. void DoUpdateState() const override {
  2675. State.Set(ENodeState::Const, true);
  2676. }
  2677. protected:
  2678. TNodePtr Node;
  2679. const bool AutoConvert;
  2680. const bool Strict;
  2681. };
  2682. TNodePtr BuildYsonOptionsNode(TPosition pos, bool autoConvert, bool strict, bool fastYson) {
  2683. if (fastYson)
  2684. return new TYsonOptionsNode<true>(pos, autoConvert, strict);
  2685. else
  2686. return new TYsonOptionsNode<false>(pos, autoConvert, strict);
  2687. }
  2688. class TDoCall final : public INode {
  2689. public:
  2690. TDoCall(TPosition pos, const TNodePtr& node)
  2691. : INode(pos)
  2692. , Node(node)
  2693. {
  2694. FakeSource = BuildFakeSource(pos);
  2695. }
  2696. ISource* GetSource() final {
  2697. return FakeSource.Get();
  2698. }
  2699. bool DoInit(TContext& ctx, ISource* src) final {
  2700. Y_UNUSED(src);
  2701. if (!Node->Init(ctx, FakeSource.Get())) {
  2702. return false;
  2703. }
  2704. return true;
  2705. }
  2706. TAstNode* Translate(TContext& ctx) const final {
  2707. return Node->Translate(ctx);
  2708. }
  2709. TPtr DoClone() const final {
  2710. return new TDoCall(Pos, Node->Clone());
  2711. }
  2712. void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const final {
  2713. Y_DEBUG_ABORT_UNLESS(Node);
  2714. Node->VisitTree(func, visited);
  2715. }
  2716. private:
  2717. TNodePtr Node;
  2718. TSourcePtr FakeSource;
  2719. };
  2720. TNodePtr BuildDoCall(TPosition pos, const TNodePtr& node) {
  2721. return new TDoCall(pos, node);
  2722. }
  2723. bool Parseui32(TNodePtr from, ui32& to) {
  2724. const TString* val;
  2725. if (!(val = from->GetLiteral("Int32"))) {
  2726. if (!(val = from->GetLiteral("Uint32"))) {
  2727. return false;
  2728. }
  2729. }
  2730. return TryFromString(*val, to);
  2731. }
  2732. TNodePtr GroundWithExpr(const TNodePtr& ground, const TNodePtr& expr) {
  2733. return ground ? expr->Y("block", expr->Q(expr->L(ground, expr->Y("return", expr)))) : expr;
  2734. }
  2735. TSourcePtr TryMakeSourceFromExpression(TPosition pos, TContext& ctx, const TString& currService, const TDeferredAtom& currCluster,
  2736. TNodePtr node, const TString& view) {
  2737. if (currCluster.Empty()) {
  2738. ctx.Error() << "No cluster name given and no default cluster is selected";
  2739. return nullptr;
  2740. }
  2741. if (auto literal = node->GetLiteral("String")) {
  2742. TNodePtr tableKey = BuildTableKey(node->GetPos(), currService, currCluster, TDeferredAtom(node->GetPos(), *literal), {view});
  2743. TTableRef table(ctx.MakeName("table"), currService, currCluster, tableKey);
  2744. table.Options = BuildInputOptions(node->GetPos(), GetContextHints(ctx));
  2745. return BuildTableSource(node->GetPos(), table);
  2746. }
  2747. if (node->GetLambdaNode()) {
  2748. ctx.Error() << "Lambda is not allowed to be used as source. Did you forget to call a subquery template?";
  2749. return nullptr;
  2750. }
  2751. auto wrappedNode = new TAstListNodeImpl(pos, {
  2752. new TAstAtomNodeImpl(pos, "EvaluateAtom", TNodeFlags::Default),
  2753. node
  2754. });
  2755. TNodePtr tableKey = BuildTableKey(node->GetPos(), currService, currCluster, TDeferredAtom(wrappedNode, ctx), {view});
  2756. TTableRef table(ctx.MakeName("table"), currService, currCluster, tableKey);
  2757. table.Options = BuildInputOptions(node->GetPos(), GetContextHints(ctx));
  2758. return BuildTableSource(node->GetPos(), table);
  2759. }
  2760. void MakeTableFromExpression(TPosition pos, TContext& ctx, TNodePtr node, TDeferredAtom& table, const TString& prefix) {
  2761. if (auto literal = node->GetLiteral("String")) {
  2762. table = TDeferredAtom(node->GetPos(), prefix + *literal);
  2763. return;
  2764. }
  2765. if (auto access = node->GetAccessNode()) {
  2766. auto ret = access->TryMakeTable();
  2767. if (ret) {
  2768. table = TDeferredAtom(node->GetPos(), prefix + *ret);
  2769. return;
  2770. }
  2771. }
  2772. if (!prefix.empty()) {
  2773. node = node->Y("Concat", node->Y("String", node->Q(prefix)), node);
  2774. }
  2775. auto wrappedNode = new TAstListNodeImpl(pos, {
  2776. new TAstAtomNodeImpl(pos, "EvaluateAtom", TNodeFlags::Default),
  2777. node
  2778. });
  2779. table = TDeferredAtom(wrappedNode, ctx);
  2780. }
  2781. TDeferredAtom MakeAtomFromExpression(TPosition pos, TContext& ctx, TNodePtr node, const TString& prefix) {
  2782. if (auto literal = node->GetLiteral("String")) {
  2783. return TDeferredAtom(node->GetPos(), prefix + *literal);
  2784. }
  2785. if (!prefix.empty()) {
  2786. node = node->Y("Concat", node->Y("String", node->Q(prefix)), node);
  2787. }
  2788. auto wrappedNode = new TAstListNodeImpl(pos, {
  2789. new TAstAtomNodeImpl(pos, "EvaluateAtom", TNodeFlags::Default),
  2790. node
  2791. });
  2792. return TDeferredAtom(wrappedNode, ctx);
  2793. }
  2794. class TTupleResultNode: public INode {
  2795. public:
  2796. TTupleResultNode(TNodePtr&& tuple, size_t ensureTupleSize)
  2797. : INode(tuple->GetPos())
  2798. , Node(std::move(tuple))
  2799. , EnsureTupleSize(ensureTupleSize)
  2800. {
  2801. }
  2802. bool DoInit(TContext& ctx, ISource* src) override {
  2803. if (!Node->Init(ctx, src)) {
  2804. return false;
  2805. }
  2806. Node = Y("EnsureTupleSize", Node, Q(ToString(EnsureTupleSize)));
  2807. return true;
  2808. }
  2809. TAstNode* Translate(TContext& ctx) const override {
  2810. return Node->Translate(ctx);
  2811. }
  2812. TPtr DoClone() const final {
  2813. return new TTupleResultNode(Node->Clone(), EnsureTupleSize);
  2814. }
  2815. void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const final {
  2816. Y_DEBUG_ABORT_UNLESS(Node);
  2817. Node->VisitTree(func, visited);
  2818. }
  2819. protected:
  2820. TNodePtr Node;
  2821. const size_t EnsureTupleSize;
  2822. };
  2823. TNodePtr BuildTupleResult(TNodePtr tuple, size_t ensureTupleSize) {
  2824. return new TTupleResultNode(std::move(tuple), ensureTupleSize);
  2825. }
  2826. class TNamedExprReferenceNode: public IProxyNode {
  2827. public:
  2828. TNamedExprReferenceNode(TNodePtr parent, const TString& name, TMaybe<size_t> tupleIndex)
  2829. : IProxyNode(parent->GetPos(), parent)
  2830. , Name(name)
  2831. , TupleIndex(tupleIndex)
  2832. {
  2833. }
  2834. bool DoInit(TContext& ctx, ISource* src) final {
  2835. Y_UNUSED(src);
  2836. if (!IProxyNode::DoInit(ctx, nullptr) || !IProxyNode::InitReference(ctx)) {
  2837. return false;
  2838. }
  2839. Node = BuildAtom(GetPos(), Name, TNodeFlags::Default);
  2840. if (TupleIndex.Defined()) {
  2841. Node = Y("Nth", Node, Q(ToString(*TupleIndex)));
  2842. }
  2843. return true;
  2844. }
  2845. TAstNode* Translate(TContext& ctx) const override {
  2846. YQL_ENSURE(Node, "Init() should be done before Translate()");
  2847. return Node->Translate(ctx);
  2848. }
  2849. TPtr DoClone() const final {
  2850. // do not clone Inner here
  2851. return new TNamedExprReferenceNode(Inner, Name, TupleIndex);
  2852. }
  2853. private:
  2854. const TString Name;
  2855. const TMaybe<size_t> TupleIndex;
  2856. TNodePtr Node;
  2857. };
  2858. TNodePtr BuildNamedExprReference(TNodePtr parent, const TString& name, TMaybe<size_t> tupleIndex) {
  2859. YQL_ENSURE(parent);
  2860. return new TNamedExprReferenceNode(parent, name, tupleIndex);
  2861. }
  2862. class TNamedExprNode: public IProxyNode {
  2863. public:
  2864. TNamedExprNode(TNodePtr parent)
  2865. : IProxyNode(parent->GetPos(), parent)
  2866. , FakeSource(BuildFakeSource(parent->GetPos()))
  2867. , Referenced(false)
  2868. {
  2869. }
  2870. bool DoInit(TContext& ctx, ISource* src) final {
  2871. YQL_ENSURE(!Referenced, "Refrence is initialized before named expr itself");
  2872. Y_UNUSED(src);
  2873. if (ctx.ValidateUnusedExprs) {
  2874. return IProxyNode::DoInit(ctx, FakeSource.Get());
  2875. }
  2876. // do actual init in InitReference()
  2877. return true;
  2878. }
  2879. bool InitReference(TContext& ctx) final {
  2880. Referenced = true;
  2881. return IProxyNode::DoInit(ctx, FakeSource.Get());
  2882. }
  2883. TAstNode* Translate(TContext& ctx) const override {
  2884. if (ctx.ValidateUnusedExprs || Referenced) {
  2885. return Inner->Translate(ctx);
  2886. }
  2887. auto unused = BuildQuotedAtom(GetPos(), "unused", TNodeFlags::Default);
  2888. return unused->Translate(ctx);
  2889. }
  2890. TPtr DoClone() const final {
  2891. return new TNamedExprNode(Inner->Clone());
  2892. }
  2893. private:
  2894. const TSourcePtr FakeSource;
  2895. bool Referenced;
  2896. };
  2897. TNodePtr BuildNamedExpr(TNodePtr parent) {
  2898. YQL_ENSURE(parent);
  2899. return new TNamedExprNode(parent);
  2900. }
  2901. bool TVectorIndexSettings::Validate(TContext& ctx) const {
  2902. if (!Distance && !Similarity) {
  2903. ctx.Error() << "either distance or similarity should be set";
  2904. return false;
  2905. }
  2906. if (!VectorType) {
  2907. ctx.Error() << "vector_type should be set";
  2908. return false;
  2909. }
  2910. if (!VectorDimension) {
  2911. ctx.Error() << "vector_dimension should be set";
  2912. return false;
  2913. }
  2914. return true;
  2915. }
  2916. } // namespace NSQLTranslationV1