rtldynfield.cpp 71 KB

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