rtldynfield.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include <math.h>
  15. #include <stdio.h>
  16. #include "jmisc.hpp"
  17. #include "jlib.hpp"
  18. #include "eclhelper.hpp"
  19. #include "eclrtl_imp.hpp"
  20. #include "rtldynfield.hpp"
  21. #include "rtlrecord.hpp"
  22. #include "rtlembed.hpp"
  23. #include "rtlnewkey.hpp"
  24. //#define TRACE_TRANSLATION
  25. #define VALIDATE_TYPEINFO_HASHES
  26. #define RTLTYPEINFO_FORMAT_1 80 // In case we ever want to support more than one format
  27. //---------------------------------------------------------------------------------------------------------------------
  28. extern ECLRTL_API RecordTranslationMode getTranslationMode(const char *val)
  29. {
  30. if (!val || strToBool(val) || strieq(val, "payload"))
  31. return RecordTranslationMode::Payload;
  32. else if (strieq(val, "alwaysDisk"))
  33. return RecordTranslationMode::AlwaysDisk;
  34. else if (strieq(val, "alwaysECL"))
  35. return RecordTranslationMode::AlwaysECL;
  36. else
  37. return RecordTranslationMode::None;
  38. }
  39. extern ECLRTL_API const char *getTranslationModeText(RecordTranslationMode val)
  40. {
  41. switch (val)
  42. {
  43. case RecordTranslationMode::AlwaysDisk: return "alwaysDisk";
  44. case RecordTranslationMode::AlwaysECL: return "alwaysECL";
  45. case RecordTranslationMode::Payload: return "payload";
  46. case RecordTranslationMode::None: return "off";
  47. }
  48. throwUnexpected();
  49. }
  50. //---------------------------------------------------------------------------------------------------------------------
  51. const RtlTypeInfo *FieldTypeInfoStruct::createRtlTypeInfo(IThorIndexCallback *_callback) const
  52. {
  53. const RtlTypeInfo *ret = nullptr;
  54. switch (fieldType & RFTMkind)
  55. {
  56. case type_boolean:
  57. ret = new RtlBoolTypeInfo(fieldType, length);
  58. break;
  59. case type_keyedint:
  60. ret = new RtlKeyedIntTypeInfo(fieldType, length, childType);
  61. break;
  62. case type_blob: // MORE - will need its own type (see code below)
  63. case type_int:
  64. ret = new RtlIntTypeInfo(fieldType, length);
  65. break;
  66. #if 0 // Later when implemented
  67. case type_blob:
  68. ret = new RtlBlobTypeInfo(fieldType, length, childType, _callback);
  69. break;
  70. #endif
  71. case type_filepos:
  72. #if __BYTE_ORDER == __LITTLE_ENDIAN
  73. ret = new RtlSwapIntTypeInfo(fieldType, length);
  74. #else
  75. ret = new RtlIntTypeInfo(fieldType, length);
  76. #endif
  77. break;
  78. case type_real:
  79. ret = new RtlRealTypeInfo(fieldType, length);
  80. break;
  81. case type_decimal:
  82. ret = new RtlDecimalTypeInfo(fieldType, length);
  83. break;
  84. case type_string:
  85. ret = new RtlStringTypeInfo(fieldType, length);
  86. break;
  87. case type_bitfield:
  88. ret = new RtlBitfieldTypeInfo(fieldType, length);
  89. break;
  90. case type_varstring:
  91. ret = new RtlVarStringTypeInfo(fieldType, length);
  92. break;
  93. case type_data:
  94. ret = new RtlDataTypeInfo(fieldType, length);
  95. break;
  96. case type_table:
  97. assert(childType);
  98. ret = new RtlDatasetTypeInfo(fieldType, length, childType);
  99. break;
  100. case type_dictionary:
  101. assert(childType);
  102. ret = new RtlDictionaryTypeInfo(fieldType, length, childType);
  103. break;
  104. case type_set:
  105. assert(childType);
  106. ret = new RtlSetTypeInfo(fieldType, length, childType);
  107. break;
  108. case type_row:
  109. assert(childType);
  110. ret = new RtlRowTypeInfo(fieldType, length, childType);
  111. break;
  112. case type_swapint:
  113. ret = new RtlSwapIntTypeInfo(fieldType, length);
  114. break;
  115. case type_packedint:
  116. ret = new RtlPackedIntTypeInfo(fieldType, length);
  117. break;
  118. case type_qstring:
  119. ret = new RtlQStringTypeInfo(fieldType, length);
  120. break;
  121. case type_unicode:
  122. ret = new RtlUnicodeTypeInfo(fieldType, length, locale);
  123. break;
  124. case type_varunicode:
  125. ret = new RtlVarUnicodeTypeInfo(fieldType, length, locale);
  126. break;
  127. case type_utf8:
  128. ret = new RtlUtf8TypeInfo(fieldType, length, locale);
  129. break;
  130. case type_record:
  131. ret = new RtlRecordTypeInfo(fieldType, length, fieldsArray);
  132. break;
  133. case type_ifblock:
  134. ret = new RtlDynamicIfBlockTypeInfo(fieldType, length, fieldsArray, nullptr, filter);
  135. break;
  136. case type_alien:
  137. assert(childType);
  138. ret = new RtlAlienTypeInfo(fieldType, length, childType);
  139. break;
  140. default:
  141. throwUnexpected();
  142. }
  143. return ret;
  144. };
  145. typedef MapBetween<const RtlTypeInfo *, const RtlTypeInfo *, StringAttr, const char *> TypeNameMap;
  146. typedef MapBetween<const RtlTypeInfo *, const RtlTypeInfo *, unsigned, unsigned> TypeNumMap;
  147. /**
  148. * class CRtlFieldTypeSerializer
  149. *
  150. * Serializer class for creating json representation of a RtlTypeInfo structure.
  151. *
  152. */
  153. class CRtlFieldTypeSerializer
  154. {
  155. public:
  156. /**
  157. * Serialize a RtlTypeInfo structure to JSON
  158. *
  159. * @param out Buffer for resulting serialized string
  160. * @param type RtlTypeInfo structure to be serialized
  161. * @return Referenced to supplied buffer
  162. */
  163. static StringBuffer &serialize(StringBuffer &out, const RtlTypeInfo *type)
  164. {
  165. CRtlFieldTypeSerializer s(out, type);
  166. s.doSerialize();
  167. return out;
  168. }
  169. private:
  170. CRtlFieldTypeSerializer(StringBuffer &_out, const RtlTypeInfo *_base)
  171. : json(_out), base(_base)
  172. {
  173. }
  174. void doSerialize()
  175. {
  176. json.append("{");
  177. serializeType(base);
  178. json.append("\n}");
  179. }
  180. void serializeType(const RtlTypeInfo *type)
  181. {
  182. if (!serialized(type))
  183. {
  184. // Make sure all child types are serialized first
  185. const RtlTypeInfo *childType = type->queryChildType();
  186. if (childType)
  187. serializeType(childType);
  188. const RtlFieldInfo * const * fields = type->queryFields();
  189. if (fields)
  190. {
  191. for (;;)
  192. {
  193. const RtlFieldInfo * child = *fields;
  194. if (!child)
  195. break;
  196. serializeType(child->type);
  197. fields++;
  198. }
  199. }
  200. // Now serialize this one
  201. if (type != base)
  202. {
  203. VStringBuffer newName("ty%d", ++nextTypeName);
  204. types.setValue(type, newName.str());
  205. startField(newName.str());
  206. serializeMe(type);
  207. closeCurly();
  208. }
  209. else
  210. serializeMe(type);
  211. }
  212. }
  213. void serializeMe(const RtlTypeInfo *type)
  214. {
  215. if (!type->canSerialize())
  216. throw makeStringException(MSGAUD_user, 1000, "This type structure cannot be serialized");
  217. addPropHex("fieldType", type->fieldType);
  218. addProp("length", type->length);
  219. addPropNonEmpty("locale", type->queryLocale());
  220. const RtlTypeInfo *childType = type->queryChildType();
  221. if (childType)
  222. addPropType("child", childType);
  223. const IFieldFilter * filter = type->queryFilter();
  224. if (filter)
  225. {
  226. StringBuffer filterText;
  227. filter->serialize(filterText);
  228. addPropType("filterType", &filter->queryType());
  229. addProp("filter", filterText);
  230. }
  231. const RtlFieldInfo * const * fields = type->queryFields();
  232. if (fields)
  233. {
  234. startFields();
  235. for (;;)
  236. {
  237. const RtlFieldInfo * child = *fields;
  238. if (!child)
  239. break;
  240. newline();
  241. openCurly();
  242. addProp("name", child->name);
  243. addPropType("type", child->type);
  244. addProp("xpath", child->xpath);
  245. if (child->flags)
  246. addPropHex("flags", child->flags);
  247. // initializer is tricky - it's not (in general) a null-terminated string but the actual length is not easily available
  248. if (child->initializer)
  249. {
  250. addProp("init", child->type->size(child->initializer, nullptr), child->initializer);
  251. }
  252. closeCurly();
  253. fields++;
  254. }
  255. endFields();
  256. }
  257. }
  258. bool serialized(const RtlTypeInfo *type)
  259. {
  260. return types.find(type) != nullptr;
  261. }
  262. void startField(const char *name)
  263. {
  264. newline().appendf("\"%s\": ", name);
  265. openCurly();
  266. }
  267. void addProp(const char *propName, const char *propVal)
  268. {
  269. if (propVal)
  270. {
  271. newline();
  272. encodeJSON(json.append("\""), propName).append("\": ");
  273. encodeJSON(json.append("\""), propVal).append("\"");
  274. }
  275. }
  276. void addProp(const char *propName, size32_t propLen, const byte *propVal)
  277. {
  278. if (propVal)
  279. {
  280. newline();
  281. encodeJSON(json.append("\""), propName).append("\": \"");
  282. JBASE64_Encode(propVal, propLen, json, false);
  283. json.append("\"");
  284. }
  285. }
  286. void addPropNonEmpty(const char *propName, const char *propVal)
  287. {
  288. if (propVal && *propVal)
  289. addProp(propName, propVal);
  290. }
  291. void addProp(const char *propName, unsigned propVal)
  292. {
  293. newline().appendf("\"%s\": %u", propName, propVal);
  294. }
  295. void addPropHex(const char *propName, unsigned propVal)
  296. {
  297. newline().appendf("\"%s\": %u", propName, propVal); // Nice idea but json does not support hex constants :(
  298. }
  299. void addPropType(const char *propName, const RtlTypeInfo *type)
  300. {
  301. addProp(propName, queryTypeName(type));
  302. }
  303. const char *queryTypeName(const RtlTypeInfo *type)
  304. {
  305. StringAttr *typeName = types.getValue(type);
  306. assertex(typeName);
  307. return typeName->get();
  308. }
  309. void startFields()
  310. {
  311. newline().appendf("\"fields\": ");
  312. openCurly('[');
  313. }
  314. void endFields()
  315. {
  316. closeCurly(']');
  317. }
  318. StringBuffer &newline()
  319. {
  320. if (commaPending)
  321. json.append(',');
  322. json.appendf("\n%*s", indent, "");
  323. commaPending = true;
  324. return json;
  325. }
  326. void closeCurly(char brace = '}')
  327. {
  328. indent--;
  329. json.appendf("\n%*s%c", indent, "", brace);
  330. commaPending = true;
  331. }
  332. void openCurly(char brace = '{')
  333. {
  334. json.append(brace);
  335. indent++;
  336. commaPending = false;
  337. }
  338. TypeNameMap types;
  339. StringBuffer &json;
  340. const RtlTypeInfo *base = nullptr;
  341. unsigned indent = 1;
  342. unsigned nextTypeName = 0;
  343. bool commaPending = false;
  344. };
  345. class CRtlFieldTypeBinSerializer
  346. {
  347. public:
  348. /**
  349. * Serialize a RtlTypeInfo structure to binary
  350. *
  351. * @param out Buffer for resulting serialized string
  352. * @param type RtlTypeInfo structure to be serialized
  353. * @return Referenced to supplied buffer
  354. */
  355. static MemoryBuffer &serialize(MemoryBuffer &out, const RtlTypeInfo *type)
  356. {
  357. int oldEnd = out.setEndian(__LITTLE_ENDIAN);
  358. CRtlFieldTypeBinSerializer s(out);
  359. byte format = RTLTYPEINFO_FORMAT_1;
  360. out.append(format);
  361. DelayedMarker<hash64_t> hash(out);
  362. DelayedSizeMarker size(out);
  363. size32_t pos = out.length();
  364. s.serializeType(type);
  365. size.write();
  366. hash.write(rtlHash64Data(size.size(), out.toByteArray()+pos, 0));
  367. out.setEndian(oldEnd);
  368. return out;
  369. }
  370. private:
  371. CRtlFieldTypeBinSerializer(MemoryBuffer &_out)
  372. : out(_out)
  373. {
  374. }
  375. void serializeType(const RtlTypeInfo *type)
  376. {
  377. if (!serialized(type))
  378. {
  379. // Make sure all child types are serialized first
  380. const RtlTypeInfo *child = type->queryChildType();
  381. if (child)
  382. serializeType(child);
  383. const RtlFieldInfo * const * fields = type->queryFields();
  384. if (fields)
  385. {
  386. for (unsigned idx = 0;;idx++)
  387. {
  388. const RtlFieldInfo * child = fields[idx];
  389. if (!child)
  390. break;
  391. serializeType(child->type);
  392. }
  393. }
  394. // Now serialize this one
  395. types.setValue(type, nextTypeNum++);
  396. serializeMe(type);
  397. }
  398. }
  399. void serializeMe(const RtlTypeInfo *type)
  400. {
  401. if (!type->canSerialize())
  402. throw makeStringException(MSGAUD_user, 1000, "This type structure cannot be serialized");
  403. unsigned fieldType = type->fieldType;
  404. const char *locale = type->queryLocale();
  405. if (locale && *locale)
  406. fieldType |= RFTMhasLocale;
  407. const RtlTypeInfo *child = type->queryChildType();
  408. if (child)
  409. fieldType |= RFTMhasChildType;
  410. const RtlFieldInfo * const * fields = type->queryFields();
  411. if (fields)
  412. fieldType |= RFTMhasFields;
  413. out.append(fieldType);
  414. out.appendPacked(type->length);
  415. if (fieldType & RFTMhasLocale)
  416. out.append(locale);
  417. if (child)
  418. out.appendPacked(queryTypeIdx(child));
  419. const IFieldFilter * filter = type->queryFilter();
  420. if (filter)
  421. {
  422. out.appendPacked(queryTypeIdx(&filter->queryType()));
  423. filter->serialize(out);
  424. }
  425. if (fields)
  426. {
  427. unsigned count = countFields(fields);
  428. out.appendPacked(count);
  429. for (;;)
  430. {
  431. const RtlFieldInfo * child = *fields;
  432. if (!child)
  433. break;
  434. out.append(child->name);
  435. out.appendPacked(queryTypeIdx(child->type));
  436. unsigned flags = child->flags;
  437. if (child->xpath)
  438. flags |= RFTMhasXpath;
  439. if (child->initializer)
  440. flags |= RFTMhasInitializer;
  441. out.append(flags);
  442. if (child->xpath)
  443. out.append(child->xpath);
  444. // initializer is tricky - it's not (in general) a null-terminated string but the actual length is not easily available
  445. if (child->initializer)
  446. {
  447. unsigned initLength = child->type->size(child->initializer, nullptr);
  448. out.appendPacked(initLength).append(initLength, child->initializer);
  449. }
  450. fields++;
  451. }
  452. }
  453. }
  454. bool serialized(const RtlTypeInfo *type)
  455. {
  456. return types.find(type) != nullptr;
  457. }
  458. unsigned queryTypeIdx(const RtlTypeInfo *type)
  459. {
  460. unsigned *typeNum = types.getValue(type);
  461. assertex(typeNum);
  462. return *typeNum;
  463. }
  464. TypeNumMap types;
  465. MemoryBuffer &out;
  466. unsigned nextTypeNum = 0;
  467. };
  468. /**
  469. * class CRtlFieldTypeDeserializer
  470. *
  471. * Deserializer class for creating a RtlTypeInfo structure from json representation.
  472. *
  473. * Note that the resulting RtlTypeInfo structures are owned by this object and will be
  474. * destroyed when this object is destroyed.
  475. *
  476. */
  477. class CRtlFieldTypeDeserializer : public CInterfaceOf<IRtlFieldTypeDeserializer>
  478. {
  479. public:
  480. /**
  481. * CRtlFieldTypeDeserializer constructor
  482. *
  483. * @param _callback Supplies a callback to be used for blobs/filepositions.
  484. */
  485. CRtlFieldTypeDeserializer(IThorIndexCallback *_callback)
  486. : callback(_callback)
  487. {
  488. }
  489. /**
  490. * CRtlFieldTypeDeserializer destructor
  491. * <p>
  492. * Releases all RtlTypeInfo and related structures created by this deserializer
  493. */
  494. ~CRtlFieldTypeDeserializer()
  495. {
  496. // Need some care - all the RtlTypeInfo objects I created need to be destroyed, together with anything else I had to create
  497. // Strings (other than the init strings) are preserved in the AtomTable
  498. // First allow the types to clean up any critical cached information, then delete them in a second pass
  499. HashIterator allTypes(types);
  500. ForEach(allTypes)
  501. {
  502. const RtlTypeInfo **type = types.mapToValue(&allTypes.query());
  503. cleanupType(*type);
  504. }
  505. cleanupType(base);
  506. ForEach(allTypes)
  507. {
  508. const RtlTypeInfo **type = types.mapToValue(&allTypes.query());
  509. deleteType(*type);
  510. }
  511. deleteType(base);
  512. }
  513. /**
  514. * Obtain the deserialized type information
  515. * <p>
  516. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  517. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  518. * that created them is deleted.
  519. * <p>
  520. * Do not call more than once.
  521. *
  522. * @param _json JSON text to be deserialized, as created by CRtlFieldTypeSerializer
  523. * @return Deserialized type object
  524. */
  525. virtual const RtlTypeInfo *deserialize(const char *json) override
  526. {
  527. assertex(!base);
  528. Owned<IPropertyTree> jsonTree = createPTreeFromJSONString(json);
  529. base = deserializeType(jsonTree, jsonTree);
  530. return base;
  531. }
  532. /**
  533. * Obtain the deserialized type information
  534. * <p>
  535. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  536. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  537. * that created them is deleted.
  538. * <p>
  539. * Do not call more than once.
  540. *
  541. * @param _jsonTree JSON property tree to be deserialized, as created by CRtlFieldTypeSerializer
  542. * @return Deserialized type object
  543. */
  544. virtual const RtlTypeInfo *deserialize(IPropertyTree &jsonTree) override
  545. {
  546. assertex(!base);
  547. base = deserializeType(&jsonTree, &jsonTree);
  548. return base;
  549. }
  550. /**
  551. * Obtain the deserialized type information
  552. * <p>
  553. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  554. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  555. * that created them is deleted.
  556. * <p>
  557. * Do not call more than once.
  558. *
  559. * @param buf Binary serialized typeinfo to be deserialized, as created by CRtlFieldTypeSerializer
  560. * @return Deserialized type object
  561. */
  562. virtual const RtlTypeInfo *deserialize(MemoryBuffer &buf) override
  563. {
  564. assertex(!base);
  565. unsigned nextTypeNum = 0;
  566. int oldEndian = buf.setEndian(__LITTLE_ENDIAN);
  567. try
  568. {
  569. byte format;
  570. buf.read(format);
  571. if (format != RTLTYPEINFO_FORMAT_1)
  572. throw MakeStringException(0, "Invalid type info (%d) in CRtlFieldTypeDeserializer::deserialize", format);
  573. hash64_t hash;
  574. buf.read(hash);
  575. size32_t size;
  576. buf.read(size);
  577. #ifdef VALIDATE_TYPEINFO_HASHES
  578. hash64_t expected = rtlHash64Data(size, buf.readDirect(0), 0);
  579. if (expected != hash)
  580. throw MakeStringException(0, "Invalid type info hash in CRtlFieldTypeDeserializer::deserialize");
  581. #endif
  582. size32_t endpos = buf.getPos() + size;
  583. while (buf.getPos() < endpos)
  584. {
  585. if (base)
  586. {
  587. addType(base, nextTypeNum++);
  588. base = nullptr; // in case of exceptions...
  589. }
  590. base = deserializeType(buf);
  591. }
  592. if (buf.getPos()!=endpos)
  593. throw MakeStringException(0, "Invalid type info (incorrect size data) in CRtlFieldTypeDeserializer::deserialize");
  594. buf.setEndian(oldEndian);
  595. return base;
  596. }
  597. catch(...)
  598. {
  599. buf.setEndian(oldEndian);
  600. throw;
  601. }
  602. }
  603. virtual const RtlTypeInfo *addType(FieldTypeInfoStruct &info, const IInterface *typeOrIfblock) override
  604. {
  605. VStringBuffer name("%p", typeOrIfblock);
  606. const RtlTypeInfo ** found = types.getValue(name);
  607. if (found)
  608. return *found;
  609. savedTypes.append(LINK(typeOrIfblock));
  610. info.locale = keep(info.locale);
  611. const RtlTypeInfo * ret = info.createRtlTypeInfo(callback);
  612. types.setValue(name, ret);
  613. unsigned baseType = (info.fieldType & RFTMkind);
  614. if (baseType == type_record)
  615. patchIfBlockParentRow(ret, static_cast<const RtlRecordTypeInfo *>(ret));
  616. return ret;
  617. }
  618. virtual const RtlTypeInfo *lookupType(const IInterface * typeOrIfBlock) const override
  619. {
  620. VStringBuffer name("%p", typeOrIfBlock);
  621. const RtlTypeInfo ** found = types.getValue(name);
  622. if (found)
  623. return *found;
  624. return nullptr;
  625. }
  626. virtual const RtlFieldInfo *addFieldInfo(const char *fieldName, const char *xpath, const RtlTypeInfo *type, unsigned flags, const char *init) override
  627. {
  628. // MORE - we could hang onto this for cleanup, rather than assuming that we keep it via a later addType() call?
  629. return new RtlFieldStrInfo(keep(fieldName), keep(xpath), type, flags, init);
  630. }
  631. private:
  632. KeptAtomTable atoms; // Used to ensure proper lifetime of strings used in type structures
  633. MapStringTo<const RtlTypeInfo *> types; // Ensures structures only generated once
  634. const RtlTypeInfo *base = nullptr; // Holds the resulting type
  635. IThorIndexCallback *callback = nullptr;
  636. IConstPointerArray savedTypes; // ensure types remain alive for subsequent lookups
  637. void deleteType(const RtlTypeInfo *type)
  638. {
  639. if (type)
  640. {
  641. // Releases all memory for a single RtlTypeInfo object
  642. const RtlFieldInfo * const * fields = type->queryFields();
  643. if (fields)
  644. {
  645. const RtlFieldInfo * const * cur = fields;
  646. for (;;)
  647. {
  648. const RtlFieldInfo * child = *cur;
  649. if (!child)
  650. break;
  651. // We don't need to delete other strings - they are owned by atom table.
  652. // But the initializer is decoded and thus owned by me
  653. free((void *)child->initializer);
  654. delete child;
  655. cur++;
  656. }
  657. delete [] fields;
  658. }
  659. type->doDelete();
  660. }
  661. }
  662. void cleanupType(const RtlTypeInfo *type)
  663. {
  664. if (type)
  665. type->doCleanup();
  666. }
  667. const RtlTypeInfo *lookupType(const char *name, IPropertyTree *all)
  668. {
  669. const RtlTypeInfo ** found = types.getValue(name);
  670. if (found)
  671. return *found;
  672. const RtlTypeInfo *type = deserializeType(all->queryPropTree(name), all);
  673. types.setValue(name, type);
  674. return type;
  675. }
  676. const RtlTypeInfo *lookupType(unsigned idx)
  677. {
  678. // Could keep an expanding array of types instead - but the hash table is already there for json support...
  679. VStringBuffer key("%u", idx);
  680. const RtlTypeInfo ** found = types.getValue(key);
  681. if (found)
  682. return *found;
  683. throw makeStringException(-1, "Invalid serialized type information");
  684. }
  685. void addType(const RtlTypeInfo *type, unsigned idx)
  686. {
  687. VStringBuffer key("%u", idx);
  688. assert(types.getValue(key)==nullptr);
  689. types.setValue(key, type);
  690. }
  691. const char *keep(const char *string)
  692. {
  693. if (string)
  694. return str(atoms.addAtom(string));
  695. else
  696. return nullptr;
  697. }
  698. const RtlTypeInfo *deserializeType(IPropertyTree *type, IPropertyTree *all)
  699. {
  700. FieldTypeInfoStruct info;
  701. info.fieldType = type->getPropInt("fieldType");
  702. info.length = type->getPropInt("length");
  703. info.locale = keep(type->queryProp("locale"));
  704. const char *child = type->queryProp("child");
  705. if (child)
  706. info.childType = lookupType(child, all);
  707. unsigned baseType = (info.fieldType & RFTMkind);
  708. if ((baseType == type_record) || (baseType == type_ifblock))
  709. {
  710. unsigned numFields = type->getCount("fields");
  711. info.fieldsArray = new const RtlFieldInfo * [numFields+1];
  712. info.fieldsArray[numFields] = nullptr;
  713. Owned<IPropertyTreeIterator> fields = type->getElements("fields");
  714. unsigned n = 0;
  715. ForEach(*fields)
  716. {
  717. IPropertyTree &field = fields->query();
  718. const char *fieldTypeName = field.queryProp("type");
  719. const char *fieldName = keep(field.queryProp("name"));
  720. const char *fieldXpath = keep(field.queryProp("xpath"));
  721. unsigned flags = field.getPropInt("flags");
  722. const char *fieldInit = field.queryProp("init");
  723. if (fieldInit)
  724. {
  725. StringBuffer decoded;
  726. JBASE64_Decode(fieldInit, decoded);
  727. fieldInit = decoded.detach(); // NOTE - this gets freed in cleanupType()
  728. }
  729. info.fieldsArray[n] = new RtlFieldStrInfo(fieldName, fieldXpath, lookupType(fieldTypeName, all), flags, fieldInit);
  730. n++;
  731. }
  732. }
  733. if (baseType == type_ifblock)
  734. {
  735. //Filter field needs to be deserialized and the type resolved separately outside the deserialize call
  736. //because there isn't a RtlTypeInfo available to resolve the field (since we are currently deserializing it!)
  737. const char * filterText = type->queryProp("filter");
  738. StringBuffer fieldIdText;
  739. readFieldFromFieldFilter(fieldIdText, filterText);
  740. unsigned fieldId = atoi(fieldIdText);
  741. const RtlTypeInfo * fieldType = lookupType(type->queryProp("filterType"), all);
  742. info.filter = deserializeFieldFilter(fieldId, *fieldType, filterText);
  743. }
  744. const RtlTypeInfo * result = info.createRtlTypeInfo(callback);
  745. if (baseType == type_record)
  746. patchIfBlockParentRow(result, static_cast<const RtlRecordTypeInfo *>(result));
  747. return result;
  748. }
  749. const RtlTypeInfo *deserializeType(MemoryBuffer &type)
  750. {
  751. FieldTypeInfoStruct info;
  752. type.read(info.fieldType);
  753. type.readPacked(info.length);
  754. if (info.fieldType & RFTMhasLocale)
  755. {
  756. const char *locale;
  757. type.read(locale);
  758. info.locale = keep(locale);
  759. }
  760. if (info.fieldType & RFTMhasChildType)
  761. {
  762. unsigned childIdx;
  763. type.readPacked(childIdx);
  764. info.childType = lookupType(childIdx);
  765. }
  766. unsigned baseType = (info.fieldType & RFTMkind);
  767. if (baseType == type_ifblock)
  768. {
  769. unsigned childIdx;
  770. type.readPacked(childIdx);
  771. const RtlTypeInfo * fieldType = lookupType(childIdx);
  772. unsigned fieldId;
  773. type.readPacked(fieldId);
  774. info.filter = deserializeFieldFilter(fieldId, *fieldType, type);
  775. }
  776. if (info.fieldType & RFTMhasFields)
  777. {
  778. unsigned numFields;
  779. type.readPacked(numFields);
  780. info.fieldsArray = new const RtlFieldInfo * [numFields+1];
  781. info.fieldsArray[numFields] = nullptr;
  782. for (int n = 0; n < numFields; n++)
  783. {
  784. const char *fieldName;
  785. type.read(fieldName);
  786. if (fieldName[0] == '\0')
  787. fieldName = nullptr;
  788. unsigned fieldType;
  789. type.readPacked(fieldType);
  790. unsigned fieldFlags;
  791. type.read(fieldFlags);
  792. const char *xpath = nullptr;
  793. if (fieldFlags & RFTMhasXpath)
  794. type.read(xpath);
  795. void *init = nullptr;
  796. if (fieldFlags & RFTMhasInitializer)
  797. {
  798. unsigned initLength;
  799. type.readPacked(initLength);
  800. init = malloc(initLength);
  801. memcpy(init, type.readDirect(initLength), initLength);
  802. }
  803. fieldFlags &= ~RFTMserializerFlags;
  804. info.fieldsArray[n] = new RtlFieldStrInfo(keep(fieldName), keep(xpath), lookupType(fieldType), fieldFlags, (const char *) init);
  805. }
  806. }
  807. info.fieldType &= ~RFTMserializerFlags;
  808. const RtlTypeInfo * result = info.createRtlTypeInfo(callback);
  809. if (baseType == type_record)
  810. patchIfBlockParentRow(result, static_cast<const RtlRecordTypeInfo *>(result));
  811. return result;
  812. }
  813. void patchIndexFilePos()
  814. {
  815. if (callback && (base->fieldType & RFTMkind) == type_record)
  816. {
  817. // Yukky hack time
  818. // Assumes that the fieldinfo is not shared...
  819. // But that is also assumed by the code that cleans them up.
  820. const RtlFieldInfo * const *fields = base->queryFields();
  821. for(;;)
  822. {
  823. const RtlFieldInfo *field = *fields++;
  824. if (!field)
  825. break;
  826. if (field->type->getType() == type_blob)
  827. {
  828. static_cast<RtlBlobTypeInfo *>(const_cast<RtlTypeInfo *>(field->type))->setCallback(callback);
  829. }
  830. }
  831. }
  832. }
  833. void patchIfBlockParentRow(const RtlTypeInfo * fieldType, const RtlRecordTypeInfo * parentRow)
  834. {
  835. const RtlFieldInfo * const * fields = fieldType->queryFields();
  836. for (;*fields;fields++)
  837. {
  838. const RtlFieldInfo * cur = *fields;
  839. if (!cur)
  840. break;
  841. const RtlTypeInfo * curType = cur->type;
  842. if ((curType->fieldType & RFTMkind) == type_ifblock)
  843. {
  844. const RtlDynamicIfBlockTypeInfo * constifblock = static_cast<const RtlDynamicIfBlockTypeInfo *>(curType);
  845. RtlDynamicIfBlockTypeInfo * ifblock = const_cast<RtlDynamicIfBlockTypeInfo *>(constifblock);
  846. ifblock->setParent(parentRow);
  847. patchIfBlockParentRow(curType, parentRow);
  848. }
  849. }
  850. }
  851. };
  852. extern ECLRTL_API IRtlFieldTypeDeserializer *createRtlFieldTypeDeserializer(IThorIndexCallback *callback)
  853. {
  854. return new CRtlFieldTypeDeserializer(callback);
  855. }
  856. extern ECLRTL_API StringBuffer &dumpTypeInfo(StringBuffer &ret, const RtlTypeInfo *t)
  857. {
  858. return CRtlFieldTypeSerializer::serialize(ret, t);
  859. }
  860. extern ECLRTL_API bool dumpTypeInfo(MemoryBuffer &ret, const RtlTypeInfo *t)
  861. {
  862. try
  863. {
  864. CRtlFieldTypeBinSerializer::serialize(ret, t);
  865. return true;
  866. }
  867. catch (IException *E)
  868. {
  869. EXCLOG(E);
  870. return false;
  871. }
  872. }
  873. extern ECLRTL_API void serializeRecordType(size32_t & __lenResult, void * & __result, IOutputMetaData & metaVal)
  874. {
  875. MemoryBuffer ret;
  876. try
  877. {
  878. CRtlFieldTypeBinSerializer::serialize(ret, metaVal.queryTypeInfo());
  879. }
  880. catch (IException * e)
  881. {
  882. ret.clear();
  883. e->Release();
  884. }
  885. __lenResult = ret.length();
  886. __result = ret.detach();
  887. }
  888. extern ECLRTL_API void dumpRecordType(size32_t & __lenResult,char * & __result,IOutputMetaData &metaVal)
  889. {
  890. StringBuffer ret;
  891. try
  892. {
  893. CRtlFieldTypeSerializer::serialize(ret, metaVal.queryTypeInfo());
  894. #ifdef _DEBUG
  895. StringBuffer ret2;
  896. CRtlFieldTypeDeserializer deserializer(nullptr);
  897. CRtlFieldTypeSerializer::serialize(ret2, deserializer.deserialize(ret));
  898. assert(streq(ret, ret2));
  899. MemoryBuffer out;
  900. CRtlFieldTypeBinSerializer::serialize(out, metaVal.queryTypeInfo());
  901. CRtlFieldTypeDeserializer bindeserializer(nullptr);
  902. CRtlFieldTypeSerializer::serialize(ret2.clear(), bindeserializer.deserialize(out));
  903. assert(streq(ret, ret2));
  904. #endif
  905. }
  906. catch (IException * e)
  907. {
  908. e->errorMessage(ret.clear());
  909. e->Release();
  910. }
  911. __lenResult = ret.length();
  912. __result = ret.detach();
  913. }
  914. extern ECLRTL_API void getFieldVal(size32_t & __lenResult,char * & __result, int column, IOutputMetaData & metaVal, const byte *row)
  915. {
  916. __lenResult = 0;
  917. __result = nullptr;
  918. if (column >= 0)
  919. {
  920. const RtlRecord &r = metaVal.queryRecordAccessor(true);
  921. if (column < r.getNumFields())
  922. {
  923. unsigned numOffsets = r.getNumVarFields() + 1;
  924. size_t * variableOffsets = (size_t *)alloca(numOffsets * sizeof(size_t));
  925. RtlRow offsetCalculator(r, row, numOffsets, variableOffsets);
  926. offsetCalculator.getUtf8(__lenResult, __result, column);
  927. }
  928. }
  929. }
  930. extern ECLRTL_API int getFieldNum(const char *fieldName, IOutputMetaData & metaVal)
  931. {
  932. const RtlRecord r = metaVal.queryRecordAccessor(true);
  933. return r.getFieldNum(fieldName);
  934. }
  935. enum FieldMatchType {
  936. // On a field, exactly one of the below is set, but translator returns a bitmap indicating
  937. // which were required (and we can restrict translation to allow some types but not others)
  938. match_perfect = 0x00, // exact type match - use memcpy
  939. match_link = 0x01, // copy a nested dataset by linking
  940. match_move = 0x02, // at least one field has moved (set on translator)
  941. match_remove = 0x04, // at least one field has been removed (set on translator)
  942. match_truncate = 0x08, // dest is truncated copy of source - use memcpy
  943. match_extend = 0x10, // dest is padded version of source - use memcpy and memset
  944. match_typecast = 0x20, // type has changed - cast required
  945. match_none = 0x40, // No matching field in source - use null value
  946. match_recurse = 0x80, // Use recursive translator for child records/datasets
  947. match_fail = 0x100, // no translation possible
  948. match_keychange = 0x200, // at least one affected field not marked as payload (set on translator)
  949. // This flag may be set in conjunction with the others
  950. match_inifblock = 0x400, // matching to a field in an ifblock - may not be present
  951. };
  952. StringBuffer &describeFlags(StringBuffer &out, FieldMatchType flags)
  953. {
  954. if (flags == match_perfect)
  955. return out.append("perfect");
  956. unsigned origlen = out.length();
  957. if (flags & match_link) out.append("|link");
  958. if (flags & match_move) out.append("|move");
  959. if (flags & match_remove) out.append("|remove");
  960. if (flags & match_truncate) out.append("|truncate");
  961. if (flags & match_extend) out.append("|extend");
  962. if (flags & match_typecast) out.append("|typecast");
  963. if (flags & match_none) out.append("|none");
  964. if (flags & match_recurse) out.append("|recurse");
  965. if (flags & match_inifblock) out.append("|ifblock");
  966. if (flags & match_keychange) out.append("|keychange");
  967. if (flags & match_fail) out.append("|fail");
  968. assertex(out.length() > origlen);
  969. return out.remove(origlen, 1);
  970. }
  971. inline constexpr FieldMatchType operator|(FieldMatchType a, FieldMatchType b) { return (FieldMatchType)((int)a | (int)b); }
  972. inline FieldMatchType &operator|=(FieldMatchType &a, FieldMatchType b) { return (FieldMatchType &) ((int &)a |= (int)b); }
  973. class GeneralRecordTranslator : public CInterfaceOf<IDynamicTransform>
  974. {
  975. public:
  976. GeneralRecordTranslator(const RtlRecord &_destRecInfo, const RtlRecord &_srcRecInfo)
  977. : destRecInfo(_destRecInfo), sourceRecInfo(_srcRecInfo)
  978. {
  979. matchInfo = new MatchInfo[destRecInfo.getNumFields()];
  980. createMatchInfo();
  981. }
  982. ~GeneralRecordTranslator()
  983. {
  984. delete [] matchInfo;
  985. }
  986. virtual void describe() const override
  987. {
  988. doDescribe(0);
  989. }
  990. virtual size32_t translate(ARowBuilder &builder, const byte *sourceRec) const override
  991. {
  992. return doTranslate(builder, 0, sourceRec);
  993. }
  994. virtual size32_t translate(ARowBuilder &builder, const RtlRow &sourceRow) const override
  995. {
  996. sourceRow.lazyCalcOffsets(-1); // MORE - could save the max one we actually need...
  997. return doTranslate(builder, 0, sourceRow);
  998. }
  999. virtual bool canTranslate() const override
  1000. {
  1001. return (matchFlags & match_fail) == 0;
  1002. }
  1003. virtual bool needsTranslate() const override
  1004. {
  1005. return (matchFlags & ~match_link) != 0;
  1006. }
  1007. virtual bool keyedTranslated() const override
  1008. {
  1009. return (matchFlags & match_keychange) != 0;
  1010. }
  1011. private:
  1012. void doDescribe(unsigned indent) const
  1013. {
  1014. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1015. {
  1016. const char *source = destRecInfo.queryName(idx);
  1017. const MatchInfo &match = matchInfo[idx];
  1018. if (match.matchType == match_none)
  1019. DBGLOG("%*sNo match for field %s - default value will be used", indent, "", source);
  1020. else
  1021. {
  1022. StringBuffer matchStr;
  1023. DBGLOG("%*sMatch (%s) to field %d for field %s (%x)", indent, "", describeFlags(matchStr, match.matchType).str(), match.matchIdx, source, destRecInfo.queryType(idx)->fieldType);
  1024. if (match.subTrans)
  1025. match.subTrans->doDescribe(indent+2);
  1026. }
  1027. }
  1028. if (!canTranslate())
  1029. DBGLOG("%*sTranslation is NOT possible", indent, "");
  1030. else if (needsTranslate())
  1031. {
  1032. StringBuffer matchStr;
  1033. DBGLOG("%*sTranslation is possible (%s)", indent, "", describeFlags(matchStr, matchFlags).str());
  1034. }
  1035. else
  1036. DBGLOG("%*sTranslation is not necessary", indent, "");
  1037. }
  1038. size32_t doTranslate(ARowBuilder &builder, size32_t offset, const byte *sourceRec) const
  1039. {
  1040. unsigned numOffsets = sourceRecInfo.getNumVarFields() + 1;
  1041. size_t * variableOffsets = (size_t *)alloca(numOffsets * sizeof(size_t));
  1042. RtlRow sourceRow(sourceRecInfo, sourceRec, numOffsets, variableOffsets); // MORE - could save the max source offset we actually need, and only set up that many...
  1043. return doTranslate(builder, offset, sourceRow);
  1044. }
  1045. size32_t doTranslate(ARowBuilder &builder, size32_t offset, const RtlRow &sourceRow) const
  1046. {
  1047. dbgassertex(canTranslate());
  1048. byte * destConditions = (byte *)alloca(destRecInfo.getNumIfBlocks() * sizeof(byte));
  1049. memset(destConditions, 2, destRecInfo.getNumIfBlocks() * sizeof(byte));
  1050. size32_t estimate = destRecInfo.getFixedSize();
  1051. if (!estimate)
  1052. {
  1053. estimate = estimateNewSize(sourceRow);
  1054. builder.ensureCapacity(offset+estimate, "record");
  1055. }
  1056. size32_t origOffset = offset;
  1057. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1058. {
  1059. const RtlFieldInfo *field = destRecInfo.queryField(idx);
  1060. if (field->omitable() && destRecInfo.excluded(field, builder.getSelf(), destConditions))
  1061. continue;
  1062. const RtlTypeInfo *type = field->type;
  1063. const MatchInfo &match = matchInfo[idx];
  1064. if (match.matchType == match_none || match.matchType==match_fail)
  1065. offset = type->buildNull(builder, offset, field);
  1066. else
  1067. {
  1068. unsigned matchField = match.matchIdx;
  1069. const RtlTypeInfo *sourceType = sourceRecInfo.queryType(matchField);
  1070. size_t sourceOffset = sourceRow.getOffset(matchField);
  1071. const byte *source = sourceRow.queryRow() + sourceOffset;
  1072. size_t copySize = sourceRow.getSize(matchField);
  1073. if (copySize == 0 && (match.matchType & match_inifblock)) // Field is missing because of an ifblock - use default value
  1074. {
  1075. offset = type->buildNull(builder, offset, field);
  1076. }
  1077. else
  1078. {
  1079. switch (match.matchType & ~match_inifblock)
  1080. {
  1081. case match_perfect:
  1082. {
  1083. // Look ahead for other perfect matches and combine the copies
  1084. while (idx < destRecInfo.getNumFields()-1)
  1085. {
  1086. const MatchInfo &nextMatch = matchInfo[idx+1];
  1087. if (nextMatch.matchType == match_perfect && nextMatch.matchIdx == matchField+1)
  1088. {
  1089. idx++;
  1090. matchField++;
  1091. }
  1092. else
  1093. break;
  1094. }
  1095. size_t copySize = sourceRow.getOffset(matchField+1) - sourceOffset;
  1096. builder.ensureCapacity(offset+copySize, field->name);
  1097. memcpy(builder.getSelf()+offset, source, copySize);
  1098. offset += copySize;
  1099. break;
  1100. }
  1101. case match_truncate:
  1102. {
  1103. assert(type->isFixedSize());
  1104. size32_t copySize = type->getMinSize();
  1105. builder.ensureCapacity(offset+copySize, field->name);
  1106. memcpy(builder.getSelf()+offset, source, copySize);
  1107. offset += copySize;
  1108. break;
  1109. }
  1110. case match_extend:
  1111. {
  1112. assert(type->isFixedSize());
  1113. size32_t destSize = type->getMinSize();
  1114. builder.ensureCapacity(offset+destSize, field->name);
  1115. memcpy(builder.getSelf()+offset, source, copySize);
  1116. offset += copySize;
  1117. unsigned fillSize = destSize - copySize;
  1118. memset(builder.getSelf()+offset, match.fillChar, fillSize);
  1119. offset += fillSize;
  1120. break;
  1121. }
  1122. case match_typecast:
  1123. offset = translateScalar(builder, offset, field, *type, *sourceType, source);
  1124. break;
  1125. case match_link:
  1126. {
  1127. // a 32-bit record count, and a (linked) pointer to an array of record pointers
  1128. byte *dest = builder.ensureCapacity(offset+sizeof(size32_t)+sizeof(const byte **), field->name)+offset;
  1129. *(size32_t *)dest = *(size32_t *)source;
  1130. *(const byte ***)(dest + sizeof(size32_t)) = rtlLinkRowset(*(const byte ***)(source + sizeof(size32_t)));
  1131. offset += sizeof(size32_t)+sizeof(const byte **);
  1132. break;
  1133. }
  1134. case match_recurse:
  1135. if (type->getType()==type_record)
  1136. offset = match.subTrans->doTranslate(builder, offset, source);
  1137. else if (type->isLinkCounted())
  1138. {
  1139. // a 32-bit record count, and a pointer to an array of record pointers
  1140. IEngineRowAllocator *childAllocator = builder.queryAllocator()->createChildRowAllocator(type->queryChildType());
  1141. assertex(childAllocator); // May not be available when using serialized types (but unlikely to want to create linkcounted children remotely either)
  1142. size32_t sizeInBytes = sizeof(size32_t) + sizeof(void *);
  1143. builder.ensureCapacity(offset+sizeInBytes, field->name);
  1144. size32_t numRows = 0;
  1145. const byte **childRows = nullptr;
  1146. if (sourceType->isLinkCounted())
  1147. {
  1148. // a 32-bit count, then a pointer to the source rows
  1149. size32_t childCount = *(size32_t *) source;
  1150. source += sizeof(size32_t);
  1151. const byte ** sourceRows = *(const byte***) source;
  1152. for (size32_t childRow = 0; childRow < childCount; childRow++)
  1153. {
  1154. RtlDynamicRowBuilder childBuilder(*childAllocator);
  1155. size32_t childLen = match.subTrans->doTranslate(childBuilder, 0, sourceRows[childRow]);
  1156. childRows = childAllocator->appendRowOwn(childRows, ++numRows, (void *) childBuilder.finalizeRowClear(childLen));
  1157. }
  1158. }
  1159. else
  1160. {
  1161. // a 32-bit size, then rows inline
  1162. size32_t childSize = *(size32_t *) source;
  1163. source += sizeof(size32_t);
  1164. const byte *initialSource = source;
  1165. while ((size_t)(source - initialSource) < childSize)
  1166. {
  1167. RtlDynamicRowBuilder childBuilder(*childAllocator);
  1168. size32_t childLen = match.subTrans->doTranslate(childBuilder, 0, source);
  1169. childRows = childAllocator->appendRowOwn(childRows, ++numRows, (void *) childBuilder.finalizeRowClear(childLen));
  1170. source += sourceType->queryChildType()->size(source, nullptr); // MORE - shame to repeat a calculation that the translate above almost certainly just did
  1171. }
  1172. }
  1173. // Go back in and patch the count, remembering it may have moved
  1174. rtlWriteInt4(builder.getSelf()+offset, numRows);
  1175. * ( const void * * ) (builder.getSelf()+offset+sizeof(size32_t)) = childRows;
  1176. offset += sizeInBytes;
  1177. }
  1178. else
  1179. {
  1180. size32_t countOffset = offset;
  1181. byte *dest = builder.ensureCapacity(offset+sizeof(size32_t), field->name)+offset;
  1182. offset += sizeof(size32_t);
  1183. size32_t initialOffset = offset;
  1184. *(size32_t *)dest = 0; // patched below when true figure known
  1185. if (sourceType->isLinkCounted())
  1186. {
  1187. // a 32-bit count, then a pointer to the source rows
  1188. size32_t childCount = *(size32_t *) source;
  1189. source += sizeof(size32_t);
  1190. const byte ** sourceRows = *(const byte***) source;
  1191. for (size32_t childRow = 0; childRow < childCount; childRow++)
  1192. {
  1193. offset = match.subTrans->doTranslate(builder, offset, sourceRows[childRow]);
  1194. }
  1195. }
  1196. else
  1197. {
  1198. // a 32-bit size, then rows inline
  1199. size32_t childSize = *(size32_t *) source;
  1200. source += sizeof(size32_t);
  1201. const byte *initialSource = source;
  1202. while ((size_t)(source - initialSource) < childSize)
  1203. {
  1204. offset = match.subTrans->doTranslate(builder, offset, source);
  1205. source += sourceType->queryChildType()->size(source, nullptr); // MORE - shame to repeat a calculation that the translate above almost certainly just did
  1206. }
  1207. }
  1208. dest = builder.getSelf() + countOffset; // Note - may have been moved by reallocs since last calculated
  1209. *(size32_t *)dest = offset - initialOffset;
  1210. }
  1211. break;
  1212. default:
  1213. throwUnexpected();
  1214. }
  1215. }
  1216. }
  1217. }
  1218. if (estimate && offset-origOffset != estimate)
  1219. {
  1220. // Note - ifblocks make this assertion invalid. We do not account for potentially omitted fields
  1221. // when estimating target record size.
  1222. if (!destRecInfo.getNumIfBlocks())
  1223. assert(offset-origOffset > estimate); // Estimate is always supposed to be conservative
  1224. #ifdef TRACE_TRANSLATION
  1225. DBGLOG("Wrote %u bytes to record (estimate was %u)\n", offset-origOffset, estimate);
  1226. #endif
  1227. }
  1228. return offset;
  1229. }
  1230. inline FieldMatchType match() const
  1231. {
  1232. return matchFlags;
  1233. }
  1234. const RtlRecord &destRecInfo;
  1235. const RtlRecord &sourceRecInfo;
  1236. unsigned fixedDelta = 0; // total size of all fixed-size source fields that are not matched
  1237. UnsignedArray unmatched; // List of all variable-size source fields that are unmatched
  1238. FieldMatchType matchFlags = match_perfect;
  1239. struct MatchInfo
  1240. {
  1241. unsigned matchIdx = 0;
  1242. FieldMatchType matchType = match_fail;
  1243. char fillChar = 0;
  1244. GeneralRecordTranslator *subTrans = nullptr;
  1245. ~MatchInfo()
  1246. {
  1247. delete subTrans;
  1248. }
  1249. } *matchInfo;
  1250. size32_t estimateNewSize(const RtlRow &sourceRow) const
  1251. {
  1252. //DBGLOG("Source record size is %d", (int) sourceRow.getRecordSize());
  1253. size32_t expectedSize = sourceRow.getRecordSize() - fixedDelta;
  1254. //DBGLOG("Source record size without omitted fixed size fields is %d", expectedSize);
  1255. ForEachItemIn(i, unmatched)
  1256. {
  1257. unsigned fieldNo = unmatched.item(i);
  1258. expectedSize -= sourceRow.getSize(fieldNo);
  1259. //DBGLOG("Reducing estimated size by %d to %d for omitted field %d (%s)", (int) sourceRow.getSize(fieldNo), expectedSize, fieldNo, sourceRecInfo.queryName(fieldNo));
  1260. }
  1261. if (matchFlags & ~(match_perfect|match_link|match_none|match_extend|match_truncate))
  1262. {
  1263. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1264. {
  1265. const MatchInfo &match = matchInfo[idx];
  1266. const RtlTypeInfo *type = destRecInfo.queryType(idx);
  1267. unsigned matchField = match.matchIdx;
  1268. switch (match.matchType)
  1269. {
  1270. case match_perfect:
  1271. case match_link:
  1272. case match_none:
  1273. case match_extend:
  1274. case match_truncate:
  1275. // These ones were already included in fixedDelta
  1276. break;
  1277. default:
  1278. // This errs on the side of small - i.e. it assumes that all typecasts end up at minimum size
  1279. // We could do better in some cases e.g. variable string <-> variable unicode we can assume factor of 2,
  1280. // uft8 <-> string we could calculate here - but unlikely to be worth the effort.
  1281. // But it's fine for fixed size output fields, including truncate/extend
  1282. // We could also precalculate the expected delta if all omitted fields are fixed size - but not sure how likely/worthwhile that is.
  1283. expectedSize += type->getMinSize() - sourceRow.getSize(matchField);
  1284. //DBGLOG("Adjusting estimated size by (%d - %d) to %d for translated field %d (%s)", (int) sourceRow.getSize(matchField), type->getMinSize(), expectedSize, matchField, sourceRecInfo.queryName(matchField));
  1285. break;
  1286. }
  1287. }
  1288. }
  1289. return expectedSize;
  1290. }
  1291. void createMatchInfo()
  1292. {
  1293. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1294. {
  1295. const RtlFieldInfo *field = destRecInfo.queryField(idx);
  1296. const RtlTypeInfo *type = field->type;
  1297. MatchInfo &info = matchInfo[idx];
  1298. info.matchIdx = sourceRecInfo.getFieldNum(destRecInfo.queryName(idx));
  1299. if (info.matchIdx == -1)
  1300. {
  1301. info.matchType = match_none;
  1302. size32_t defaultSize = field->initializer ? type->size(field->initializer, nullptr) : type->getMinSize();
  1303. fixedDelta -= defaultSize;
  1304. if ((field->flags & RFTMispayloadfield) == 0)
  1305. matchFlags |= match_keychange;
  1306. //DBGLOG("Decreasing fixedDelta size by %d to %d for defaulted field %d (%s)", defaultSize, fixedDelta, idx, destRecInfo.queryName(idx));
  1307. }
  1308. else
  1309. {
  1310. const RtlTypeInfo *sourceType = sourceRecInfo.queryType(info.matchIdx);
  1311. if (!type->isScalar() || !sourceType->isScalar())
  1312. {
  1313. if (type->getType() != sourceType->getType())
  1314. info.matchType = match_fail; // No translation from one non-scalar type to another
  1315. else
  1316. {
  1317. switch (type->getType())
  1318. {
  1319. case type_set:
  1320. if (type->queryChildType()->fieldType==sourceType->queryChildType()->fieldType &&
  1321. type->queryChildType()->length==sourceType->queryChildType()->length)
  1322. info.matchType = match_perfect;
  1323. else
  1324. info.matchType = match_typecast;
  1325. break;
  1326. case type_row: // These are not expected I think...
  1327. throwUnexpected();
  1328. case type_ifblock:
  1329. case type_record:
  1330. case type_table:
  1331. {
  1332. const RtlRecord *subDest = destRecInfo.queryNested(idx);
  1333. const RtlRecord *subSrc = sourceRecInfo.queryNested(info.matchIdx);
  1334. info.subTrans = new GeneralRecordTranslator(*subDest, *subSrc);
  1335. if (!info.subTrans->needsTranslate())
  1336. {
  1337. // Child does not require translation, but check linkcount mode matches too!
  1338. if (type->isLinkCounted())
  1339. if (sourceType->isLinkCounted())
  1340. info.matchType = match_link;
  1341. else
  1342. info.matchType = match_recurse;
  1343. else
  1344. if (sourceType->isLinkCounted())
  1345. info.matchType = match_recurse;
  1346. else
  1347. info.matchType = match_perfect;
  1348. if (info.matchType != match_recurse)
  1349. {
  1350. delete info.subTrans;
  1351. info.subTrans = nullptr;
  1352. }
  1353. }
  1354. else if (info.subTrans->canTranslate())
  1355. {
  1356. info.matchType = match_recurse;
  1357. matchFlags |= info.subTrans->matchFlags;
  1358. }
  1359. else
  1360. info.matchType = match_fail;
  1361. break;
  1362. }
  1363. default:
  1364. info.matchType = match_fail;
  1365. break;
  1366. }
  1367. }
  1368. }
  1369. else if (type->fieldType==sourceType->fieldType)
  1370. {
  1371. if (type->length==sourceType->length)
  1372. {
  1373. info.matchType = match_perfect;
  1374. }
  1375. else
  1376. {
  1377. assert(type->isFixedSize()); // Both variable size would have matched length above
  1378. info.matchType = match_typecast;
  1379. if (type->length < sourceType->length)
  1380. {
  1381. if (type->canTruncate())
  1382. {
  1383. info.matchType = match_truncate;
  1384. fixedDelta += sourceType->getMinSize()-type->getMinSize();
  1385. //DBGLOG("Increasing fixedDelta size by %d to %d for truncated field %d (%s)", sourceType->getMinSize()-type->getMinSize(), fixedDelta, idx, destRecInfo.queryName(idx));
  1386. }
  1387. }
  1388. else
  1389. {
  1390. if (type->canExtend(info.fillChar))
  1391. {
  1392. info.matchType = match_extend;
  1393. fixedDelta += sourceType->getMinSize()-type->getMinSize();
  1394. //DBGLOG("Decreasing fixedDelta size by %d to %d for truncated field %d (%s)", type->getMinSize()-sourceType->getMinSize(), fixedDelta, idx, destRecInfo.queryName(idx));
  1395. }
  1396. }
  1397. }
  1398. }
  1399. else
  1400. info.matchType = match_typecast;
  1401. unsigned sourceFlags = sourceRecInfo.queryField(info.matchIdx)->flags;
  1402. if (sourceFlags & RFTMinifblock)
  1403. info.matchType |= match_inifblock; // Avoids incorrect commoning up of adjacent matches
  1404. // MORE - could note the highest interesting fieldnumber in the source and not bother filling in offsets after that
  1405. // Not sure it would help much though - usually need to know the total record size anyway in real life
  1406. if (idx != info.matchIdx)
  1407. matchFlags |= match_move;
  1408. if (info.matchType != match_perfect && ((field->flags & RFTMispayloadfield) == 0 || (sourceFlags & RFTMispayloadfield) == 0))
  1409. matchFlags |= match_keychange;
  1410. }
  1411. matchFlags |= info.matchType;
  1412. }
  1413. if (sourceRecInfo.getNumFields() > destRecInfo.getNumFields())
  1414. matchFlags |= match_remove;
  1415. if (matchFlags && !destRecInfo.getFixedSize())
  1416. {
  1417. for (unsigned idx = 0; idx < sourceRecInfo.getNumFields(); idx++)
  1418. {
  1419. const RtlFieldInfo *field = sourceRecInfo.queryField(idx);
  1420. const char *name = sourceRecInfo.queryName(idx);
  1421. if (destRecInfo.getFieldNum(name) == (unsigned) -1)
  1422. {
  1423. // unmatched field
  1424. if ((field->flags & RFTMispayloadfield) == 0)
  1425. matchFlags |= match_keychange;
  1426. if (!destRecInfo.getFixedSize())
  1427. {
  1428. const RtlTypeInfo *type = field->type;
  1429. if (type->isFixedSize())
  1430. {
  1431. //DBGLOG("Reducing estimated size by %d for (fixed size) omitted field %s", (int) type->getMinSize(), field->name);
  1432. fixedDelta += type->getMinSize();
  1433. }
  1434. else
  1435. unmatched.append(idx);
  1436. }
  1437. }
  1438. }
  1439. //DBGLOG("Source record contains %d bytes of omitted fixed size fields", fixedDelta);
  1440. }
  1441. }
  1442. };
  1443. extern ECLRTL_API const IDynamicTransform *createRecordTranslator(const RtlRecord &_destRecInfo, const RtlRecord &_srcRecInfo)
  1444. {
  1445. return new GeneralRecordTranslator(_destRecInfo, _srcRecInfo);
  1446. }
  1447. class TranslatedRowStream : public CInterfaceOf<IRowStream>
  1448. {
  1449. public:
  1450. TranslatedRowStream(IRowStream *_inputStream, IEngineRowAllocator *_resultAllocator, const RtlRecord &outputRecord, const RtlRecord &inputRecord)
  1451. : inputStream(_inputStream), resultAllocator(_resultAllocator), translator(new GeneralRecordTranslator(outputRecord, inputRecord))
  1452. {
  1453. translator->describe();
  1454. }
  1455. virtual const void *nextRow()
  1456. {
  1457. if (eof)
  1458. return NULL;
  1459. const void *inRow = inputStream->nextRow();
  1460. if (!inRow)
  1461. {
  1462. if (eogSeen)
  1463. eof = true;
  1464. else
  1465. eogSeen = true;
  1466. return nullptr;
  1467. }
  1468. else
  1469. eogSeen = false;
  1470. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1471. size32_t len = translator->translate(rowBuilder, (const byte *) inRow);
  1472. rtlReleaseRow(inRow);
  1473. return rowBuilder.finalizeRowClear(len);
  1474. }
  1475. virtual void stop() override
  1476. {
  1477. resultAllocator.clear();
  1478. }
  1479. bool canTranslate() const
  1480. {
  1481. return translator->canTranslate();
  1482. }
  1483. bool needsTranslate() const
  1484. {
  1485. return translator->needsTranslate();
  1486. }
  1487. protected:
  1488. Linked<IRowStream> inputStream;
  1489. Linked<IEngineRowAllocator> resultAllocator;
  1490. Owned<const IDynamicTransform> translator;
  1491. unsigned numOffsets = 0;
  1492. size_t * variableOffsets = nullptr;
  1493. bool eof = false;
  1494. bool eogSeen = false;
  1495. };
  1496. extern ECLRTL_API IRowStream * transformRecord(IEngineRowAllocator * resultAllocator,IOutputMetaData & metaInput,IRowStream * input)
  1497. {
  1498. if (resultAllocator->queryOutputMeta()==&metaInput)
  1499. return LINK(input);
  1500. Owned<TranslatedRowStream> stream = new TranslatedRowStream(input, resultAllocator,
  1501. resultAllocator->queryOutputMeta()->queryRecordAccessor(true),
  1502. metaInput.queryRecordAccessor(true));
  1503. if (!stream->needsTranslate())
  1504. return LINK(input);
  1505. else if (!stream->canTranslate())
  1506. rtlFail(0, "Cannot translate record stream");
  1507. else
  1508. return stream.getClear();
  1509. }
  1510. // A key translator allows us to transform a RowFilter that refers to src to one that refers to dest.
  1511. // Basically just a map of those fields with matching types.
  1512. class CKeyTranslator : public CInterfaceOf<IKeyTranslator>
  1513. {
  1514. public:
  1515. CKeyTranslator(const RtlRecord &actual, const RtlRecord &expected)
  1516. {
  1517. translateNeeded = false;
  1518. for (unsigned expectedIdx = 0; expectedIdx < expected.getNumFields(); expectedIdx++)
  1519. {
  1520. unsigned actualIdx = actual.getFieldNum(expected.queryName(expectedIdx));
  1521. if (actualIdx != -1)
  1522. {
  1523. const RtlTypeInfo *expectedType = expected.queryType(expectedIdx);
  1524. const RtlTypeInfo *actualType = actual.queryType(actualIdx);
  1525. if (!actualType->equivalent(expectedType))
  1526. actualIdx = (unsigned) -2;
  1527. }
  1528. map.append(actualIdx);
  1529. if (actualIdx != expectedIdx)
  1530. translateNeeded = true;
  1531. }
  1532. }
  1533. virtual void describe() const override
  1534. {
  1535. ForEachItemIn(idx, map)
  1536. {
  1537. unsigned mapped = map.item(idx);
  1538. switch (mapped)
  1539. {
  1540. case (unsigned) -1: DBGLOG("No match for field %d", idx); break;
  1541. case (unsigned) -2: DBGLOG("Incompatible field match for field %d", idx); break;
  1542. default: DBGLOG("keyed field %d can map to field %d", idx, mapped); break;
  1543. }
  1544. }
  1545. }
  1546. virtual bool translate(RowFilter &filters) const override
  1547. {
  1548. bool mapNeeded = false;
  1549. if (translateNeeded)
  1550. {
  1551. unsigned numFields = filters.numFilterFields();
  1552. for (unsigned idx = 0; idx < numFields; idx++)
  1553. {
  1554. unsigned fieldNum = filters.queryFilter(idx).queryFieldIndex();
  1555. unsigned mappedFieldNum = map.isItem(fieldNum) ? map.item(fieldNum) : (unsigned) -1;
  1556. if (mappedFieldNum != fieldNum)
  1557. {
  1558. mapNeeded = true;
  1559. switch (mappedFieldNum)
  1560. {
  1561. case (unsigned) -1: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - no matching field", idx);
  1562. case (unsigned) -2: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - incompatible matching field type", idx);
  1563. default:
  1564. filters.remapField(idx, mappedFieldNum);
  1565. break;
  1566. }
  1567. }
  1568. }
  1569. if (mapNeeded)
  1570. filters.recalcFieldsRequired();
  1571. }
  1572. return mapNeeded;
  1573. }
  1574. virtual bool translate(RowFilter &filter, IConstArrayOf<IFieldFilter> &in) const override
  1575. {
  1576. bool mapNeeded = false;
  1577. if (translateNeeded)
  1578. {
  1579. unsigned numFields = in.length();
  1580. for (unsigned idx = 0; idx < numFields; idx++)
  1581. {
  1582. unsigned fieldNum = in.item(idx).queryFieldIndex();
  1583. unsigned mappedFieldNum = map.isItem(fieldNum) ? map.item(fieldNum) : (unsigned) -1;
  1584. if (mappedFieldNum != fieldNum)
  1585. {
  1586. mapNeeded = true;
  1587. switch (mappedFieldNum)
  1588. {
  1589. case (unsigned) -1: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - no matching field", idx);
  1590. case (unsigned) -2: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - incompatible matching field type", idx);
  1591. default:
  1592. filter.addFilter(*in.item(idx).remap(mappedFieldNum));
  1593. break;
  1594. }
  1595. }
  1596. else
  1597. filter.addFilter(OLINK(in.item(idx)));
  1598. }
  1599. }
  1600. return mapNeeded;
  1601. }
  1602. virtual bool needsTranslate() const
  1603. {
  1604. return translateNeeded;
  1605. }
  1606. protected:
  1607. UnsignedArray map;
  1608. bool translateNeeded = false;
  1609. };
  1610. extern ECLRTL_API const IKeyTranslator *createKeyTranslator(const RtlRecord &_destRecInfo, const RtlRecord &_srcRecInfo)
  1611. {
  1612. return new CKeyTranslator(_destRecInfo, _srcRecInfo);
  1613. }