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