rtldynfield.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  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 81 // In case we ever want to support more than one format or change how it is stored
  27. //---------------------------------------------------------------------------------------------------------------------
  28. extern ECLRTL_API RecordTranslationMode getTranslationMode(const char *val)
  29. {
  30. if (isEmptyString(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() 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_int:
  63. ret = new RtlIntTypeInfo(fieldType, length);
  64. break;
  65. case type_blob:
  66. ret = new RtlBlobTypeInfo(fieldType, length, childType);
  67. break;
  68. case type_filepos:
  69. #if __BYTE_ORDER == __LITTLE_ENDIAN
  70. ret = new RtlSwapIntTypeInfo(fieldType, length);
  71. #else
  72. ret = new RtlIntTypeInfo(fieldType, length);
  73. #endif
  74. break;
  75. case type_real:
  76. ret = new RtlRealTypeInfo(fieldType, length);
  77. break;
  78. case type_decimal:
  79. ret = new RtlDecimalTypeInfo(fieldType, length);
  80. break;
  81. case type_string:
  82. ret = new RtlStringTypeInfo(fieldType, length);
  83. break;
  84. case type_bitfield:
  85. ret = new RtlBitfieldTypeInfo(fieldType, length);
  86. break;
  87. case type_varstring:
  88. ret = new RtlVarStringTypeInfo(fieldType, length);
  89. break;
  90. case type_data:
  91. ret = new RtlDataTypeInfo(fieldType, length);
  92. break;
  93. case type_table:
  94. assert(childType);
  95. ret = new RtlDatasetTypeInfo(fieldType, length, childType);
  96. break;
  97. case type_dictionary:
  98. assert(childType);
  99. ret = new RtlDictionaryTypeInfo(fieldType, length, childType);
  100. break;
  101. case type_set:
  102. assert(childType);
  103. ret = new RtlSetTypeInfo(fieldType, length, childType);
  104. break;
  105. case type_row:
  106. assert(childType);
  107. ret = new RtlRowTypeInfo(fieldType, length, childType);
  108. break;
  109. case type_swapint:
  110. ret = new RtlSwapIntTypeInfo(fieldType, length);
  111. break;
  112. case type_packedint:
  113. ret = new RtlPackedIntTypeInfo(fieldType, length);
  114. break;
  115. case type_qstring:
  116. ret = new RtlQStringTypeInfo(fieldType, length);
  117. break;
  118. case type_unicode:
  119. ret = new RtlUnicodeTypeInfo(fieldType, length, locale);
  120. break;
  121. case type_varunicode:
  122. ret = new RtlVarUnicodeTypeInfo(fieldType, length, locale);
  123. break;
  124. case type_utf8:
  125. ret = new RtlUtf8TypeInfo(fieldType, length, locale);
  126. break;
  127. case type_record:
  128. ret = new RtlRecordTypeInfo(fieldType, length, fieldsArray);
  129. break;
  130. case type_ifblock:
  131. ret = new RtlDynamicIfBlockTypeInfo(fieldType, length, fieldsArray, nullptr, filter);
  132. break;
  133. case type_alien:
  134. assert(childType);
  135. ret = new RtlAlienTypeInfo(fieldType, length, childType);
  136. break;
  137. default:
  138. throwUnexpected();
  139. }
  140. return ret;
  141. };
  142. typedef MapBetween<const RtlTypeInfo *, const RtlTypeInfo *, StringAttr, const char *> TypeNameMap;
  143. typedef MapBetween<const RtlTypeInfo *, const RtlTypeInfo *, unsigned, unsigned> TypeNumMap;
  144. /**
  145. * class CRtlFieldTypeSerializer
  146. *
  147. * Serializer class for creating json representation of a RtlTypeInfo structure.
  148. *
  149. */
  150. class CRtlFieldTypeSerializer
  151. {
  152. public:
  153. /**
  154. * Serialize a RtlTypeInfo structure to JSON
  155. *
  156. * @param out Buffer for resulting serialized string
  157. * @param type RtlTypeInfo structure to be serialized
  158. * @return Referenced to supplied buffer
  159. */
  160. static StringBuffer &serialize(StringBuffer &out, const RtlTypeInfo *type)
  161. {
  162. CRtlFieldTypeSerializer s(out, type);
  163. s.doSerialize();
  164. return out;
  165. }
  166. private:
  167. CRtlFieldTypeSerializer(StringBuffer &_out, const RtlTypeInfo *_base)
  168. : json(_out), base(_base)
  169. {
  170. }
  171. void doSerialize()
  172. {
  173. json.append("{");
  174. serializeType(base);
  175. json.append("\n}");
  176. }
  177. void serializeType(const RtlTypeInfo *type)
  178. {
  179. if (!serialized(type))
  180. {
  181. // Make sure all child types are serialized first
  182. const RtlTypeInfo *childType = type->queryChildType();
  183. if (childType)
  184. serializeType(childType);
  185. const RtlFieldInfo * const * fields = type->queryFields();
  186. if (fields)
  187. {
  188. for (;;)
  189. {
  190. const RtlFieldInfo * child = *fields;
  191. if (!child)
  192. break;
  193. serializeType(child->type);
  194. fields++;
  195. }
  196. }
  197. // Now serialize this one
  198. if (type != base)
  199. {
  200. VStringBuffer newName("ty%d", ++nextTypeName);
  201. types.setValue(type, newName.str());
  202. startField(newName.str());
  203. serializeMe(type);
  204. closeCurly();
  205. }
  206. else
  207. serializeMe(type);
  208. }
  209. }
  210. void serializeMe(const RtlTypeInfo *type)
  211. {
  212. if (!type->canSerialize())
  213. throw makeStringException(MSGAUD_user, 1000, "This type structure cannot be serialized");
  214. addPropHex("fieldType", type->fieldType);
  215. addProp("length", type->length);
  216. addPropNonEmpty("locale", type->queryLocale());
  217. const RtlTypeInfo *childType = type->queryChildType();
  218. if (childType)
  219. addPropType("child", childType);
  220. const IFieldFilter * filter = type->queryFilter();
  221. if (filter)
  222. {
  223. StringBuffer filterText;
  224. filter->serialize(filterText);
  225. addPropType("filterType", &filter->queryType());
  226. addProp("filter", filterText);
  227. }
  228. const RtlFieldInfo * const * fields = type->queryFields();
  229. if (fields)
  230. {
  231. startFields();
  232. for (;;)
  233. {
  234. const RtlFieldInfo * child = *fields;
  235. if (!child)
  236. break;
  237. newline();
  238. openCurly();
  239. addProp("name", child->name);
  240. addPropType("type", child->type);
  241. addProp("xpath", child->xpath);
  242. if (child->flags)
  243. addPropHex("flags", child->flags);
  244. // initializer is tricky - it's not (in general) a null-terminated string but the actual length is not easily available
  245. if (child->initializer)
  246. {
  247. if (isVirtualInitializer(child->initializer))
  248. addProp("vinit", getVirtualInitializer(child->initializer));
  249. else
  250. addProp("init", child->type->size((const byte *) child->initializer, nullptr), (const byte *) child->initializer);
  251. }
  252. closeCurly();
  253. fields++;
  254. }
  255. endFields();
  256. }
  257. }
  258. bool serialized(const RtlTypeInfo *type)
  259. {
  260. return types.find(type) != nullptr;
  261. }
  262. void startField(const char *name)
  263. {
  264. newline().appendf("\"%s\": ", name);
  265. openCurly();
  266. }
  267. void addProp(const char *propName, const char *propVal)
  268. {
  269. if (propVal)
  270. {
  271. newline();
  272. encodeJSON(json.append("\""), propName).append("\": ");
  273. encodeJSON(json.append("\""), propVal).append("\"");
  274. }
  275. }
  276. void addProp(const char *propName, size32_t propLen, const byte *propVal)
  277. {
  278. if (propVal)
  279. {
  280. newline();
  281. encodeJSON(json.append("\""), propName).append("\": \"");
  282. JBASE64_Encode(propVal, propLen, json, false);
  283. json.append("\"");
  284. }
  285. }
  286. void addPropNonEmpty(const char *propName, const char *propVal)
  287. {
  288. if (propVal && *propVal)
  289. addProp(propName, propVal);
  290. }
  291. void addProp(const char *propName, unsigned propVal)
  292. {
  293. newline().appendf("\"%s\": %u", propName, propVal);
  294. }
  295. void addPropHex(const char *propName, unsigned propVal)
  296. {
  297. newline().appendf("\"%s\": %u", propName, propVal); // Nice idea but json does not support hex constants :(
  298. }
  299. void addPropType(const char *propName, const RtlTypeInfo *type)
  300. {
  301. addProp(propName, queryTypeName(type));
  302. }
  303. const char *queryTypeName(const RtlTypeInfo *type)
  304. {
  305. StringAttr *typeName = types.getValue(type);
  306. assertex(typeName);
  307. return typeName->get();
  308. }
  309. void startFields()
  310. {
  311. newline().appendf("\"fields\": ");
  312. openCurly('[');
  313. }
  314. void endFields()
  315. {
  316. closeCurly(']');
  317. }
  318. StringBuffer &newline()
  319. {
  320. if (commaPending)
  321. json.append(',');
  322. json.appendf("\n%*s", indent, "");
  323. commaPending = true;
  324. return json;
  325. }
  326. void closeCurly(char brace = '}')
  327. {
  328. indent--;
  329. json.appendf("\n%*s%c", indent, "", brace);
  330. commaPending = true;
  331. }
  332. void openCurly(char brace = '{')
  333. {
  334. json.append(brace);
  335. indent++;
  336. commaPending = false;
  337. }
  338. TypeNameMap types;
  339. StringBuffer &json;
  340. const RtlTypeInfo *base = nullptr;
  341. unsigned indent = 1;
  342. unsigned nextTypeName = 0;
  343. bool commaPending = false;
  344. };
  345. class CRtlFieldTypeBinSerializer
  346. {
  347. public:
  348. /**
  349. * Serialize a RtlTypeInfo structure to binary
  350. *
  351. * @param out Buffer for resulting serialized string
  352. * @param type RtlTypeInfo structure to be serialized
  353. * @return Referenced to supplied buffer
  354. */
  355. static MemoryBuffer &serialize(MemoryBuffer &out, const RtlTypeInfo *type)
  356. {
  357. int oldEnd = out.setEndian(__LITTLE_ENDIAN);
  358. CRtlFieldTypeBinSerializer s(out);
  359. byte format = RTLTYPEINFO_FORMAT_1;
  360. out.append(format);
  361. DelayedMarker<hash64_t> hash(out);
  362. DelayedSizeMarker size(out);
  363. size32_t pos = out.length();
  364. s.serializeType(type);
  365. size.write();
  366. hash.write(rtlHash64Data(size.size(), out.toByteArray()+pos, 0));
  367. out.setEndian(oldEnd);
  368. return out;
  369. }
  370. private:
  371. CRtlFieldTypeBinSerializer(MemoryBuffer &_out)
  372. : out(_out)
  373. {
  374. }
  375. void serializeType(const RtlTypeInfo *type)
  376. {
  377. if (!serialized(type))
  378. {
  379. // Make sure all child types are serialized first
  380. const RtlTypeInfo *child = type->queryChildType();
  381. if (child)
  382. serializeType(child);
  383. const RtlFieldInfo * const * fields = type->queryFields();
  384. if (fields)
  385. {
  386. for (unsigned idx = 0;;idx++)
  387. {
  388. const RtlFieldInfo * child = fields[idx];
  389. if (!child)
  390. break;
  391. serializeType(child->type);
  392. }
  393. }
  394. // Now serialize this one
  395. types.setValue(type, nextTypeNum++);
  396. serializeMe(type);
  397. }
  398. }
  399. void serializeMe(const RtlTypeInfo *type)
  400. {
  401. if (!type->canSerialize())
  402. throw makeStringException(MSGAUD_user, 1000, "This type structure cannot be serialized");
  403. unsigned fieldType = type->fieldType;
  404. const char *locale = type->queryLocale();
  405. if (locale && *locale)
  406. fieldType |= RFTMhasLocale;
  407. const RtlTypeInfo *child = type->queryChildType();
  408. if (child)
  409. fieldType |= RFTMhasChildType;
  410. const RtlFieldInfo * const * fields = type->queryFields();
  411. if (fields)
  412. fieldType |= RFTMhasFields;
  413. out.append(fieldType);
  414. out.appendPacked(type->length);
  415. if (fieldType & RFTMhasLocale)
  416. out.append(locale);
  417. if (child)
  418. out.appendPacked(queryTypeIdx(child));
  419. const IFieldFilter * filter = type->queryFilter();
  420. if (filter)
  421. {
  422. out.appendPacked(queryTypeIdx(&filter->queryType()));
  423. filter->serialize(out);
  424. }
  425. if (fields)
  426. {
  427. unsigned count = countFields(fields);
  428. out.appendPacked(count);
  429. for (;;)
  430. {
  431. const RtlFieldInfo * child = *fields;
  432. if (!child)
  433. break;
  434. out.append(child->name);
  435. out.appendPacked(queryTypeIdx(child->type));
  436. unsigned flags = child->flags;
  437. if (child->xpath)
  438. flags |= RFTMhasXpath;
  439. if (child->initializer)
  440. {
  441. if (isVirtualInitializer(child->initializer))
  442. flags |= RFTMhasVirtualInitializer;
  443. else
  444. flags |= RFTMhasInitializer;
  445. }
  446. out.append(flags);
  447. if (child->xpath)
  448. out.append(child->xpath);
  449. // initializer is tricky - it's not (in general) a null-terminated string but the actual length is not easily available
  450. if (flags & RFTMhasInitializer)
  451. {
  452. unsigned initLength = child->type->size((const byte *) child->initializer, nullptr);
  453. out.appendPacked(initLength).append(initLength, (const byte *) child->initializer);
  454. }
  455. else if (flags &RFTMhasVirtualInitializer)
  456. out.append(getVirtualInitializer(child->initializer));
  457. fields++;
  458. }
  459. }
  460. }
  461. bool serialized(const RtlTypeInfo *type)
  462. {
  463. return types.find(type) != nullptr;
  464. }
  465. unsigned queryTypeIdx(const RtlTypeInfo *type)
  466. {
  467. unsigned *typeNum = types.getValue(type);
  468. assertex(typeNum);
  469. return *typeNum;
  470. }
  471. TypeNumMap types;
  472. MemoryBuffer &out;
  473. unsigned nextTypeNum = 0;
  474. };
  475. /**
  476. * class CRtlFieldTypeDeserializer
  477. *
  478. * Deserializer class for creating a RtlTypeInfo structure from json representation.
  479. *
  480. * Note that the resulting RtlTypeInfo structures are owned by this object and will be
  481. * destroyed when this object is destroyed.
  482. *
  483. */
  484. class CRtlFieldTypeDeserializer : public CInterfaceOf<IRtlFieldTypeDeserializer>
  485. {
  486. public:
  487. /**
  488. * CRtlFieldTypeDeserializer constructor
  489. *
  490. * @param _callback Supplies a callback to be used for blobs/filepositions.
  491. */
  492. CRtlFieldTypeDeserializer()
  493. {
  494. }
  495. /**
  496. * CRtlFieldTypeDeserializer destructor
  497. * <p>
  498. * Releases all RtlTypeInfo and related structures created by this deserializer
  499. */
  500. ~CRtlFieldTypeDeserializer()
  501. {
  502. // Need some care - all the RtlTypeInfo objects I created need to be destroyed, together with anything else I had to create
  503. // Strings (other than the init strings) are preserved in the AtomTable
  504. // First allow the types to clean up any critical cached information, then delete them in a second pass
  505. HashIterator allTypes(types);
  506. ForEach(allTypes)
  507. {
  508. const RtlTypeInfo **type = types.mapToValue(&allTypes.query());
  509. cleanupType(*type);
  510. }
  511. cleanupType(base);
  512. ForEach(allTypes)
  513. {
  514. const RtlTypeInfo **type = types.mapToValue(&allTypes.query());
  515. deleteType(*type);
  516. }
  517. deleteType(base);
  518. }
  519. /**
  520. * Obtain the deserialized type information
  521. * <p>
  522. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  523. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  524. * that created them is deleted.
  525. * <p>
  526. * Do not call more than once.
  527. *
  528. * @param _json JSON text to be deserialized, as created by CRtlFieldTypeSerializer
  529. * @return Deserialized type object
  530. */
  531. virtual const RtlTypeInfo *deserialize(const char *json) override
  532. {
  533. assertex(!base);
  534. Owned<IPropertyTree> jsonTree = createPTreeFromJSONString(json);
  535. base = deserializeType(jsonTree, jsonTree);
  536. return base;
  537. }
  538. /**
  539. * Obtain the deserialized type information
  540. * <p>
  541. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  542. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  543. * that created them is deleted.
  544. * <p>
  545. * Do not call more than once.
  546. *
  547. * @param _jsonTree JSON property tree to be deserialized, as created by CRtlFieldTypeSerializer
  548. * @return Deserialized type object
  549. */
  550. virtual const RtlTypeInfo *deserialize(IPropertyTree &jsonTree) override
  551. {
  552. assertex(!base);
  553. base = deserializeType(&jsonTree, &jsonTree);
  554. return base;
  555. }
  556. /**
  557. * Obtain the deserialized type information
  558. * <p>
  559. * Note that the RtlTypeInfo objects are not link-counted, so the lifetime of these objects
  560. * is determined by the lifetime of the deserializer. They will be released once the deserializer
  561. * that created them is deleted.
  562. * <p>
  563. * Do not call more than once.
  564. *
  565. * @param buf Binary serialized typeinfo to be deserialized, as created by CRtlFieldTypeSerializer
  566. * @return Deserialized type object
  567. */
  568. virtual const RtlTypeInfo *deserialize(MemoryBuffer &buf) override
  569. {
  570. assertex(!base);
  571. unsigned nextTypeNum = 0;
  572. int oldEndian = buf.setEndian(__LITTLE_ENDIAN);
  573. try
  574. {
  575. byte format;
  576. buf.read(format);
  577. if (format != RTLTYPEINFO_FORMAT_1)
  578. throw MakeStringException(0, "Invalid type info (%d) in CRtlFieldTypeDeserializer::deserialize", format);
  579. hash64_t hash;
  580. buf.read(hash);
  581. size32_t size;
  582. buf.read(size);
  583. #ifdef VALIDATE_TYPEINFO_HASHES
  584. hash64_t expected = rtlHash64Data(size, buf.readDirect(0), 0);
  585. if (expected != hash)
  586. throw MakeStringException(0, "Invalid type info hash in CRtlFieldTypeDeserializer::deserialize");
  587. #endif
  588. size32_t endpos = buf.getPos() + size;
  589. while (buf.getPos() < endpos)
  590. {
  591. if (base)
  592. {
  593. addType(base, nextTypeNum++);
  594. base = nullptr; // in case of exceptions...
  595. }
  596. base = deserializeType(buf);
  597. }
  598. if (buf.getPos()!=endpos)
  599. throw MakeStringException(0, "Invalid type info (incorrect size data) in CRtlFieldTypeDeserializer::deserialize");
  600. buf.setEndian(oldEndian);
  601. return base;
  602. }
  603. catch(...)
  604. {
  605. buf.setEndian(oldEndian);
  606. throw;
  607. }
  608. }
  609. virtual const RtlTypeInfo *addType(FieldTypeInfoStruct &info, const IInterface *typeOrIfblock) override
  610. {
  611. VStringBuffer name("%p", typeOrIfblock);
  612. const RtlTypeInfo ** found = types.getValue(name);
  613. if (found)
  614. return *found;
  615. savedTypes.append(LINK(typeOrIfblock));
  616. info.locale = keep(info.locale);
  617. const RtlTypeInfo * ret = info.createRtlTypeInfo();
  618. types.setValue(name, ret);
  619. unsigned baseType = (info.fieldType & RFTMkind);
  620. if (baseType == type_record)
  621. patchIfBlockParentRow(ret, static_cast<const RtlRecordTypeInfo *>(ret));
  622. return ret;
  623. }
  624. virtual const RtlTypeInfo *lookupType(const IInterface * typeOrIfBlock) const override
  625. {
  626. VStringBuffer name("%p", typeOrIfBlock);
  627. const RtlTypeInfo ** found = types.getValue(name);
  628. if (found)
  629. return *found;
  630. return nullptr;
  631. }
  632. virtual const RtlFieldInfo *addFieldInfo(const char *fieldName, const char *xpath, const RtlTypeInfo *type, unsigned flags, const char *init) override
  633. {
  634. // MORE - we could hang onto this for cleanup, rather than assuming that we keep it via a later addType() call?
  635. return new RtlFieldStrInfo(keep(fieldName), keep(xpath), type, flags, init);
  636. }
  637. private:
  638. KeptAtomTable atoms; // Used to ensure proper lifetime of strings used in type structures
  639. MapStringTo<const RtlTypeInfo *> types; // Ensures structures only generated once
  640. const RtlTypeInfo *base = nullptr; // Holds the resulting type
  641. IConstPointerArray savedTypes; // ensure types remain alive for subsequent lookups
  642. void deleteType(const RtlTypeInfo *type)
  643. {
  644. if (type)
  645. {
  646. // Releases all memory for a single RtlTypeInfo object
  647. const RtlFieldInfo * const * fields = type->queryFields();
  648. if (fields)
  649. {
  650. const RtlFieldInfo * const * cur = fields;
  651. for (;;)
  652. {
  653. const RtlFieldInfo * child = *cur;
  654. if (!child)
  655. break;
  656. // We don't need to delete other strings - they are owned by atom table.
  657. // But the initializer is decoded and thus owned by me
  658. if (!isVirtualInitializer(child->initializer))
  659. free((void *)child->initializer);
  660. delete child;
  661. cur++;
  662. }
  663. delete [] fields;
  664. }
  665. type->doDelete();
  666. }
  667. }
  668. void cleanupType(const RtlTypeInfo *type)
  669. {
  670. if (type)
  671. type->doCleanup();
  672. }
  673. const RtlTypeInfo *lookupType(const char *name, IPropertyTree *all)
  674. {
  675. const RtlTypeInfo ** found = types.getValue(name);
  676. if (found)
  677. return *found;
  678. const RtlTypeInfo *type = deserializeType(all->queryPropTree(name), all);
  679. types.setValue(name, type);
  680. return type;
  681. }
  682. const RtlTypeInfo *lookupType(unsigned idx)
  683. {
  684. // Could keep an expanding array of types instead - but the hash table is already there for json support...
  685. VStringBuffer key("%u", idx);
  686. const RtlTypeInfo ** found = types.getValue(key);
  687. if (found)
  688. return *found;
  689. throw makeStringException(-1, "Invalid serialized type information");
  690. }
  691. void addType(const RtlTypeInfo *type, unsigned idx)
  692. {
  693. VStringBuffer key("%u", idx);
  694. assert(types.getValue(key)==nullptr);
  695. types.setValue(key, type);
  696. }
  697. const char *keep(const char *string)
  698. {
  699. if (string)
  700. return str(atoms.addAtom(string));
  701. else
  702. return nullptr;
  703. }
  704. const RtlTypeInfo *deserializeType(IPropertyTree *type, IPropertyTree *all)
  705. {
  706. FieldTypeInfoStruct info;
  707. info.fieldType = type->getPropInt("fieldType");
  708. info.length = type->getPropInt("length");
  709. info.locale = keep(type->queryProp("locale"));
  710. const char *child = type->queryProp("child");
  711. if (child)
  712. info.childType = lookupType(child, all);
  713. unsigned baseType = (info.fieldType & RFTMkind);
  714. if ((baseType == type_record) || (baseType == type_ifblock))
  715. {
  716. unsigned numFields = type->getCount("fields");
  717. info.fieldsArray = new const RtlFieldInfo * [numFields+1];
  718. info.fieldsArray[numFields] = nullptr;
  719. Owned<IPropertyTreeIterator> fields = type->getElements("fields");
  720. unsigned n = 0;
  721. ForEach(*fields)
  722. {
  723. IPropertyTree &field = fields->query();
  724. const char *fieldTypeName = field.queryProp("type");
  725. const char *fieldName = keep(field.queryProp("name"));
  726. const char *fieldXpath = keep(field.queryProp("xpath"));
  727. unsigned flags = field.getPropInt("flags");
  728. const char *fieldInit = field.queryProp("init");
  729. const char *fieldVInit = field.queryProp("vinit");
  730. if (fieldInit)
  731. {
  732. StringBuffer decoded;
  733. JBASE64_Decode(fieldInit, decoded);
  734. fieldInit = decoded.detach(); // NOTE - this gets freed in cleanupType()
  735. }
  736. else if (fieldVInit)
  737. {
  738. fieldInit = (const char *)(memsize_t)atoi(fieldVInit);
  739. }
  740. info.fieldsArray[n] = new RtlFieldStrInfo(fieldName, fieldXpath, lookupType(fieldTypeName, all), flags, fieldInit);
  741. n++;
  742. }
  743. }
  744. if (baseType == type_ifblock)
  745. {
  746. //Filter field needs to be deserialized and the type resolved separately outside the deserialize call
  747. //because there isn't a RtlTypeInfo available to resolve the field (since we are currently deserializing it!)
  748. const char * filterText = type->queryProp("filter");
  749. StringBuffer fieldIdText;
  750. readFieldFromFieldFilter(fieldIdText, filterText);
  751. unsigned fieldId = atoi(fieldIdText);
  752. const RtlTypeInfo * fieldType = lookupType(type->queryProp("filterType"), all);
  753. info.filter = deserializeFieldFilter(fieldId, *fieldType, filterText);
  754. }
  755. const RtlTypeInfo * result = info.createRtlTypeInfo();
  756. if (baseType == type_record)
  757. patchIfBlockParentRow(result, static_cast<const RtlRecordTypeInfo *>(result));
  758. return result;
  759. }
  760. const RtlTypeInfo *deserializeType(MemoryBuffer &type)
  761. {
  762. FieldTypeInfoStruct info;
  763. type.read(info.fieldType);
  764. type.readPacked(info.length);
  765. if (info.fieldType & RFTMhasLocale)
  766. {
  767. const char *locale;
  768. type.read(locale);
  769. info.locale = keep(locale);
  770. }
  771. if (info.fieldType & RFTMhasChildType)
  772. {
  773. unsigned childIdx;
  774. type.readPacked(childIdx);
  775. info.childType = lookupType(childIdx);
  776. }
  777. unsigned baseType = (info.fieldType & RFTMkind);
  778. if (baseType == type_ifblock)
  779. {
  780. unsigned childIdx;
  781. type.readPacked(childIdx);
  782. const RtlTypeInfo * fieldType = lookupType(childIdx);
  783. unsigned fieldId;
  784. type.readPacked(fieldId);
  785. info.filter = deserializeFieldFilter(fieldId, *fieldType, type);
  786. }
  787. if (info.fieldType & RFTMhasFields)
  788. {
  789. unsigned numFields;
  790. type.readPacked(numFields);
  791. info.fieldsArray = new const RtlFieldInfo * [numFields+1];
  792. info.fieldsArray[numFields] = nullptr;
  793. for (unsigned n = 0; n < numFields; n++)
  794. {
  795. const char *fieldName;
  796. type.read(fieldName);
  797. if (fieldName[0] == '\0')
  798. fieldName = nullptr;
  799. unsigned fieldType;
  800. type.readPacked(fieldType);
  801. unsigned fieldFlags;
  802. type.read(fieldFlags);
  803. const char *xpath = nullptr;
  804. if (fieldFlags & RFTMhasXpath)
  805. type.read(xpath);
  806. void *init = nullptr;
  807. if (fieldFlags & RFTMhasInitializer)
  808. {
  809. unsigned initLength;
  810. type.readPacked(initLength);
  811. init = malloc(initLength);
  812. memcpy(init, type.readDirect(initLength), initLength);
  813. }
  814. else if (fieldFlags & RFTMhasVirtualInitializer)
  815. {
  816. byte virtualKind;
  817. type.read(virtualKind);
  818. init = (void *)(memsize_t)virtualKind;
  819. }
  820. fieldFlags &= ~RFTMserializerFlags;
  821. info.fieldsArray[n] = new RtlFieldStrInfo(keep(fieldName), keep(xpath), lookupType(fieldType), fieldFlags, (const char *) init);
  822. }
  823. }
  824. info.fieldType &= ~RFTMserializerFlags;
  825. const RtlTypeInfo * result = info.createRtlTypeInfo();
  826. if (baseType == type_record)
  827. patchIfBlockParentRow(result, static_cast<const RtlRecordTypeInfo *>(result));
  828. return result;
  829. }
  830. void patchIfBlockParentRow(const RtlTypeInfo * fieldType, const RtlRecordTypeInfo * parentRow)
  831. {
  832. const RtlFieldInfo * const * fields = fieldType->queryFields();
  833. for (;*fields;fields++)
  834. {
  835. const RtlFieldInfo * cur = *fields;
  836. if (!cur)
  837. break;
  838. const RtlTypeInfo * curType = cur->type;
  839. if ((curType->fieldType & RFTMkind) == type_ifblock)
  840. {
  841. const RtlDynamicIfBlockTypeInfo * constifblock = static_cast<const RtlDynamicIfBlockTypeInfo *>(curType);
  842. RtlDynamicIfBlockTypeInfo * ifblock = const_cast<RtlDynamicIfBlockTypeInfo *>(constifblock);
  843. ifblock->setParent(parentRow);
  844. patchIfBlockParentRow(curType, parentRow);
  845. }
  846. }
  847. }
  848. };
  849. extern ECLRTL_API IRtlFieldTypeDeserializer *createRtlFieldTypeDeserializer()
  850. {
  851. return new CRtlFieldTypeDeserializer();
  852. }
  853. extern ECLRTL_API StringBuffer &dumpTypeInfo(StringBuffer &ret, const RtlTypeInfo *t)
  854. {
  855. return CRtlFieldTypeSerializer::serialize(ret, t);
  856. }
  857. extern ECLRTL_API bool dumpTypeInfo(MemoryBuffer &ret, const RtlTypeInfo *t)
  858. {
  859. try
  860. {
  861. CRtlFieldTypeBinSerializer::serialize(ret, t);
  862. return true;
  863. }
  864. catch (IException *E)
  865. {
  866. EXCLOG(E);
  867. return false;
  868. }
  869. }
  870. extern ECLRTL_API void serializeRecordType(size32_t & __lenResult, void * & __result, IOutputMetaData & metaVal)
  871. {
  872. MemoryBuffer ret;
  873. try
  874. {
  875. CRtlFieldTypeBinSerializer::serialize(ret, metaVal.queryTypeInfo());
  876. }
  877. catch (IException * e)
  878. {
  879. ret.clear();
  880. e->Release();
  881. }
  882. __lenResult = ret.length();
  883. __result = ret.detach();
  884. }
  885. extern ECLRTL_API void dumpRecordType(size32_t & __lenResult,char * & __result,IOutputMetaData &metaVal)
  886. {
  887. StringBuffer ret;
  888. try
  889. {
  890. CRtlFieldTypeSerializer::serialize(ret, metaVal.queryTypeInfo());
  891. #ifdef _DEBUG
  892. StringBuffer ret2;
  893. CRtlFieldTypeDeserializer deserializer;
  894. CRtlFieldTypeSerializer::serialize(ret2, deserializer.deserialize(ret));
  895. assert(streq(ret, ret2));
  896. MemoryBuffer out;
  897. CRtlFieldTypeBinSerializer::serialize(out, metaVal.queryTypeInfo());
  898. CRtlFieldTypeDeserializer bindeserializer;
  899. CRtlFieldTypeSerializer::serialize(ret2.clear(), bindeserializer.deserialize(out));
  900. assert(streq(ret, ret2));
  901. #endif
  902. }
  903. catch (IException * e)
  904. {
  905. e->errorMessage(ret.clear());
  906. e->Release();
  907. }
  908. __lenResult = ret.length();
  909. __result = ret.detach();
  910. }
  911. extern ECLRTL_API void getFieldVal(size32_t & __lenResult,char * & __result, int column, IOutputMetaData & metaVal, const byte *row)
  912. {
  913. __lenResult = 0;
  914. __result = nullptr;
  915. if (column >= 0)
  916. {
  917. const RtlRecord &r = metaVal.queryRecordAccessor(true);
  918. if ((unsigned) column < r.getNumFields())
  919. {
  920. unsigned numOffsets = r.getNumVarFields() + 1;
  921. size_t * variableOffsets = (size_t *)alloca(numOffsets * sizeof(size_t));
  922. RtlRow offsetCalculator(r, row, numOffsets, variableOffsets);
  923. offsetCalculator.getUtf8(__lenResult, __result, column);
  924. }
  925. }
  926. }
  927. extern ECLRTL_API int getFieldNum(const char *fieldName, IOutputMetaData & metaVal)
  928. {
  929. const RtlRecord r = metaVal.queryRecordAccessor(true);
  930. return r.getFieldNum(fieldName);
  931. }
  932. enum FieldMatchType {
  933. // On a field, exactly one of the below is set, but translator returns a bitmap indicating
  934. // which were required (and we can restrict translation to allow some types but not others)
  935. match_perfect = 0x00, // exact type match - use memcpy
  936. match_link = 0x01, // copy a nested dataset by linking
  937. match_move = 0x02, // at least one field has moved (set on translator)
  938. match_remove = 0x04, // at least one field has been removed (set on translator)
  939. match_truncate = 0x08, // dest is truncated copy of source - use memcpy
  940. match_extend = 0x10, // dest is padded version of source - use memcpy and memset
  941. match_typecast = 0x20, // type has changed - cast required
  942. match_none = 0x40, // No matching field in source - use null value
  943. match_recurse = 0x80, // Use recursive translator for child records/datasets
  944. match_fail = 0x100, // no translation possible
  945. match_keychange = 0x200, // at least one affected field not marked as payload (set on translator)
  946. match_virtual = 0x800, // at least one affected field is a virtual field (set on translator)
  947. // This flag may be set in conjunction with the others
  948. match_inifblock = 0x400, // matching to a field in an ifblock - may not be present
  949. match_deblob = 0x1000, // source needs fetching from a blob prior to translation
  950. match_dynamic = 0x2000, // source needs fetching from dynamic source (callback)
  951. };
  952. StringBuffer &describeFlags(StringBuffer &out, FieldMatchType flags)
  953. {
  954. if (flags == match_perfect)
  955. return out.append("perfect");
  956. unsigned origlen = out.length();
  957. if (flags & match_link) out.append("|link");
  958. if (flags & match_move) out.append("|move");
  959. if (flags & match_remove) out.append("|remove");
  960. if (flags & match_truncate) out.append("|truncate");
  961. if (flags & match_extend) out.append("|extend");
  962. if (flags & match_typecast) out.append("|typecast");
  963. if (flags & match_none) out.append("|none");
  964. if (flags & match_recurse) out.append("|recurse");
  965. if (flags & match_inifblock) out.append("|ifblock");
  966. if (flags & match_keychange) out.append("|keychange");
  967. if (flags & match_fail) out.append("|fail");
  968. if (flags & match_virtual) out.append("|virtual");
  969. if (flags & match_deblob) out.append("|blob");
  970. if (flags & match_dynamic) out.append("|dynamic");
  971. assertex(out.length() > origlen);
  972. return out.remove(origlen, 1);
  973. }
  974. inline constexpr FieldMatchType operator|(FieldMatchType a, FieldMatchType b) { return (FieldMatchType)((int)a | (int)b); }
  975. inline FieldMatchType &operator|=(FieldMatchType &a, FieldMatchType b) { return (FieldMatchType &) ((int &)a |= (int)b); }
  976. class GeneralRecordTranslator : public CInterfaceOf<IDynamicTransform>
  977. {
  978. public:
  979. GeneralRecordTranslator(const RtlRecord &_destRecInfo, const RtlRecord &_srcRecInfo, bool _binarySource, type_vals _callbackRawType = type_any)
  980. : destRecInfo(_destRecInfo), sourceRecInfo(_srcRecInfo), binarySource(_binarySource), callbackRawType(_callbackRawType)
  981. {
  982. matchInfo = new MatchInfo[destRecInfo.getNumFields()];
  983. createMatchInfo();
  984. #ifdef _DEBUG
  985. //describe();
  986. #endif
  987. }
  988. ~GeneralRecordTranslator()
  989. {
  990. delete [] matchInfo;
  991. }
  992. // IDynamicTransform impl.
  993. virtual void describe() const override
  994. {
  995. doDescribe(0);
  996. }
  997. virtual size32_t translate(ARowBuilder &builder, IVirtualFieldCallback & callback, const byte *sourceRec) const override
  998. {
  999. assertex(binarySource);
  1000. return doTranslate(builder, callback, 0, sourceRec);
  1001. }
  1002. virtual size32_t translate(ARowBuilder &builder, IVirtualFieldCallback & callback, const RtlRow &sourceRow) const override
  1003. {
  1004. assertex(binarySource);
  1005. sourceRow.lazyCalcOffsets(-1); // MORE - could save the max one we actually need...
  1006. return doTranslateOpaqueType(builder, callback, 0, &sourceRow);
  1007. }
  1008. virtual size32_t translate(ARowBuilder &builder, IVirtualFieldCallback & callback, const IDynamicFieldValueFetcher & fetcher) const override
  1009. {
  1010. assertex(!binarySource);
  1011. return doTranslateOpaqueType(builder, callback, 0, &fetcher);
  1012. }
  1013. virtual bool canTranslate() const override
  1014. {
  1015. return (matchFlags & match_fail) == 0;
  1016. }
  1017. virtual bool needsTranslate() const override
  1018. {
  1019. return !binarySource || (matchFlags & ~(match_link|match_inifblock)) != 0;
  1020. }
  1021. virtual bool needsNonVirtualTranslate() const override
  1022. {
  1023. return (matchFlags & ~(match_link|match_virtual|match_keychange|match_inifblock)) != 0;
  1024. }
  1025. virtual bool keyedTranslated() const override
  1026. {
  1027. return (matchFlags & match_keychange) != 0;
  1028. }
  1029. private:
  1030. void doDescribe(unsigned indent) const
  1031. {
  1032. unsigned perfect=0;
  1033. unsigned reported=0;
  1034. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1035. {
  1036. const char *source = destRecInfo.queryName(idx);
  1037. const MatchInfo &match = matchInfo[idx];
  1038. if (match.matchType == match_none)
  1039. DBGLOG("%*sNo match for field %s - default value will be used", indent, "", source);
  1040. else if (match.matchType == match_virtual)
  1041. DBGLOG("%*sUse virtual value for field %s", indent, "", source);
  1042. else
  1043. {
  1044. if (match.matchType != match_perfect)
  1045. {
  1046. reported++;
  1047. StringBuffer matchStr;
  1048. DBGLOG("%*sMatch (%s) to field %d for field %s (typecode %x)", indent, "", describeFlags(matchStr, match.matchType).str(), match.matchIdx, source, destRecInfo.queryType(idx)->fieldType);
  1049. if (match.subTrans)
  1050. match.subTrans->doDescribe(indent+2);
  1051. }
  1052. else
  1053. perfect++;
  1054. }
  1055. }
  1056. if (allUnmatched.ordinality())
  1057. {
  1058. VStringBuffer msg("%*sDropped field", indent, "");
  1059. if (allUnmatched.ordinality()>1)
  1060. msg.append('s');
  1061. for (unsigned idx = 0; idx < allUnmatched.ordinality() && idx < 5; idx++)
  1062. {
  1063. if (idx)
  1064. msg.append(',');
  1065. msg.appendf(" %s", sourceRecInfo.queryName(allUnmatched.item(idx)));
  1066. }
  1067. if (allUnmatched.ordinality() > 5)
  1068. msg.appendf(" and %u other fields", allUnmatched.ordinality() - 5);
  1069. DBGLOG("%s", msg.str());
  1070. }
  1071. if (!canTranslate())
  1072. DBGLOG("%*sTranslation is NOT possible", indent, "");
  1073. else if (needsTranslate())
  1074. {
  1075. StringBuffer matchStr;
  1076. if (perfect)
  1077. DBGLOG("%u %sfield%s matched perfectly", perfect, reported ? "other " : "", perfect==1 ? "" : "s");
  1078. DBGLOG("%*sTranslation is possible (%s)", indent, "", describeFlags(matchStr, matchFlags).str());
  1079. }
  1080. else
  1081. DBGLOG("%*sTranslation is not necessary", indent, "");
  1082. }
  1083. size32_t doTranslate(ARowBuilder &builder, IVirtualFieldCallback & callback, size32_t offset, const byte *sourceRec) const
  1084. {
  1085. unsigned numOffsets = sourceRecInfo.getNumVarFields() + 1;
  1086. size_t * variableOffsets = (size_t *)alloca(numOffsets * sizeof(size_t));
  1087. RtlRow sourceRow(sourceRecInfo, sourceRec, numOffsets, variableOffsets); // MORE - could save the max source offset we actually need, and only set up that many...
  1088. return doTranslateOpaqueType(builder, callback, offset, &sourceRow);
  1089. }
  1090. size32_t doTranslateOpaqueType(ARowBuilder &builder, IVirtualFieldCallback & callback, size32_t offset, const void *sourceRow) const
  1091. {
  1092. dbgassertex(canTranslate());
  1093. byte * destConditions = (byte *)alloca(destRecInfo.getNumIfBlocks() * sizeof(byte));
  1094. memset(destConditions, 2, destRecInfo.getNumIfBlocks() * sizeof(byte));
  1095. size32_t estimate = destRecInfo.getFixedSize();
  1096. bool hasBlobs = false;
  1097. if (!estimate)
  1098. {
  1099. if (binarySource)
  1100. estimate = estimateNewSize(*(const RtlRow *)sourceRow);
  1101. else
  1102. estimate = destRecInfo.getMinRecordSize();
  1103. builder.ensureCapacity(offset+estimate, "record");
  1104. }
  1105. size32_t origOffset = offset;
  1106. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1107. {
  1108. const RtlFieldInfo *field = destRecInfo.queryField(idx);
  1109. if (field->omitable() && destRecInfo.excluded(field, builder.getSelf(), destConditions))
  1110. continue;
  1111. const RtlTypeInfo *type = field->type;
  1112. const MatchInfo &match = matchInfo[idx];
  1113. if (match.matchType == match_none || match.matchType==match_fail)
  1114. {
  1115. offset = type->buildNull(builder, offset, field);
  1116. }
  1117. else if (match.matchType == match_virtual)
  1118. {
  1119. switch (getVirtualInitializer(field->initializer))
  1120. {
  1121. case FVirtualFilePosition:
  1122. offset = type->buildInt(builder, offset, field, callback.getFilePosition(sourceRow));
  1123. break;
  1124. case FVirtualLocalFilePosition:
  1125. offset = type->buildInt(builder, offset, field, callback.getLocalFilePosition(sourceRow));
  1126. break;
  1127. case FVirtualFilename:
  1128. {
  1129. const char * filename = callback.queryLogicalFilename(sourceRow);
  1130. offset = type->buildString(builder, offset, field, strlen(filename), filename);
  1131. break;
  1132. }
  1133. default:
  1134. throwUnexpected();
  1135. }
  1136. }
  1137. else
  1138. {
  1139. unsigned matchField = match.matchIdx;
  1140. const RtlTypeInfo *sourceType = sourceRecInfo.queryType(matchField);
  1141. size_t sourceOffset = 0;
  1142. const byte *source = nullptr;
  1143. size_t copySize = 0;
  1144. if (binarySource)
  1145. {
  1146. const RtlRow &rtlRow = *(const RtlRow *)sourceRow;
  1147. sourceOffset = rtlRow.getOffset(matchField);
  1148. source = rtlRow.queryRow() + sourceOffset;
  1149. copySize = rtlRow.getSize(matchField);
  1150. }
  1151. if (match.matchType & match_deblob)
  1152. {
  1153. offset_t blobId = sourceType->getInt(source);
  1154. sourceType = sourceType->queryChildType();
  1155. sourceOffset = 0;
  1156. source = callback.lookupBlob(blobId);
  1157. copySize = sourceType->size(source, source);
  1158. hasBlobs = true;
  1159. }
  1160. if (copySize == 0 && (match.matchType & match_inifblock)) // Field is missing because of an ifblock - use default value
  1161. {
  1162. offset = type->buildNull(builder, offset, field);
  1163. }
  1164. else
  1165. {
  1166. switch (match.matchType & ~(match_inifblock|match_deblob))
  1167. {
  1168. case match_perfect:
  1169. {
  1170. // Look ahead for other perfect matches and combine the copies
  1171. if (!(match.matchType & match_deblob))
  1172. {
  1173. while (idx < destRecInfo.getNumFields()-1)
  1174. {
  1175. const MatchInfo &nextMatch = matchInfo[idx+1];
  1176. if (nextMatch.matchType == match_perfect && nextMatch.matchIdx == matchField+1)
  1177. {
  1178. idx++;
  1179. matchField++;
  1180. }
  1181. else
  1182. break;
  1183. }
  1184. copySize = ((const RtlRow *)sourceRow)->getOffset(matchField+1) - sourceOffset;
  1185. }
  1186. builder.ensureCapacity(offset+copySize, field->name);
  1187. memcpy(builder.getSelf()+offset, source, copySize);
  1188. offset += copySize;
  1189. break;
  1190. }
  1191. case match_truncate:
  1192. {
  1193. assert(type->isFixedSize());
  1194. copySize = type->getMinSize();
  1195. builder.ensureCapacity(offset+copySize, field->name);
  1196. memcpy(builder.getSelf()+offset, source, copySize);
  1197. offset += copySize;
  1198. break;
  1199. }
  1200. case match_extend:
  1201. {
  1202. assert(type->isFixedSize());
  1203. size32_t destSize = type->getMinSize();
  1204. builder.ensureCapacity(offset+destSize, field->name);
  1205. memcpy(builder.getSelf()+offset, source, copySize);
  1206. offset += copySize;
  1207. unsigned fillSize = destSize - copySize;
  1208. memset(builder.getSelf()+offset, match.fillChar, fillSize);
  1209. offset += fillSize;
  1210. break;
  1211. }
  1212. case match_typecast:
  1213. offset = translateScalar(builder, offset, field, *type, *sourceType, source);
  1214. break;
  1215. case match_typecast|match_dynamic:
  1216. {
  1217. const IDynamicFieldValueFetcher &callbackRowHandler = *(const IDynamicFieldValueFetcher *)sourceRow;
  1218. source = callbackRowHandler.queryValue(matchField, copySize);
  1219. if (callbackRawType == type_string)
  1220. offset = translateScalarFromString(builder, offset, field, *type, *sourceType, (const char *)source, (size_t)copySize);
  1221. else
  1222. offset = translateScalarFromUtf8(builder, offset, field, *type, *sourceType, (const char *)source, (size_t)copySize);
  1223. break;
  1224. }
  1225. case match_link:
  1226. {
  1227. // a 32-bit record count, and a (linked) pointer to an array of record pointers
  1228. byte *dest = builder.ensureCapacity(offset+sizeof(size32_t)+sizeof(const byte **), field->name)+offset;
  1229. *(size32_t *)dest = *(size32_t *)source;
  1230. *(const byte ***)(dest + sizeof(size32_t)) = rtlLinkRowset(*(const byte ***)(source + sizeof(size32_t)));
  1231. offset += sizeof(size32_t)+sizeof(const byte **);
  1232. break;
  1233. }
  1234. case match_recurse|match_dynamic:
  1235. {
  1236. const IDynamicFieldValueFetcher &callbackRowHandler = *(const IDynamicFieldValueFetcher *)sourceRow;
  1237. Owned<IDynamicRowIterator> iterator = callbackRowHandler.getNestedIterator(matchField);
  1238. if (type->getType()==type_record)
  1239. {
  1240. IDynamicFieldValueFetcher &fieldFetcher = iterator->query();
  1241. offset = match.subTrans->doTranslateOpaqueType(builder, callback, offset, &fieldFetcher);
  1242. }
  1243. else if (type->isLinkCounted())
  1244. {
  1245. // a 32-bit record count, and a pointer to an array of record pointers
  1246. IEngineRowAllocator *childAllocator = builder.queryAllocator()->createChildRowAllocator(type->queryChildType());
  1247. assertex(childAllocator); // May not be available when using serialized types (but unlikely to want to create linkcounted children remotely either)
  1248. size32_t sizeInBytes = sizeof(size32_t) + sizeof(void *);
  1249. builder.ensureCapacity(offset+sizeInBytes, field->name);
  1250. size32_t numRows = 0;
  1251. const byte **childRows = nullptr;
  1252. ForEach(*iterator)
  1253. {
  1254. IDynamicFieldValueFetcher &fieldFetcher = iterator->query();
  1255. RtlDynamicRowBuilder childBuilder(*childAllocator);
  1256. size32_t childLen = match.subTrans->doTranslateOpaqueType(childBuilder, callback, 0, &fieldFetcher);
  1257. childRows = childAllocator->appendRowOwn(childRows, ++numRows, (void *) childBuilder.finalizeRowClear(childLen));
  1258. }
  1259. if (type->getType() == type_dictionary)
  1260. {
  1261. const RtlTypeInfo * childType = type->queryChildType();
  1262. assertex(childType && childType->getType() == type_record);
  1263. CHThorHashLookupInfo lookupHelper(static_cast<const RtlRecordTypeInfo &>(*childType));
  1264. rtlCreateDictionaryFromDataset(numRows, childRows, childAllocator, lookupHelper);
  1265. }
  1266. // Go back in and patch the count, remembering it may have moved
  1267. rtlWriteInt4(builder.getSelf()+offset, numRows);
  1268. * ( const void * * ) (builder.getSelf()+offset+sizeof(size32_t)) = childRows;
  1269. offset += sizeInBytes;
  1270. }
  1271. else
  1272. {
  1273. size32_t countOffset = offset;
  1274. byte *dest = builder.ensureCapacity(offset+sizeof(size32_t), field->name)+offset;
  1275. offset += sizeof(size32_t);
  1276. size32_t initialOffset = offset;
  1277. *(size32_t *)dest = 0; // patched below when true figure known
  1278. ForEach(*iterator)
  1279. {
  1280. IDynamicFieldValueFetcher &fieldFetcher = iterator->query();
  1281. offset = match.subTrans->doTranslateOpaqueType(builder, callback, offset, &fieldFetcher);
  1282. }
  1283. dest = builder.getSelf() + countOffset; // Note - may have been moved by reallocs since last calculated
  1284. *(size32_t *)dest = offset - initialOffset;
  1285. }
  1286. break;
  1287. }
  1288. case match_recurse:
  1289. if (type->getType()==type_record)
  1290. offset = match.subTrans->doTranslate(builder, callback, offset, source);
  1291. else if (type->isLinkCounted())
  1292. {
  1293. // a 32-bit record count, and a pointer to an array of record pointers
  1294. Owned<IEngineRowAllocator> childAllocator = builder.queryAllocator()->createChildRowAllocator(type->queryChildType());
  1295. assertex(childAllocator); // May not be available when using serialized types (but unlikely to want to create linkcounted children remotely either)
  1296. size32_t sizeInBytes = sizeof(size32_t) + sizeof(void *);
  1297. builder.ensureCapacity(offset+sizeInBytes, field->name);
  1298. size32_t numRows = 0;
  1299. const byte **childRows = nullptr;
  1300. if (sourceType->isLinkCounted())
  1301. {
  1302. // a 32-bit count, then a pointer to the source rows
  1303. size32_t childCount = *(size32_t *) source;
  1304. source += sizeof(size32_t);
  1305. const byte ** sourceRows = *(const byte***) source;
  1306. for (size32_t childRow = 0; childRow < childCount; childRow++)
  1307. {
  1308. RtlDynamicRowBuilder childBuilder(*childAllocator);
  1309. size32_t childLen = match.subTrans->doTranslate(childBuilder, callback, 0, sourceRows[childRow]);
  1310. childRows = childAllocator->appendRowOwn(childRows, ++numRows, (void *) childBuilder.finalizeRowClear(childLen));
  1311. }
  1312. }
  1313. else
  1314. {
  1315. // a 32-bit size, then rows inline
  1316. size32_t childSize = *(size32_t *) source;
  1317. source += sizeof(size32_t);
  1318. const byte *initialSource = source;
  1319. while ((size_t)(source - initialSource) < childSize)
  1320. {
  1321. RtlDynamicRowBuilder childBuilder(*childAllocator);
  1322. size32_t childLen = match.subTrans->doTranslate(childBuilder, callback, 0, source);
  1323. childRows = childAllocator->appendRowOwn(childRows, ++numRows, (void *) childBuilder.finalizeRowClear(childLen));
  1324. source += sourceType->queryChildType()->size(source, nullptr); // MORE - shame to repeat a calculation that the translate above almost certainly just did
  1325. }
  1326. }
  1327. if (type->getType() == type_dictionary)
  1328. {
  1329. const RtlTypeInfo * childType = type->queryChildType();
  1330. assertex(childType && childType->getType() == type_record);
  1331. CHThorHashLookupInfo lookupHelper(static_cast<const RtlRecordTypeInfo &>(*childType));
  1332. rtlCreateDictionaryFromDataset(numRows, childRows, childAllocator, lookupHelper);
  1333. }
  1334. // Go back in and patch the count, remembering it may have moved
  1335. rtlWriteInt4(builder.getSelf()+offset, numRows);
  1336. * ( const void * * ) (builder.getSelf()+offset+sizeof(size32_t)) = childRows;
  1337. offset += sizeInBytes;
  1338. }
  1339. else
  1340. {
  1341. size32_t countOffset = offset;
  1342. byte *dest = builder.ensureCapacity(offset+sizeof(size32_t), field->name)+offset;
  1343. offset += sizeof(size32_t);
  1344. size32_t initialOffset = offset;
  1345. *(size32_t *)dest = 0; // patched below when true figure known
  1346. if (sourceType->isLinkCounted())
  1347. {
  1348. // a 32-bit count, then a pointer to the source rows
  1349. size32_t childCount = *(size32_t *) source;
  1350. source += sizeof(size32_t);
  1351. const byte ** sourceRows = *(const byte***) source;
  1352. for (size32_t childRow = 0; childRow < childCount; childRow++)
  1353. {
  1354. const byte * row = sourceRows[childRow];
  1355. //Dictionaries have blank rows - ignore them when serializing (to a dataset)
  1356. if (row)
  1357. offset = match.subTrans->doTranslate(builder, callback, offset, row);
  1358. }
  1359. }
  1360. else
  1361. {
  1362. // a 32-bit size, then rows inline
  1363. size32_t childSize = *(size32_t *) source;
  1364. source += sizeof(size32_t);
  1365. const byte *initialSource = source;
  1366. while ((size_t)(source - initialSource) < childSize)
  1367. {
  1368. offset = match.subTrans->doTranslate(builder, callback, offset, source);
  1369. source += sourceType->queryChildType()->size(source, nullptr); // MORE - shame to repeat a calculation that the translate above almost certainly just did
  1370. }
  1371. }
  1372. dest = builder.getSelf() + countOffset; // Note - may have been moved by reallocs since last calculated
  1373. *(size32_t *)dest = offset - initialOffset;
  1374. }
  1375. break;
  1376. default:
  1377. throwUnexpected();
  1378. }
  1379. }
  1380. }
  1381. }
  1382. if (estimate && offset-origOffset != estimate)
  1383. {
  1384. if (offset == origOffset)
  1385. {
  1386. //Zero size records are treated as single byte to avoid confusion with sizes returned from transforms etc.
  1387. offset++;
  1388. }
  1389. else
  1390. {
  1391. // Note - ifblocks make this assertion invalid. We do not account for potentially omitted fields
  1392. // when estimating target record size.
  1393. if (!destRecInfo.getNumIfBlocks() && !hasBlobs)
  1394. assert(offset-origOffset > estimate); // Estimate is always supposed to be conservative
  1395. #ifdef TRACE_TRANSLATION
  1396. DBGLOG("Wrote %u bytes to record (estimate was %u)\n", offset-origOffset, estimate);
  1397. #endif
  1398. }
  1399. }
  1400. return offset;
  1401. }
  1402. inline FieldMatchType match() const
  1403. {
  1404. return matchFlags;
  1405. }
  1406. const RtlRecord &destRecInfo;
  1407. const RtlRecord &sourceRecInfo;
  1408. bool binarySource = true;
  1409. type_vals callbackRawType;
  1410. unsigned fixedDelta = 0; // total size of all fixed-size source fields that are not matched
  1411. UnsignedArray allUnmatched; // List of all source fields that are unmatched (so that we can trace them)
  1412. UnsignedArray variableUnmatched; // List of all variable-size source fields that are unmatched
  1413. FieldMatchType matchFlags = match_perfect;
  1414. struct MatchInfo
  1415. {
  1416. unsigned matchIdx = 0;
  1417. FieldMatchType matchType = match_fail;
  1418. char fillChar = 0;
  1419. GeneralRecordTranslator *subTrans = nullptr;
  1420. ~MatchInfo()
  1421. {
  1422. delete subTrans;
  1423. }
  1424. } *matchInfo;
  1425. static size32_t translateScalarFromUtf8(ARowBuilder &builder, size32_t offset, const RtlFieldInfo *field, const RtlTypeInfo &destType, const RtlTypeInfo &sourceType, const char *source, size_t srcSize)
  1426. {
  1427. switch(destType.getType())
  1428. {
  1429. case type_boolean:
  1430. case type_int:
  1431. case type_swapint:
  1432. case type_packedint:
  1433. case type_filepos:
  1434. case type_keyedint:
  1435. {
  1436. __int64 res = rtlStrToInt8(srcSize, source);
  1437. offset = destType.buildInt(builder, offset, field, res);
  1438. break;
  1439. }
  1440. case type_real:
  1441. {
  1442. double res = rtlStrToReal(srcSize, source);
  1443. offset = destType.buildReal(builder, offset, field, res);
  1444. break;
  1445. }
  1446. case type_data:
  1447. case type_string:
  1448. case type_decimal: // Go via string - not common enough to special-case
  1449. case type_varstring:
  1450. case type_qstring:
  1451. case type_utf8:
  1452. //MORE: Could special case casting from utf8 to utf8 similar to strings above
  1453. case type_unicode:
  1454. case type_varunicode:
  1455. {
  1456. size32_t utf8chars = rtlUtf8Length(srcSize, source);
  1457. offset = destType.buildUtf8(builder, offset, field, utf8chars, source);
  1458. break;
  1459. }
  1460. case type_set:
  1461. {
  1462. UNIMPLEMENTED; // JCS->GH - but perhaps can/should translate using iterator too?
  1463. break;
  1464. }
  1465. default:
  1466. throwUnexpected();
  1467. }
  1468. return offset;
  1469. }
  1470. static size32_t translateScalarFromString(ARowBuilder &builder, size32_t offset, const RtlFieldInfo *field, const RtlTypeInfo &destType, const RtlTypeInfo &sourceType, const char *source, size_t srcSize)
  1471. {
  1472. switch(destType.getType())
  1473. {
  1474. case type_boolean:
  1475. case type_int:
  1476. case type_swapint:
  1477. case type_packedint:
  1478. case type_filepos:
  1479. case type_keyedint:
  1480. {
  1481. __int64 res = rtlStrToInt8(srcSize, source);
  1482. offset = destType.buildInt(builder, offset, field, res);
  1483. break;
  1484. }
  1485. case type_real:
  1486. {
  1487. double res = rtlStrToReal(srcSize, source);
  1488. offset = destType.buildReal(builder, offset, field, res);
  1489. break;
  1490. }
  1491. case type_data:
  1492. case type_string:
  1493. case type_decimal: // Go via string - not common enough to special-case
  1494. case type_varstring:
  1495. case type_qstring:
  1496. case type_utf8:
  1497. //MORE: Could special case casting from utf8 to utf8 similar to strings above
  1498. case type_unicode:
  1499. case type_varunicode:
  1500. {
  1501. offset = destType.buildString(builder, offset, field, srcSize, source);
  1502. break;
  1503. }
  1504. case type_set:
  1505. {
  1506. UNIMPLEMENTED; // JCS->GH - but perhaps can/should translate using iterator too?
  1507. break;
  1508. }
  1509. default:
  1510. throwUnexpected();
  1511. }
  1512. return offset;
  1513. }
  1514. static bool canTranslateNonScalar(const RtlTypeInfo * type, const RtlTypeInfo * sourceType)
  1515. {
  1516. auto target = type->getType();
  1517. auto source = sourceType->getType();
  1518. if (target == source)
  1519. return true;
  1520. if ((target == type_dictionary) && (source == type_table))
  1521. return true;
  1522. if ((target == type_table) && (source == type_dictionary))
  1523. return true;
  1524. return false;
  1525. }
  1526. void createMatchInfo()
  1527. {
  1528. unsigned defaulted = 0;
  1529. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1530. {
  1531. const RtlFieldInfo *field = destRecInfo.queryField(idx);
  1532. const RtlTypeInfo *type = field->type;
  1533. MatchInfo &info = matchInfo[idx];
  1534. info.matchIdx = sourceRecInfo.getFieldNum(destRecInfo.queryName(idx));
  1535. if (info.matchIdx == (unsigned) -1)
  1536. {
  1537. const byte * initializer = (const byte *) field->initializer;
  1538. info.matchType = isVirtualInitializer(initializer) ? match_virtual : match_none;
  1539. size32_t defaultSize = (initializer && !isVirtualInitializer(initializer)) ? type->size(initializer, nullptr) : type->getMinSize();
  1540. fixedDelta -= defaultSize;
  1541. if ((field->flags & RFTMispayloadfield) == 0)
  1542. matchFlags |= match_keychange;
  1543. defaulted++;
  1544. //DBGLOG("Decreasing fixedDelta size by %d to %d for defaulted field %d (%s)", defaultSize, fixedDelta, idx, destRecInfo.queryName(idx));
  1545. }
  1546. else
  1547. {
  1548. bool deblob = false;
  1549. const RtlTypeInfo *sourceType = sourceRecInfo.queryType(info.matchIdx);
  1550. if (binarySource && sourceType->isBlob())
  1551. {
  1552. if (type->isBlob())
  1553. {
  1554. }
  1555. else
  1556. {
  1557. sourceType = sourceType->queryChildType();
  1558. deblob = true;
  1559. }
  1560. }
  1561. if (!type->isScalar() || !sourceType->isScalar())
  1562. {
  1563. if (!canTranslateNonScalar(type, sourceType))
  1564. info.matchType = match_fail; // No translation from one non-scalar type to another
  1565. else
  1566. {
  1567. switch (type->getType())
  1568. {
  1569. case type_set:
  1570. if (binarySource)
  1571. {
  1572. if (type->queryChildType()->fieldType==sourceType->queryChildType()->fieldType &&
  1573. type->queryChildType()->length==sourceType->queryChildType()->length)
  1574. info.matchType = match_perfect;
  1575. else
  1576. info.matchType = match_typecast;
  1577. }
  1578. else
  1579. info.matchType = match_typecast|match_dynamic;
  1580. break;
  1581. case type_row: // These are not expected I think...
  1582. throwUnexpected();
  1583. case type_ifblock:
  1584. case type_record:
  1585. case type_table:
  1586. case type_dictionary:
  1587. {
  1588. const RtlRecord *subDest = destRecInfo.queryNested(idx);
  1589. const RtlRecord *subSrc = sourceRecInfo.queryNested(info.matchIdx);
  1590. info.subTrans = new GeneralRecordTranslator(*subDest, *subSrc, binarySource);
  1591. if (!info.subTrans->needsTranslate())
  1592. {
  1593. if (!binarySource)
  1594. info.matchType = match_recurse|match_dynamic;
  1595. else
  1596. {
  1597. // Child does not require translation, but check linkcount mode matches too!
  1598. if (type->isLinkCounted())
  1599. {
  1600. if (sourceType->isLinkCounted())
  1601. info.matchType = match_link;
  1602. else
  1603. info.matchType = match_recurse;
  1604. }
  1605. else
  1606. {
  1607. if (sourceType->isLinkCounted())
  1608. info.matchType = match_recurse;
  1609. else
  1610. info.matchType = match_perfect;
  1611. }
  1612. if (info.matchType != match_recurse)
  1613. {
  1614. delete info.subTrans;
  1615. info.subTrans = nullptr;
  1616. }
  1617. }
  1618. }
  1619. else if (info.subTrans->canTranslate())
  1620. {
  1621. info.matchType = binarySource ? match_recurse : (match_recurse|match_dynamic);
  1622. unsigned childFlags = info.subTrans->matchFlags;
  1623. //Ignore differences in the keyed flag for child structures (it will be set later if this field is keyed)
  1624. matchFlags |= (FieldMatchType)(childFlags & ~match_keychange);
  1625. }
  1626. else
  1627. info.matchType = match_fail;
  1628. break;
  1629. }
  1630. case type_blob:
  1631. if (!binarySource)
  1632. info.matchType = match_fail;
  1633. else if (sourceType->isBlob())
  1634. info.matchType = match_perfect; // We don't check that the child type matches
  1635. else
  1636. info.matchType = match_fail;
  1637. break;
  1638. default:
  1639. info.matchType = match_fail;
  1640. break;
  1641. }
  1642. }
  1643. }
  1644. else if (!binarySource)
  1645. info.matchType = match_typecast|match_dynamic;
  1646. else if ((type->fieldType==sourceType->fieldType))
  1647. {
  1648. if (type->length==sourceType->length)
  1649. {
  1650. info.matchType = match_perfect;
  1651. }
  1652. else
  1653. {
  1654. assert(type->isFixedSize()); // Both variable size would have matched length above
  1655. info.matchType = match_typecast;
  1656. if (type->length < sourceType->length)
  1657. {
  1658. if (type->canTruncate())
  1659. {
  1660. info.matchType = match_truncate;
  1661. fixedDelta += sourceType->getMinSize()-type->getMinSize();
  1662. //DBGLOG("Increasing fixedDelta size by %d to %d for truncated field %d (%s)", sourceType->getMinSize()-type->getMinSize(), fixedDelta, idx, destRecInfo.queryName(idx));
  1663. }
  1664. }
  1665. else
  1666. {
  1667. if (type->canExtend(info.fillChar))
  1668. {
  1669. info.matchType = match_extend;
  1670. fixedDelta += sourceType->getMinSize()-type->getMinSize();
  1671. //DBGLOG("Decreasing fixedDelta size by %d to %d for truncated field %d (%s)", type->getMinSize()-sourceType->getMinSize(), fixedDelta, idx, destRecInfo.queryName(idx));
  1672. }
  1673. }
  1674. }
  1675. }
  1676. else
  1677. info.matchType = match_typecast;
  1678. if (deblob)
  1679. info.matchType |= match_deblob;
  1680. unsigned sourceFlags = sourceRecInfo.queryField(info.matchIdx)->flags;
  1681. if (sourceFlags & RFTMinifblock)
  1682. info.matchType |= match_inifblock; // Avoids incorrect commoning up of adjacent matches
  1683. // MORE - could note the highest interesting fieldnumber in the source and not bother filling in offsets after that
  1684. // Not sure it would help much though - usually need to know the total record size anyway in real life
  1685. if (idx != info.matchIdx)
  1686. matchFlags |= match_move;
  1687. //Whether this field is in an ifblock, or needs to be copied by linking it do not count as changes
  1688. FieldMatchType maskedType = (FieldMatchType)(info.matchType & ~(match_link|match_inifblock));
  1689. if (((maskedType != match_perfect) || (idx != info.matchIdx)) && ((field->flags & RFTMispayloadfield) == 0 || (sourceFlags & RFTMispayloadfield) == 0))
  1690. matchFlags |= match_keychange;
  1691. }
  1692. matchFlags |= info.matchType;
  1693. }
  1694. if (sourceRecInfo.getNumFields() > destRecInfo.getNumFields()-defaulted)
  1695. {
  1696. matchFlags |= match_remove;
  1697. for (unsigned idx = 0; idx < sourceRecInfo.getNumFields(); idx++)
  1698. {
  1699. const RtlFieldInfo *field = sourceRecInfo.queryField(idx);
  1700. const char *name = sourceRecInfo.queryName(idx);
  1701. if (destRecInfo.getFieldNum(name) == (unsigned) -1)
  1702. {
  1703. // unmatched field
  1704. if ((field->flags & RFTMispayloadfield) == 0)
  1705. matchFlags |= match_keychange;
  1706. if (!destRecInfo.getFixedSize())
  1707. {
  1708. const RtlTypeInfo *type = field->type;
  1709. if (type->isFixedSize())
  1710. {
  1711. //DBGLOG("Reducing estimated size by %d for (fixed size) omitted field %s", (int) type->getMinSize(), field->name);
  1712. fixedDelta += type->getMinSize();
  1713. }
  1714. else
  1715. variableUnmatched.append(idx);
  1716. }
  1717. allUnmatched.append(idx);
  1718. }
  1719. }
  1720. //DBGLOG("Source record contains %d bytes of omitted fixed size fields", fixedDelta);
  1721. }
  1722. }
  1723. size32_t estimateNewSize(const RtlRow &sourceRow) const
  1724. {
  1725. //DBGLOG("Source record size is %d", (int) sourceRow.getRecordSize());
  1726. size32_t expectedSize = sourceRow.getRecordSize() - fixedDelta;
  1727. //DBGLOG("Source record size without omitted fixed size fields is %d", expectedSize);
  1728. ForEachItemIn(i, variableUnmatched)
  1729. {
  1730. unsigned fieldNo = variableUnmatched.item(i);
  1731. expectedSize -= sourceRow.getSize(fieldNo);
  1732. //DBGLOG("Reducing estimated size by %d to %d for omitted field %d (%s)", (int) sourceRow.getSize(fieldNo), expectedSize, fieldNo, sourceRecInfo.queryName(fieldNo));
  1733. }
  1734. if (matchFlags & ~(match_perfect|match_link|match_none|match_virtual|match_extend|match_truncate))
  1735. {
  1736. for (unsigned idx = 0; idx < destRecInfo.getNumFields(); idx++)
  1737. {
  1738. const MatchInfo &match = matchInfo[idx];
  1739. const RtlTypeInfo *type = destRecInfo.queryType(idx);
  1740. unsigned matchField = match.matchIdx;
  1741. switch (match.matchType)
  1742. {
  1743. case match_perfect:
  1744. case match_link:
  1745. case match_none:
  1746. case match_virtual:
  1747. case match_extend:
  1748. case match_truncate:
  1749. // These ones were already included in fixedDelta
  1750. break;
  1751. default:
  1752. // This errs on the side of small - i.e. it assumes that all typecasts end up at minimum size
  1753. // We could do better in some cases e.g. variable string <-> variable unicode we can assume factor of 2,
  1754. // uft8 <-> string we could calculate here - but unlikely to be worth the effort.
  1755. // But it's fine for fixed size output fields, including truncate/extend
  1756. // We could also precalculate the expected delta if all omitted fields are fixed size - but not sure how likely/worthwhile that is.
  1757. expectedSize += type->getMinSize() - sourceRow.getSize(matchField);
  1758. //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));
  1759. break;
  1760. }
  1761. }
  1762. }
  1763. return expectedSize;
  1764. }
  1765. };
  1766. extern ECLRTL_API const IDynamicTransform *createRecordTranslator(const RtlRecord &destRecInfo, const RtlRecord &srcRecInfo)
  1767. {
  1768. return new GeneralRecordTranslator(destRecInfo, srcRecInfo, true);
  1769. }
  1770. extern ECLRTL_API const IDynamicTransform *createRecordTranslatorViaCallback(const RtlRecord &destRecInfo, const RtlRecord &srcRecInfo, type_vals rawType)
  1771. {
  1772. return new GeneralRecordTranslator(destRecInfo, srcRecInfo, false, rawType);
  1773. }
  1774. extern ECLRTL_API void throwTranslationError(const RtlRecord & destRecInfo, const RtlRecord & srcRecInfo, const char * filename)
  1775. {
  1776. Owned<const IDynamicTransform> translator = createRecordTranslator(destRecInfo, srcRecInfo);
  1777. #ifdef _DEBUG
  1778. translator->describe();
  1779. #endif
  1780. if (!translator->canTranslate())
  1781. throw MakeStringException(0, "Untranslatable record layout mismatch detected for: %s", filename);
  1782. throw MakeStringException(0, "Translatable key layout mismatch reading file %s but translation disabled", filename);
  1783. }
  1784. class TranslatedRowStream : public CInterfaceOf<IRowStream>
  1785. {
  1786. public:
  1787. TranslatedRowStream(IRowStream *_inputStream, IEngineRowAllocator *_resultAllocator, const RtlRecord &outputRecord, const RtlRecord &inputRecord)
  1788. : inputStream(_inputStream), resultAllocator(_resultAllocator)
  1789. {
  1790. translator.setown(createRecordTranslator(outputRecord, inputRecord));
  1791. translator->describe();
  1792. }
  1793. virtual const void *nextRow() override
  1794. {
  1795. if (eof)
  1796. return NULL;
  1797. const void *inRow = inputStream->nextRow();
  1798. if (!inRow)
  1799. {
  1800. if (eogSeen)
  1801. eof = true;
  1802. else
  1803. eogSeen = true;
  1804. return nullptr;
  1805. }
  1806. else
  1807. eogSeen = false;
  1808. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1809. size32_t len = translator->translate(rowBuilder, fieldCallback, (const byte *) inRow);
  1810. rtlReleaseRow(inRow);
  1811. return rowBuilder.finalizeRowClear(len);
  1812. }
  1813. virtual void stop() override
  1814. {
  1815. resultAllocator.clear();
  1816. }
  1817. bool canTranslate() const
  1818. {
  1819. return translator->canTranslate();
  1820. }
  1821. bool needsTranslate() const
  1822. {
  1823. return translator->needsTranslate();
  1824. }
  1825. UnexpectedVirtualFieldCallback fieldCallback; // I'm not sure if an non unexpected callback can be implemented
  1826. protected:
  1827. Linked<IRowStream> inputStream;
  1828. Linked<IEngineRowAllocator> resultAllocator;
  1829. Owned<const IDynamicTransform> translator;
  1830. unsigned numOffsets = 0;
  1831. size_t * variableOffsets = nullptr;
  1832. bool eof = false;
  1833. bool eogSeen = false;
  1834. };
  1835. extern ECLRTL_API IRowStream * transformRecord(IEngineRowAllocator * resultAllocator,IOutputMetaData & metaInput,IRowStream * input)
  1836. {
  1837. if (resultAllocator->queryOutputMeta()==&metaInput)
  1838. return LINK(input);
  1839. Owned<TranslatedRowStream> stream = new TranslatedRowStream(input, resultAllocator,
  1840. resultAllocator->queryOutputMeta()->queryRecordAccessor(true),
  1841. metaInput.queryRecordAccessor(true));
  1842. if (!stream->needsTranslate())
  1843. return LINK(input);
  1844. else if (!stream->canTranslate())
  1845. rtlFail(0, "Cannot translate record stream");
  1846. else
  1847. return stream.getClear();
  1848. }
  1849. // A key translator allows us to transform a RowFilter that refers to src to one that refers to dest.
  1850. // Basically just a map of those fields with matching types.
  1851. class CKeyTranslator : public CInterfaceOf<IKeyTranslator>
  1852. {
  1853. public:
  1854. CKeyTranslator(const RtlRecord &actual, const RtlRecord &expected)
  1855. {
  1856. translateNeeded = false;
  1857. for (unsigned expectedIdx = 0; expectedIdx < expected.getNumFields(); expectedIdx++)
  1858. {
  1859. unsigned actualIdx = actual.getFieldNum(expected.queryName(expectedIdx));
  1860. if (actualIdx != (unsigned) -1)
  1861. {
  1862. const RtlTypeInfo *expectedType = expected.queryType(expectedIdx);
  1863. const RtlTypeInfo *actualType = actual.queryType(actualIdx);
  1864. if (!actualType->equivalent(expectedType))
  1865. actualIdx = (unsigned) -2;
  1866. }
  1867. map.append(actualIdx);
  1868. if (actualIdx != expectedIdx)
  1869. translateNeeded = true;
  1870. }
  1871. }
  1872. virtual void describe() const override
  1873. {
  1874. ForEachItemIn(idx, map)
  1875. {
  1876. unsigned mapped = map.item(idx);
  1877. switch (mapped)
  1878. {
  1879. case (unsigned) -1: DBGLOG("No match for field %d", idx); break;
  1880. case (unsigned) -2: DBGLOG("Incompatible field match for field %d", idx); break;
  1881. default: DBGLOG("keyed field %d can map to field %d", idx, mapped); break;
  1882. }
  1883. }
  1884. }
  1885. virtual bool translate(RowFilter &filters) const override
  1886. {
  1887. bool mapNeeded = false;
  1888. if (translateNeeded)
  1889. {
  1890. unsigned numFields = filters.numFilterFields();
  1891. for (unsigned idx = 0; idx < numFields; idx++)
  1892. {
  1893. unsigned fieldNum = filters.queryFilter(idx).queryFieldIndex();
  1894. unsigned mappedFieldNum = map.isItem(fieldNum) ? map.item(fieldNum) : (unsigned) -1;
  1895. if (mappedFieldNum != fieldNum)
  1896. {
  1897. mapNeeded = true;
  1898. switch (mappedFieldNum)
  1899. {
  1900. case (unsigned) -1: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - no matching field", idx);
  1901. case (unsigned) -2: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - incompatible matching field type", idx);
  1902. default:
  1903. filters.remapField(idx, mappedFieldNum);
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. if (mapNeeded)
  1909. filters.recalcFieldsRequired();
  1910. }
  1911. return mapNeeded;
  1912. }
  1913. virtual bool translate(RowFilter &filter, IConstArrayOf<IFieldFilter> &in) const override
  1914. {
  1915. bool mapNeeded = false;
  1916. if (translateNeeded)
  1917. {
  1918. unsigned numFields = in.length();
  1919. for (unsigned idx = 0; idx < numFields; idx++)
  1920. {
  1921. unsigned fieldNum = in.item(idx).queryFieldIndex();
  1922. unsigned mappedFieldNum = map.isItem(fieldNum) ? map.item(fieldNum) : (unsigned) -1;
  1923. if (mappedFieldNum != fieldNum)
  1924. {
  1925. mapNeeded = true;
  1926. switch (mappedFieldNum)
  1927. {
  1928. case (unsigned) -1: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - no matching field", idx);
  1929. case (unsigned) -2: throw makeStringExceptionV(0, "Cannot translate keyed filter on field %u - incompatible matching field type", idx);
  1930. default:
  1931. filter.addFilter(*in.item(idx).remap(mappedFieldNum));
  1932. break;
  1933. }
  1934. }
  1935. else
  1936. filter.addFilter(OLINK(in.item(idx)));
  1937. }
  1938. }
  1939. return mapNeeded;
  1940. }
  1941. virtual bool needsTranslate() const
  1942. {
  1943. return translateNeeded;
  1944. }
  1945. protected:
  1946. UnsignedArray map;
  1947. bool translateNeeded = false;
  1948. };
  1949. extern ECLRTL_API const IKeyTranslator *createKeyTranslator(const RtlRecord &_destRecInfo, const RtlRecord &_srcRecInfo)
  1950. {
  1951. return new CKeyTranslator(_destRecInfo, _srcRecInfo);
  1952. }
  1953. //---------------------------------------------------------------------------------------------------------------------
  1954. const char * NullVirtualFieldCallback::queryLogicalFilename(const void * row)
  1955. {
  1956. return "";
  1957. }
  1958. unsigned __int64 NullVirtualFieldCallback::getFilePosition(const void * row)
  1959. {
  1960. return 0;
  1961. }
  1962. unsigned __int64 NullVirtualFieldCallback::getLocalFilePosition(const void * row)
  1963. {
  1964. return 0;
  1965. }
  1966. const byte * NullVirtualFieldCallback::lookupBlob(unsigned __int64 id)
  1967. {
  1968. return nullptr;
  1969. }
  1970. const char * UnexpectedVirtualFieldCallback::queryLogicalFilename(const void * row)
  1971. {
  1972. throwUnexpectedX("VIRTUAL(LOGICALFILENAME)");
  1973. }
  1974. unsigned __int64 UnexpectedVirtualFieldCallback::getFilePosition(const void * row)
  1975. {
  1976. throwUnexpectedX("VIRTUAL(FILEPOSITION)");
  1977. }
  1978. unsigned __int64 UnexpectedVirtualFieldCallback::getLocalFilePosition(const void * row)
  1979. {
  1980. throwUnexpectedX("VIRTUAL(LOCALFILEPOSITION)");
  1981. }
  1982. const byte * UnexpectedVirtualFieldCallback::lookupBlob(unsigned __int64 id)
  1983. {
  1984. throwUnexpectedX("BLOB");
  1985. }
  1986. unsigned __int64 FetchVirtualFieldCallback::getFilePosition(const void * row)
  1987. {
  1988. return filepos;
  1989. }
  1990. const char * LocalVirtualFieldCallback::queryLogicalFilename(const void * row)
  1991. {
  1992. return filename;
  1993. }
  1994. unsigned __int64 LocalVirtualFieldCallback::getFilePosition(const void * row)
  1995. {
  1996. return filepos;
  1997. }
  1998. unsigned __int64 LocalVirtualFieldCallback::getLocalFilePosition(const void * row)
  1999. {
  2000. return localfilepos;
  2001. }
  2002. const byte * LocalVirtualFieldCallback::lookupBlob(unsigned __int64 id)
  2003. {
  2004. throwUnexpectedX("BLOB");
  2005. }