catalog.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357
  1. #include "catalog.h"
  2. #include <yql/essentials/parser/pg_catalog/proto/pg_catalog.pb.h>
  3. #include <yql/essentials/utils/log/profile.h>
  4. #include <util/generic/array_size.h>
  5. #include <util/generic/utility.h>
  6. #include <util/generic/hash.h>
  7. #include <util/generic/hash_set.h>
  8. #include <util/string/builder.h>
  9. #include <util/string/cast.h>
  10. #include <util/string/split.h>
  11. #include <util/stream/file.h>
  12. #include <util/system/env.h>
  13. #include <util/system/mutex.h>
  14. #include <util/system/tempfile.h>
  15. #include <library/cpp/resource/resource.h>
  16. #include <library/cpp/digest/md5/md5.h>
  17. namespace NYql::NPg {
  18. const ui32 MaximumExtensionsCount = 64; // see TTypeAnnotationNode::GetUsedPgExtensions
  19. constexpr ui32 FuncMaxArgs = 100;
  20. constexpr ui32 InvalidOid = 0;
  21. constexpr ui32 Int2VectorOid = 22;
  22. constexpr ui32 RegProcOid = 24;
  23. constexpr ui32 OidOid = 26;
  24. constexpr ui32 OidVectorOid = 30;
  25. constexpr ui32 RegProcedureOid = 2202;
  26. constexpr ui32 RegOperOid = 2203;
  27. constexpr ui32 RegOperatorOid = 2204;
  28. constexpr ui32 RegClassOid = 2205;
  29. constexpr ui32 RegTypeOid = 2206;
  30. //constexpr ui32 AnyElementOid = 2283;
  31. //constexpr ui32 AnyNonArrayOid = 2776;
  32. constexpr ui32 RegConfigOid = 3734;
  33. constexpr ui32 RegDictionaryOid = 3769;
  34. constexpr ui32 RegNamespaceOid = 4089;
  35. constexpr ui32 RegRoleOid = 4096;
  36. //constexpr ui32 AnyCompatibleOid = 5077;
  37. //constexpr ui32 AnyCompatibleArrayOid = 5078;
  38. //constexpr ui32 AnyCompatibleNonArrayOid = 5079;
  39. // See GetCCHashEqFuncs in PG sources
  40. // https://doxygen.postgresql.org/catcache_8c.html#a8a2dc395011dba02c083bfbf6b87ce6c
  41. const THashSet<ui32> regClasses({
  42. RegProcOid, RegProcedureOid, RegOperOid, RegOperatorOid, RegClassOid, RegTypeOid,
  43. RegConfigOid, RegDictionaryOid, RegRoleOid, RegNamespaceOid});
  44. using TOperators = THashMap<ui32, TOperDesc>;
  45. using TProcs = THashMap<ui32, TProcDesc>;
  46. using TTypes = THashMap<ui32, TTypeDesc>;
  47. using TCasts = THashMap<ui32, TCastDesc>;
  48. using TAggregations = THashMap<ui32, TAggregateDesc>;
  49. using TAms = THashMap<ui32, TAmDesc>;
  50. using TNamespaces = THashMap<decltype(TNamespaceDesc::Oid), TNamespaceDesc>;
  51. using TOpFamilies = THashMap<TString, TOpFamilyDesc>;
  52. using TOpClasses = THashMap<std::pair<EOpClassMethod, ui32>, TOpClassDesc>;
  53. using TAmOps = THashMap<std::tuple<ui32, ui32, ui32, ui32>, TAmOpDesc>;
  54. using TAmProcs = THashMap<std::tuple<ui32, ui32, ui32, ui32>, TAmProcDesc>;
  55. using TConversions = THashMap<std::pair<TString, TString>, TConversionDesc>;
  56. using TLanguages = THashMap<ui32, TLanguageDesc>;
  57. using TExtensions = TVector<TExtensionDesc>;
  58. using TExtensionsByName = THashMap<TString, ui32>;
  59. bool IsCompatibleTo(ui32 actualTypeId, ui32 expectedTypeId, const TTypes& types) {
  60. if (actualTypeId == expectedTypeId) {
  61. return true;
  62. }
  63. if (actualTypeId == InvalidOid) {
  64. return true;
  65. }
  66. if (actualTypeId == UnknownOid) {
  67. return true;
  68. }
  69. if (expectedTypeId == AnyOid) {
  70. return true;
  71. }
  72. // TODO: add checks for polymorphic types
  73. if (expectedTypeId == UnknownOid) {
  74. return true;
  75. }
  76. if (expectedTypeId == AnyArrayOid) {
  77. const auto& actualDescPtr = types.FindPtr(actualTypeId);
  78. Y_ENSURE(actualDescPtr);
  79. return actualDescPtr->ArrayTypeId && actualDescPtr->ArrayTypeId == actualDescPtr->TypeId;
  80. }
  81. if (expectedTypeId == AnyNonArrayOid) {
  82. const auto& actualDescPtr = types.FindPtr(actualTypeId);
  83. Y_ENSURE(actualDescPtr);
  84. return actualDescPtr->ArrayTypeId && actualDescPtr->ArrayTypeId != actualDescPtr->TypeId;
  85. }
  86. return false;
  87. }
  88. TString ArgTypesList(const TVector<ui32>& ids) {
  89. TStringBuilder str;
  90. str << '(';
  91. for (ui32 i = 0; i < ids.size(); ++i) {
  92. if (i > 0) {
  93. str << ',';
  94. }
  95. str << (ids[i] ? LookupType(ids[i]).Name : "NULL");
  96. }
  97. str << ')';
  98. return str;
  99. }
  100. TStringBuf GetCanonicalTypeName(TStringBuf name) {
  101. if (name == "boolean") {
  102. return "bool";
  103. }
  104. if (name == "character") {
  105. return "bpchar";
  106. }
  107. if (name == "charactervarying") {
  108. return "varchar";
  109. }
  110. if (name == "bitvarying") {
  111. return "varbit";
  112. }
  113. if (name == "real") {
  114. return "float4";
  115. }
  116. if (name == "doubleprecision") {
  117. return "float8";
  118. }
  119. if (name == "smallint") {
  120. return "int2";
  121. }
  122. if (name == "integer" || name == "int") {
  123. return "int4";
  124. }
  125. if (name == "bigint") {
  126. return "int8";
  127. }
  128. if (name == "timewithouttimezone") {
  129. return "time";
  130. }
  131. if (name == "timewithtimezone") {
  132. return "timetz";
  133. }
  134. if (name == "timestampwithouttimezone") {
  135. return "timestamp";
  136. }
  137. if (name == "timestampwithtimezone") {
  138. return "timestamptz";
  139. }
  140. if (name == "decimal") {
  141. return "numeric";
  142. }
  143. return name;
  144. }
  145. bool ValidateArgs(const TVector<ui32>& descArgTypeIds, const TVector<ui32>& argTypeIds, const TTypes& types, ui32 variadicArgType = 0) {
  146. if (argTypeIds.size() > FuncMaxArgs) {
  147. return false;
  148. }
  149. if (argTypeIds.size() < descArgTypeIds.size()) {
  150. return false;
  151. }
  152. if (!variadicArgType && argTypeIds.size() > descArgTypeIds.size()) {
  153. return false;
  154. }
  155. if (variadicArgType && argTypeIds.size() == descArgTypeIds.size()) {
  156. // at least one variadic argument is required
  157. return false;
  158. }
  159. for (size_t i = 0; i < descArgTypeIds.size(); ++i) {
  160. if (!IsCompatibleTo(argTypeIds[i], descArgTypeIds[i], types)) {
  161. return false;
  162. }
  163. }
  164. for (size_t i = descArgTypeIds.size(); i < argTypeIds.size(); ++i) {
  165. if (!IsCompatibleTo(argTypeIds[i], variadicArgType, types)) {
  166. return false;
  167. }
  168. }
  169. return true;
  170. }
  171. class TParser {
  172. public:
  173. virtual ~TParser() = default;
  174. void Do(const TString& dat) {
  175. enum class EState {
  176. WaitBracket,
  177. InsideBrackets,
  178. WaitForEndOfKey,
  179. WaitForValue,
  180. WaitForEndOfValue
  181. };
  182. EState state = EState::WaitBracket;
  183. bool AfterBackSlash = false;
  184. TStringBuilder key;
  185. TStringBuilder value;
  186. for (char c : dat) {
  187. switch (state) {
  188. case EState::WaitBracket: {
  189. if (c == '{') {
  190. state = EState::InsideBrackets;
  191. }
  192. break;
  193. }
  194. case EState::InsideBrackets: {
  195. if (c == '}') {
  196. state = EState::WaitBracket;
  197. OnFinish();
  198. continue;
  199. }
  200. if (c == ' ' || c == ',' || c == '\n') {
  201. continue;
  202. }
  203. key.clear();
  204. key << c;
  205. state = EState::WaitForEndOfKey;
  206. break;
  207. }
  208. case EState::WaitForEndOfKey: {
  209. if (c != ' ') {
  210. key << c;
  211. continue;
  212. }
  213. state = EState::WaitForValue;
  214. break;
  215. }
  216. case EState::WaitForValue: {
  217. if (c != '\'') {
  218. continue;
  219. }
  220. state = EState::WaitForEndOfValue;
  221. value.clear();
  222. break;
  223. }
  224. case EState::WaitForEndOfValue: {
  225. if (c == '\\' && !AfterBackSlash) {
  226. AfterBackSlash = true;
  227. continue;
  228. }
  229. if (AfterBackSlash) {
  230. AfterBackSlash = false;
  231. value << c;
  232. continue;
  233. }
  234. if (c != '\'') {
  235. value << c;
  236. continue;
  237. }
  238. state = EState::InsideBrackets;
  239. OnKey(key, value);
  240. break;
  241. }
  242. }
  243. }
  244. }
  245. virtual void OnFinish() = 0;
  246. virtual void OnKey(const TString& key, const TString& value) = 0;
  247. };
  248. bool ValidateOperArgs(const TOperDesc& d, const TVector<ui32>& argTypeIds, const TTypes& types) {
  249. ui32 size = d.Kind == EOperKind::Binary ? 2 : 1;
  250. if (argTypeIds.size() != size) {
  251. return false;
  252. }
  253. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  254. ui32 expectedArgType;
  255. if (d.Kind == EOperKind::RightUnary || (d.Kind == EOperKind::Binary && i == 0)) {
  256. expectedArgType = d.LeftType;
  257. }
  258. else {
  259. expectedArgType = d.RightType;
  260. }
  261. if (!IsCompatibleTo(argTypeIds[i], expectedArgType, types)) {
  262. return false;
  263. }
  264. }
  265. return true;
  266. }
  267. struct TLazyOperInfo {
  268. TString Com;
  269. TString Negate;
  270. };
  271. class TOperatorsParser : public TParser {
  272. public:
  273. TOperatorsParser(TOperators& operators, const THashMap<TString, ui32>& typeByName, const TTypes& types,
  274. const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs, THashMap<ui32, TLazyOperInfo>& lazyInfos)
  275. : Operators(operators)
  276. , TypeByName(typeByName)
  277. , Types(types)
  278. , ProcByName(procByName)
  279. , Procs(procs)
  280. , LazyInfos(lazyInfos)
  281. {}
  282. void OnKey(const TString& key, const TString& value) override {
  283. if (key == "oid") {
  284. LastOperator.OperId = FromString<ui32>(value);
  285. } else if (key == "oprname") {
  286. LastOperator.Name = value;
  287. } else if (key == "descr") {
  288. LastOperator.Descr = value;
  289. } else if (key == "oprkind") {
  290. if (value == "r") {
  291. LastOperator.Kind = EOperKind::RightUnary;
  292. } else if (value == "l") {
  293. LastOperator.Kind = EOperKind::LeftUnary;
  294. }
  295. } else if (key == "oprleft") {
  296. if (value != "0") {
  297. auto typeIdPtr = TypeByName.FindPtr(value);
  298. Y_ENSURE(typeIdPtr);
  299. LastOperator.LeftType = *typeIdPtr;
  300. }
  301. } else if (key == "oprright") {
  302. if (value != "0") {
  303. auto typeIdPtr = TypeByName.FindPtr(value);
  304. Y_ENSURE(typeIdPtr);
  305. LastOperator.RightType = *typeIdPtr;
  306. }
  307. } else if (key == "oprresult") {
  308. auto typeIdPtr = TypeByName.FindPtr(value);
  309. Y_ENSURE(typeIdPtr);
  310. LastOperator.ResultType = *typeIdPtr;
  311. } else if (key == "oprcode") {
  312. LastCode = value;
  313. } else if (key == "oprnegate") {
  314. LastNegate = value;
  315. } else if (key == "oprcom") {
  316. LastCom = value;
  317. }
  318. }
  319. void OnFinish() override {
  320. if (IsSupported) {
  321. auto pos = LastCode.find('(');
  322. auto code = LastCode.substr(0, pos);
  323. auto procIdPtr = ProcByName.FindPtr(code);
  324. // skip operator if proc isn't builtin, e.g. path_contain_pt
  325. if (!procIdPtr) {
  326. IsSupported = false;
  327. } else {
  328. for (auto procId : *procIdPtr) {
  329. auto procPtr = Procs.FindPtr(procId);
  330. Y_ENSURE(procPtr);
  331. if (ValidateOperArgs(LastOperator, procPtr->ArgTypes, Types)) {
  332. Y_ENSURE(!LastOperator.ProcId);
  333. LastOperator.ProcId = procId;
  334. }
  335. }
  336. // can be missing for example jsonb - _text
  337. if (LastOperator.ProcId) {
  338. Y_ENSURE(!LastOperator.Name.empty());
  339. Operators[LastOperator.OperId] = LastOperator;
  340. }
  341. if (!LastCom.empty()) {
  342. LazyInfos[LastOperator.OperId].Com = LastCom;
  343. }
  344. if (!LastNegate.empty()) {
  345. LazyInfos[LastOperator.OperId].Negate = LastNegate;
  346. }
  347. }
  348. }
  349. LastOperator = TOperDesc();
  350. LastCode = "";
  351. LastNegate = "";
  352. LastCom = "";
  353. IsSupported = true;
  354. }
  355. private:
  356. TOperators& Operators;
  357. const THashMap<TString, ui32>& TypeByName;
  358. const TTypes& Types;
  359. const THashMap<TString, TVector<ui32>>& ProcByName;
  360. const TProcs& Procs;
  361. THashMap<ui32, TLazyOperInfo>& LazyInfos;
  362. TOperDesc LastOperator;
  363. bool IsSupported = true;
  364. TString LastCode;
  365. TString LastNegate;
  366. TString LastCom;
  367. };
  368. class TProcsParser : public TParser {
  369. public:
  370. TProcsParser(TProcs& procs, const THashMap<TString, ui32>& typeByName)
  371. : Procs(procs)
  372. , TypeByName(typeByName)
  373. {}
  374. void OnKey(const TString& key, const TString& value) override {
  375. if (key == "oid") {
  376. LastProc.ProcId = FromString<ui32>(value);
  377. } else if (key == "provariadic") {
  378. auto idPtr = TypeByName.FindPtr(value);
  379. Y_ENSURE(idPtr);
  380. LastProc.VariadicType = *idPtr;
  381. } else if (key == "descr") {
  382. LastProc.Descr = value;
  383. } else if (key == "prokind") {
  384. if (value == "f") {
  385. LastProc.Kind = EProcKind::Function;
  386. } else if (value == "a") {
  387. LastProc.Kind = EProcKind::Aggregate;
  388. } else if (value == "w") {
  389. LastProc.Kind = EProcKind::Window;
  390. } else {
  391. IsSupported = false;
  392. }
  393. } else if (key == "prorettype") {
  394. auto idPtr = TypeByName.FindPtr(value);
  395. Y_ENSURE(idPtr);
  396. LastProc.ResultType = *idPtr;
  397. } else if (key == "proname") {
  398. LastProc.Name = value;
  399. } else if (key == "prosrc") {
  400. LastProc.Src = value;
  401. } else if (key == "prolang") {
  402. if (value == "sql") {
  403. LastProc.Lang = LangSQL;
  404. } else if (value == "c") {
  405. LastProc.Lang = LangC;
  406. } else {
  407. IsSupported = false;
  408. }
  409. } else if (key == "proargtypes") {
  410. TVector<TString> strArgs;
  411. Split(value, " ", strArgs);
  412. LastProc.ArgTypes.reserve(strArgs.size());
  413. for (const auto& s : strArgs) {
  414. auto idPtr = TypeByName.FindPtr(s);
  415. Y_ENSURE(idPtr);
  416. LastProc.ArgTypes.push_back(*idPtr);
  417. }
  418. } else if (key == "proisstrict") {
  419. LastProc.IsStrict = (value == "t");
  420. } else if (key == "proretset") {
  421. LastProc.ReturnSet = (value == "t");
  422. } else if (key == "proallargtypes") {
  423. AllArgTypesStr = value;
  424. } else if (key == "proargmodes") {
  425. ArgModesStr = value;
  426. } else if (key == "proargnames") {
  427. ArgNamesStr = value;
  428. }
  429. }
  430. void OnFinish() override {
  431. if (IsSupported) {
  432. if (LastProc.VariadicType) {
  433. Y_ENSURE(!ArgModesStr.empty());
  434. }
  435. if (!ArgModesStr.empty()) {
  436. Y_ENSURE(ArgModesStr.front() == '{');
  437. Y_ENSURE(ArgModesStr.back() == '}');
  438. TVector<TString> modes;
  439. Split(ArgModesStr.substr(1, ArgModesStr.size() - 2), ",", modes);
  440. Y_ENSURE(modes.size() >= LastProc.ArgTypes.size());
  441. ui32 inputArgsCount = 0;
  442. bool startedVarArgs = false;
  443. bool startedOutArgs = false;
  444. for (size_t i = 0; i < modes.size(); ++i) {
  445. if (modes[i] == "i") {
  446. Y_ENSURE(!startedVarArgs && !startedOutArgs);
  447. inputArgsCount = i + 1;
  448. } else if (modes[i] == "o") {
  449. startedOutArgs = true;
  450. } else {
  451. Y_ENSURE(!startedVarArgs && !startedOutArgs);
  452. Y_ENSURE(modes[i] == "v");
  453. Y_ENSURE(LastProc.VariadicType);
  454. startedVarArgs = true;
  455. }
  456. }
  457. if (LastProc.VariadicType) {
  458. Y_ENSURE(LastProc.ArgTypes.size() > inputArgsCount);
  459. LastProc.VariadicArgType = LastProc.ArgTypes[inputArgsCount];
  460. Y_ENSURE(LastProc.VariadicArgType);
  461. }
  462. LastProc.ArgTypes.resize(inputArgsCount);
  463. }
  464. }
  465. if (IsSupported) {
  466. auto variadicDelta = LastProc.VariadicType ? 1 : 0;
  467. if (!ArgNamesStr.empty()) {
  468. Y_ENSURE(ArgNamesStr.front() == '{');
  469. Y_ENSURE(ArgNamesStr.back() == '}');
  470. TVector<TString> names;
  471. Split(ArgNamesStr.substr(1, ArgNamesStr.size() - 2), ",", names);
  472. Y_ENSURE(names.size() >= LastProc.ArgTypes.size() + variadicDelta);
  473. LastProc.OutputArgNames.insert(LastProc.OutputArgNames.begin(), names.begin() + LastProc.ArgTypes.size() + variadicDelta, names.end());
  474. if (LastProc.VariadicType) {
  475. LastProc.VariadicArgName = names[LastProc.ArgTypes.size()];
  476. }
  477. LastProc.InputArgNames.insert(LastProc.InputArgNames.begin(), names.begin(), names.begin() + LastProc.ArgTypes.size());
  478. }
  479. if (!AllArgTypesStr.empty()) {
  480. Y_ENSURE(!ArgModesStr.empty());
  481. Y_ENSURE(AllArgTypesStr.front() == '{');
  482. Y_ENSURE(AllArgTypesStr.back() == '}');
  483. TVector<TString> types;
  484. Split(AllArgTypesStr.substr(1, AllArgTypesStr.size() - 2), ",", types);
  485. Y_ENSURE(types.size() >= LastProc.ArgTypes.size() + variadicDelta);
  486. for (size_t i = LastProc.ArgTypes.size() + variadicDelta; i < types.size(); ++i) {
  487. auto idPtr = TypeByName.FindPtr(types[i]);
  488. Y_ENSURE(idPtr);
  489. LastProc.OutputArgTypes.push_back(*idPtr);
  490. }
  491. }
  492. }
  493. if (IsSupported) {
  494. Y_ENSURE(!LastProc.Name.empty());
  495. Procs[LastProc.ProcId] = LastProc;
  496. }
  497. IsSupported = true;
  498. LastProc = TProcDesc();
  499. AllArgTypesStr = "";
  500. ArgModesStr = "";
  501. ArgNamesStr = "";
  502. }
  503. private:
  504. TProcs& Procs;
  505. const THashMap<TString, ui32>& TypeByName;
  506. TProcDesc LastProc;
  507. bool IsSupported = true;
  508. TString AllArgTypesStr;
  509. TString ArgModesStr;
  510. TString ArgNamesStr;
  511. };
  512. struct TLazyTypeInfo {
  513. TString ElementType;
  514. TString InFunc;
  515. TString OutFunc;
  516. TString SendFunc;
  517. TString ReceiveFunc;
  518. TString ModInFunc;
  519. TString ModOutFunc;
  520. TString SubscriptFunc;
  521. };
  522. class TTypesParser : public TParser {
  523. public:
  524. TTypesParser(TTypes& types, THashMap<ui32, TLazyTypeInfo>& lazyInfos)
  525. : Types(types)
  526. , LazyInfos(lazyInfos)
  527. {}
  528. void OnKey(const TString& key, const TString& value) override {
  529. if (key == "oid") {
  530. LastType.TypeId = FromString<ui32>(value);
  531. } else if (key == "array_type_oid") {
  532. LastType.ArrayTypeId = FromString<ui32>(value);
  533. } else if (key == "descr") {
  534. LastType.Descr = value;
  535. } else if (key == "typname") {
  536. LastType.Name = value;
  537. } else if (key == "typcategory") {
  538. Y_ENSURE(value.size() == 1);
  539. LastType.Category = value[0];
  540. } else if (key == "typlen") {
  541. if (value == "NAMEDATALEN") {
  542. LastType.TypeLen = 64;
  543. } else if (value == "SIZEOF_POINTER") {
  544. LastType.TypeLen = 8;
  545. } else {
  546. LastType.TypeLen = FromString<i32>(value);
  547. }
  548. } else if (key == "typalign") {
  549. if (value == "ALIGNOF_POINTER") {
  550. LastType.TypeAlign = 'i'; // doesn't matter for pointers
  551. } else {
  552. Y_ENSURE(value.size() == 1);
  553. LastType.TypeAlign = value[0];
  554. }
  555. } else if (key == "typdelim") {
  556. Y_ENSURE(value.size() == 1);
  557. LastType.TypeDelim = value[0];
  558. } else if (key == "typtype") {
  559. Y_ENSURE(value.size() == 1);
  560. const auto typType = value[0];
  561. LastType.TypType =
  562. (typType == 'b') ? ETypType::Base :
  563. (typType == 'c') ? ETypType::Composite :
  564. (typType == 'd') ? ETypType::Domain :
  565. (typType == 'e') ? ETypType::Enum :
  566. (typType == 'm') ? ETypType::Multirange :
  567. (typType == 'p') ? ETypType::Pseudo :
  568. (typType == 'r') ? ETypType::Range :
  569. ythrow yexception() << "Unknown typtype value: " << value;
  570. } else if (key == "typcollation") {
  571. // hardcode collations for now. There are only three of 'em in .dat file
  572. LastType.TypeCollation =
  573. (value == "default") ? DefaultCollationOid :
  574. (value == "C") ? C_CollationOid :
  575. (value == "POSIX") ? PosixCollationOid :
  576. ythrow yexception() << "Unknown typcollation value: " << value;
  577. } else if (key == "typelem") {
  578. LastLazyTypeInfo.ElementType = value; // resolve later
  579. } else if (key == "typinput") {
  580. LastLazyTypeInfo.InFunc = value; // resolve later
  581. } else if (key == "typoutput") {
  582. LastLazyTypeInfo.OutFunc = value; // resolve later
  583. } else if (key == "typsend") {
  584. LastLazyTypeInfo.SendFunc = value; // resolve later
  585. } else if (key == "typreceive") {
  586. LastLazyTypeInfo.ReceiveFunc = value; // resolve later
  587. } else if (key == "typmodin") {
  588. LastLazyTypeInfo.ModInFunc = value; // resolve later
  589. } else if (key == "typmodout") {
  590. LastLazyTypeInfo.ModOutFunc = value; // resolve later
  591. } else if (key == "typsubscript") {
  592. LastLazyTypeInfo.SubscriptFunc = value; // resolve later
  593. } else if (key == "typbyval") {
  594. if (value == "f") {
  595. LastType.PassByValue = false;
  596. } else if (value == "t" || value == "FLOAT8PASSBYVAL") {
  597. LastType.PassByValue = true;
  598. } else {
  599. ythrow yexception() << "Unknown typbyval value: " << value;
  600. }
  601. } else if (key == "typispreferred") {
  602. LastType.IsPreferred = (value == "t");
  603. }
  604. }
  605. void OnFinish() override {
  606. Y_ENSURE(!LastType.Name.empty());
  607. Y_ENSURE(LastType.TypeLen != 0);
  608. if (LastType.TypeLen < 0 || LastType.TypeLen > 8) {
  609. Y_ENSURE(!LastType.PassByValue);
  610. }
  611. Types[LastType.TypeId] = LastType;
  612. if (LastType.ArrayTypeId) {
  613. auto arrayType = LastType;
  614. arrayType.Name = "_" + arrayType.Name;
  615. arrayType.ElementTypeId = arrayType.TypeId;
  616. arrayType.TypeId = LastType.ArrayTypeId;
  617. arrayType.PassByValue = false;
  618. arrayType.TypeLen = -1;
  619. Types[LastType.ArrayTypeId] = arrayType;
  620. }
  621. LazyInfos[LastType.TypeId] = LastLazyTypeInfo;
  622. if (LastType.ArrayTypeId) {
  623. LastLazyTypeInfo.OutFunc = "array_out";
  624. LastLazyTypeInfo.InFunc = "array_in";
  625. LastLazyTypeInfo.SendFunc = "array_send";
  626. LastLazyTypeInfo.ReceiveFunc = "array_recv";
  627. LastLazyTypeInfo.ElementType = "";
  628. LazyInfos[LastType.ArrayTypeId] = LastLazyTypeInfo;
  629. }
  630. LastType = TTypeDesc();
  631. LastLazyTypeInfo = TLazyTypeInfo();
  632. }
  633. private:
  634. TTypes& Types;
  635. THashMap<ui32, TLazyTypeInfo>& LazyInfos;
  636. TTypeDesc LastType;
  637. TLazyTypeInfo LastLazyTypeInfo;
  638. };
  639. class TCastsParser : public TParser {
  640. public:
  641. TCastsParser(TCasts& casts, const THashMap<TString, ui32>& typeByName, const TTypes& types,
  642. const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs)
  643. : Casts(casts)
  644. , TypeByName(typeByName)
  645. , Types(types)
  646. , ProcByName(procByName)
  647. , Procs(procs)
  648. {}
  649. void OnKey(const TString& key, const TString& value) override {
  650. if (key == "castsource") {
  651. auto typePtr = TypeByName.FindPtr(value);
  652. Y_ENSURE(typePtr);
  653. LastCast.SourceId = *typePtr;
  654. } else if (key == "casttarget") {
  655. auto typePtr = TypeByName.FindPtr(value);
  656. Y_ENSURE(typePtr);
  657. LastCast.TargetId = *typePtr;
  658. } else if (key == "castfunc") {
  659. if (value != "0") {
  660. if (value.Contains('(')) {
  661. auto pos1 = value.find('(');
  662. auto pos2 = value.find(')');
  663. auto pos3 = value.find(',');
  664. Y_ENSURE(pos1 != TString::npos);
  665. Y_ENSURE(pos2 != TString::npos);
  666. if (pos3 != TString::npos) {
  667. pos2 = pos3;
  668. }
  669. auto funcName = value.substr(0, pos1);
  670. auto inputType = value.substr(pos1 + 1, pos2 - pos1 - 1);
  671. auto inputTypeIdPtr = TypeByName.FindPtr(inputType);
  672. Y_ENSURE(inputTypeIdPtr);
  673. auto procIdPtr = ProcByName.FindPtr(funcName);
  674. Y_ENSURE(procIdPtr);
  675. bool found = false;
  676. for (const auto& procId : *procIdPtr) {
  677. auto procPtr = Procs.FindPtr(procId);
  678. Y_ENSURE(procPtr);
  679. if (procPtr->ArgTypes.size() < 1) {
  680. continue;
  681. }
  682. if (IsCompatibleTo(*inputTypeIdPtr, procPtr->ArgTypes[0], Types)) {
  683. LastCast.FunctionId = procPtr->ProcId;
  684. found = true;
  685. break;
  686. }
  687. }
  688. if (!found) {
  689. // e.g. convert circle to 12-vertex polygon, used sql proc
  690. IsSupported = false;
  691. }
  692. } else {
  693. auto procIdPtr = ProcByName.FindPtr(value);
  694. Y_ENSURE(procIdPtr);
  695. Y_ENSURE(procIdPtr->size() == 1);
  696. LastCast.FunctionId = procIdPtr->at(0);
  697. }
  698. }
  699. } else if (key == "castmethod") {
  700. if (value == "f") {
  701. LastCast.Method = ECastMethod::Function;
  702. } else if (value == "i") {
  703. LastCast.Method = ECastMethod::InOut;
  704. } else if (value == "b") {
  705. LastCast.Method = ECastMethod::Binary;
  706. } else {
  707. ythrow yexception() << "Unknown castmethod value: " << value;
  708. }
  709. } else if (key == "castcontext") {
  710. Y_ENSURE(value.size() == 1);
  711. const auto castCtx = value[0];
  712. LastCast.CoercionCode =
  713. (castCtx == 'i') ? ECoercionCode::Implicit :
  714. (castCtx == 'a') ? ECoercionCode::Assignment :
  715. (castCtx == 'e') ? ECoercionCode::Explicit :
  716. ythrow yexception() << "Unknown castcontext value: " << value;
  717. }
  718. }
  719. void OnFinish() override {
  720. if (IsSupported) {
  721. auto id = 1 + Casts.size();
  722. Casts[id] = LastCast;
  723. }
  724. LastCast = TCastDesc();
  725. IsSupported = true;
  726. }
  727. private:
  728. TCasts& Casts;
  729. const THashMap<TString, ui32>& TypeByName;
  730. const TTypes& Types;
  731. const THashMap<TString, TVector<ui32>>& ProcByName;
  732. const TProcs& Procs;
  733. TCastDesc LastCast;
  734. bool IsSupported = true;
  735. };
  736. class TAggregationsParser : public TParser {
  737. public:
  738. TAggregationsParser(TAggregations& aggregations, const THashMap<TString, ui32>& typeByName,
  739. const TTypes& types, const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs)
  740. : Aggregations(aggregations)
  741. , TypeByName(typeByName)
  742. , Types(types)
  743. , ProcByName(procByName)
  744. , Procs(procs)
  745. {}
  746. void OnKey(const TString& key, const TString& value) override {
  747. Y_UNUSED(ProcByName);
  748. if (key == "aggtranstype") {
  749. auto typeId = TypeByName.FindPtr(value);
  750. Y_ENSURE(typeId);
  751. LastAggregation.TransTypeId = *typeId;
  752. } else if (key == "aggfnoid") {
  753. LastOid = value;
  754. } else if (key == "aggtransfn") {
  755. LastTransFunc = value;
  756. } else if (key == "aggfinalfn") {
  757. LastFinalFunc = value;
  758. } else if (key == "aggcombinefn") {
  759. LastCombineFunc = value;
  760. } else if (key == "aggserialfn") {
  761. LastSerializeFunc = value;
  762. } else if (key == "aggdeserialfn") {
  763. LastDeserializeFunc = value;
  764. } else if (key == "aggkind") {
  765. if (value == "n") {
  766. LastAggregation.Kind = EAggKind::Normal;
  767. } else if (value == "o") {
  768. LastAggregation.Kind = EAggKind::OrderedSet;
  769. } else if (value == "h") {
  770. LastAggregation.Kind = EAggKind::Hypothetical;
  771. } else {
  772. ythrow yexception() << "Unknown aggkind value: " << value;
  773. }
  774. } else if (key == "agginitval") {
  775. LastAggregation.InitValue = value;
  776. } else if (key == "aggfinalextra") {
  777. LastAggregation.FinalExtra = (value == "t");;
  778. } else if (key == "aggnumdirectargs") {
  779. LastAggregation.NumDirectArgs = FromString<ui32>(value);
  780. }
  781. }
  782. void OnFinish() override {
  783. if (IsSupported) {
  784. if (FillSupported()) {
  785. Aggregations[LastAggregation.AggId] = LastAggregation;
  786. }
  787. }
  788. LastAggregation = TAggregateDesc();
  789. IsSupported = true;
  790. LastOid = "";
  791. LastTransFunc = "";
  792. LastFinalFunc = "";
  793. LastCombineFunc = "";
  794. LastSerializeFunc = "";
  795. LastDeserializeFunc = "";
  796. }
  797. bool FillSupported() {
  798. Y_ENSURE(LastAggregation.TransTypeId);
  799. Y_ENSURE(LastOid);
  800. Y_ENSURE(LastTransFunc);
  801. auto transFuncIdsPtr = ProcByName.FindPtr(LastTransFunc);
  802. if (!transFuncIdsPtr) {
  803. // e.g. variadic ordered_set_transition_multi
  804. return false;
  805. }
  806. for (const auto id : *transFuncIdsPtr) {
  807. auto procPtr = Procs.FindPtr(id);
  808. Y_ENSURE(procPtr);
  809. if (procPtr->ArgTypes.size() >= 1 &&
  810. IsCompatibleTo(LastAggregation.TransTypeId, procPtr->ArgTypes[0], Types)) {
  811. Y_ENSURE(!LastAggregation.TransFuncId);
  812. LastAggregation.TransFuncId = id;
  813. }
  814. }
  815. Y_ENSURE(LastAggregation.TransFuncId);
  816. // oid format: name(arg1,arg2...)
  817. auto pos1 = LastOid.find('(');
  818. if (pos1 != TString::npos) {
  819. LastAggregation.Name = LastOid.substr(0, pos1);
  820. auto pos = pos1 + 1;
  821. for (;;) {
  822. auto nextPos = Min(LastOid.find(',', pos), LastOid.find(')', pos));
  823. Y_ENSURE(nextPos != TString::npos);
  824. if (pos == nextPos) {
  825. break;
  826. }
  827. auto arg = LastOid.substr(pos, nextPos - pos);
  828. auto argTypeId = TypeByName.FindPtr(arg);
  829. Y_ENSURE(argTypeId);
  830. LastAggregation.ArgTypes.push_back(*argTypeId);
  831. pos = nextPos;
  832. if (LastOid[pos] == ')') {
  833. break;
  834. } else {
  835. ++pos;
  836. }
  837. }
  838. } else {
  839. // no signature in oid, use transfunc
  840. LastAggregation.Name = LastOid;
  841. auto procPtr = Procs.FindPtr(LastAggregation.TransFuncId);
  842. Y_ENSURE(procPtr);
  843. LastAggregation.ArgTypes = procPtr->ArgTypes;
  844. Y_ENSURE(LastAggregation.ArgTypes.size() >= 1);
  845. Y_ENSURE(IsCompatibleTo(LastAggregation.TransTypeId, LastAggregation.ArgTypes[0], Types));
  846. LastAggregation.ArgTypes.erase(LastAggregation.ArgTypes.begin());
  847. }
  848. Y_ENSURE(!LastAggregation.Name.empty());
  849. auto funcIdsPtr = ProcByName.FindPtr(LastAggregation.Name);
  850. Y_ENSURE(funcIdsPtr);
  851. if (funcIdsPtr->size() == 1) {
  852. LastAggregation.AggId = funcIdsPtr->front();
  853. } else {
  854. for (const auto id : *funcIdsPtr) {
  855. auto procPtr = Procs.FindPtr(id);
  856. Y_ENSURE(procPtr);
  857. if (ValidateArgs(procPtr->ArgTypes, LastAggregation.ArgTypes, Types, procPtr->VariadicType)) {
  858. LastAggregation.AggId = id;
  859. break;
  860. }
  861. }
  862. }
  863. Y_ENSURE(LastAggregation.AggId);
  864. if (!ResolveFunc(LastFinalFunc, LastAggregation.FinalFuncId, 1)) {
  865. return false;
  866. }
  867. if (!ResolveFunc(LastCombineFunc, LastAggregation.CombineFuncId, 2)) {
  868. return false;
  869. }
  870. if (!ResolveFunc(LastSerializeFunc, LastAggregation.SerializeFuncId, 1)) {
  871. return false;
  872. }
  873. if (!ResolveFunc(LastDeserializeFunc, LastAggregation.DeserializeFuncId, 0)) {
  874. return false;
  875. }
  876. return true;
  877. }
  878. bool ResolveFunc(const TString& name, ui32& funcId, ui32 stateArgsCount) {
  879. if (name) {
  880. auto funcIdsPtr = ProcByName.FindPtr(name);
  881. if (!funcIdsPtr) {
  882. return false;
  883. }
  884. if (!stateArgsCount) {
  885. Y_ENSURE(funcIdsPtr->size() == 1);
  886. }
  887. for (const auto id : *funcIdsPtr) {
  888. auto procPtr = Procs.FindPtr(id);
  889. Y_ENSURE(procPtr);
  890. bool found = true;
  891. if (stateArgsCount > 0 && procPtr->ArgTypes.size() == stateArgsCount) {
  892. for (ui32 i = 0; i < stateArgsCount; ++i) {
  893. if (!IsCompatibleTo(LastAggregation.TransTypeId, procPtr->ArgTypes[i], Types)) {
  894. found = false;
  895. break;
  896. }
  897. }
  898. }
  899. if (found) {
  900. Y_ENSURE(!funcId);
  901. funcId = id;
  902. }
  903. }
  904. Y_ENSURE(funcId);
  905. }
  906. return true;
  907. }
  908. private:
  909. TAggregations& Aggregations;
  910. const THashMap<TString, ui32>& TypeByName;
  911. const TTypes& Types;
  912. const THashMap<TString, TVector<ui32>>& ProcByName;
  913. const TProcs& Procs;
  914. TAggregateDesc LastAggregation;
  915. bool IsSupported = true;
  916. TString LastOid;
  917. TString LastTransFunc;
  918. TString LastFinalFunc;
  919. TString LastCombineFunc;
  920. TString LastSerializeFunc;
  921. TString LastDeserializeFunc;
  922. };
  923. class TOpFamiliesParser : public TParser {
  924. public:
  925. TOpFamiliesParser(TOpFamilies& opFamilies)
  926. : OpFamilies(opFamilies)
  927. {}
  928. void OnKey(const TString& key, const TString& value) override {
  929. if (key == "oid") {
  930. LastOpfId = FromString<ui32>(value);
  931. } else if (key == "opfmethod") {
  932. if (value == "btree" || value == "hash") {
  933. LastOpfMethod = value;
  934. } else {
  935. IsSupported = false;
  936. }
  937. } else if (key == "opfname") {
  938. LastOpfName = value;
  939. }
  940. }
  941. void OnFinish() override {
  942. if (IsSupported) {
  943. Y_ENSURE(LastOpfId != InvalidOid);
  944. // opfamily references have opf_method/opf_name format in PG catalogs
  945. TOpFamilyDesc desc;
  946. desc.Name = LastOpfMethod + "/" + LastOpfName;
  947. desc.FamilyId = LastOpfId;
  948. Y_ENSURE(OpFamilies.emplace(desc.Name, desc).second);
  949. }
  950. IsSupported = true;
  951. LastOpfId = InvalidOid;
  952. LastOpfMethod.clear();
  953. LastOpfName.clear();
  954. }
  955. private:
  956. TOpFamilies& OpFamilies;
  957. ui32 LastOpfId = InvalidOid;
  958. TString LastOpfMethod;
  959. TString LastOpfName;
  960. bool IsSupported = true;
  961. };
  962. class TOpClassesParser : public TParser {
  963. public:
  964. TOpClassesParser(TOpClasses& opClasses, const THashMap<TString, ui32>& typeByName,
  965. const TOpFamilies &opFamilies)
  966. : OpClasses(opClasses)
  967. , TypeByName(typeByName)
  968. , OpFamilies(opFamilies)
  969. {}
  970. void OnKey(const TString& key, const TString& value) override {
  971. if (key == "opcmethod") {
  972. if (value == "btree") {
  973. LastOpClass.Method = EOpClassMethod::Btree;
  974. } else if (value == "hash") {
  975. LastOpClass.Method = EOpClassMethod::Hash;
  976. } else {
  977. IsSupported = false;
  978. }
  979. } else if (key == "opcintype") {
  980. auto idPtr = TypeByName.FindPtr(value);
  981. Y_ENSURE(idPtr);
  982. LastOpClass.TypeId = *idPtr;
  983. } else if (key == "opcname") {
  984. LastOpClass.Name = value;
  985. } else if (key == "opcfamily") {
  986. LastOpClass.Family = value;
  987. auto opFamilyPtr = OpFamilies.FindPtr(value);
  988. if (opFamilyPtr) {
  989. LastOpClass.FamilyId = opFamilyPtr->FamilyId;
  990. } else {
  991. IsSupported = false;
  992. }
  993. } else if (key == "opcdefault") {
  994. IsDefault = (value[0] != 'f');
  995. }
  996. }
  997. void OnFinish() override {
  998. // Only default opclasses are used so far
  999. if (IsSupported && IsDefault) {
  1000. Y_ENSURE(!LastOpClass.Name.empty());
  1001. const auto key = std::make_pair(LastOpClass.Method, LastOpClass.TypeId);
  1002. if (OpClasses.contains(key)) {
  1003. throw yexception() << "Duplicate opclass: (" << (key.first == EOpClassMethod::Btree ? "btree" : "hash")
  1004. << ", " << key.second << ")";
  1005. }
  1006. OpClasses[key] = LastOpClass;
  1007. }
  1008. IsSupported = true;
  1009. IsDefault = true;
  1010. LastOpClass = TOpClassDesc();
  1011. }
  1012. private:
  1013. TOpClasses& OpClasses;
  1014. const THashMap<TString, ui32>& TypeByName;
  1015. const TOpFamilies OpFamilies;
  1016. TOpClassDesc LastOpClass;
  1017. bool IsSupported = true;
  1018. bool IsDefault = true;
  1019. };
  1020. class TAmOpsParser : public TParser {
  1021. public:
  1022. TAmOpsParser(TAmOps& amOps, const THashMap<TString, ui32>& typeByName, const TTypes& types,
  1023. const THashMap<TString, TVector<ui32>>& operatorsByName, const TOperators& operators,
  1024. const TOpFamilies &opFamilies)
  1025. : AmOps(amOps)
  1026. , TypeByName(typeByName)
  1027. , Types(types)
  1028. , OperatorsByName(operatorsByName)
  1029. , Operators(operators)
  1030. , OpFamilies(opFamilies)
  1031. {}
  1032. void OnKey(const TString& key, const TString& value) override {
  1033. if (key == "amopfamily") {
  1034. LastAmOp.Family = value;
  1035. auto opFamilyPtr = OpFamilies.FindPtr(value);
  1036. if (opFamilyPtr) {
  1037. LastAmOp.FamilyId = opFamilyPtr->FamilyId;
  1038. } else {
  1039. IsSupported = false;
  1040. }
  1041. } else if (key == "amoplefttype") {
  1042. auto leftTypePtr = TypeByName.FindPtr(value);
  1043. Y_ENSURE(leftTypePtr);
  1044. LastAmOp.LeftType = *leftTypePtr;
  1045. } else if (key == "amoprighttype") {
  1046. auto rightTypePtr = TypeByName.FindPtr(value);
  1047. Y_ENSURE(rightTypePtr);
  1048. LastAmOp.RightType = *rightTypePtr;
  1049. } else if (key == "amopstrategy") {
  1050. LastAmOp.Strategy = FromString<ui32>(value);
  1051. } else if (key == "amopopr") {
  1052. auto pos = value.find('(');
  1053. Y_ENSURE(pos != TString::npos);
  1054. LastOp = value.substr(0, pos);
  1055. }
  1056. }
  1057. void OnFinish() override {
  1058. if (IsSupported) {
  1059. auto operIdPtr = OperatorsByName.FindPtr(LastOp);
  1060. Y_ENSURE(operIdPtr);
  1061. for (const auto& id : *operIdPtr) {
  1062. const auto& d = Operators.FindPtr(id);
  1063. Y_ENSURE(d);
  1064. if (d->Kind == EOperKind::Binary &&
  1065. IsCompatibleTo(LastAmOp.LeftType, d->LeftType, Types) &&
  1066. IsCompatibleTo(LastAmOp.RightType, d->RightType, Types)) {
  1067. Y_ENSURE(!LastAmOp.OperId);
  1068. LastAmOp.OperId = d->OperId;
  1069. }
  1070. }
  1071. Y_ENSURE(LastAmOp.OperId);
  1072. AmOps[std::make_tuple(LastAmOp.FamilyId, LastAmOp.Strategy, LastAmOp.LeftType, LastAmOp.RightType)] = LastAmOp;
  1073. }
  1074. LastAmOp = TAmOpDesc();
  1075. LastOp = "";
  1076. IsSupported = true;
  1077. }
  1078. private:
  1079. TAmOps& AmOps;
  1080. const THashMap<TString, ui32>& TypeByName;
  1081. const TTypes& Types;
  1082. const THashMap<TString, TVector<ui32>>& OperatorsByName;
  1083. const TOperators& Operators;
  1084. const TOpFamilies& OpFamilies;
  1085. TAmOpDesc LastAmOp;
  1086. TString LastOp;
  1087. bool IsSupported = true;
  1088. };
  1089. class TAmsParser : public TParser {
  1090. public:
  1091. TAmsParser(TAms& ams) : Ams_(ams) {}
  1092. void OnKey(const TString& key, const TString& value) override {
  1093. if (key == "oid") {
  1094. CurrDesc_.Oid = FromString<ui32>(value);
  1095. } else if (key == "descr") {
  1096. CurrDesc_.Descr = value;
  1097. } else if (key == "amname") {
  1098. CurrDesc_.AmName = value;
  1099. } else if (key == "amtype") {
  1100. Y_ENSURE(value.size() == 1);
  1101. if ((char)EAmType::Index == value[0]) {
  1102. CurrDesc_.AmType = EAmType::Index;
  1103. } else if ((char)EAmType::Table == value[0]) {
  1104. CurrDesc_.AmType = EAmType::Table;
  1105. } else {
  1106. Y_ENSURE(false, "Expected correct AmType");
  1107. }
  1108. }
  1109. }
  1110. void OnFinish() override {
  1111. Ams_[CurrDesc_.Oid] = std::move(CurrDesc_);
  1112. CurrDesc_ = TAmDesc();
  1113. }
  1114. private:
  1115. TAmDesc CurrDesc_;
  1116. TAms& Ams_;
  1117. };
  1118. class TAmProcsParser : public TParser {
  1119. public:
  1120. TAmProcsParser(TAmProcs& amProcs, const THashMap<TString, ui32>& typeByName,
  1121. const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs,
  1122. const TOpFamilies& opFamilies)
  1123. : AmProcs(amProcs)
  1124. , TypeByName(typeByName)
  1125. , ProcByName(procByName)
  1126. , Procs(procs)
  1127. , OpFamilies(opFamilies)
  1128. {}
  1129. void OnKey(const TString& key, const TString& value) override {
  1130. if (key == "amprocfamily") {
  1131. LastAmProc.Family = value;
  1132. auto opFamilyPtr = OpFamilies.FindPtr(value);
  1133. if (opFamilyPtr) {
  1134. LastAmProc.FamilyId = opFamilyPtr->FamilyId;
  1135. } else {
  1136. IsSupported = false;
  1137. }
  1138. } else if (key == "amproclefttype") {
  1139. auto leftTypePtr = TypeByName.FindPtr(value);
  1140. Y_ENSURE(leftTypePtr);
  1141. LastAmProc.LeftType = *leftTypePtr;
  1142. } else if (key == "amprocrighttype") {
  1143. auto rightTypePtr = TypeByName.FindPtr(value);
  1144. Y_ENSURE(rightTypePtr);
  1145. LastAmProc.RightType = *rightTypePtr;
  1146. } else if (key == "amprocnum") {
  1147. LastAmProc.ProcNum = FromString<ui32>(value);
  1148. } else if (key == "amproc") {
  1149. LastName = value;
  1150. }
  1151. }
  1152. void OnFinish() override {
  1153. if (IsSupported) {
  1154. if (LastName.find('(') == TString::npos) {
  1155. auto procIdPtr = ProcByName.FindPtr(LastName);
  1156. Y_ENSURE(procIdPtr);
  1157. for (const auto& id : *procIdPtr) {
  1158. const auto& d = Procs.FindPtr(id);
  1159. Y_ENSURE(d);
  1160. Y_ENSURE(!LastAmProc.ProcId);
  1161. LastAmProc.ProcId = d->ProcId;
  1162. }
  1163. Y_ENSURE(LastAmProc.ProcId);
  1164. AmProcs[std::make_tuple(LastAmProc.FamilyId, LastAmProc.ProcNum, LastAmProc.LeftType, LastAmProc.RightType)] = LastAmProc;
  1165. }
  1166. }
  1167. LastAmProc = TAmProcDesc();
  1168. LastName = "";
  1169. IsSupported = true;
  1170. }
  1171. private:
  1172. TAmProcs& AmProcs;
  1173. const THashMap<TString, ui32>& TypeByName;
  1174. const THashMap<TString, TVector<ui32>>& ProcByName;
  1175. const TProcs& Procs;
  1176. const TOpFamilies& OpFamilies;
  1177. TAmProcDesc LastAmProc;
  1178. TString LastName;
  1179. bool IsSupported = true;
  1180. };
  1181. class TConversionsParser : public TParser {
  1182. public:
  1183. TConversionsParser(TConversions& conversions, const THashMap<TString, TVector<ui32>>& procByName)
  1184. : Conversions(conversions)
  1185. , ProcByName(procByName)
  1186. {}
  1187. void OnKey(const TString& key, const TString& value) override {
  1188. if (key == "oid") {
  1189. LastConversion.ConversionId = FromString<ui32>(value);
  1190. } else if (key == "conforencoding") {
  1191. Y_ENSURE(value.StartsWith("PG_"));
  1192. LastConversion.From = value.substr(3);
  1193. } else if (key == "descr") {
  1194. LastConversion.Descr = value;
  1195. } else if (key == "contoencoding") {
  1196. Y_ENSURE(value.StartsWith("PG_"));
  1197. LastConversion.To = value.substr(3);
  1198. } else if (key == "conproc") {
  1199. auto found = ProcByName.FindPtr(value);
  1200. if (found && found->size() == 1) {
  1201. LastConversion.ProcId = found->front();
  1202. }
  1203. }
  1204. }
  1205. void OnFinish() override {
  1206. if (LastConversion.ProcId) {
  1207. Conversions[std::make_pair(LastConversion.From, LastConversion.To)] = LastConversion;
  1208. }
  1209. LastConversion = TConversionDesc();
  1210. }
  1211. private:
  1212. TConversions& Conversions;
  1213. const THashMap<TString, TVector<ui32>>& ProcByName;
  1214. TConversionDesc LastConversion;
  1215. };
  1216. class TLanguagesParser : public TParser {
  1217. public:
  1218. TLanguagesParser(TLanguages& languages)
  1219. : Languages(languages)
  1220. {}
  1221. void OnKey(const TString& key, const TString& value) override {
  1222. if (key == "oid") {
  1223. LastLanguage.LangId = FromString<ui32>(value);
  1224. } else if (key == "lanname") {
  1225. LastLanguage.Name = value;
  1226. } else if (key == "descr") {
  1227. LastLanguage.Descr = value;
  1228. }
  1229. }
  1230. void OnFinish() override {
  1231. Languages[LastLanguage.LangId] = LastLanguage;
  1232. LastLanguage = TLanguageDesc();
  1233. }
  1234. private:
  1235. TLanguages& Languages;
  1236. TLanguageDesc LastLanguage;
  1237. };
  1238. TOperators ParseOperators(const TString& dat, const THashMap<TString, ui32>& typeByName,
  1239. const TTypes& types, const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs, THashMap<ui32, TLazyOperInfo>& lazyInfos) {
  1240. TOperators ret;
  1241. TOperatorsParser parser(ret, typeByName, types, procByName, procs, lazyInfos);
  1242. parser.Do(dat);
  1243. return ret;
  1244. }
  1245. ui32 FindOperator(const THashMap<TString, TVector<ui32>>& operatorsByName, const THashMap<TString, ui32>& typeByName, TOperators& operators, const TString& signature) {
  1246. auto pos1 = signature.find('(');
  1247. auto pos2 = signature.find(')');
  1248. Y_ENSURE(pos1 != TString::npos && pos1 > 0);
  1249. Y_ENSURE(pos2 != TString::npos && pos2 > pos1);
  1250. auto name = signature.substr(0, pos1);
  1251. auto operIdsPtr = operatorsByName.FindPtr(name);
  1252. Y_ENSURE(operIdsPtr);
  1253. TVector<TString> strArgs;
  1254. Split(signature.substr(pos1 + 1, pos2 - pos1 - 1), ",", strArgs);
  1255. Y_ENSURE(strArgs.size() >= 1 && strArgs.size() <= 2);
  1256. TVector<ui32> argTypes;
  1257. for (const auto& str : strArgs) {
  1258. auto typePtr = typeByName.FindPtr(str);
  1259. Y_ENSURE(typePtr);
  1260. argTypes.push_back(*typePtr);
  1261. }
  1262. for (const auto& operId : *operIdsPtr) {
  1263. auto operPtr = operators.FindPtr(operId);
  1264. Y_ENSURE(operPtr);
  1265. if (argTypes.size() == 1) {
  1266. if (operPtr->RightType != argTypes[0]) {
  1267. continue;
  1268. }
  1269. } else {
  1270. if (operPtr->LeftType != argTypes[0]) {
  1271. continue;
  1272. }
  1273. if (operPtr->RightType != argTypes[1]) {
  1274. continue;
  1275. }
  1276. }
  1277. return operId;
  1278. }
  1279. // for example, some operators are based on SQL system_functions.sql
  1280. return 0;
  1281. }
  1282. void ApplyLazyOperInfos(TOperators& operators, const THashMap<TString, TVector<ui32>>& operatorsByName, const THashMap<TString, ui32>& typeByName, const THashMap<ui32, TLazyOperInfo>& lazyInfos) {
  1283. for (const auto& x : lazyInfos) {
  1284. if (!x.second.Com.empty()) {
  1285. operators[x.first].ComId = FindOperator(operatorsByName, typeByName, operators, x.second.Com);
  1286. }
  1287. if (!x.second.Negate.empty()) {
  1288. operators[x.first].NegateId = FindOperator(operatorsByName, typeByName, operators, x.second.Negate);
  1289. }
  1290. }
  1291. }
  1292. TAggregations ParseAggregations(const TString& dat, const THashMap<TString, ui32>& typeByName,
  1293. const TTypes& types, const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs) {
  1294. TAggregations ret;
  1295. TAggregationsParser parser(ret, typeByName, types, procByName, procs);
  1296. parser.Do(dat);
  1297. return ret;
  1298. }
  1299. TProcs ParseProcs(const TString& dat, const THashMap<TString, ui32>& typeByName) {
  1300. TProcs ret;
  1301. TProcsParser parser(ret, typeByName);
  1302. parser.Do(dat);
  1303. return ret;
  1304. }
  1305. TTypes ParseTypes(const TString& dat, THashMap<ui32, TLazyTypeInfo>& lazyInfos) {
  1306. TTypes ret;
  1307. TTypesParser parser(ret, lazyInfos);
  1308. parser.Do(dat);
  1309. return ret;
  1310. }
  1311. TCasts ParseCasts(const TString& dat, const THashMap<TString, ui32>& typeByName, const TTypes& types,
  1312. const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs) {
  1313. TCasts ret;
  1314. TCastsParser parser(ret, typeByName, types, procByName, procs);
  1315. parser.Do(dat);
  1316. return ret;
  1317. }
  1318. TOpFamilies ParseOpFamilies(const TString& dat) {
  1319. TOpFamilies ret;
  1320. TOpFamiliesParser parser(ret);
  1321. parser.Do(dat);
  1322. return ret;
  1323. }
  1324. TOpClasses ParseOpClasses(const TString& dat, const THashMap<TString, ui32>& typeByName,
  1325. const TOpFamilies& opFamilies) {
  1326. TOpClasses ret;
  1327. TOpClassesParser parser(ret, typeByName, opFamilies);
  1328. parser.Do(dat);
  1329. return ret;
  1330. }
  1331. TAmOps ParseAmOps(const TString& dat, const THashMap<TString, ui32>& typeByName, const TTypes& types,
  1332. const THashMap<TString, TVector<ui32>>& operatorsByName, const TOperators& operators,
  1333. const TOpFamilies& opFamilies) {
  1334. TAmOps ret;
  1335. TAmOpsParser parser(ret, typeByName, types, operatorsByName, operators, opFamilies);
  1336. parser.Do(dat);
  1337. return ret;
  1338. }
  1339. TAmProcs ParseAmProcs(const TString& dat, const THashMap<TString, ui32>& typeByName,
  1340. const THashMap<TString, TVector<ui32>>& procByName, const TProcs& procs,
  1341. const TOpFamilies& opFamilies) {
  1342. TAmProcs ret;
  1343. TAmProcsParser parser(ret, typeByName, procByName, procs, opFamilies);
  1344. parser.Do(dat);
  1345. return ret;
  1346. }
  1347. TConversions ParseConversions(const TString& dat, const THashMap<TString, TVector<ui32>>& procByName) {
  1348. TConversions ret;
  1349. TConversionsParser parser(ret, procByName);
  1350. parser.Do(dat);
  1351. return ret;
  1352. }
  1353. TAms ParseAms(const TString& dat) {
  1354. TAms ret;
  1355. TAmsParser parser(ret);
  1356. parser.Do(dat);
  1357. return ret;
  1358. }
  1359. TLanguages ParseLanguages(const TString& dat) {
  1360. TLanguages ret;
  1361. TLanguagesParser parser(ret);
  1362. parser.Do(dat);
  1363. return ret;
  1364. }
  1365. TNamespaces FillNamespaces() {
  1366. const ui32 PgInformationSchemaNamepace = 1;
  1367. const ui32 PgCatalogNamepace = 11;
  1368. const ui32 PgPublicNamepace = 2200;
  1369. return TNamespaces{
  1370. {PgInformationSchemaNamepace, TNamespaceDesc{PgInformationSchemaNamepace, "information_schema", "information_schema namespace"}},
  1371. {PgPublicNamepace, TNamespaceDesc{PgPublicNamepace, "public", "public namespace"}},
  1372. {PgCatalogNamepace, TNamespaceDesc{PgCatalogNamepace, "pg_catalog", "pg_catalog namespace"}},
  1373. };
  1374. }
  1375. struct TTableInfoKeyRaw {
  1376. const char* Schema;
  1377. const char* Name;
  1378. };
  1379. struct TTableInfoRaw : public TTableInfoKeyRaw {
  1380. ERelKind Kind;
  1381. ui32 Oid;
  1382. };
  1383. struct TColumnInfoRaw {
  1384. const char* Schema;
  1385. const char* TableName;
  1386. const char* Name;
  1387. const char* UdtType;
  1388. };
  1389. const TTableInfoRaw AllStaticTablesRaw[] = {
  1390. #include "pg_class.generated.h"
  1391. };
  1392. const TColumnInfoRaw AllStaticColumnsRaw[] = {
  1393. #include "columns.generated.h"
  1394. };
  1395. const char* AllowedProcsRaw[] = {
  1396. #include "safe_procs.h"
  1397. #include "used_procs.h"
  1398. #include "postgis_procs.h"
  1399. };
  1400. struct TCatalog : public IExtensionSqlBuilder {
  1401. TCatalog() {
  1402. Init();
  1403. }
  1404. void Clear() {
  1405. State.Clear();
  1406. }
  1407. void Init() {
  1408. Clear();
  1409. State.ConstructInPlace();
  1410. for (size_t i = 0; i < Y_ARRAY_SIZE(AllStaticTablesRaw); ++i) {
  1411. const auto& raw = AllStaticTablesRaw[i];
  1412. State->AllStaticTables.push_back(
  1413. {{TString(raw.Schema), TString(raw.Name)}, raw.Kind, raw.Oid}
  1414. );
  1415. }
  1416. for (size_t i = 0; i < Y_ARRAY_SIZE(AllStaticColumnsRaw); ++i) {
  1417. const auto& raw = AllStaticColumnsRaw[i];
  1418. State->AllStaticColumns.push_back(
  1419. {TString(raw.Schema), TString(raw.TableName), TString(raw.Name), TString(raw.UdtType)}
  1420. );
  1421. }
  1422. if ( GetEnv("YDB_EXPERIMENTAL_PG") == "1"){
  1423. // grafana migration_log
  1424. State->AllStaticTables.push_back(
  1425. {{"public", "migration_log"}, ERelKind::Relation, 100001}
  1426. );
  1427. State->AllStaticColumns.push_back(
  1428. {"public", "migration_log", "id", "int"}
  1429. );
  1430. State->AllStaticColumns.push_back(
  1431. {"public", "migration_log", "migration_id", "character varying(255)"}
  1432. );
  1433. State->AllStaticColumns.push_back(
  1434. {"public", "migration_log", "sql", "text"}
  1435. );
  1436. State->AllStaticColumns.push_back(
  1437. {"public", "migration_log", "success", "boolean"}
  1438. );
  1439. State->AllStaticColumns.push_back(
  1440. {"public", "migration_log", "error", "text"}
  1441. );
  1442. State->AllStaticColumns.push_back(
  1443. {"public", "migration_log", "timestamp", "timestamp without time zone"}
  1444. );
  1445. // zabbix config
  1446. State->AllStaticTables.push_back(
  1447. {{"public", "config"}, ERelKind::Relation, 100001}
  1448. );
  1449. State->AllStaticColumns.push_back(
  1450. {"public", "config", "configid", "bigint"}
  1451. );
  1452. State->AllStaticColumns.push_back(
  1453. {"public", "config", "server_check_interval", "integer"}
  1454. );
  1455. State->AllStaticColumns.push_back(
  1456. {"public", "config", "dbversion_status", "text"}
  1457. );
  1458. // zabbix dbversion
  1459. State->AllStaticTables.push_back(
  1460. {{"public", "dbversion"}, ERelKind::Relation, 100002}
  1461. );
  1462. State->AllStaticColumns.push_back(
  1463. {"public", "dbversion", "dbversionid", "bigint"}
  1464. );
  1465. State->AllStaticColumns.push_back(
  1466. {"public", "dbversion", "mandatory", "integer"}
  1467. );
  1468. State->AllStaticColumns.push_back(
  1469. {"public", "dbversion", "mandatory", "optional"}
  1470. );
  1471. }
  1472. THashSet<ui32> usedTableOids;
  1473. for (const auto& t : State->AllStaticTables) {
  1474. State->StaticColumns.insert(std::make_pair(t, TVector<TColumnInfo>()));
  1475. Y_ENSURE(usedTableOids.insert(t.Oid).first);
  1476. State->StaticTables.insert(std::make_pair(TTableInfoKey(t), t));
  1477. }
  1478. for (const auto& c: State->AllStaticColumns) {
  1479. auto tablePtr = State->StaticColumns.FindPtr(TTableInfoKey{c.Schema, c.TableName});
  1480. Y_ENSURE(tablePtr);
  1481. tablePtr->push_back(c);
  1482. }
  1483. for (const auto& t : State->StaticColumns) {
  1484. Y_ENSURE(!t.second.empty());
  1485. }
  1486. TString typeData;
  1487. Y_ENSURE(NResource::FindExact("pg_type.dat", &typeData));
  1488. TString opData;
  1489. Y_ENSURE(NResource::FindExact("pg_operator.dat", &opData));
  1490. TString procData;
  1491. Y_ENSURE(NResource::FindExact("pg_proc.dat", &procData));
  1492. TString castData;
  1493. Y_ENSURE(NResource::FindExact("pg_cast.dat", &castData));
  1494. TString aggData;
  1495. Y_ENSURE(NResource::FindExact("pg_aggregate.dat", &aggData));
  1496. TString opFamiliesData;
  1497. Y_ENSURE(NResource::FindExact("pg_opfamily.dat", &opFamiliesData));
  1498. TString opClassData;
  1499. Y_ENSURE(NResource::FindExact("pg_opclass.dat", &opClassData));
  1500. TString amProcData;
  1501. Y_ENSURE(NResource::FindExact("pg_amproc.dat", &amProcData));
  1502. TString amOpData;
  1503. Y_ENSURE(NResource::FindExact("pg_amop.dat", &amOpData));
  1504. TString conversionData;
  1505. Y_ENSURE(NResource::FindExact("pg_conversion.dat", &conversionData));
  1506. TString amData;
  1507. Y_ENSURE(NResource::FindExact("pg_am.dat", &amData));
  1508. TString languagesData;
  1509. Y_ENSURE(NResource::FindExact("pg_language.dat", &languagesData));
  1510. THashMap<ui32, TLazyTypeInfo> lazyTypeInfos;
  1511. State->Types = ParseTypes(typeData, lazyTypeInfos);
  1512. for (const auto& [k, v] : State->Types) {
  1513. if (k == v.TypeId) {
  1514. Y_ENSURE(State->TypeByName.insert(std::make_pair(v.Name, k)).second);
  1515. }
  1516. if (k == v.ArrayTypeId) {
  1517. Y_ENSURE(State->TypeByName.insert(std::make_pair("_" + v.Name, k)).second);
  1518. }
  1519. }
  1520. State->Procs = ParseProcs(procData, State->TypeByName);
  1521. for (const auto& [k, v] : State->Procs) {
  1522. State->ProcByName[v.Name].push_back(k);
  1523. }
  1524. const ui32 cstringId = 2275;
  1525. const ui32 byteaId = 17;
  1526. const ui32 internalId = 2281;
  1527. for (const auto& [k, v] : lazyTypeInfos) {
  1528. auto typePtr = State->Types.FindPtr(k);
  1529. Y_ENSURE(typePtr);
  1530. auto inFuncIdPtr = State->ProcByName.FindPtr(v.InFunc);
  1531. Y_ENSURE(inFuncIdPtr);
  1532. Y_ENSURE(inFuncIdPtr->size() == 1);
  1533. auto inFuncPtr = State->Procs.FindPtr(inFuncIdPtr->at(0));
  1534. Y_ENSURE(inFuncPtr);
  1535. Y_ENSURE(inFuncPtr->ArgTypes.size() >= 1); // may have mods
  1536. Y_ENSURE(inFuncPtr->ArgTypes[0] == cstringId);
  1537. typePtr->InFuncId = inFuncIdPtr->at(0);
  1538. auto outFuncIdPtr = State->ProcByName.FindPtr(v.OutFunc);
  1539. Y_ENSURE(outFuncIdPtr);
  1540. Y_ENSURE(outFuncIdPtr->size() == 1);
  1541. auto outFuncPtr = State->Procs.FindPtr(outFuncIdPtr->at(0));
  1542. Y_ENSURE(outFuncPtr);
  1543. Y_ENSURE(outFuncPtr->ArgTypes.size() == 1);
  1544. Y_ENSURE(outFuncPtr->ResultType == cstringId);
  1545. typePtr->OutFuncId = outFuncIdPtr->at(0);
  1546. if (v.ReceiveFunc != "-") {
  1547. auto receiveFuncIdPtr = State->ProcByName.FindPtr(v.ReceiveFunc);
  1548. Y_ENSURE(receiveFuncIdPtr);
  1549. Y_ENSURE(receiveFuncIdPtr->size() == 1);
  1550. auto receiveFuncPtr = State->Procs.FindPtr(receiveFuncIdPtr->at(0));
  1551. Y_ENSURE(receiveFuncPtr);
  1552. Y_ENSURE(receiveFuncPtr->ArgTypes.size() >= 1);
  1553. Y_ENSURE(receiveFuncPtr->ArgTypes[0] == internalId); // mutable StringInfo
  1554. typePtr->ReceiveFuncId = receiveFuncIdPtr->at(0);
  1555. }
  1556. if (v.SendFunc != "-") {
  1557. auto sendFuncIdPtr = State->ProcByName.FindPtr(v.SendFunc);
  1558. Y_ENSURE(sendFuncIdPtr);
  1559. Y_ENSURE(sendFuncIdPtr->size() == 1);
  1560. auto sendFuncPtr = State->Procs.FindPtr(sendFuncIdPtr->at(0));
  1561. Y_ENSURE(sendFuncPtr);
  1562. Y_ENSURE(sendFuncPtr->ArgTypes.size() == 1);
  1563. Y_ENSURE(sendFuncPtr->ResultType == byteaId);
  1564. typePtr->SendFuncId = sendFuncIdPtr->at(0);
  1565. }
  1566. if (v.ModInFunc) {
  1567. auto modInFuncIdPtr = State->ProcByName.FindPtr(v.ModInFunc);
  1568. Y_ENSURE(modInFuncIdPtr);
  1569. Y_ENSURE(modInFuncIdPtr->size() == 1);
  1570. auto modInFuncPtr = State->Procs.FindPtr(modInFuncIdPtr->at(0));
  1571. Y_ENSURE(modInFuncPtr);
  1572. Y_ENSURE(modInFuncPtr->ArgTypes.size() == 1);
  1573. typePtr->TypeModInFuncId = modInFuncIdPtr->at(0);
  1574. }
  1575. if (v.ModOutFunc) {
  1576. auto modOutFuncIdPtr = State->ProcByName.FindPtr(v.ModOutFunc);
  1577. Y_ENSURE(modOutFuncIdPtr);
  1578. Y_ENSURE(modOutFuncIdPtr->size() == 1);
  1579. auto modOutFuncPtr = State->Procs.FindPtr(modOutFuncIdPtr->at(0));
  1580. Y_ENSURE(modOutFuncPtr);
  1581. Y_ENSURE(modOutFuncPtr->ArgTypes.size() == 1);
  1582. typePtr->TypeModOutFuncId = modOutFuncIdPtr->at(0);
  1583. }
  1584. if (v.SubscriptFunc) {
  1585. auto subscriptFuncIdPtr = State->ProcByName.FindPtr(v.SubscriptFunc);
  1586. Y_ENSURE(subscriptFuncIdPtr);
  1587. Y_ENSURE(subscriptFuncIdPtr->size() == 1);
  1588. auto subscriptFuncPtr = State->Procs.FindPtr(subscriptFuncIdPtr->at(0));
  1589. Y_ENSURE(subscriptFuncPtr);
  1590. Y_ENSURE(subscriptFuncPtr->ArgTypes.size() == 1);
  1591. typePtr->TypeSubscriptFuncId = subscriptFuncIdPtr->at(0);
  1592. }
  1593. if (v.ElementType) {
  1594. auto elemTypePtr = State->TypeByName.FindPtr(v.ElementType);
  1595. Y_ENSURE(elemTypePtr);
  1596. typePtr->ElementTypeId = *elemTypePtr;
  1597. }
  1598. }
  1599. State->Casts = ParseCasts(castData, State->TypeByName, State->Types, State->ProcByName, State->Procs);
  1600. for (const auto&[k, v] : State->Casts) {
  1601. Y_ENSURE(State->CastsByDir.insert(std::make_pair(std::make_pair(v.SourceId, v.TargetId), k)).second);
  1602. }
  1603. THashMap<ui32, TLazyOperInfo> lazyOperInfos;
  1604. State->Operators = ParseOperators(opData, State->TypeByName, State->Types, State->ProcByName, State->Procs, lazyOperInfos);
  1605. for (const auto&[k, v] : State->Operators) {
  1606. State->OperatorsByName[v.Name].push_back(k);
  1607. }
  1608. ApplyLazyOperInfos(State->Operators, State->OperatorsByName, State->TypeByName, lazyOperInfos);
  1609. State->Aggregations = ParseAggregations(aggData, State->TypeByName, State->Types, State->ProcByName, State->Procs);
  1610. for (const auto&[k, v] : State->Aggregations) {
  1611. State->AggregationsByName[v.Name].push_back(k);
  1612. }
  1613. State->OpFamilies = ParseOpFamilies(opFamiliesData);
  1614. State->OpClasses = ParseOpClasses(opClassData, State->TypeByName, State->OpFamilies);
  1615. State->AmOps = ParseAmOps(amOpData, State->TypeByName, State->Types, State->OperatorsByName, State->Operators, State->OpFamilies);
  1616. State->AmProcs = ParseAmProcs(amProcData, State->TypeByName, State->ProcByName, State->Procs, State->OpFamilies);
  1617. State->Ams = ParseAms(amData);
  1618. State->Namespaces = FillNamespaces();
  1619. for (auto& [k, v] : State->Types) {
  1620. if (v.TypeId != v.ArrayTypeId) {
  1621. auto lookupId = (v.TypeId == VarcharOid ? TextOid : v.TypeId);
  1622. if (regClasses.contains(lookupId)) {
  1623. lookupId = OidOid;
  1624. }
  1625. CacheAmFuncs(lookupId, v);
  1626. }
  1627. }
  1628. State->Conversions = ParseConversions(conversionData, State->ProcByName);
  1629. State->Languages = ParseLanguages(languagesData);
  1630. if (GetEnv("YQL_ALLOW_ALL_PG_FUNCTIONS")) {
  1631. State->AllowAllFunctions = true;
  1632. } else if (auto exportDir = GetEnv("YQL_EXPORT_PG_FUNCTIONS_DIR")) {
  1633. State->AllowAllFunctions = true;
  1634. ExportFile.ConstructInPlace(MakeTempName(exportDir.c_str(), "procs"), CreateAlways | RdWr);
  1635. for (const auto& a : State->Aggregations) {
  1636. const auto& desc = a.second;
  1637. ExportFunction(desc.TransFuncId);
  1638. ExportFunction(desc.FinalFuncId);
  1639. ExportFunction(desc.CombineFuncId);
  1640. ExportFunction(desc.SerializeFuncId);
  1641. ExportFunction(desc.DeserializeFuncId);
  1642. }
  1643. for (const auto& t : State->Types) {
  1644. const auto& desc = t.second;
  1645. ExportFunction(desc.InFuncId);
  1646. ExportFunction(desc.OutFuncId);
  1647. ExportFunction(desc.SendFuncId);
  1648. ExportFunction(desc.ReceiveFuncId);
  1649. ExportFunction(desc.TypeModInFuncId);
  1650. ExportFunction(desc.TypeModOutFuncId);
  1651. ExportFunction(desc.TypeSubscriptFuncId);
  1652. ExportFunction(desc.LessProcId);
  1653. ExportFunction(desc.EqualProcId);
  1654. ExportFunction(desc.CompareProcId);
  1655. ExportFunction(desc.HashProcId);
  1656. }
  1657. for (const auto& o : State->Operators) {
  1658. const auto& desc = o.second;
  1659. ExportFunction(desc.ProcId);
  1660. }
  1661. for (const auto& c : State->Casts) {
  1662. const auto& desc = c.second;
  1663. ExportFunction(desc.FunctionId);
  1664. }
  1665. } else {
  1666. for (size_t i = 0; i < Y_ARRAY_SIZE(AllowedProcsRaw); ++i) {
  1667. const auto& raw = AllowedProcsRaw[i];
  1668. State->AllowedProcs.insert(raw);
  1669. }
  1670. for (const auto& t : State->Types) {
  1671. State->AllowedProcs.insert(t.second.Name);
  1672. }
  1673. }
  1674. }
  1675. void ExportFunction(ui32 procOid) const {
  1676. if (!procOid || !ExportFile) {
  1677. return;
  1678. }
  1679. auto procPtr = State->Procs.FindPtr(procOid);
  1680. Y_ENSURE(procPtr);
  1681. ExportFunction(procPtr->Name);
  1682. }
  1683. void ExportFunction(const TString& name) const {
  1684. if (!ExportFile) {
  1685. return;
  1686. }
  1687. TString line = TStringBuilder() << "\"" << name << "\",\n";
  1688. with_lock(ExportGuard) {
  1689. ExportFile->Write(line.data(), line.size());
  1690. }
  1691. }
  1692. void CacheAmFuncs(ui32 typeId, TTypeDesc& v) {
  1693. auto btreeOpClassPtr = State->OpClasses.FindPtr(std::make_pair(EOpClassMethod::Btree, typeId));
  1694. if (btreeOpClassPtr) {
  1695. auto lessAmOpPtr = State->AmOps.FindPtr(std::make_tuple(btreeOpClassPtr->FamilyId, ui32(EBtreeAmStrategy::Less), typeId, typeId));
  1696. Y_ENSURE(lessAmOpPtr);
  1697. auto equalAmOpPtr = State->AmOps.FindPtr(std::make_tuple(btreeOpClassPtr->FamilyId, ui32(EBtreeAmStrategy::Equal), typeId, typeId));
  1698. Y_ENSURE(equalAmOpPtr);
  1699. auto lessOperPtr = State->Operators.FindPtr(lessAmOpPtr->OperId);
  1700. Y_ENSURE(lessOperPtr);
  1701. auto equalOperPtr = State->Operators.FindPtr(equalAmOpPtr->OperId);
  1702. Y_ENSURE(equalOperPtr);
  1703. v.LessProcId = lessOperPtr->ProcId;
  1704. v.EqualProcId = equalOperPtr->ProcId;
  1705. auto compareAmProcPtr = State->AmProcs.FindPtr(std::make_tuple(btreeOpClassPtr->FamilyId, ui32(EBtreeAmProcNum::Compare), typeId, typeId));
  1706. Y_ENSURE(compareAmProcPtr);
  1707. v.CompareProcId = compareAmProcPtr->ProcId;
  1708. }
  1709. auto hashOpClassPtr = State->OpClasses.FindPtr(std::make_pair(EOpClassMethod::Hash, typeId));
  1710. if (hashOpClassPtr) {
  1711. auto hashAmProcPtr = State->AmProcs.FindPtr(std::make_tuple(hashOpClassPtr->FamilyId, ui32(EHashAmProcNum::Hash), typeId, typeId));
  1712. Y_ENSURE(hashAmProcPtr);
  1713. v.HashProcId = hashAmProcPtr->ProcId;
  1714. }
  1715. }
  1716. void CreateProc(const TProcDesc& desc) final {
  1717. Y_ENSURE(desc.ExtensionIndex);
  1718. TProcDesc newDesc = desc;
  1719. newDesc.Name = to_lower(newDesc.Name);
  1720. newDesc.ProcId = 16000 + State->Procs.size();
  1721. State->Procs[newDesc.ProcId] = newDesc;
  1722. State->ProcByName[newDesc.Name].push_back(newDesc.ProcId);
  1723. }
  1724. void PrepareType(ui32 extensionIndex, const TString& name) final {
  1725. Y_ENSURE(extensionIndex);
  1726. auto lowerName = to_lower(name);
  1727. if (auto idPtr = State->TypeByName.FindPtr(lowerName)) {
  1728. auto typePtr = State->Types.FindPtr(*idPtr);
  1729. Y_ENSURE(typePtr);
  1730. Y_ENSURE(!typePtr->ExtensionIndex || typePtr->ExtensionIndex == extensionIndex);
  1731. return;
  1732. }
  1733. TTypeDesc newDesc;
  1734. newDesc.Name = lowerName;
  1735. newDesc.TypeId = 16000 + State->Types.size();
  1736. newDesc.ExtensionIndex = extensionIndex;
  1737. newDesc.ArrayTypeId = newDesc.TypeId + 1;
  1738. newDesc.Category = 'U';
  1739. State->Types[newDesc.TypeId] = newDesc;
  1740. State->TypeByName[newDesc.Name] = newDesc.TypeId;
  1741. TTypeDesc newArrayDesc = newDesc;
  1742. newArrayDesc.TypeId += 1;
  1743. newArrayDesc.Name = "_" + newArrayDesc.Name;
  1744. newArrayDesc.ElementTypeId = newDesc.TypeId;
  1745. newArrayDesc.ArrayTypeId = newArrayDesc.TypeId;
  1746. newArrayDesc.PassByValue = false;
  1747. newArrayDesc.TypeLen = -1;
  1748. newArrayDesc.SendFuncId = (*State->ProcByName.FindPtr("array_send"))[0];
  1749. newArrayDesc.ReceiveFuncId = (*State->ProcByName.FindPtr("array_recv"))[0];
  1750. newArrayDesc.InFuncId = (*State->ProcByName.FindPtr("array_in"))[0];
  1751. newArrayDesc.OutFuncId = (*State->ProcByName.FindPtr("array_out"))[0];
  1752. newArrayDesc.Category = 'A';
  1753. State->Types[newArrayDesc.TypeId] = newArrayDesc;
  1754. State->TypeByName[newArrayDesc.Name] = newArrayDesc.TypeId;
  1755. }
  1756. void UpdateType(const TTypeDesc& desc) final {
  1757. Y_ENSURE(desc.ExtensionIndex);
  1758. auto byIdPtr = State->Types.FindPtr(desc.TypeId);
  1759. Y_ENSURE(byIdPtr);
  1760. Y_ENSURE(byIdPtr->Name == desc.Name);
  1761. Y_ENSURE(byIdPtr->ArrayTypeId == desc.ArrayTypeId);
  1762. Y_ENSURE(byIdPtr->TypeId == desc.TypeId);
  1763. Y_ENSURE(byIdPtr->ExtensionIndex == desc.ExtensionIndex);
  1764. if (desc.InFuncId) {
  1765. State->AllowedProcs.insert(State->Procs.FindPtr(desc.InFuncId)->Name);
  1766. }
  1767. if (desc.OutFuncId) {
  1768. State->AllowedProcs.insert(State->Procs.FindPtr(desc.OutFuncId)->Name);
  1769. }
  1770. if (desc.SendFuncId) {
  1771. State->AllowedProcs.insert(State->Procs.FindPtr(desc.SendFuncId)->Name);
  1772. }
  1773. if (desc.ReceiveFuncId) {
  1774. State->AllowedProcs.insert(State->Procs.FindPtr(desc.ReceiveFuncId)->Name);
  1775. }
  1776. if (desc.TypeModInFuncId) {
  1777. State->AllowedProcs.insert(State->Procs.FindPtr(desc.TypeModInFuncId)->Name);
  1778. }
  1779. if (desc.TypeModOutFuncId) {
  1780. State->AllowedProcs.insert(State->Procs.FindPtr(desc.TypeModOutFuncId)->Name);
  1781. }
  1782. *byIdPtr = desc;
  1783. }
  1784. void CreateTable(const TTableInfo& table, const TVector<TColumnInfo>& columns) final {
  1785. Y_ENSURE(table.ExtensionIndex);
  1786. Y_ENSURE(!columns.empty());
  1787. THashSet<TString> usedColumns;
  1788. for (const auto& c : columns) {
  1789. Y_ENSURE(c.Schema == table.Schema);
  1790. Y_ENSURE(c.TableName == table.Name);
  1791. Y_ENSURE(c.ExtensionIndex == table.ExtensionIndex);
  1792. Y_ENSURE(usedColumns.insert(c.Name).second);
  1793. }
  1794. TTableInfoKey key{table};
  1795. TTableInfo value = table;
  1796. value.Oid = 16000 + State->StaticTables.size();
  1797. Y_ENSURE(State->StaticTables.emplace(key, value).second);
  1798. Y_ENSURE(State->StaticColumns.emplace(key, columns).second);
  1799. State->AllStaticTables.push_back(value);
  1800. for (const auto& c : columns) {
  1801. State->AllStaticColumns.push_back(c);
  1802. }
  1803. }
  1804. void InsertValues(const TTableInfoKey& table, const TVector<TString>& columns,
  1805. const TVector<TMaybe<TString>>& data) final {
  1806. Y_ENSURE(State->StaticTables.contains(table));
  1807. const auto& columnDefs = *State->StaticColumns.FindPtr(table);
  1808. Y_ENSURE(columnDefs.size() == columns.size());
  1809. Y_ENSURE(data.size() % columns.size() == 0);
  1810. THashMap<TString, ui32> columnToIndex;
  1811. for (ui32 i = 0; i < columnDefs.size(); ++i) {
  1812. columnToIndex[columnDefs[i].Name] = i;
  1813. }
  1814. THashSet<TString> usedColumns;
  1815. TVector<ui32> dataColumnRemap;
  1816. for (const auto& c : columns) {
  1817. Y_ENSURE(usedColumns.insert(c).second);
  1818. dataColumnRemap.push_back(*columnToIndex.FindPtr(c));
  1819. }
  1820. auto& tableData = State->StaticTablesData[table];
  1821. size_t writePos = tableData.size();
  1822. tableData.resize(tableData.size() + data.size());
  1823. size_t readRowPos = 0;
  1824. while (writePos < tableData.size()) {
  1825. for (size_t colIdx = 0; colIdx < columns.size(); ++colIdx) {
  1826. tableData[writePos++] = data[readRowPos + dataColumnRemap[colIdx]];
  1827. }
  1828. readRowPos += columns.size();
  1829. }
  1830. Y_ENSURE(readRowPos == data.size());
  1831. }
  1832. void CreateCast(const TCastDesc& desc) final {
  1833. Y_ENSURE(desc.ExtensionIndex);
  1834. auto id = 1 + State->Casts.size();
  1835. State->Casts[id] = desc;
  1836. Y_ENSURE(State->CastsByDir.insert(std::make_pair(std::make_pair(desc.SourceId, desc.TargetId), id)).second);
  1837. if (desc.FunctionId) {
  1838. auto funcPtr = State->Procs.FindPtr(desc.FunctionId);
  1839. Y_ENSURE(funcPtr);
  1840. State->AllowedProcs.insert(funcPtr->Name);
  1841. }
  1842. }
  1843. void PrepareOper(ui32 extensionIndex, const TString& name, const TVector<ui32>& args) final {
  1844. Y_ENSURE(args.size() >= 1 && args.size() <= 2);
  1845. Y_ENSURE(extensionIndex);
  1846. auto lowerName = to_lower(name);
  1847. auto operIdPtr = State->OperatorsByName.FindPtr(lowerName);
  1848. if (operIdPtr) {
  1849. for (const auto& id : *operIdPtr) {
  1850. const auto& d = State->Operators.FindPtr(id);
  1851. Y_ENSURE(d);
  1852. if (d->LeftType == args[0] && (args.size() == 1 || d->RightType == args[1])) {
  1853. Y_ENSURE(!d->ExtensionIndex || d->ExtensionIndex == extensionIndex);
  1854. return;
  1855. }
  1856. }
  1857. }
  1858. if (!operIdPtr) {
  1859. operIdPtr = &State->OperatorsByName[lowerName];
  1860. }
  1861. TOperDesc desc;
  1862. desc.Name = name;
  1863. desc.LeftType = args[0];
  1864. if (args.size() == 1) {
  1865. desc.Kind = EOperKind::LeftUnary;
  1866. } else {
  1867. desc.RightType = args[1];
  1868. }
  1869. auto id = 16000 + State->Operators.size();
  1870. desc.OperId = id;
  1871. desc.ExtensionIndex = extensionIndex;
  1872. Y_ENSURE(State->Operators.emplace(id, desc).second);
  1873. operIdPtr->push_back(id);
  1874. }
  1875. void UpdateOper(const TOperDesc& desc) final {
  1876. Y_ENSURE(desc.ExtensionIndex);
  1877. const auto& d = State->Operators.FindPtr(desc.OperId);
  1878. Y_ENSURE(d);
  1879. Y_ENSURE(d->Name == desc.Name);
  1880. Y_ENSURE(d->ExtensionIndex == desc.ExtensionIndex);
  1881. Y_ENSURE(d->LeftType == desc.LeftType);
  1882. Y_ENSURE(d->RightType == desc.RightType);
  1883. Y_ENSURE(d->Kind == desc.Kind);
  1884. d->ProcId = desc.ProcId;
  1885. d->ComId = desc.ComId;
  1886. d->NegateId = desc.NegateId;
  1887. d->ResultType = desc.ResultType;
  1888. auto procPtr = State->Procs.FindPtr(desc.ProcId);
  1889. Y_ENSURE(procPtr);
  1890. State->AllowedProcs.insert(procPtr->Name);
  1891. }
  1892. void CreateAggregate(const TAggregateDesc& desc) final {
  1893. Y_ENSURE(desc.ExtensionIndex);
  1894. auto id = 16000 + State->Aggregations.size();
  1895. auto newDesc = desc;
  1896. newDesc.Name = to_lower(newDesc.Name);
  1897. newDesc.AggId = id;
  1898. Y_ENSURE(State->Aggregations.emplace(id, newDesc).second);
  1899. State->AggregationsByName[newDesc.Name].push_back(id);
  1900. if (desc.CombineFuncId) {
  1901. State->AllowedProcs.insert(State->Procs.FindPtr(desc.CombineFuncId)->Name);
  1902. }
  1903. if (desc.DeserializeFuncId) {
  1904. State->AllowedProcs.insert(State->Procs.FindPtr(desc.DeserializeFuncId)->Name);
  1905. }
  1906. if (desc.SerializeFuncId) {
  1907. State->AllowedProcs.insert(State->Procs.FindPtr(desc.SerializeFuncId)->Name);
  1908. }
  1909. if (desc.FinalFuncId) {
  1910. State->AllowedProcs.insert(State->Procs.FindPtr(desc.FinalFuncId)->Name);
  1911. }
  1912. State->AllowedProcs.insert(State->Procs.FindPtr(desc.TransFuncId)->Name);
  1913. }
  1914. void CreateOpClass(const TOpClassDesc& opclass, const TVector<TAmOpDesc>& ops, const TVector<TAmProcDesc>& procs) final {
  1915. Y_ENSURE(opclass.ExtensionIndex);
  1916. auto newDesc = opclass;
  1917. newDesc.Family = to_lower(newDesc.Family);
  1918. newDesc.Name = to_lower(newDesc.Name);
  1919. auto newFamilyId = 16000 + State->OpFamilies.size();
  1920. TOpFamilyDesc opFamilyDesc;
  1921. opFamilyDesc.FamilyId = newFamilyId;
  1922. opFamilyDesc.Name = newDesc.Family;
  1923. opFamilyDesc.ExtensionIndex = opclass.ExtensionIndex;
  1924. Y_ENSURE(State->OpFamilies.emplace(newDesc.Family, opFamilyDesc).second);
  1925. newDesc.FamilyId = newFamilyId;
  1926. const auto key = std::make_pair(newDesc.Method, newDesc.TypeId);
  1927. Y_ENSURE(State->OpClasses.emplace(key, newDesc).second);
  1928. for (const auto& o : ops) {
  1929. Y_ENSURE(opclass.ExtensionIndex == o.ExtensionIndex);
  1930. Y_ENSURE(opclass.Family == o.Family);
  1931. auto newOpDesc = o;
  1932. newOpDesc.FamilyId = newFamilyId;
  1933. newOpDesc.Family = newDesc.Name;
  1934. Y_ENSURE(State->AmOps.emplace(std::make_tuple(newFamilyId, o.Strategy, o.LeftType, o.RightType), newOpDesc).second);
  1935. auto operPtr = State->Operators.FindPtr(o.OperId);
  1936. Y_ENSURE(operPtr);
  1937. auto procPtr = State->Procs.FindPtr(operPtr->ProcId);
  1938. Y_ENSURE(procPtr);
  1939. State->AllowedProcs.emplace(procPtr->Name);
  1940. }
  1941. for (const auto& p : procs) {
  1942. Y_ENSURE(opclass.ExtensionIndex == p.ExtensionIndex);
  1943. Y_ENSURE(opclass.Family == p.Family);
  1944. auto newProcDesc = p;
  1945. newProcDesc.FamilyId = newFamilyId;
  1946. newProcDesc.Family = newDesc.Name;
  1947. Y_ENSURE(State->AmProcs.emplace(std::make_tuple(newFamilyId, p.ProcNum, p.LeftType, p.RightType), newProcDesc).second);
  1948. auto procPtr = State->Procs.FindPtr(p.ProcId);
  1949. Y_ENSURE(procPtr);
  1950. State->AllowedProcs.emplace(procPtr->Name);
  1951. }
  1952. auto typePtr = State->Types.FindPtr(opclass.TypeId);
  1953. Y_ENSURE(typePtr);
  1954. Y_ENSURE(typePtr->ExtensionIndex == opclass.ExtensionIndex);
  1955. CacheAmFuncs(opclass.TypeId, *typePtr);
  1956. }
  1957. static const TCatalog& Instance() {
  1958. return *Singleton<TCatalog>();
  1959. }
  1960. static TCatalog& MutableInstance() {
  1961. return *Singleton<TCatalog>();
  1962. }
  1963. struct TState {
  1964. TExtensionsByName ExtensionsByName, ExtensionsByInstallName;
  1965. TExtensions Extensions;
  1966. TOperators Operators;
  1967. TProcs Procs;
  1968. TTypes Types;
  1969. TCasts Casts;
  1970. TAggregations Aggregations;
  1971. TAms Ams;
  1972. TNamespaces Namespaces;
  1973. TOpFamilies OpFamilies;
  1974. TOpClasses OpClasses;
  1975. TAmOps AmOps;
  1976. TAmProcs AmProcs;
  1977. TConversions Conversions;
  1978. TLanguages Languages;
  1979. THashMap<TString, TVector<ui32>> ProcByName;
  1980. THashMap<TString, ui32> TypeByName;
  1981. THashMap<std::pair<ui32, ui32>, ui32> CastsByDir;
  1982. THashMap<TString, TVector<ui32>> OperatorsByName;
  1983. THashMap<TString, TVector<ui32>> AggregationsByName;
  1984. TVector<TTableInfo> AllStaticTables;
  1985. TVector<TColumnInfo> AllStaticColumns;
  1986. THashMap<TTableInfoKey, TTableInfo> StaticTables;
  1987. THashMap<TTableInfoKey, TVector<TColumnInfo>> StaticColumns;
  1988. THashMap<TTableInfoKey, TVector<TMaybe<TString>>> StaticTablesData;
  1989. bool AllowAllFunctions = false;
  1990. THashSet<TString> AllowedProcs;
  1991. bool SystemFunctionInit = false;
  1992. };
  1993. mutable TMaybe<TFile> ExportFile;
  1994. TMutex ExportGuard;
  1995. TMaybe<TState> State;
  1996. TMutex ExtensionsGuard;
  1997. bool ExtensionsInit = false;
  1998. };
  1999. bool ValidateProcArgs(const TProcDesc& d, const TVector<ui32>& argTypeIds) {
  2000. const auto& catalog = TCatalog::Instance();
  2001. return ValidateArgs(d.ArgTypes, argTypeIds, catalog.State->Types, d.VariadicType);
  2002. }
  2003. const TProcDesc& LookupProc(ui32 procId, const TVector<ui32>& argTypeIds) {
  2004. const auto& catalog = TCatalog::Instance();
  2005. auto procPtr = catalog.State->Procs.FindPtr(procId);
  2006. if (!procPtr) {
  2007. throw yexception() << "No such proc: " << procId;
  2008. }
  2009. if (!catalog.State->AllowAllFunctions && !catalog.State->AllowedProcs.contains(procPtr->Name)) {
  2010. throw yexception() << "No access to proc: " << procPtr->Name;
  2011. }
  2012. if (!ValidateProcArgs(*procPtr, argTypeIds)) {
  2013. throw yexception() << "Unable to find an overload for proc with oid " << procId << " with given argument types: " <<
  2014. ArgTypesList(argTypeIds);
  2015. }
  2016. catalog.ExportFunction(procId);
  2017. return *procPtr;
  2018. }
  2019. const TProcDesc& LookupProc(const TString& name, const TVector<ui32>& argTypeIds) {
  2020. const auto& catalog = TCatalog::Instance();
  2021. auto lower = to_lower(name);
  2022. auto procIdPtr = catalog.State->ProcByName.FindPtr(lower);
  2023. if (!procIdPtr) {
  2024. throw yexception() << "No such proc: " << name;
  2025. }
  2026. for (const auto& id : *procIdPtr) {
  2027. const auto& d = catalog.State->Procs.FindPtr(id);
  2028. Y_ENSURE(d);
  2029. if (!catalog.State->AllowAllFunctions && !catalog.State->AllowedProcs.contains(d->Name)) {
  2030. throw yexception() << "No access to proc: " << d->Name;
  2031. }
  2032. if (!ValidateProcArgs(*d, argTypeIds)) {
  2033. continue;
  2034. }
  2035. catalog.ExportFunction(d->Name);
  2036. return *d;
  2037. }
  2038. throw yexception() << "Unable to find an overload for proc " << name << " with given argument types: "
  2039. << ArgTypesList(argTypeIds);
  2040. }
  2041. const TProcDesc& LookupProc(ui32 procId) {
  2042. const auto& catalog = TCatalog::Instance();
  2043. auto procPtr = catalog.State->Procs.FindPtr(procId);
  2044. if (!procPtr) {
  2045. throw yexception() << "No such proc: " << procId;
  2046. }
  2047. if (!catalog.State->AllowAllFunctions && !catalog.State->AllowedProcs.contains(procPtr->Name)) {
  2048. throw yexception() << "No access to proc: " << procPtr->Name;
  2049. }
  2050. catalog.ExportFunction(procId);
  2051. return *procPtr;
  2052. }
  2053. void EnumProc(std::function<void(ui32, const TProcDesc&)> f) {
  2054. const auto& catalog = TCatalog::Instance();
  2055. for (const auto& x : catalog.State->Procs) {
  2056. if (catalog.State->AllowAllFunctions || catalog.State->AllowedProcs.contains(x.second.Name)) {
  2057. f(x.first, x.second);
  2058. }
  2059. }
  2060. }
  2061. bool HasProc(const TString& name, EProcKind kind) {
  2062. const auto& catalog = TCatalog::Instance();
  2063. auto procIdPtr = catalog.State->ProcByName.FindPtr(to_lower(name));
  2064. if (!procIdPtr) {
  2065. return false;
  2066. }
  2067. for (const auto& id : *procIdPtr) {
  2068. const auto& d = catalog.State->Procs.FindPtr(id);
  2069. Y_ENSURE(d);
  2070. if (d->Kind == kind) {
  2071. return true;
  2072. }
  2073. }
  2074. return false;
  2075. }
  2076. bool HasReturnSetProc(const TString& name) {
  2077. const auto& catalog = TCatalog::Instance();
  2078. auto procIdPtr = catalog.State->ProcByName.FindPtr(to_lower(name));
  2079. if (!procIdPtr) {
  2080. return false;
  2081. }
  2082. for (const auto& id : *procIdPtr) {
  2083. const auto& d = catalog.State->Procs.FindPtr(id);
  2084. Y_ENSURE(d);
  2085. if (d->ReturnSet) {
  2086. return true;
  2087. }
  2088. }
  2089. return false;
  2090. }
  2091. bool HasType(const TString& name) {
  2092. const auto& catalog = TCatalog::Instance();
  2093. return catalog.State->TypeByName.contains(GetCanonicalTypeName(to_lower(name)));
  2094. }
  2095. const TTypeDesc& LookupType(const TString& name) {
  2096. const auto& catalog = TCatalog::Instance();
  2097. const auto typeIdPtr = catalog.State->TypeByName.FindPtr(GetCanonicalTypeName(to_lower(name)));
  2098. if (!typeIdPtr) {
  2099. throw yexception() << "No such type: " << name;
  2100. }
  2101. const auto typePtr = catalog.State->Types.FindPtr(*typeIdPtr);
  2102. Y_ENSURE(typePtr);
  2103. return *typePtr;
  2104. }
  2105. bool HasType(ui32 typeId) {
  2106. const auto& catalog = TCatalog::Instance();
  2107. return catalog.State->Types.contains(typeId);
  2108. }
  2109. const TTypeDesc& LookupType(ui32 typeId) {
  2110. const auto& catalog = TCatalog::Instance();
  2111. const auto typePtr = catalog.State->Types.FindPtr(typeId);
  2112. if (!typePtr) {
  2113. throw yexception() << "No such type: " << typeId;
  2114. }
  2115. return *typePtr;
  2116. }
  2117. void EnumTypes(std::function<void(ui32, const TTypeDesc&)> f) {
  2118. const auto& catalog = TCatalog::Instance();
  2119. for (const auto& [typeId, desc] : catalog.State->Types) {
  2120. f(typeId, desc);
  2121. }
  2122. }
  2123. const TAmDesc& LookupAm(ui32 oid) {
  2124. const auto& catalog = TCatalog::Instance();
  2125. const auto typePtr = catalog.State->Ams.FindPtr(oid);
  2126. if (!typePtr) {
  2127. throw yexception() << "No such am: " << oid;
  2128. }
  2129. return *typePtr;
  2130. }
  2131. void EnumAm(std::function<void(ui32, const TAmDesc&)> f) {
  2132. const auto& catalog = TCatalog::Instance();
  2133. for (const auto& [oid, desc] : catalog.State->Ams) {
  2134. f(oid, desc);
  2135. }
  2136. }
  2137. void EnumConversions(std::function<void(const TConversionDesc&)> f) {
  2138. const auto& catalog = TCatalog::Instance();
  2139. for (const auto& [_, desc] : catalog.State->Conversions) {
  2140. f(desc);
  2141. }
  2142. }
  2143. const TNamespaceDesc& LookupNamespace(ui32 oid) {
  2144. const auto& catalog = TCatalog::Instance();
  2145. const auto typePtr = catalog.State->Namespaces.FindPtr(oid);
  2146. if (!typePtr) {
  2147. throw yexception() << "No such namespace: " << oid;
  2148. }
  2149. return *typePtr;
  2150. }
  2151. void EnumNamespace(std::function<void(ui32, const TNamespaceDesc&)> f) {
  2152. const auto& catalog = TCatalog::Instance();
  2153. for (const auto& [oid, desc] : catalog.State->Namespaces) {
  2154. f(oid, desc);
  2155. }
  2156. }
  2157. void EnumOperators(std::function<void(const TOperDesc&)> f) {
  2158. const auto& catalog = TCatalog::Instance();
  2159. for (const auto& [_, desc] : catalog.State->Operators) {
  2160. f(desc);
  2161. }
  2162. }
  2163. bool HasCast(ui32 sourceId, ui32 targetId) {
  2164. const auto& catalog = TCatalog::Instance();
  2165. return catalog.State->CastsByDir.contains(std::make_pair(sourceId, targetId));
  2166. }
  2167. const TCastDesc& LookupCast(ui32 sourceId, ui32 targetId) {
  2168. const auto& catalog = TCatalog::Instance();
  2169. auto castByDirPtr = catalog.State->CastsByDir.FindPtr(std::make_pair(sourceId, targetId));
  2170. if (!castByDirPtr) {
  2171. throw yexception() << "No such cast";
  2172. }
  2173. auto castPtr = catalog.State->Casts.FindPtr(*castByDirPtr);
  2174. Y_ENSURE(castPtr);
  2175. return *castPtr;
  2176. }
  2177. namespace NPrivate {
  2178. constexpr ui64 NoFitScore = 0;
  2179. bool CanUseCoercionType(ECoercionCode requiredCoercionLevel, ECoercionCode actualCoercionLevel) {
  2180. switch (requiredCoercionLevel) {
  2181. case NYql::NPg::ECoercionCode::Implicit:
  2182. return actualCoercionLevel == ECoercionCode::Implicit;
  2183. case NYql::NPg::ECoercionCode::Assignment:
  2184. return (actualCoercionLevel == ECoercionCode::Implicit) || (actualCoercionLevel == ECoercionCode::Assignment);
  2185. case NYql::NPg::ECoercionCode::Explicit:
  2186. return (actualCoercionLevel != ECoercionCode::Unknown);
  2187. case NYql::NPg::ECoercionCode::Unknown:
  2188. return false;
  2189. }
  2190. }
  2191. enum class ECoercionSearchResult
  2192. {
  2193. None,
  2194. Func,
  2195. BinaryCompatible,
  2196. ArrayCoerce,
  2197. IOCoerce,
  2198. };
  2199. ECoercionSearchResult FindCoercionPath(ui32 fromTypeId, ui32 toTypeId, ECoercionCode coercionType, const TCatalog& catalog) {
  2200. if (fromTypeId == toTypeId) {
  2201. return ECoercionSearchResult::BinaryCompatible;
  2202. }
  2203. const auto* castId = catalog.State->CastsByDir.FindPtr(std::make_pair(fromTypeId, toTypeId));
  2204. if (castId != nullptr) {
  2205. const auto* castPtr = catalog.State->Casts.FindPtr(*castId);
  2206. Y_ENSURE(castPtr);
  2207. if (!CanUseCoercionType(coercionType, castPtr->CoercionCode)) {
  2208. return ECoercionSearchResult::None;
  2209. }
  2210. switch (castPtr->Method) {
  2211. case ECastMethod::Function:
  2212. return ECoercionSearchResult::Func;
  2213. case ECastMethod::Binary:
  2214. return ECoercionSearchResult::BinaryCompatible;
  2215. case ECastMethod::InOut:
  2216. return ECoercionSearchResult::IOCoerce;
  2217. }
  2218. }
  2219. if (toTypeId != OidVectorOid && toTypeId != Int2VectorOid) {
  2220. const auto* toTypePtr = catalog.State->Types.FindPtr(toTypeId);
  2221. Y_ENSURE(toTypePtr);
  2222. const auto* fromTypePtr = catalog.State->Types.FindPtr(fromTypeId);
  2223. Y_ENSURE(fromTypePtr);
  2224. if (IsArrayType(*toTypePtr) && IsArrayType(*fromTypePtr)) {
  2225. if (FindCoercionPath(fromTypePtr->ElementTypeId, toTypePtr->ElementTypeId, coercionType, catalog) != ECoercionSearchResult::None) {
  2226. return ECoercionSearchResult::ArrayCoerce;
  2227. }
  2228. }
  2229. }
  2230. if (coercionType == ECoercionCode::Assignment || coercionType == ECoercionCode::Explicit) {
  2231. const auto* toTypePtr = catalog.State->Types.FindPtr(toTypeId);
  2232. Y_ENSURE(toTypePtr);
  2233. if (toTypePtr->Category == 'S') {
  2234. return ECoercionSearchResult::IOCoerce;
  2235. }
  2236. if (coercionType == ECoercionCode::Explicit) {
  2237. const auto* fromTypePtr = catalog.State->Types.FindPtr(fromTypeId);
  2238. Y_ENSURE(fromTypePtr);
  2239. if (fromTypePtr->Category == 'S') {
  2240. return ECoercionSearchResult::IOCoerce;
  2241. }
  2242. }
  2243. }
  2244. return ECoercionSearchResult::None;
  2245. }
  2246. bool IsCoercible(ui32 fromTypeId, ui32 toTypeId, ECoercionCode coercionType, const TCatalog& catalog) {
  2247. if (fromTypeId == toTypeId) {
  2248. return true;
  2249. }
  2250. if (toTypeId == AnyOid) {
  2251. return true;
  2252. }
  2253. //TODO: support polymorphic types
  2254. if (fromTypeId == UnknownOid) {
  2255. return true;
  2256. }
  2257. if (FindCoercionPath(fromTypeId, toTypeId, coercionType, catalog) != ECoercionSearchResult::None ) {
  2258. return true;
  2259. }
  2260. // TODO: support record & complex types
  2261. // TODO: support record array
  2262. // TODO: support inheritance
  2263. if (toTypeId == AnyArrayOid) {
  2264. const auto& actualDescPtr = catalog.State->Types.FindPtr(fromTypeId);
  2265. Y_ENSURE(actualDescPtr);
  2266. return actualDescPtr->ArrayTypeId == actualDescPtr->TypeId;
  2267. }
  2268. if (toTypeId == AnyNonArrayOid) {
  2269. const auto& actualDescPtr = catalog.State->Types.FindPtr(fromTypeId);
  2270. Y_ENSURE(actualDescPtr);
  2271. return actualDescPtr->ArrayTypeId != actualDescPtr->TypeId;
  2272. }
  2273. return false;
  2274. }
  2275. bool IsPreferredType(char categoryId, const TTypeDesc& type) {
  2276. Y_ENSURE(type.Category != InvalidCategory);
  2277. return (categoryId == type.Category) ? type.IsPreferred : false;
  2278. }
  2279. constexpr ui32 CoercibleMatchShift = 16;
  2280. constexpr ui64 ArgExactTypeMatch = 1ULL << 2*CoercibleMatchShift;
  2281. constexpr ui64 ArgPreferredTypeMatch = 1ULL << CoercibleMatchShift;
  2282. constexpr ui64 ArgCoercibleTypeMatch = 1ULL;
  2283. constexpr ui64 ArgTypeMismatch = 0;
  2284. ui64 CalcArgumentMatchScore(ui32 operArgTypeId, ui32 argTypeId, const TCatalog& catalog) {
  2285. Y_ENSURE(operArgTypeId != UnknownOid);
  2286. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 2
  2287. if (argTypeId == operArgTypeId) {
  2288. return ArgExactTypeMatch;
  2289. }
  2290. if (argTypeId == UnknownOid) {
  2291. return ArgCoercibleTypeMatch;
  2292. }
  2293. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 3.c
  2294. if (IsCoercible(argTypeId, operArgTypeId, ECoercionCode::Implicit, catalog)) {
  2295. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 3.d
  2296. const auto& argType = catalog.State->Types.FindPtr(argTypeId);
  2297. Y_ENSURE(argType);
  2298. const auto& operArgType = catalog.State->Types.FindPtr(operArgTypeId);
  2299. Y_ENSURE(operArgType);
  2300. return IsPreferredType(argType->Category, *operArgType)
  2301. ? ArgPreferredTypeMatch
  2302. : ArgCoercibleTypeMatch;
  2303. }
  2304. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 3.a
  2305. return ArgTypeMismatch;
  2306. }
  2307. ui64 CalcBinaryOperatorScore(const TOperDesc& oper, ui32 leftArgTypeId, ui32 rightArgTypeId, const TCatalog& catalog) {
  2308. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 2.a
  2309. if (leftArgTypeId == UnknownOid && rightArgTypeId != InvalidOid) {
  2310. if (oper.LeftType == rightArgTypeId && oper.RightType == rightArgTypeId) {
  2311. return ArgExactTypeMatch + ArgExactTypeMatch;
  2312. }
  2313. }
  2314. else if (rightArgTypeId == UnknownOid && leftArgTypeId != InvalidOid) {
  2315. if (oper.LeftType == leftArgTypeId && oper.RightType == leftArgTypeId) {
  2316. return ArgExactTypeMatch + ArgExactTypeMatch;
  2317. }
  2318. }
  2319. // https://www.postgresql.org/docs/14/typeconv-oper.html, steps 3.a, 3.c, 3.d
  2320. auto lscore = CalcArgumentMatchScore(oper.LeftType, leftArgTypeId, catalog);
  2321. auto rscore = CalcArgumentMatchScore(oper.RightType, rightArgTypeId, catalog);
  2322. if (lscore == ArgTypeMismatch || rscore == ArgTypeMismatch) {
  2323. return ArgTypeMismatch;
  2324. }
  2325. return lscore + rscore;
  2326. }
  2327. ui64 CalcUnaryOperatorScore(const TOperDesc& oper, ui32 argTypeId, const TCatalog& catalog) {
  2328. return CalcArgumentMatchScore(oper.RightType, argTypeId, catalog);
  2329. }
  2330. bool IsExactMatch(const TVector<ui32>& procArgTypes, ui32 procVariadicType, const TVector<ui32>& argTypeIds) {
  2331. if (argTypeIds.size() < procArgTypes.size()) {
  2332. return false;
  2333. }
  2334. if (!procVariadicType && argTypeIds.size() > procArgTypes.size()) {
  2335. return false;
  2336. }
  2337. for (ui32 i = 0; i < procArgTypes.size(); ++i) {
  2338. if (procArgTypes[i] != argTypeIds[i]) {
  2339. return false;
  2340. }
  2341. }
  2342. if (procVariadicType) {
  2343. if (argTypeIds.size() == procArgTypes.size()) {
  2344. return false;
  2345. }
  2346. for (ui32 i = procArgTypes.size(); i < argTypeIds.size(); ++i) {
  2347. if (procVariadicType != argTypeIds[i]) {
  2348. return false;
  2349. }
  2350. }
  2351. }
  2352. return true;
  2353. }
  2354. ui64 CalcProcScore(const TVector<ui32>& procArgTypes, ui32 procVariadicType, ui32 procDefArgs, const TVector<ui32>& argTypeIds, const TCatalog& catalog) {
  2355. ui64 result = 0UL;
  2356. if (!procVariadicType) {
  2357. ++result;
  2358. }
  2359. Y_ENSURE(procArgTypes.size() >= procDefArgs);
  2360. if (argTypeIds.size() < procArgTypes.size() - procDefArgs) {
  2361. return ArgTypeMismatch;
  2362. }
  2363. if (!procVariadicType && argTypeIds.size() > procArgTypes.size()) {
  2364. return ArgTypeMismatch;
  2365. }
  2366. if (procVariadicType && argTypeIds.size() == procArgTypes.size()) {
  2367. return ArgTypeMismatch;
  2368. }
  2369. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  2370. auto score = CalcArgumentMatchScore(i >= procArgTypes.size() ? procVariadicType : procArgTypes[i], argTypeIds[i], catalog);
  2371. if (score == ArgTypeMismatch) {
  2372. return ArgTypeMismatch;
  2373. }
  2374. result += score;
  2375. }
  2376. return result;
  2377. }
  2378. [[noreturn]] void ThrowOperatorNotFound(const TString& name, const TVector<ui32>& argTypeIds) {
  2379. throw yexception() << "Unable to find an overload for operator " << name << " with given argument type(s): "
  2380. << ArgTypesList(argTypeIds);
  2381. }
  2382. [[noreturn]] void ThrowOperatorAmbiguity(const TString& name, const TVector<ui32>& argTypeIds) {
  2383. throw yexception() << "Ambiguity for operator " << name << " with given argument type(s): "
  2384. << ArgTypesList(argTypeIds);
  2385. }
  2386. [[noreturn]] void ThrowProcNotFound(const TString& name, const TVector<ui32>& argTypeIds) {
  2387. throw yexception() << "Unable to find an overload for proc " << name << " with given argument types: "
  2388. << ArgTypesList(argTypeIds);
  2389. }
  2390. [[noreturn]] void ThrowProcAmbiguity(const TString& name, const TVector<ui32>& argTypeIds) {
  2391. throw yexception() << "Ambiguity for proc " << name << " with given argument type(s): "
  2392. << ArgTypesList(argTypeIds);
  2393. }
  2394. [[noreturn]] void ThrowAggregateNotFound(const TString& name, const TVector<ui32>& argTypeIds) {
  2395. throw yexception() << "Unable to find an overload for aggregate " << name << " with given argument types: "
  2396. << ArgTypesList(argTypeIds);
  2397. }
  2398. [[noreturn]] void ThrowAggregateAmbiguity(const TString& name, const TVector<ui32>& argTypeIds) {
  2399. throw yexception() << "Ambiguity for aggregate " << name << " with given argument type(s): "
  2400. << ArgTypesList(argTypeIds);
  2401. }
  2402. struct TCommonCategoryDesc {
  2403. size_t Position;
  2404. char Category = InvalidCategory;
  2405. bool IsPreferred = false;
  2406. TCommonCategoryDesc(size_t position, char category, bool isPreferred)
  2407. : Position(position), Category(category), IsPreferred(isPreferred) {}
  2408. };
  2409. template <class C>
  2410. char FindCommonCategory(const TVector<const C*> &candidates, std::function<ui32(const C*)> getTypeId, const TCatalog &catalog, bool &isPreferred) {
  2411. char category = InvalidCategory;
  2412. auto isConflict = false;
  2413. isPreferred = false;
  2414. for (const auto* candidate : candidates) {
  2415. const auto argTypeId = getTypeId(candidate);
  2416. const auto& argTypePtr = catalog.State->Types.FindPtr(argTypeId);
  2417. Y_ENSURE(argTypePtr);
  2418. if (InvalidCategory == category) {
  2419. category = argTypePtr->Category;
  2420. isPreferred = argTypePtr->IsPreferred;
  2421. } else if (category == argTypePtr->Category) {
  2422. isPreferred |= argTypePtr->IsPreferred;
  2423. } else {
  2424. if (argTypePtr->Category == 'S') {
  2425. category = argTypePtr->Category;
  2426. isPreferred = argTypePtr->IsPreferred;
  2427. } else {
  2428. isConflict = true;
  2429. }
  2430. }
  2431. }
  2432. if (isConflict && category != 'S') {
  2433. isPreferred = false;
  2434. return InvalidCategory;
  2435. }
  2436. return category;
  2437. }
  2438. template <class C>
  2439. TVector<const C*> TryResolveUnknownsByCategory(const TVector<const C*>& candidates, const TVector<ui32>& argTypeIds, const TCatalog& catalog) {
  2440. TVector<NPrivate::TCommonCategoryDesc> argCommonCategory;
  2441. size_t unknownsCnt = 0;
  2442. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  2443. if (argTypeIds[i] != UnknownOid) {
  2444. continue;
  2445. }
  2446. ++unknownsCnt;
  2447. char category = InvalidCategory;
  2448. bool isPreferred = false;
  2449. std::function<ui32(const C *)> typeGetter = [i] (const auto* candidate) {
  2450. if constexpr (std::is_same_v<C, TProcDesc>) {
  2451. return i < candidate->ArgTypes.size() ? candidate->ArgTypes[i] : candidate->VariadicType;
  2452. } else {
  2453. return candidate->ArgTypes[i];
  2454. }
  2455. };
  2456. if (InvalidCategory != (category = NPrivate::FindCommonCategory<C>(candidates, typeGetter, catalog, isPreferred))) {
  2457. argCommonCategory.emplace_back(i, category, isPreferred);
  2458. }
  2459. }
  2460. if (argCommonCategory.size() < unknownsCnt) {
  2461. return candidates;
  2462. }
  2463. TVector<const C*> filteredCandidates;
  2464. for (const auto* candidate : candidates) {
  2465. auto keepIt = true;
  2466. for (const auto& category : argCommonCategory) {
  2467. ui32 argTypeId;
  2468. if constexpr (std::is_same_v<C, TProcDesc>) {
  2469. argTypeId = category.Position < candidate->ArgTypes.size() ? candidate->ArgTypes[category.Position] : candidate->VariadicType;
  2470. } else {
  2471. argTypeId = candidate->ArgTypes[category.Position];
  2472. }
  2473. const auto& argTypePtr = catalog.State->Types.FindPtr(argTypeId);
  2474. Y_ENSURE(argTypePtr);
  2475. if (argTypePtr->Category != category.Category) {
  2476. keepIt = false;
  2477. break;
  2478. }
  2479. if (category.IsPreferred && !argTypePtr->IsPreferred) {
  2480. keepIt = false;
  2481. break;
  2482. }
  2483. }
  2484. if (keepIt) {
  2485. filteredCandidates.push_back(candidate);
  2486. }
  2487. }
  2488. return filteredCandidates.empty() ? candidates : filteredCandidates;
  2489. }
  2490. template <>
  2491. TVector<const TOperDesc*> TryResolveUnknownsByCategory<TOperDesc>(const TVector<const TOperDesc*>& candidates, const TVector<ui32>& argTypeIds, const TCatalog& catalog) {
  2492. TVector<NPrivate::TCommonCategoryDesc> argCommonCategory;
  2493. size_t unknownsCnt = 0;
  2494. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  2495. if (argTypeIds[i] != UnknownOid) {
  2496. continue;
  2497. }
  2498. ++unknownsCnt;
  2499. char category = InvalidCategory;
  2500. bool isPreferred = false;
  2501. std::function <ui32(const TOperDesc*)> typeGetter;
  2502. if (i == 1) {
  2503. typeGetter = [] (const auto* candidate) {
  2504. return candidate->RightType;
  2505. };
  2506. } else {
  2507. typeGetter = [] (const auto* candidate) {
  2508. return (candidate->Kind == EOperKind::Binary)
  2509. ? candidate->LeftType
  2510. : candidate->RightType;
  2511. };
  2512. }
  2513. if (InvalidCategory != (category = NPrivate::FindCommonCategory<TOperDesc>(candidates, typeGetter, catalog, isPreferred))) {
  2514. argCommonCategory.emplace_back(i, category, isPreferred);
  2515. }
  2516. }
  2517. if (argCommonCategory.size() < unknownsCnt) {
  2518. return candidates;
  2519. }
  2520. TVector<const TOperDesc*> filteredCandidates;
  2521. for (const auto* candidate : candidates) {
  2522. auto keepIt = true;
  2523. for (const auto& category : argCommonCategory) {
  2524. const auto argTypeId = (category.Position == 1)
  2525. ? candidate->RightType
  2526. : (candidate->Kind == EOperKind::Binary) ? candidate->LeftType : candidate->RightType;
  2527. const auto& argTypePtr = catalog.State->Types.FindPtr(argTypeId);
  2528. Y_ENSURE(argTypePtr);
  2529. if (argTypePtr->Category != category.Category) {
  2530. keepIt = false;
  2531. break;
  2532. }
  2533. if (category.IsPreferred && !argTypePtr->IsPreferred) {
  2534. keepIt = false;
  2535. break;
  2536. }
  2537. }
  2538. if (keepIt) {
  2539. filteredCandidates.push_back(candidate);
  2540. }
  2541. }
  2542. return filteredCandidates.empty() ? candidates : filteredCandidates;
  2543. }
  2544. bool CanCastImplicitly(ui32 fromTypeId, ui32 toTypeId, const TCatalog& catalog) {
  2545. const auto* castId = catalog.State->CastsByDir.FindPtr(std::make_pair(fromTypeId, toTypeId));
  2546. if (!castId) {
  2547. return false;
  2548. }
  2549. const auto* castPtr = catalog.State->Casts.FindPtr(*castId);
  2550. Y_ENSURE(castPtr);
  2551. return (castPtr->CoercionCode == ECoercionCode::Implicit);
  2552. }
  2553. } // NPrivate
  2554. bool IsCoercible(ui32 fromTypeId, ui32 toTypeId, ECoercionCode coercionType) {
  2555. const auto& catalog = TCatalog::Instance();
  2556. return NPrivate::IsCoercible(fromTypeId, toTypeId, coercionType, catalog);
  2557. }
  2558. std::variant<const TProcDesc*, const TTypeDesc*> LookupProcWithCasts(const TString& name, const TVector<ui32>& argTypeIds) {
  2559. const auto& catalog = TCatalog::Instance();
  2560. auto lower = to_lower(name);
  2561. auto procIdPtr = catalog.State->ProcByName.FindPtr(lower);
  2562. if (!procIdPtr) {
  2563. throw yexception() << "No such proc: " << name;
  2564. }
  2565. auto bestScore = NPrivate::NoFitScore;
  2566. TVector<const TProcDesc*> candidates;
  2567. for (const auto& id : *procIdPtr) {
  2568. const auto& d = catalog.State->Procs.FindPtr(id);
  2569. Y_ENSURE(d);
  2570. if (!catalog.State->AllowAllFunctions && !catalog.State->AllowedProcs.contains(d->Name)) {
  2571. throw yexception() << "No access to proc: " << d->Name;
  2572. }
  2573. if (NPrivate::IsExactMatch(d->ArgTypes, d->VariadicType, argTypeIds)) {
  2574. // At most one exact match is possible, so look no further
  2575. // https://www.postgresql.org/docs/14/typeconv-func.html, step 2
  2576. catalog.ExportFunction(d->Name);
  2577. return d;
  2578. }
  2579. // https://www.postgresql.org/docs/14/typeconv-func.html, steps 4.a, 4.c, 4.d
  2580. auto score = NPrivate::CalcProcScore(d->ArgTypes, d->VariadicType, d->DefaultArgs.size(), argTypeIds, catalog);
  2581. if (bestScore < score) {
  2582. bestScore = score;
  2583. candidates.clear();
  2584. candidates.push_back(d);
  2585. } else if (bestScore == score && NPrivate::NoFitScore < score) {
  2586. candidates.push_back(d);
  2587. }
  2588. }
  2589. // check, if it's a form of typecast
  2590. // https://www.postgresql.org/docs/14/typeconv-func.html, step 3
  2591. if (argTypeIds.size() == 1) {
  2592. const auto typeIdPtr = catalog.State->TypeByName.FindPtr(to_lower(name));
  2593. if (typeIdPtr) {
  2594. const auto typePtr = catalog.State->Types.FindPtr(*typeIdPtr);
  2595. Y_ENSURE(typePtr);
  2596. const auto fromTypeId = argTypeIds[0];
  2597. if (fromTypeId == UnknownOid) {
  2598. return typePtr;
  2599. }
  2600. const auto coercionType = NPrivate::FindCoercionPath(fromTypeId, typePtr->TypeId,
  2601. ECoercionCode::Explicit, catalog);
  2602. switch (coercionType) {
  2603. case NPrivate::ECoercionSearchResult::BinaryCompatible:
  2604. return typePtr;
  2605. case NPrivate::ECoercionSearchResult::IOCoerce:
  2606. if (!(fromTypeId == RecordOid /* || TODO: IsComplex */ && typePtr->Category == 'S')) {
  2607. return typePtr;
  2608. }
  2609. default:
  2610. break;
  2611. }
  2612. }
  2613. }
  2614. switch (candidates.size()) {
  2615. case 1:
  2616. // https://www.postgresql.org/docs/14/typeconv-func.html, end of steps 4.a, 4.c or 4.d
  2617. catalog.ExportFunction(candidates[0]->Name);
  2618. return candidates[0];
  2619. case 0:
  2620. NPrivate::ThrowProcNotFound(name, argTypeIds);
  2621. }
  2622. // https://www.postgresql.org/docs/14/typeconv-func.html, step 4.e
  2623. const size_t unknownsCount = std::count(argTypeIds.cbegin(), argTypeIds.cend(), UnknownOid);
  2624. if (0 == unknownsCount) {
  2625. NPrivate::ThrowProcNotFound(name, argTypeIds);
  2626. }
  2627. // https://www.postgresql.org/docs/14/typeconv-funcr.html, step 4.e
  2628. candidates = NPrivate::TryResolveUnknownsByCategory<TProcDesc>(candidates, argTypeIds, catalog);
  2629. if (1 == candidates.size()) {
  2630. // https://www.postgresql.org/docs/14/typeconv-func.html, end of step 4.e
  2631. catalog.ExportFunction(candidates[0]->Name);
  2632. return candidates[0];
  2633. }
  2634. // https://www.postgresql.org/docs/14/typeconv-func.html, step 4.f
  2635. if (unknownsCount < argTypeIds.size()) {
  2636. ui32 commonType = UnknownOid;
  2637. for (const auto argType: argTypeIds) {
  2638. if (argType == UnknownOid) {
  2639. continue;
  2640. }
  2641. if (commonType == UnknownOid) {
  2642. commonType = argType;
  2643. continue;
  2644. }
  2645. if (argType != commonType) {
  2646. commonType = UnknownOid;
  2647. break;
  2648. }
  2649. }
  2650. if (commonType != UnknownOid) {
  2651. const TProcDesc* finalCandidate = nullptr;
  2652. for (const auto* candidate : candidates) {
  2653. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  2654. if (NPrivate::IsCoercible(commonType, i >= candidate->ArgTypes.size() ? candidate->VariadicType : candidate->ArgTypes[i], ECoercionCode::Implicit, catalog)) {
  2655. if (finalCandidate) {
  2656. NPrivate::ThrowProcAmbiguity(name, argTypeIds);
  2657. }
  2658. finalCandidate = candidate;
  2659. }
  2660. }
  2661. }
  2662. if (finalCandidate) {
  2663. catalog.ExportFunction(finalCandidate->Name);
  2664. return finalCandidate;
  2665. }
  2666. }
  2667. }
  2668. NPrivate::ThrowProcNotFound(name, argTypeIds);
  2669. }
  2670. TMaybe<TIssue> LookupCommonType(const TVector<ui32>& typeIds, const std::function<TPosition(size_t i)>& GetPosition, const TTypeDesc*& typeDesc, bool& castsNeeded) {
  2671. Y_ENSURE(0 != typeIds.size());
  2672. const auto& catalog = TCatalog::Instance();
  2673. size_t unknownsCnt = (typeIds[0] == UnknownOid || typeIds[0] == InvalidOid) ? 1 : 0;
  2674. castsNeeded = (unknownsCnt != 0);
  2675. const TTypeDesc* commonType = nullptr;
  2676. char commonCategory = 0;
  2677. if (typeIds[0] != InvalidOid) {
  2678. commonType = &LookupType(typeIds[0]);
  2679. commonCategory = commonType->Category;
  2680. }
  2681. size_t i = 1;
  2682. for (auto typeId = typeIds.cbegin() + 1; typeId != typeIds.cend(); ++typeId, ++i) {
  2683. if (*typeId == UnknownOid || *typeId == InvalidOid) {
  2684. ++unknownsCnt;
  2685. castsNeeded = true;
  2686. continue;
  2687. }
  2688. if (commonType && *typeId == commonType->TypeId) {
  2689. continue;
  2690. }
  2691. const TTypeDesc& otherType = LookupType(*typeId);
  2692. if (!commonType || commonType->TypeId == UnknownOid) {
  2693. commonType = &otherType;
  2694. commonCategory = otherType.Category;
  2695. continue;
  2696. }
  2697. if (otherType.Category != commonCategory) {
  2698. // https://www.postgresql.org/docs/14/typeconv-union-case.html, step 4
  2699. return TIssue(GetPosition(i), TStringBuilder() << "Cannot infer common type for types "
  2700. << commonType->TypeId << " and " << otherType.TypeId);
  2701. }
  2702. castsNeeded = true;
  2703. if (NPrivate::CanCastImplicitly(otherType.TypeId, commonType->TypeId, catalog)) {
  2704. continue;
  2705. }
  2706. if (commonType->IsPreferred || !NPrivate::CanCastImplicitly(commonType->TypeId, otherType.TypeId, catalog)) {
  2707. return TIssue(GetPosition(i), TStringBuilder() << "Cannot infer common type for types "
  2708. << commonType->TypeId << " and " << otherType.TypeId);
  2709. }
  2710. commonType = &otherType;
  2711. }
  2712. // https://www.postgresql.org/docs/14/typeconv-union-case.html, step 3
  2713. if (unknownsCnt == typeIds.size()) {
  2714. castsNeeded = true;
  2715. typeDesc = &LookupType("text");
  2716. } else {
  2717. typeDesc = commonType;
  2718. }
  2719. return {};
  2720. }
  2721. TMaybe<TIssue> LookupCommonType(const TVector<ui32>& typeIds, const std::function<TPosition(size_t i)>&GetPosition, const TTypeDesc*& typeDesc) {
  2722. bool _;
  2723. return LookupCommonType(typeIds, GetPosition, typeDesc, _);
  2724. }
  2725. const TOperDesc& LookupOper(const TString& name, const TVector<ui32>& argTypeIds) {
  2726. const auto& catalog = TCatalog::Instance();
  2727. auto operIdPtr = catalog.State->OperatorsByName.FindPtr(to_lower(name));
  2728. if (!operIdPtr) {
  2729. throw yexception() << "No such operator: " << name;
  2730. }
  2731. EOperKind expectedOpKind;
  2732. std::function<ui64(const TOperDesc*)> calcScore;
  2733. switch (argTypeIds.size()) {
  2734. case 2:
  2735. expectedOpKind = EOperKind::Binary;
  2736. calcScore = [&] (const auto* d) {
  2737. return NPrivate::CalcBinaryOperatorScore(*d, argTypeIds[0], argTypeIds[1], catalog);
  2738. };
  2739. break;
  2740. case 1:
  2741. expectedOpKind = EOperKind::LeftUnary;
  2742. calcScore = [&] (const auto* d) {
  2743. return NPrivate::CalcUnaryOperatorScore(*d, argTypeIds[0], catalog);
  2744. };
  2745. break;
  2746. default:
  2747. throw yexception() << "Operator's number of arguments should be 1 or 2, got: " << argTypeIds.size();
  2748. }
  2749. auto bestScore = NPrivate::NoFitScore;
  2750. TVector<const TOperDesc*> candidates;
  2751. const ui64 maxPossibleScore = NPrivate::ArgExactTypeMatch * argTypeIds.size();
  2752. for (const auto& operId : *operIdPtr) {
  2753. const auto& oper = catalog.State->Operators.FindPtr(operId);
  2754. Y_ENSURE(oper);
  2755. if (expectedOpKind != oper->Kind) {
  2756. continue;
  2757. }
  2758. auto score = calcScore(oper);
  2759. if (maxPossibleScore == score) {
  2760. // The only exact match is possible, so look no further
  2761. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 2
  2762. return *oper;
  2763. }
  2764. // https://www.postgresql.org/docs/14/typeconv-oper.html, steps 3.a, 3.c, 3.d
  2765. if (bestScore < score) {
  2766. bestScore = score;
  2767. candidates.clear();
  2768. candidates.push_back(oper);
  2769. } else if (bestScore == score && NPrivate::NoFitScore < score) {
  2770. candidates.push_back(oper);
  2771. }
  2772. }
  2773. switch (candidates.size()) {
  2774. case 1:
  2775. // https://www.postgresql.org/docs/14/typeconv-oper.html, end of steps 3.a, 3.c or 3.d
  2776. return *candidates[0];
  2777. case 0:
  2778. NPrivate::ThrowOperatorNotFound(name, argTypeIds);
  2779. }
  2780. if (!(argTypeIds[0] == UnknownOid || (2 == argTypeIds.size() && argTypeIds[1] == UnknownOid))) {
  2781. NPrivate::ThrowOperatorNotFound(name, argTypeIds);
  2782. }
  2783. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 3.e
  2784. candidates = NPrivate::TryResolveUnknownsByCategory<TOperDesc>(candidates, argTypeIds, catalog);
  2785. if (1 == candidates.size()) {
  2786. // https://www.postgresql.org/docs/14/typeconv-oper.html, end of step 3.e
  2787. return *candidates[0];
  2788. }
  2789. // https://www.postgresql.org/docs/14/typeconv-oper.html, step 3.f
  2790. if (EOperKind::LeftUnary == expectedOpKind) {
  2791. NPrivate::ThrowOperatorNotFound(name, argTypeIds);
  2792. }
  2793. auto TryResolveUnknownsBySpreadingType = [&] (ui32 argTypeId, std::function<ui32(const TOperDesc*)> getArgType) {
  2794. const TOperDesc* finalCandidate = nullptr;
  2795. for (const auto* candidate : candidates) {
  2796. if (NPrivate::IsCoercible(argTypeId, getArgType(candidate), ECoercionCode::Implicit, catalog)) {
  2797. if (finalCandidate) {
  2798. NPrivate::ThrowOperatorAmbiguity(name, argTypeIds);
  2799. }
  2800. finalCandidate = candidate;
  2801. }
  2802. }
  2803. return finalCandidate;
  2804. };
  2805. const TOperDesc* finalCandidate = nullptr;
  2806. if (argTypeIds[0] == UnknownOid) {
  2807. finalCandidate = TryResolveUnknownsBySpreadingType(argTypeIds[1], [&] (const auto* oper) { return oper->LeftType; });
  2808. } else if (argTypeIds[1] == UnknownOid) {
  2809. finalCandidate = TryResolveUnknownsBySpreadingType(argTypeIds[0], [&] (const auto* oper) { return oper->RightType; });
  2810. }
  2811. if (finalCandidate) {
  2812. return *finalCandidate;
  2813. }
  2814. NPrivate::ThrowOperatorNotFound(name, argTypeIds);
  2815. }
  2816. const TOperDesc& LookupOper(ui32 operId, const TVector<ui32>& argTypeIds) {
  2817. const auto& catalog = TCatalog::Instance();
  2818. auto operPtr = catalog.State->Operators.FindPtr(operId);
  2819. if (!operPtr) {
  2820. throw yexception() << "No such oper: " << operId;
  2821. }
  2822. if (!ValidateOperArgs(*operPtr, argTypeIds, catalog.State->Types)) {
  2823. throw yexception() << "Unable to find an overload for operator with oid " << operId << " with given argument types: "
  2824. << ArgTypesList(argTypeIds);
  2825. }
  2826. return *operPtr;
  2827. }
  2828. const TOperDesc& LookupOper(ui32 operId) {
  2829. const auto& catalog = TCatalog::Instance();
  2830. auto operPtr = catalog.State->Operators.FindPtr(operId);
  2831. if (!operPtr) {
  2832. throw yexception() << "No such oper: " << operId;
  2833. }
  2834. return *operPtr;
  2835. }
  2836. bool HasAggregation(const TString& name, EAggKind kind) {
  2837. const auto& catalog = TCatalog::Instance();
  2838. auto aggIdPtr = catalog.State->AggregationsByName.FindPtr(to_lower(name));
  2839. if (!aggIdPtr) {
  2840. return false;
  2841. }
  2842. for (const auto& id : *aggIdPtr) {
  2843. const auto& d = catalog.State->Aggregations.FindPtr(id);
  2844. Y_ENSURE(d);
  2845. if (d->Kind == kind) {
  2846. return true;
  2847. }
  2848. }
  2849. return false;
  2850. }
  2851. bool ValidateAggregateArgs(const TAggregateDesc& d, const TVector<ui32>& argTypeIds) {
  2852. const auto& catalog = TCatalog::Instance();
  2853. return ValidateArgs(d.ArgTypes, argTypeIds, catalog.State->Types);
  2854. }
  2855. bool ValidateAggregateArgs(const TAggregateDesc& d, ui32 stateType, ui32 resultType) {
  2856. auto expectedStateType = LookupProc(d.SerializeFuncId ? d.SerializeFuncId : d.TransFuncId).ResultType;
  2857. if (stateType != expectedStateType) {
  2858. return false;
  2859. }
  2860. auto expectedResultType = LookupProc(d.FinalFuncId ? d.FinalFuncId : d.TransFuncId).ResultType;
  2861. if (resultType != expectedResultType) {
  2862. return false;
  2863. }
  2864. return true;
  2865. }
  2866. const TAggregateDesc& LookupAggregation(const TString& name, const TVector<ui32>& argTypeIds) {
  2867. const auto& catalog = TCatalog::Instance();
  2868. auto aggIdPtr = catalog.State->AggregationsByName.FindPtr(to_lower(name));
  2869. if (!aggIdPtr) {
  2870. throw yexception() << "No such aggregate: " << name;
  2871. }
  2872. auto bestScore = NPrivate::NoFitScore;
  2873. TVector<const TAggregateDesc*> candidates;
  2874. for (const auto& id : *aggIdPtr) {
  2875. const auto& d = catalog.State->Aggregations.FindPtr(id);
  2876. Y_ENSURE(d);
  2877. if (NPrivate::IsExactMatch(d->ArgTypes, 0, argTypeIds)) {
  2878. // At most one exact match is possible, so look no further
  2879. // https://www.postgresql.org/docs/14/typeconv-func.html, step 2
  2880. return *d;
  2881. }
  2882. // https://www.postgresql.org/docs/14/typeconv-func.html, steps 4.a, 4.c, 4.d
  2883. auto score = NPrivate::CalcProcScore(d->ArgTypes, 0, 0, argTypeIds, catalog);
  2884. if (bestScore < score) {
  2885. bestScore = score;
  2886. candidates.clear();
  2887. candidates.push_back(d);
  2888. } else if (bestScore == score && NPrivate::NoFitScore < score) {
  2889. candidates.push_back(d);
  2890. }
  2891. }
  2892. switch (candidates.size()) {
  2893. case 1:
  2894. // https://www.postgresql.org/docs/14/typeconv-func.html, end of steps 4.a, 4.c or 4.d
  2895. return *candidates[0];
  2896. case 0:
  2897. NPrivate::ThrowAggregateNotFound(name, argTypeIds);
  2898. }
  2899. // https://www.postgresql.org/docs/14/typeconv-func.html, step 4.e
  2900. const size_t unknownsCount = std::count(argTypeIds.cbegin(), argTypeIds.cend(), UnknownOid);
  2901. if (0 == unknownsCount) {
  2902. NPrivate::ThrowAggregateNotFound(name, argTypeIds);
  2903. }
  2904. // https://www.postgresql.org/docs/14/typeconv-funcr.html, step 4.e
  2905. candidates = NPrivate::TryResolveUnknownsByCategory<TAggregateDesc>(candidates, argTypeIds, catalog);
  2906. if (1 == candidates.size()) {
  2907. // https://www.postgresql.org/docs/14/typeconv-func.html, end of step 4.e
  2908. return *candidates[0];
  2909. }
  2910. // https://www.postgresql.org/docs/14/typeconv-func.html, step 4.f
  2911. if (unknownsCount < argTypeIds.size()) {
  2912. ui32 commonType = UnknownOid;
  2913. for (const auto argType: argTypeIds) {
  2914. if (argType == UnknownOid) {
  2915. continue;
  2916. }
  2917. if (commonType == UnknownOid) {
  2918. commonType = argType;
  2919. continue;
  2920. }
  2921. if (argType != commonType) {
  2922. commonType = UnknownOid;
  2923. break;
  2924. }
  2925. }
  2926. if (commonType != UnknownOid) {
  2927. const TAggregateDesc* finalCandidate = nullptr;
  2928. for (const auto* candidate : candidates) {
  2929. for (size_t i = 0; i < argTypeIds.size(); ++i) {
  2930. if (NPrivate::IsCoercible(commonType, candidate->ArgTypes[i], ECoercionCode::Implicit, catalog)) {
  2931. if (finalCandidate) {
  2932. NPrivate::ThrowAggregateAmbiguity(name, argTypeIds);
  2933. }
  2934. finalCandidate = candidate;
  2935. }
  2936. }
  2937. }
  2938. if (finalCandidate) {
  2939. return *finalCandidate;
  2940. }
  2941. }
  2942. }
  2943. NPrivate::ThrowAggregateNotFound(name, argTypeIds);
  2944. }
  2945. const TAggregateDesc& LookupAggregation(const TString& name, ui32 stateType, ui32 resultType) {
  2946. TStringBuf realName = name;
  2947. TMaybe<ui32> aggId;
  2948. TStringBuf left, right;
  2949. if (realName.TrySplit('#', left, right)) {
  2950. aggId = FromString<ui32>(right);
  2951. realName = left;
  2952. }
  2953. const auto& catalog = TCatalog::Instance();
  2954. auto aggIdPtr = catalog.State->AggregationsByName.FindPtr(to_lower(TString(realName)));
  2955. if (!aggIdPtr) {
  2956. throw yexception() << "No such aggregate: " << name;
  2957. }
  2958. for (const auto& id : *aggIdPtr) {
  2959. const auto& d = catalog.State->Aggregations.FindPtr(id);
  2960. Y_ENSURE(d);
  2961. if (aggId && d->AggId != *aggId) {
  2962. continue;
  2963. }
  2964. if (!ValidateAggregateArgs(*d, stateType, resultType)) {
  2965. continue;
  2966. }
  2967. return *d;
  2968. }
  2969. throw yexception() << "Unable to find an overload for aggregate " << name << " with given state type: " <<
  2970. NPg::LookupType(stateType).Name << " and result type: " <<
  2971. NPg::LookupType(resultType).Name;
  2972. }
  2973. void EnumAggregation(std::function<void(ui32, const TAggregateDesc&)> f) {
  2974. const auto& catalog = TCatalog::Instance();
  2975. for (const auto& x : catalog.State->Aggregations) {
  2976. f(x.first, x.second);
  2977. }
  2978. }
  2979. bool HasOpClass(EOpClassMethod method, ui32 typeId) {
  2980. const auto& catalog = TCatalog::Instance();
  2981. return catalog.State->OpClasses.contains(std::make_pair(method, typeId));
  2982. }
  2983. const TOpClassDesc* LookupDefaultOpClass(EOpClassMethod method, ui32 typeId) {
  2984. const auto& catalog = TCatalog::Instance();
  2985. auto lookupId = (typeId == VarcharOid ? TextOid : typeId);
  2986. const auto opClassPtr = catalog.State->OpClasses.FindPtr(std::make_pair(method, lookupId));
  2987. if (opClassPtr)
  2988. return opClassPtr;
  2989. throw yexception() << "No such opclass";
  2990. // TODO: support binary coercible and preferred types as define in PG's GetDefaultOpClass()
  2991. }
  2992. bool HasAmOp(ui32 familyId, ui32 strategy, ui32 leftType, ui32 rightType) {
  2993. const auto &catalog = TCatalog::Instance();
  2994. return catalog.State->AmOps.contains(std::make_tuple(familyId, strategy, leftType, rightType));
  2995. }
  2996. const TAmOpDesc& LookupAmOp(ui32 familyId, ui32 strategy, ui32 leftType, ui32 rightType) {
  2997. const auto& catalog = TCatalog::Instance();
  2998. const auto amOpPtr = catalog.State->AmOps.FindPtr(std::make_tuple(familyId, strategy, leftType, rightType));
  2999. if (!amOpPtr) {
  3000. throw yexception() << "No such amop";
  3001. }
  3002. return *amOpPtr;
  3003. }
  3004. bool HasAmProc(ui32 familyId, ui32 num, ui32 leftType, ui32 rightType) {
  3005. const auto &catalog = TCatalog::Instance();
  3006. return catalog.State->AmProcs.contains(std::make_tuple(familyId, num, leftType, rightType));
  3007. }
  3008. const TAmProcDesc& LookupAmProc(ui32 familyId, ui32 num, ui32 leftType, ui32 rightType) {
  3009. const auto& catalog = TCatalog::Instance();
  3010. auto amProcPtr = catalog.State->AmProcs.FindPtr(std::make_tuple(familyId, num, leftType, rightType));
  3011. if (!amProcPtr) {
  3012. throw yexception() << "No such amproc";
  3013. }
  3014. return *amProcPtr;
  3015. }
  3016. bool HasConversion(const TString& from, const TString& to) {
  3017. const auto &catalog = TCatalog::Instance();
  3018. return catalog.State->Conversions.contains(std::make_pair(from, to));
  3019. }
  3020. const TConversionDesc& LookupConversion(const TString& from, const TString& to) {
  3021. const auto& catalog = TCatalog::Instance();
  3022. auto convPtr = catalog.State->Conversions.FindPtr(std::make_pair(from, to));
  3023. if (!convPtr) {
  3024. throw yexception() << "No such conversion from " << from << " to " << to;
  3025. }
  3026. return *convPtr;
  3027. }
  3028. bool IsCompatibleTo(ui32 actualType, ui32 expectedType) {
  3029. const auto& catalog = TCatalog::Instance();
  3030. return IsCompatibleTo(actualType, expectedType, catalog.State->Types);
  3031. }
  3032. const TLanguageDesc& LookupLanguage(ui32 langId) {
  3033. const auto& catalog = TCatalog::Instance();
  3034. auto langPtr = catalog.State->Languages.FindPtr(langId);
  3035. if (!langPtr) {
  3036. throw yexception() << "No such lang: " << langId;
  3037. }
  3038. return *langPtr;
  3039. }
  3040. void EnumLanguages(std::function<void(ui32, const TLanguageDesc&)> f) {
  3041. const auto& catalog = TCatalog::Instance();
  3042. for (const auto& x : catalog.State->Languages) {
  3043. f(x.first, x.second);
  3044. }
  3045. }
  3046. const TVector<TTableInfo>& GetStaticTables() {
  3047. const auto& catalog = TCatalog::Instance();
  3048. return catalog.State->AllStaticTables;
  3049. }
  3050. const THashMap<TTableInfoKey, TVector<TColumnInfo>>& GetStaticColumns() {
  3051. const auto& catalog = TCatalog::Instance();
  3052. return catalog.State->StaticColumns;
  3053. }
  3054. const TTableInfo& LookupStaticTable(const TTableInfoKey& tableKey) {
  3055. const auto& catalog = TCatalog::Instance();
  3056. auto tablePtr = catalog.State->StaticTables.FindPtr(tableKey);
  3057. if (!tablePtr) {
  3058. throw yexception() << "No such table: " << tableKey.Schema << "." << tableKey.Name;
  3059. }
  3060. return *tablePtr;
  3061. }
  3062. const TVector<TMaybe<TString>>* ReadTable(
  3063. const TTableInfoKey& tableKey,
  3064. const TVector<TString>& columnNames,
  3065. size_t* columnsRemap, // should have the same length as columnNames
  3066. size_t& rowStep) {
  3067. const auto& catalog = TCatalog::Instance();
  3068. auto dataPtr = catalog.State->StaticTablesData.FindPtr(tableKey);
  3069. if (!dataPtr) {
  3070. throw yexception() << "Missing data for table "
  3071. << tableKey.Schema << "." << tableKey.Name;
  3072. }
  3073. const auto& allColumns = *catalog.State->StaticColumns.FindPtr(tableKey);
  3074. THashMap<TString, size_t> columnsToIndex;
  3075. for (size_t i = 0; i < allColumns.size(); ++i) {
  3076. Y_ENSURE(columnsToIndex.emplace(allColumns[i].Name,i).second);
  3077. }
  3078. rowStep = allColumns.size();
  3079. for (size_t i = 0; i < columnNames.size(); ++i) {
  3080. auto indexPtr = columnsToIndex.FindPtr(columnNames[i]);
  3081. if (!indexPtr) {
  3082. throw yexception() << "Missing column " << columnNames[i] << " in table "
  3083. << tableKey.Schema << "." << tableKey.Name;
  3084. }
  3085. columnsRemap[i] = *indexPtr;
  3086. }
  3087. return dataPtr;
  3088. }
  3089. bool AreAllFunctionsAllowed() {
  3090. const auto& catalog = TCatalog::Instance();
  3091. return catalog.State->AllowAllFunctions;
  3092. }
  3093. void AllowFunction(const TString& name) {
  3094. auto& catalog = TCatalog::MutableInstance();
  3095. if (!catalog.State->AllowAllFunctions) {
  3096. catalog.State->AllowedProcs.insert(name);
  3097. }
  3098. }
  3099. struct TSqlLanguageParserHolder {
  3100. std::unique_ptr<ISqlLanguageParser> Parser;
  3101. };
  3102. void SetSqlLanguageParser(std::unique_ptr<ISqlLanguageParser> parser) {
  3103. Singleton<TSqlLanguageParserHolder>()->Parser = std::move(parser);
  3104. }
  3105. ISqlLanguageParser* GetSqlLanguageParser() {
  3106. return Singleton<TSqlLanguageParserHolder>()->Parser.get();
  3107. }
  3108. void LoadSystemFunctions(ISystemFunctionsParser& parser) {
  3109. YQL_PROFILE_FUNC(DEBUG);
  3110. auto& catalog = TCatalog::MutableInstance();
  3111. with_lock (catalog.ExtensionsGuard) {
  3112. if (catalog.State->SystemFunctionInit) {
  3113. return;
  3114. }
  3115. TString data;
  3116. Y_ENSURE(NResource::FindExact("system_functions.sql", &data));
  3117. TVector<TProcDesc> procs;
  3118. parser.Parse(data, procs);
  3119. for (const auto& p : procs) {
  3120. auto procIdPtr = catalog.State->ProcByName.FindPtr(p.Name);
  3121. Y_ENSURE(procIdPtr);
  3122. TProcDesc* foundProc = nullptr;
  3123. for (auto procId : *procIdPtr) {
  3124. auto procPtr = catalog.State->Procs.FindPtr(procId);
  3125. Y_ENSURE(procPtr);
  3126. if (procPtr->ArgTypes == p.ArgTypes && procPtr->VariadicType == p.VariadicType) {
  3127. foundProc = procPtr;
  3128. break;
  3129. }
  3130. }
  3131. Y_ENSURE(foundProc);
  3132. foundProc->DefaultArgs = p.DefaultArgs;
  3133. foundProc->Src = p.Src;
  3134. foundProc->ExprNode = p.ExprNode;
  3135. }
  3136. catalog.State->SystemFunctionInit = true;
  3137. }
  3138. }
  3139. void RegisterExtensions(const TVector<TExtensionDesc>& extensions, bool typesOnly,
  3140. IExtensionSqlParser& parser, IExtensionLoader* loader) {
  3141. YQL_PROFILE_FUNC(DEBUG);
  3142. if (extensions.size() > MaximumExtensionsCount) {
  3143. throw yexception() << "Too many extensions: " << extensions.size();
  3144. }
  3145. auto& catalog = TCatalog::MutableInstance();
  3146. with_lock (catalog.ExtensionsGuard) {
  3147. Y_ENSURE(!catalog.ExtensionsInit);
  3148. auto savedAllowAllFunctions = catalog.State->AllowAllFunctions;
  3149. catalog.State->AllowAllFunctions = true;
  3150. for (ui32 i = 0; i < extensions.size(); ++i) {
  3151. auto e = extensions[i];
  3152. e.TypesOnly = e.TypesOnly || typesOnly;
  3153. if (e.Name.empty()) {
  3154. throw yexception() << "Empty extension name";
  3155. }
  3156. if (!catalog.State->ExtensionsByName.insert(std::make_pair(e.Name, i + 1)).second) {
  3157. throw yexception() << "Duplicated extension name: " << e.Name;
  3158. }
  3159. if (!catalog.State->ExtensionsByInstallName.insert(std::make_pair(e.InstallName, i + 1)).second) {
  3160. throw yexception() << "Duplicated extension install name: " << e.InstallName;
  3161. }
  3162. if (e.LibraryMD5.empty() && !e.LibraryPath.empty()) {
  3163. e.LibraryMD5 = MD5::File(e.LibraryPath);
  3164. }
  3165. catalog.State->Extensions.push_back(e);
  3166. TVector<TString> sqls;
  3167. for (const auto& p : e.SqlPaths) {
  3168. TString sql = TFileInput(p).ReadAll();
  3169. sqls.push_back(sql);
  3170. }
  3171. parser.Parse(i + 1, sqls, catalog);
  3172. if (loader && !e.TypesOnly && !e.LibraryPath.empty()) {
  3173. loader->Load(i + 1, e.Name, e.LibraryPath);
  3174. }
  3175. }
  3176. catalog.State->AllowAllFunctions = savedAllowAllFunctions;
  3177. catalog.ExtensionsInit = true;
  3178. }
  3179. }
  3180. TString ExportExtensions(const TMaybe<TSet<ui32>>& filter) {
  3181. auto& catalog = TCatalog::Instance();
  3182. if (catalog.State->Extensions.empty()) {
  3183. return TString();
  3184. }
  3185. NProto::TPgCatalog proto;
  3186. for (ui32 i = 0; i < catalog.State->Extensions.size(); ++i) {
  3187. const auto& ext = catalog.State->Extensions[i];
  3188. const bool skip = filter && !filter->contains(i + 1);
  3189. auto protoExt = proto.AddExtension();
  3190. protoExt->SetName(ext.Name);
  3191. protoExt->SetInstallName(ext.InstallName);
  3192. protoExt->SetTypesOnly(skip);
  3193. if (!skip && !ext.LibraryPath.empty()) {
  3194. protoExt->SetLibraryPath(TFsPath(".") / TFsPath(ext.LibraryPath).GetName());
  3195. protoExt->SetLibraryMD5(ext.LibraryMD5);
  3196. }
  3197. }
  3198. TVector<ui32> extTypes;
  3199. for (const auto& t : catalog.State->Types) {
  3200. const auto& desc = t.second;
  3201. if (!desc.ExtensionIndex) {
  3202. continue;
  3203. }
  3204. extTypes.push_back(t.first);
  3205. }
  3206. Sort(extTypes);
  3207. for (const auto t : extTypes) {
  3208. const auto& desc = *catalog.State->Types.FindPtr(t);
  3209. auto protoType = proto.AddType();
  3210. protoType->SetTypeId(desc.TypeId);
  3211. protoType->SetName(desc.Name);
  3212. protoType->SetExtensionIndex(desc.ExtensionIndex);
  3213. protoType->SetCategory(desc.Category);
  3214. protoType->SetTypeLen(desc.TypeLen);
  3215. protoType->SetPassByValue(desc.PassByValue);
  3216. protoType->SetTypeAlign(desc.TypeAlign);
  3217. protoType->SetElementTypeId(desc.ElementTypeId);
  3218. protoType->SetArrayTypeId(desc.ArrayTypeId);
  3219. if (desc.InFuncId) {
  3220. protoType->SetInFuncId(desc.InFuncId);
  3221. }
  3222. if (desc.OutFuncId) {
  3223. protoType->SetOutFuncId(desc.OutFuncId);
  3224. }
  3225. if (desc.SendFuncId) {
  3226. protoType->SetSendFuncId(desc.SendFuncId);
  3227. }
  3228. if (desc.ReceiveFuncId) {
  3229. protoType->SetReceiveFuncId(desc.ReceiveFuncId);
  3230. }
  3231. if (desc.TypeModInFuncId) {
  3232. protoType->SetTypeModInFuncId(desc.TypeModInFuncId);
  3233. }
  3234. if (desc.TypeModOutFuncId) {
  3235. protoType->SetTypeModOutFuncId(desc.TypeModOutFuncId);
  3236. }
  3237. if (desc.TypeSubscriptFuncId) {
  3238. protoType->SetTypeSubscriptFuncId(desc.TypeSubscriptFuncId);
  3239. }
  3240. if (desc.LessProcId) {
  3241. protoType->SetLessProcId(desc.LessProcId);
  3242. }
  3243. if (desc.EqualProcId) {
  3244. protoType->SetEqualProcId(desc.EqualProcId);
  3245. }
  3246. if (desc.CompareProcId) {
  3247. protoType->SetCompareProcId(desc.CompareProcId);
  3248. }
  3249. if (desc.HashProcId) {
  3250. protoType->SetHashProcId(desc.HashProcId);
  3251. }
  3252. }
  3253. TVector<ui32> extProcs;
  3254. for (const auto& p : catalog.State->Procs) {
  3255. const auto& desc = p.second;
  3256. if (!desc.ExtensionIndex) {
  3257. continue;
  3258. }
  3259. extProcs.push_back(p.first);
  3260. }
  3261. Sort(extProcs);
  3262. for (const auto p : extProcs) {
  3263. const auto& desc = *catalog.State->Procs.FindPtr(p);
  3264. auto protoProc = proto.AddProc();
  3265. protoProc->SetProcId(desc.ProcId);
  3266. protoProc->SetName(desc.Name);
  3267. protoProc->SetExtensionIndex(desc.ExtensionIndex);
  3268. protoProc->SetSrc(desc.Src);
  3269. for (const auto t : desc.ArgTypes) {
  3270. protoProc->AddArgType(t);
  3271. }
  3272. for (const auto t : desc.OutputArgTypes) {
  3273. protoProc->AddOutputArgType(t);
  3274. }
  3275. protoProc->SetVariadicType(desc.VariadicType);
  3276. protoProc->SetVariadicArgType(desc.VariadicArgType);
  3277. for (const auto& name : desc.InputArgNames) {
  3278. protoProc->AddInputArgName(name);
  3279. }
  3280. for (const auto& name : desc.OutputArgNames) {
  3281. protoProc->AddOutputArgName(name);
  3282. }
  3283. protoProc->SetVariadicArgName(desc.VariadicArgName);
  3284. for (const auto& d : desc.DefaultArgs) {
  3285. protoProc->AddDefaultArgNull(!d.Defined());
  3286. protoProc->AddDefaultArgValue(d ? *d : "");
  3287. }
  3288. protoProc->SetIsStrict(desc.IsStrict);
  3289. protoProc->SetLang(desc.Lang);
  3290. protoProc->SetResultType(desc.ResultType);
  3291. protoProc->SetReturnSet(desc.ReturnSet);
  3292. protoProc->SetKind((ui32)desc.Kind);
  3293. }
  3294. TVector<TTableInfoKey> extTables;
  3295. for (const auto& t : catalog.State->StaticTables) {
  3296. if (!t.second.ExtensionIndex) {
  3297. continue;
  3298. }
  3299. extTables.push_back(t.first);
  3300. }
  3301. Sort(extTables);
  3302. for (const auto& key : extTables) {
  3303. const auto& table = *catalog.State->StaticTables.FindPtr(key);
  3304. auto protoTable = proto.AddTable();
  3305. protoTable->SetOid(table.Oid);
  3306. protoTable->SetSchema(table.Schema);
  3307. protoTable->SetName(table.Name);
  3308. protoTable->SetExtensionIndex(table.ExtensionIndex);
  3309. const auto columnsPtr = catalog.State->StaticColumns.FindPtr(key);
  3310. Y_ENSURE(columnsPtr);
  3311. for (const auto& c : *columnsPtr) {
  3312. protoTable->AddColumn(c.Name);
  3313. protoTable->AddUdtType(c.UdtType);
  3314. }
  3315. const auto dataPtr = catalog.State->StaticTablesData.FindPtr(key);
  3316. if (dataPtr) {
  3317. for (const auto& v : *dataPtr) {
  3318. if (v.Defined()) {
  3319. protoTable->AddDataNull(false);
  3320. protoTable->AddDataValue(*v);
  3321. } else {
  3322. protoTable->AddDataNull(true);
  3323. protoTable->AddDataValue("");
  3324. }
  3325. }
  3326. }
  3327. }
  3328. TVector<ui32> extCasts;
  3329. for (const auto& c : catalog.State->Casts) {
  3330. const auto& desc = c.second;
  3331. if (!desc.ExtensionIndex) {
  3332. continue;
  3333. }
  3334. extCasts.push_back(c.first);
  3335. }
  3336. Sort(extCasts);
  3337. for (const auto p : extCasts) {
  3338. const auto& desc = *catalog.State->Casts.FindPtr(p);
  3339. auto protoCast = proto.AddCast();
  3340. protoCast->SetId(p);
  3341. protoCast->SetSourceId(desc.SourceId);
  3342. protoCast->SetTargetId(desc.TargetId);
  3343. protoCast->SetExtensionIndex(desc.ExtensionIndex);
  3344. protoCast->SetMethod((ui32)desc.Method);
  3345. protoCast->SetFunctionId(desc.FunctionId);
  3346. protoCast->SetCoercionCode((ui32)desc.CoercionCode);
  3347. }
  3348. TVector<ui32> extOpers;
  3349. for (const auto& o : catalog.State->Operators) {
  3350. const auto& desc = o.second;
  3351. if (!desc.ExtensionIndex) {
  3352. continue;
  3353. }
  3354. extOpers.push_back(o.first);
  3355. }
  3356. Sort(extOpers);
  3357. for (const auto o : extOpers) {
  3358. const auto& desc = *catalog.State->Operators.FindPtr(o);
  3359. auto protoOper = proto.AddOper();
  3360. protoOper->SetOperId(o);
  3361. protoOper->SetName(desc.Name);
  3362. protoOper->SetExtensionIndex(desc.ExtensionIndex);
  3363. protoOper->SetLeftType(desc.LeftType);
  3364. protoOper->SetRightType(desc.RightType);
  3365. protoOper->SetKind((ui32)desc.Kind);
  3366. protoOper->SetProcId(desc.ProcId);
  3367. protoOper->SetResultType(desc.ResultType);
  3368. protoOper->SetComId(desc.ComId);
  3369. protoOper->SetNegateId(desc.NegateId);
  3370. }
  3371. TVector<ui32> extAggs;
  3372. for (const auto& a : catalog.State->Aggregations) {
  3373. const auto& desc = a.second;
  3374. if (!desc.ExtensionIndex) {
  3375. continue;
  3376. }
  3377. extAggs.push_back(a.first);
  3378. }
  3379. Sort(extAggs);
  3380. for (const auto a : extAggs) {
  3381. const auto& desc = *catalog.State->Aggregations.FindPtr(a);
  3382. auto protoAggregation = proto.AddAggregation();
  3383. protoAggregation->SetAggId(a);
  3384. protoAggregation->SetName(desc.Name);
  3385. protoAggregation->SetExtensionIndex(desc.ExtensionIndex);
  3386. for (const auto argType : desc.ArgTypes) {
  3387. protoAggregation->AddArgType(argType);
  3388. }
  3389. protoAggregation->SetKind((ui32)desc.Kind);
  3390. protoAggregation->SetTransTypeId(desc.TransTypeId);
  3391. protoAggregation->SetTransFuncId(desc.TransFuncId);
  3392. protoAggregation->SetFinalFuncId(desc.FinalFuncId);
  3393. protoAggregation->SetCombineFuncId(desc.CombineFuncId);
  3394. protoAggregation->SetSerializeFuncId(desc.SerializeFuncId);
  3395. protoAggregation->SetDeserializeFuncId(desc.DeserializeFuncId);
  3396. protoAggregation->SetInitValue(desc.InitValue);
  3397. protoAggregation->SetFinalExtra(desc.FinalExtra);
  3398. protoAggregation->SetNumDirectArgs(desc.NumDirectArgs);
  3399. }
  3400. TVector<TString> extOpFamilies;
  3401. for (const auto& f : catalog.State->OpFamilies) {
  3402. const auto& desc = f.second;
  3403. if (!desc.ExtensionIndex) {
  3404. continue;
  3405. }
  3406. extOpFamilies.push_back(f.first);
  3407. }
  3408. Sort(extOpFamilies);
  3409. for (const auto& f : extOpFamilies) {
  3410. const auto& desc = *catalog.State->OpFamilies.FindPtr(f);
  3411. auto protoOpClassFamily = proto.AddOpClassFamily();
  3412. protoOpClassFamily->SetFamilyId(desc.FamilyId);
  3413. protoOpClassFamily->SetName(desc.Name);
  3414. protoOpClassFamily->SetExtensionIndex(desc.ExtensionIndex);
  3415. }
  3416. TVector<std::pair<NPg::EOpClassMethod, ui32>> extOpClasses;
  3417. for (const auto& c : catalog.State->OpClasses) {
  3418. const auto& desc = c.second;
  3419. if (!desc.ExtensionIndex) {
  3420. continue;
  3421. }
  3422. extOpClasses.push_back(c.first);
  3423. }
  3424. for (const auto& c : extOpClasses) {
  3425. const auto& desc = *catalog.State->OpClasses.FindPtr(c);
  3426. auto protoOpClass = proto.AddOpClass();
  3427. protoOpClass->SetMethod((ui32)desc.Method);
  3428. protoOpClass->SetTypeId(desc.TypeId);
  3429. protoOpClass->SetExtensionIndex(desc.ExtensionIndex);
  3430. protoOpClass->SetName(desc.Name);
  3431. protoOpClass->SetFamilyId(desc.FamilyId);
  3432. }
  3433. TVector<std::tuple<ui32, ui32, ui32, ui32>> extAmOps;
  3434. for (const auto& o : catalog.State->AmOps) {
  3435. const auto& desc = o.second;
  3436. if (!desc.ExtensionIndex) {
  3437. continue;
  3438. }
  3439. extAmOps.push_back(o.first);
  3440. }
  3441. for (const auto& o : extAmOps) {
  3442. const auto& desc = *catalog.State->AmOps.FindPtr(o);
  3443. auto protoAmOp = proto.AddAmOp();
  3444. protoAmOp->SetFamilyId(desc.FamilyId);
  3445. protoAmOp->SetStrategy(desc.Strategy);
  3446. protoAmOp->SetLeftType(desc.LeftType);
  3447. protoAmOp->SetRightType(desc.RightType);
  3448. protoAmOp->SetOperId(desc.OperId);
  3449. protoAmOp->SetExtensionIndex(desc.ExtensionIndex);
  3450. }
  3451. TVector<std::tuple<ui32, ui32, ui32, ui32>> extAmProcs;
  3452. for (const auto& p : catalog.State->AmProcs) {
  3453. const auto& desc = p.second;
  3454. if (!desc.ExtensionIndex) {
  3455. continue;
  3456. }
  3457. extAmProcs.push_back(p.first);
  3458. }
  3459. for (const auto& p : extAmProcs) {
  3460. const auto& desc = *catalog.State->AmProcs.FindPtr(p);
  3461. auto protoAmProc = proto.AddAmProc();
  3462. protoAmProc->SetFamilyId(desc.FamilyId);
  3463. protoAmProc->SetProcNum(desc.ProcNum);
  3464. protoAmProc->SetLeftType(desc.LeftType);
  3465. protoAmProc->SetRightType(desc.RightType);
  3466. protoAmProc->SetProcId(desc.ProcId);
  3467. protoAmProc->SetExtensionIndex(desc.ExtensionIndex);
  3468. }
  3469. return proto.SerializeAsString();
  3470. }
  3471. void ImportExtensions(const TString& exported, bool typesOnly, IExtensionLoader* loader) {
  3472. auto& catalog = TCatalog::MutableInstance();
  3473. with_lock (catalog.ExtensionsGuard) {
  3474. Y_ENSURE(!catalog.ExtensionsInit);
  3475. if (exported.empty()) {
  3476. catalog.ExtensionsInit = true;
  3477. return;
  3478. }
  3479. NProto::TPgCatalog proto;
  3480. Y_ENSURE(proto.ParseFromString(exported));
  3481. for (ui32 i = 0; i < proto.ExtensionSize(); ++i) {
  3482. const auto& protoExt = proto.GetExtension(i);
  3483. TExtensionDesc e;
  3484. e.Name = protoExt.GetName();
  3485. e.InstallName = protoExt.GetInstallName();
  3486. e.TypesOnly = protoExt.GetTypesOnly();
  3487. e.LibraryMD5 = protoExt.GetLibraryMD5();
  3488. e.LibraryPath = protoExt.GetLibraryPath();
  3489. catalog.State->Extensions.push_back(e);
  3490. if (!catalog.State->ExtensionsByName.insert(std::make_pair(e.Name, i + 1)).second) {
  3491. throw yexception() << "Duplicated extension name: " << e.Name;
  3492. }
  3493. if (!catalog.State->ExtensionsByInstallName.insert(std::make_pair(e.InstallName, i + 1)).second) {
  3494. throw yexception() << "Duplicated extension install name: " << e.InstallName;
  3495. }
  3496. }
  3497. for (const auto& protoType : proto.GetType()) {
  3498. TTypeDesc desc;
  3499. desc.TypeId = protoType.GetTypeId();
  3500. desc.Name = protoType.GetName();
  3501. desc.ExtensionIndex = protoType.GetExtensionIndex();
  3502. desc.Category = protoType.GetCategory();
  3503. desc.TypeLen = protoType.GetTypeLen();
  3504. desc.PassByValue = protoType.GetPassByValue();
  3505. desc.TypeAlign = protoType.GetTypeAlign();
  3506. desc.ElementTypeId = protoType.GetElementTypeId();
  3507. desc.ArrayTypeId = protoType.GetArrayTypeId();
  3508. desc.InFuncId = protoType.GetInFuncId();
  3509. desc.OutFuncId = protoType.GetOutFuncId();
  3510. desc.SendFuncId = protoType.GetSendFuncId();
  3511. desc.ReceiveFuncId = protoType.GetReceiveFuncId();
  3512. desc.TypeModInFuncId = protoType.GetTypeModInFuncId();
  3513. desc.TypeModOutFuncId = protoType.GetTypeModOutFuncId();
  3514. desc.TypeSubscriptFuncId = protoType.GetTypeSubscriptFuncId();
  3515. desc.LessProcId = protoType.GetLessProcId();
  3516. desc.EqualProcId = protoType.GetEqualProcId();
  3517. desc.CompareProcId = protoType.GetCompareProcId();
  3518. desc.HashProcId = protoType.GetHashProcId();
  3519. Y_ENSURE(catalog.State->Types.emplace(desc.TypeId, desc).second);
  3520. Y_ENSURE(catalog.State->TypeByName.emplace(desc.Name, desc.TypeId).second);
  3521. }
  3522. for (const auto& protoProc : proto.GetProc()) {
  3523. TProcDesc desc;
  3524. desc.ProcId = protoProc.GetProcId();
  3525. desc.Name = protoProc.GetName();
  3526. desc.ExtensionIndex = protoProc.GetExtensionIndex();
  3527. desc.Src = protoProc.GetSrc();
  3528. desc.IsStrict = protoProc.GetIsStrict();
  3529. desc.Lang = protoProc.GetLang();
  3530. desc.ResultType = protoProc.GetResultType();
  3531. desc.ReturnSet = protoProc.GetReturnSet();
  3532. desc.Kind = (EProcKind)protoProc.GetKind();
  3533. for (const auto t : protoProc.GetArgType()) {
  3534. desc.ArgTypes.push_back(t);
  3535. }
  3536. for (const auto t : protoProc.GetOutputArgType()) {
  3537. desc.OutputArgTypes.push_back(t);
  3538. }
  3539. desc.VariadicType = protoProc.GetVariadicType();
  3540. desc.VariadicArgType = protoProc.GetVariadicArgType();
  3541. for (const auto& name : protoProc.GetInputArgName()) {
  3542. desc.InputArgNames.push_back(name);
  3543. }
  3544. for (const auto& name : protoProc.GetOutputArgName()) {
  3545. desc.OutputArgNames.push_back(name);
  3546. }
  3547. desc.VariadicArgName = protoProc.GetVariadicArgName();
  3548. Y_ENSURE(protoProc.DefaultArgNullSize() == protoProc.DefaultArgValueSize());
  3549. for (ui32 i = 0; i < protoProc.DefaultArgNullSize(); ++i) {
  3550. if (protoProc.GetDefaultArgNull(i)) {
  3551. desc.DefaultArgs.push_back(Nothing());
  3552. } else {
  3553. desc.DefaultArgs.push_back(protoProc.GetDefaultArgValue(i));
  3554. }
  3555. }
  3556. Y_ENSURE(catalog.State->Procs.emplace(desc.ProcId, desc).second);
  3557. catalog.State->ProcByName[desc.Name].push_back(desc.ProcId);
  3558. }
  3559. for (const auto& protoTable : proto.GetTable()) {
  3560. TTableInfo table;
  3561. table.Oid = protoTable.GetOid();
  3562. table.Schema = protoTable.GetSchema();
  3563. table.Name = protoTable.GetName();
  3564. table.Kind = ERelKind::Relation;
  3565. table.ExtensionIndex = protoTable.GetExtensionIndex();
  3566. catalog.State->AllStaticTables.push_back(table);
  3567. TTableInfoKey key = table;
  3568. Y_ENSURE(catalog.State->StaticTables.emplace(key, table).second);
  3569. Y_ENSURE(protoTable.ColumnSize() > 0);
  3570. Y_ENSURE(protoTable.ColumnSize() == protoTable.UdtTypeSize());
  3571. for (ui32 i = 0; i < protoTable.ColumnSize(); ++i) {
  3572. TColumnInfo columnInfo;
  3573. columnInfo.Schema = table.Schema;
  3574. columnInfo.TableName = table.Name;
  3575. columnInfo.ExtensionIndex = table.ExtensionIndex;
  3576. columnInfo.Name = protoTable.GetColumn(i);
  3577. columnInfo.UdtType = protoTable.GetUdtType(i);
  3578. catalog.State->AllStaticColumns.push_back(columnInfo);
  3579. catalog.State->StaticColumns[key].push_back(columnInfo);
  3580. }
  3581. if (protoTable.DataValueSize() > 0) {
  3582. Y_ENSURE(protoTable.DataValueSize() == protoTable.DataNullSize());
  3583. auto& data = catalog.State->StaticTablesData[key];
  3584. data.reserve(protoTable.DataValueSize());
  3585. for (ui64 i = 0; i < protoTable.DataValueSize(); ++i) {
  3586. if (protoTable.GetDataNull(i)) {
  3587. data.push_back(Nothing());
  3588. } else {
  3589. data.push_back(protoTable.GetDataValue(i));
  3590. }
  3591. }
  3592. }
  3593. }
  3594. for (const auto& protoCast : proto.GetCast()) {
  3595. auto id = protoCast.GetId();
  3596. TCastDesc desc;
  3597. desc.SourceId = protoCast.GetSourceId();
  3598. desc.TargetId = protoCast.GetTargetId();
  3599. desc.ExtensionIndex = protoCast.GetExtensionIndex();
  3600. desc.Method = (ECastMethod)protoCast.GetMethod();
  3601. desc.FunctionId = protoCast.GetFunctionId();
  3602. desc.CoercionCode = (ECoercionCode)protoCast.GetCoercionCode();
  3603. Y_ENSURE(catalog.State->Casts.emplace(id, desc).second);
  3604. Y_ENSURE(catalog.State->CastsByDir.insert(std::make_pair(std::make_pair(desc.SourceId, desc.TargetId), id)).second);
  3605. }
  3606. for (const auto& protoOper : proto.GetOper()) {
  3607. TOperDesc desc;
  3608. desc.OperId = protoOper.GetOperId();
  3609. desc.Name = protoOper.GetName();
  3610. desc.ExtensionIndex = protoOper.GetExtensionIndex();
  3611. desc.LeftType = protoOper.GetLeftType();
  3612. desc.RightType = protoOper.GetRightType();
  3613. desc.Kind = (EOperKind)protoOper.GetKind();
  3614. desc.ProcId = protoOper.GetProcId();
  3615. desc.ResultType = protoOper.GetResultType();
  3616. desc.ComId = protoOper.GetComId();
  3617. desc.NegateId = protoOper.GetNegateId();
  3618. Y_ENSURE(catalog.State->Operators.emplace(desc.OperId, desc).second);
  3619. catalog.State->OperatorsByName[desc.Name].push_back(desc.OperId);
  3620. }
  3621. for (const auto& protoAggregation : proto.GetAggregation()) {
  3622. TAggregateDesc desc;
  3623. desc.AggId = protoAggregation.GetAggId();
  3624. desc.Name = protoAggregation.GetName();
  3625. desc.ExtensionIndex = protoAggregation.GetExtensionIndex();
  3626. for (const auto argType : protoAggregation.GetArgType()) {
  3627. desc.ArgTypes.push_back(argType);
  3628. }
  3629. desc.Kind = (NPg::EAggKind)protoAggregation.GetKind();
  3630. desc.TransTypeId = protoAggregation.GetTransTypeId();
  3631. desc.TransFuncId = protoAggregation.GetTransFuncId();
  3632. desc.FinalFuncId = protoAggregation.GetFinalFuncId();
  3633. desc.CombineFuncId = protoAggregation.GetCombineFuncId();
  3634. desc.SerializeFuncId = protoAggregation.GetSerializeFuncId();
  3635. desc.DeserializeFuncId = protoAggregation.GetDeserializeFuncId();
  3636. desc.InitValue = protoAggregation.GetInitValue();
  3637. desc.FinalExtra = protoAggregation.GetFinalExtra();
  3638. desc.NumDirectArgs = protoAggregation.GetNumDirectArgs();
  3639. Y_ENSURE(catalog.State->Aggregations.emplace(desc.AggId, desc).second);
  3640. catalog.State->AggregationsByName[desc.Name].push_back(desc.AggId);
  3641. }
  3642. THashMap<ui32, TString> opFamiliesByOid;
  3643. for (const auto& protoOpClassFamily : proto.GetOpClassFamily()) {
  3644. TOpFamilyDesc desc;
  3645. desc.FamilyId = protoOpClassFamily.GetFamilyId();
  3646. desc.Name = protoOpClassFamily.GetName();
  3647. desc.ExtensionIndex = protoOpClassFamily.GetExtensionIndex();
  3648. Y_ENSURE(catalog.State->OpFamilies.emplace(desc.Name, desc).second);
  3649. Y_ENSURE(opFamiliesByOid.emplace(desc.FamilyId, desc.Name).second);
  3650. }
  3651. for (const auto& protoOpClass : proto.GetOpClass()) {
  3652. TOpClassDesc desc;
  3653. desc.Method = (EOpClassMethod)protoOpClass.GetMethod();
  3654. desc.TypeId = protoOpClass.GetTypeId();
  3655. desc.ExtensionIndex = protoOpClass.GetExtensionIndex();
  3656. desc.FamilyId = protoOpClass.GetFamilyId();
  3657. desc.Name = protoOpClass.GetName();
  3658. desc.Family = *opFamiliesByOid.FindPtr(desc.FamilyId);
  3659. Y_ENSURE(catalog.State->OpClasses.emplace(std::make_pair(desc.Method, desc.TypeId), desc).second);
  3660. }
  3661. for (const auto& protoAmOp : proto.GetAmOp()) {
  3662. TAmOpDesc desc;
  3663. desc.FamilyId = protoAmOp.GetFamilyId();
  3664. desc.Strategy = protoAmOp.GetStrategy();
  3665. desc.LeftType = protoAmOp.GetLeftType();
  3666. desc.RightType = protoAmOp.GetRightType();
  3667. desc.OperId = protoAmOp.GetOperId();
  3668. desc.ExtensionIndex = protoAmOp.GetExtensionIndex();
  3669. desc.Family = *opFamiliesByOid.FindPtr(desc.FamilyId);
  3670. Y_ENSURE(catalog.State->AmOps.emplace(std::make_tuple(desc.FamilyId, desc.Strategy, desc.LeftType, desc.RightType), desc).second);
  3671. }
  3672. for (const auto& protoAmProc : proto.GetAmProc()) {
  3673. TAmProcDesc desc;
  3674. desc.FamilyId = protoAmProc.GetFamilyId();
  3675. desc.ProcNum = protoAmProc.GetProcNum();
  3676. desc.LeftType = protoAmProc.GetLeftType();
  3677. desc.RightType = protoAmProc.GetRightType();
  3678. desc.ProcId = protoAmProc.GetProcId();
  3679. desc.ExtensionIndex = protoAmProc.GetExtensionIndex();
  3680. desc.Family = *opFamiliesByOid.FindPtr(desc.FamilyId);
  3681. Y_ENSURE(catalog.State->AmProcs.emplace(std::make_tuple(desc.FamilyId, desc.ProcNum, desc.LeftType, desc.RightType), desc).second);
  3682. }
  3683. if (!typesOnly && loader) {
  3684. for (ui32 extensionIndex = 1; extensionIndex <= catalog.State->Extensions.size(); ++extensionIndex) {
  3685. const auto& e = catalog.State->Extensions[extensionIndex - 1];
  3686. if (!e.TypesOnly) {
  3687. loader->Load(extensionIndex, e.Name, e.LibraryPath);
  3688. }
  3689. }
  3690. }
  3691. catalog.State->AllowAllFunctions = true;
  3692. catalog.State->AllowedProcs.clear();
  3693. catalog.ExtensionsInit = true;
  3694. }
  3695. }
  3696. void ClearExtensions() {
  3697. auto& catalog = TCatalog::MutableInstance();
  3698. with_lock (catalog.ExtensionsGuard) {
  3699. if (!catalog.ExtensionsInit) {
  3700. return;
  3701. }
  3702. catalog.Init();
  3703. catalog.ExtensionsInit = false;
  3704. }
  3705. }
  3706. void EnumExtensions(std::function<void(ui32, const TExtensionDesc&)> f) {
  3707. const auto& catalog = TCatalog::Instance();
  3708. for (ui32 i = 0; i < catalog.State->Extensions.size(); ++i) {
  3709. f(i + 1, catalog.State->Extensions[i]);
  3710. }
  3711. }
  3712. const TExtensionDesc& LookupExtension(ui32 extIndex) {
  3713. const auto& catalog = TCatalog::Instance();
  3714. Y_ENSURE(extIndex > 0 && extIndex <= catalog.State->Extensions.size());
  3715. return catalog.State->Extensions[extIndex - 1];
  3716. }
  3717. ui32 LookupExtensionByName(const TString& name) {
  3718. const auto& catalog = TCatalog::Instance();
  3719. auto indexPtr = catalog.State->ExtensionsByName.FindPtr(name);
  3720. if (!indexPtr) {
  3721. throw yexception() << "Unknown extension name: " << name;
  3722. }
  3723. return *indexPtr;
  3724. }
  3725. ui32 LookupExtensionByInstallName(const TString& installName) {
  3726. const auto& catalog = TCatalog::Instance();
  3727. auto indexPtr = catalog.State->ExtensionsByInstallName.FindPtr(installName);
  3728. if (!indexPtr) {
  3729. throw yexception() << "Unknown extension install name: " << installName;
  3730. }
  3731. return *indexPtr;
  3732. }
  3733. }