couchbaseembed.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2016 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 "couchbaseembed.hpp"
  14. #include "platform.h"
  15. #include "jexcept.hpp"
  16. #include "jlog.hpp"
  17. #include "hqlplugins.hpp"
  18. #include "deftype.hpp"
  19. #include "eclhelper.hpp"
  20. #include "eclrtl.hpp"
  21. #include "eclrtl_imp.hpp"
  22. static const char *g_moduleName = "couchbase";
  23. static const char *g_moduleDescription = "Couchbase Embed Helper";
  24. static const char *g_version = "Couchbase Embed Helper 1.0.0";
  25. static const char *g_compatibleVersions[] = { g_version, nullptr };
  26. static const NullFieldProcessor NULLFIELD(NULL);
  27. extern "C" COUCHBASEEMBED_PLUGIN_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  28. {
  29. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  30. {
  31. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  32. pbx->compatibleVersions = g_compatibleVersions;
  33. }
  34. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  35. return false;
  36. pb->magicVersion = PLUGIN_VERSION;
  37. pb->version = g_version;
  38. pb->moduleName = g_moduleName;
  39. pb->ECL = NULL;
  40. pb->flags = PLUGIN_IMPLICIT_MODULE;
  41. pb->description = g_moduleDescription;
  42. return true;
  43. }
  44. namespace couchbaseembed
  45. {
  46. //--------------------------------------------------------------------------
  47. // Plugin Classes
  48. //--------------------------------------------------------------------------
  49. void reportIfQueryFailure(Couchbase::Query * query)
  50. {
  51. auto status = query->meta().status();
  52. if (status.errcode())
  53. {
  54. if (status.isNetworkError())
  55. failx("NetworkErr: %s", status.description());
  56. else if (status.isDataError())
  57. failx("DataErr: %s", status.description());
  58. else if (status.isInputError())
  59. failx("InputErr: %s", status.description());
  60. else if (status.isTemporary())
  61. failx("TempErr: %s", status.description());
  62. else
  63. failx("Couchbase err: %s (%d)", status.description(), status.errcode());
  64. }
  65. //consider parsing json result
  66. if (strstr(query->meta().body().to_string().c_str(), "\"status\": \"errors\""))
  67. failx("Err: %s", query->meta().body().to_string().c_str());
  68. }
  69. CouchbaseRowStream::CouchbaseRowStream(IEngineRowAllocator* resultAllocator, Couchbase::Query * cbaseQuery)
  70. : m_CouchBaseQuery(cbaseQuery),
  71. m_resultAllocator(resultAllocator)
  72. {
  73. m_currentRow = 0;
  74. m_shouldRead = true;
  75. //iterating over result rows and copying them to stringarray
  76. //is there a way to independently step through original result rows?
  77. for (auto cbrow : *m_CouchBaseQuery)
  78. m_Rows.append(cbrow.json().to_string().c_str());
  79. reportIfQueryFailure(m_CouchBaseQuery);
  80. }
  81. CouchbaseRowStream::~CouchbaseRowStream() {}
  82. const void * CouchbaseRowStream::nextRow()
  83. {
  84. const void * result = NULL;
  85. if (m_shouldRead && m_currentRow < m_Rows.length())
  86. {
  87. auto json = m_Rows.item(m_currentRow++);
  88. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json,ipt_caseInsensitive);
  89. if (contentTree)
  90. {
  91. CouchbaseRowBuilder * cbRowBuilder = new CouchbaseRowBuilder(contentTree);
  92. RtlDynamicRowBuilder rowBuilder(m_resultAllocator);
  93. const RtlTypeInfo *typeInfo = m_resultAllocator->queryOutputMeta()->queryTypeInfo();
  94. assertex(typeInfo);
  95. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  96. size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, *cbRowBuilder);
  97. return rowBuilder.finalizeRowClear(len);
  98. }
  99. else
  100. failx("Error processing result row");
  101. }
  102. return result;
  103. }
  104. void CouchbaseRowStream::stop()
  105. {
  106. m_resultAllocator.clear();
  107. m_shouldRead = false;
  108. }
  109. Couchbase::Query * CouchbaseConnection::query(Couchbase::QueryCommand * qcommand)
  110. {
  111. Couchbase::Status queryStatus;
  112. Couchbase::Query * pQuery = new Couchbase::Query(*m_pCouchbaseClient, *qcommand, queryStatus);
  113. if (!queryStatus)
  114. failx("Couldn't issue query: %s", queryStatus.description());
  115. if (!pQuery->status())
  116. failx("Couldn't execute query, reason: %s\nBody is: ", pQuery->meta().body().data());
  117. if (pQuery->meta().status().errcode() != LCB_SUCCESS )//rows.length() == 0)
  118. failx("Query execution error: %s", m_pQuery->meta().body().data());
  119. return pQuery;
  120. }
  121. extern void UNSUPPORTED(const char *feature)
  122. {
  123. throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in %s", feature, g_version);
  124. }
  125. extern void failx(const char *message, ...)
  126. {
  127. va_list args;
  128. va_start(args,message);
  129. StringBuffer msg;
  130. msg.appendf("%s: ", g_moduleName).valist_appendf(message,args);
  131. va_end(args);
  132. rtlFail(0, msg.str());
  133. }
  134. extern void fail(const char *message)
  135. {
  136. StringBuffer msg;
  137. msg.appendf("%s: ", g_moduleName).append(message);
  138. rtlFail(0, msg.str());
  139. }
  140. void bindStringParam(unsigned len, const char *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  141. {
  142. VStringBuffer cbPlaceholder("$%s", field->name);
  143. if (pQcmd)
  144. {
  145. size32_t utf8chars;
  146. char *utf8;
  147. rtlStrToUtf8X(utf8chars, utf8, len, value);
  148. auto status = pQcmd->named_param(cbPlaceholder.str(), utf8);
  149. if (!status.success())
  150. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  151. }
  152. else
  153. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  154. }
  155. void bindBoolParam(bool value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  156. {
  157. VStringBuffer cbPlaceholder("$%s", field->name);
  158. if (pQcmd)
  159. {
  160. StringBuffer serialized;
  161. TokenSerializer tokenSerializer;
  162. tokenSerializer.serialize(value, serialized);
  163. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  164. if (!status.success())
  165. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  166. }
  167. else
  168. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  169. }
  170. void bindDataParam(unsigned len, const void *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  171. {
  172. VStringBuffer cbPlaceholder("$%s", field->name);
  173. if (pQcmd)
  174. {
  175. size32_t bytes;
  176. void *data;
  177. rtlStrToDataX(bytes, data, len, value);
  178. auto status = pQcmd->named_param(cbPlaceholder.str(), (char *)data);
  179. if (!status.success())
  180. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), (char *)data);
  181. }
  182. else
  183. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  184. }
  185. void bindIntParam(__int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  186. {
  187. VStringBuffer cbPlaceholder("$%s", field->name);
  188. if (pQcmd)
  189. {
  190. StringBuffer serialized;
  191. TokenSerializer tokenSerializer;
  192. tokenSerializer.serialize(value, serialized);
  193. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  194. if (!status.success())
  195. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  196. }
  197. else
  198. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  199. }
  200. void bindUIntParam(unsigned __int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  201. {
  202. VStringBuffer cbPlaceholder("$%s", field->name);
  203. if (pQcmd)
  204. {
  205. StringBuffer serialized;
  206. TokenSerializer tokenSerializer;
  207. tokenSerializer.serialize(value, serialized);
  208. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  209. if (!status.success())
  210. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  211. }
  212. else
  213. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  214. }
  215. void bindRealParam(double value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  216. {
  217. VStringBuffer cbPlaceholder("$%s", field->name);
  218. if (pQcmd)
  219. {
  220. StringBuffer serialized;
  221. TokenSerializer tokenSerializer;
  222. tokenSerializer.serialize(value, serialized);
  223. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  224. if (!status.success())
  225. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  226. }
  227. else
  228. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  229. }
  230. void bindUnicodeParam(unsigned chars, const UChar *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  231. {
  232. VStringBuffer cbPlaceholder("$%s", field->name);
  233. if (pQcmd)
  234. {
  235. size32_t utf8chars;
  236. char *utf8;
  237. rtlUnicodeToUtf8X(utf8chars, utf8, chars, value);
  238. auto status = pQcmd->named_param(cbPlaceholder.str(), utf8);
  239. if (!status.success())
  240. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  241. }
  242. else
  243. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  244. }
  245. int CouchbaseRecordBinder::numFields()
  246. {
  247. int count = 0;
  248. const RtlFieldInfo * const *fields = typeInfo->queryFields();
  249. assertex(fields);
  250. while (*fields++)
  251. count++;
  252. return count;
  253. }
  254. void CouchbaseRecordBinder::processRow(const byte *row)
  255. {
  256. thisParam = firstParam;
  257. typeInfo->process(row, row, &dummyField, *this); // Bind the variables for the current row
  258. }
  259. void CouchbaseRecordBinder::processString(unsigned len, const char *value, const RtlFieldInfo * field)
  260. {
  261. checkNextParam(field);
  262. bindStringParam(len, value, field, m_pQcmd);
  263. }
  264. void CouchbaseRecordBinder::processBool(bool value, const RtlFieldInfo * field)
  265. {
  266. bindBoolParam(value, field, m_pQcmd);
  267. }
  268. void CouchbaseRecordBinder::processData(unsigned len, const void *value, const RtlFieldInfo * field)
  269. {
  270. bindDataParam(len, value, field, m_pQcmd);
  271. }
  272. void CouchbaseRecordBinder::processInt(__int64 value, const RtlFieldInfo * field)
  273. {
  274. bindIntParam(value, field, m_pQcmd);
  275. }
  276. void CouchbaseRecordBinder::processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  277. {
  278. bindUIntParam(value, field,m_pQcmd);
  279. }
  280. void CouchbaseRecordBinder::processReal(double value, const RtlFieldInfo * field)
  281. {
  282. bindRealParam(value, field, m_pQcmd);
  283. }
  284. void CouchbaseRecordBinder::processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  285. {
  286. Decimal val;
  287. size32_t bytes;
  288. rtlDataAttr decText;
  289. val.setDecimal(digits, precision, value);
  290. val.getStringX(bytes, decText.refstr());
  291. processUtf8(bytes, decText.getstr(), field);
  292. }
  293. void CouchbaseRecordBinder::processUnicode(unsigned chars, const UChar *value, const RtlFieldInfo * field)
  294. {
  295. bindUnicodeParam(chars, value, field, m_pQcmd);
  296. }
  297. void CouchbaseRecordBinder::processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  298. {
  299. size32_t charCount;
  300. rtlDataAttr text;
  301. rtlQStrToStrX(charCount, text.refstr(), len, value);
  302. processUtf8(charCount, text.getstr(), field);
  303. }
  304. void CouchbaseRecordBinder::processUtf8(unsigned chars, const char *value, const RtlFieldInfo * field)
  305. {
  306. bindStringParam(strlen(value), value, field, m_pQcmd);
  307. }
  308. unsigned CouchbaseRecordBinder::checkNextParam(const RtlFieldInfo * field)
  309. {
  310. if (logctx.queryTraceLevel() > 4)
  311. logctx.CTXLOG("Binding %s to %d", field->name, thisParam);
  312. return thisParam++;
  313. }
  314. CouchbaseEmbedFunctionContext::CouchbaseEmbedFunctionContext(const IContextLogger &_logctx, const char *options, unsigned _flags)
  315. : logctx(_logctx), m_NextRow(), m_nextParam(0), m_numParams(0), m_scriptFlags(_flags)
  316. {
  317. cbQueryIterator = NULL;
  318. m_pCouchbaseClient = nullptr;
  319. m_pQuery = nullptr;
  320. m_pQcmd = nullptr;
  321. const char *server = "localhost";
  322. const char *user = "";
  323. const char *password = "";
  324. const char *bucketname = "default";
  325. unsigned port = 8091;
  326. bool useSSL = false;
  327. StringBuffer connectionOptions;
  328. StringArray inputOptions;
  329. inputOptions.appendList(options, ",");
  330. ForEachItemIn(idx, inputOptions)
  331. {
  332. const char *opt = inputOptions.item(idx);
  333. const char *val = strchr(opt, '=');
  334. if (val)
  335. {
  336. StringBuffer optName(val-opt, opt);
  337. val++;
  338. if (stricmp(optName, "server")==0)
  339. server = val; // Note that lifetime of val is adequate for this to be safe
  340. else if (stricmp(optName, "port")==0)
  341. port = atoi(val);
  342. else if (stricmp(optName, "user")==0)
  343. user = val;
  344. else if (stricmp(optName, "password")==0)
  345. password = val;
  346. else if (stricmp(optName, "bucket")==0)
  347. bucketname = val;
  348. else if (stricmp(optName, "useSSL")==0)
  349. useSSL = clipStrToBool(val);
  350. //Connection String options
  351. else if (stricmp(optName, "detailed_errcodes")==0
  352. || stricmp(optName, "operation_timeout")==0
  353. || stricmp(optName, "config_total_timeout")==0
  354. || stricmp(optName, "http_poolsize")==0
  355. || stricmp(optName, "detailed_errcodes")==0)
  356. connectionOptions.appendf("%s%s=%s", connectionOptions.length() == 0 ? "?" : "&", optName.str(), val);
  357. else
  358. failx("Unknown option %s", optName.str());
  359. }
  360. }
  361. m_oCBConnection.setown(new CouchbaseConnection(useSSL, server, port, bucketname, user, password, connectionOptions.str()));
  362. m_oCBConnection->connect();
  363. }
  364. IPropertyTree * CouchbaseEmbedFunctionContext::nextResultRowTree()
  365. {
  366. for (auto cbrow : *m_pQuery)
  367. {
  368. auto json = cbrow.json().to_string();
  369. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str());
  370. return contentTree.getLink();
  371. }
  372. reportIfQueryFailure(m_pQuery);
  373. return nullptr;
  374. }
  375. IPropertyTreeIterator * CouchbaseEmbedFunctionContext::nextResultRowIterator()
  376. {
  377. for (auto cbrow : *m_pQuery)
  378. {
  379. auto json = cbrow.json().to_string();
  380. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str());
  381. if (contentTree)
  382. return contentTree->getElements("./*");
  383. failx("Could not fetch next result row.");
  384. break;
  385. }
  386. reportIfQueryFailure(m_pQuery);
  387. return nullptr;
  388. }
  389. const char * CouchbaseEmbedFunctionContext::nextResultScalar()
  390. {
  391. auto resultrow = nextResultRowIterator();
  392. if (resultrow)
  393. {
  394. resultrow->first();
  395. if(resultrow->isValid() == true)
  396. {
  397. if (resultrow->query().hasChildren())
  398. typeError("scalar", "");
  399. return resultrow->query().queryProp("");
  400. }
  401. else
  402. failx("Could not fetch next result column.");
  403. }
  404. else
  405. failx("Could not fetch next result row.");
  406. return nullptr;
  407. }
  408. bool CouchbaseEmbedFunctionContext::getBooleanResult()
  409. {
  410. bool mybool;
  411. auto scalar = nextResultScalar();
  412. handleDeserializeOutcome(m_tokenDeserializer.deserialize(scalar, mybool), "bool", scalar);
  413. return mybool;
  414. }
  415. void CouchbaseEmbedFunctionContext::getDataResult(size32_t &len, void * &result)
  416. {
  417. auto value = nextResultScalar();
  418. if (value && *value)
  419. {
  420. rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want
  421. }
  422. else
  423. {
  424. rtlStrToDataX(len, result, NULLFIELD.resultChars, NULLFIELD.stringResult);
  425. }
  426. }
  427. double CouchbaseEmbedFunctionContext::getRealResult()
  428. {
  429. double mydouble = 0.0;
  430. auto value = nextResultScalar();
  431. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value);
  432. return mydouble;
  433. }
  434. __int64 CouchbaseEmbedFunctionContext::getSignedResult()
  435. {
  436. __int64 myint64 = 0;
  437. auto value = nextResultScalar();
  438. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value);
  439. return myint64;
  440. }
  441. unsigned __int64 CouchbaseEmbedFunctionContext::getUnsignedResult()
  442. {
  443. unsigned __int64 myuint64 = 0;
  444. auto value = nextResultScalar();
  445. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value);
  446. return myuint64;
  447. }
  448. void CouchbaseEmbedFunctionContext::getStringResult(size32_t &chars, char * &result)
  449. {
  450. auto value = nextResultScalar();
  451. if (value && *value)
  452. {
  453. unsigned numchars = rtlUtf8Length(strlen(value), value);
  454. rtlUtf8ToStrX(chars, result, numchars, value);
  455. }
  456. else
  457. {
  458. rtlStrToStrX(chars, result, NULLFIELD.resultChars, NULLFIELD.stringResult);
  459. }
  460. }
  461. void CouchbaseEmbedFunctionContext::getUTF8Result(size32_t &chars, char * &result)
  462. {
  463. getStringResult(chars, result);
  464. }
  465. void CouchbaseEmbedFunctionContext::getUnicodeResult(size32_t &chars, UChar * &result)
  466. {
  467. auto value = nextResultScalar();
  468. if (value && *value)
  469. {
  470. unsigned numchars = rtlUtf8Length(strlen(value), value);
  471. rtlUtf8ToUnicodeX(chars, result, numchars, value);
  472. }
  473. else
  474. {
  475. rtlUnicodeToUnicodeX(chars, result, NULLFIELD.resultChars, NULLFIELD.unicodeResult);
  476. }
  477. }
  478. void CouchbaseEmbedFunctionContext::getDecimalResult(Decimal &value)
  479. {
  480. auto text = nextResultScalar();
  481. if (text && *text)
  482. value.setString(rtlUtf8Length(strlen(text), text), text);
  483. else
  484. value.set(NULLFIELD.decimalResult);
  485. }
  486. IRowStream * CouchbaseEmbedFunctionContext::getDatasetResult(IEngineRowAllocator * _resultAllocator)
  487. {
  488. Owned<CouchbaseRowStream> cbaseRowStream;
  489. cbaseRowStream.set(new CouchbaseRowStream(_resultAllocator, m_pQuery));
  490. return cbaseRowStream.getLink();
  491. }
  492. byte * CouchbaseEmbedFunctionContext::getRowResult(IEngineRowAllocator * _resultAllocator)
  493. {
  494. Owned<CouchbaseRowStream> cbaseRowStream;
  495. cbaseRowStream.set(new CouchbaseRowStream(_resultAllocator, m_pQuery));
  496. return (byte *)cbaseRowStream->nextRow();
  497. }
  498. size32_t CouchbaseEmbedFunctionContext::getTransformResult(ARowBuilder & rowBuilder)
  499. {
  500. execute();
  501. auto resultrow = nextResultRowTree();
  502. if (!resultrow)
  503. fail("Failed to read row");
  504. if (resultrow->getCount("./*") != 1)
  505. typeError("row", "");
  506. CouchbaseRowBuilder couchbaseRowBuilder(resultrow);
  507. const RtlTypeInfo *typeInfo = rowBuilder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  508. assertex(typeInfo);
  509. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  510. return typeInfo->build(rowBuilder, 0, &dummyField, couchbaseRowBuilder);
  511. }
  512. void CouchbaseEmbedFunctionContext::bindRowParam(const char *name, IOutputMetaData & metaVal, byte *val)
  513. {
  514. CouchbaseRecordBinder binder(logctx, metaVal.queryTypeInfo(), m_pQcmd, m_nextParam);
  515. binder.processRow(val);
  516. m_nextParam += binder.numFields();
  517. }
  518. void CouchbaseEmbedFunctionContext::bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  519. {
  520. // We only support a single dataset parameter...
  521. // MORE - look into batch?
  522. if (m_oInputStream)
  523. {
  524. fail("At most one dataset parameter supported");
  525. }
  526. m_oInputStream.setown(new CouchbaseDatasetBinder(logctx, LINK(val), metaVal.queryTypeInfo(), m_pQcmd, m_nextParam));
  527. m_nextParam += m_oInputStream->numFields();
  528. }
  529. void CouchbaseEmbedFunctionContext::bindBooleanParam(const char *name, bool val)
  530. {
  531. checkNextParam(name);
  532. StringBuffer serialized;
  533. m_tokenSerializer.serialize(val, serialized);
  534. VStringBuffer cbPlaceholder("$%s", name);
  535. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  536. if (!status.success())
  537. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  538. }
  539. void CouchbaseEmbedFunctionContext::bindDataParam(const char *name, size32_t len, const void *val)
  540. {
  541. checkNextParam(name);
  542. VStringBuffer cbPlaceholder("$%s", name);
  543. size32_t bytes;
  544. void *data;
  545. rtlStrToDataX(bytes, data, len, val);
  546. auto status = m_pQcmd->named_param(cbPlaceholder.str(), (char *)data);
  547. if (!status.success())
  548. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), (char *)data);
  549. }
  550. void CouchbaseEmbedFunctionContext::bindFloatParam(const char *name, float val)
  551. {
  552. checkNextParam(name);
  553. StringBuffer serialized;
  554. m_tokenSerializer.serialize(val, serialized);
  555. VStringBuffer cbPlaceholder("$%s", name);
  556. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  557. if (!status.success())
  558. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  559. }
  560. void CouchbaseEmbedFunctionContext::bindRealParam(const char *name, double val)
  561. {
  562. checkNextParam(name);
  563. StringBuffer serialized;
  564. m_tokenSerializer.serialize(val, serialized);
  565. VStringBuffer cbPlaceholder("$%s", name);
  566. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  567. if (!status.success())
  568. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  569. }
  570. void CouchbaseEmbedFunctionContext::bindSignedSizeParam(const char *name, int size, __int64 val)
  571. {
  572. bindSignedParam(name, val);
  573. }
  574. void CouchbaseEmbedFunctionContext::bindSignedParam(const char *name, __int64 val)
  575. {
  576. checkNextParam(name);
  577. StringBuffer serialized;
  578. m_tokenSerializer.serialize(val, serialized);
  579. VStringBuffer cbPlaceholder("$%s", name);
  580. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  581. if (!status.success())
  582. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  583. }
  584. void CouchbaseEmbedFunctionContext::bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
  585. {
  586. bindUnsignedParam(name, val);
  587. }
  588. void CouchbaseEmbedFunctionContext::bindUnsignedParam(const char *name, unsigned __int64 val)
  589. {
  590. checkNextParam(name);
  591. StringBuffer serialized;
  592. m_tokenSerializer.serialize(val, serialized);
  593. VStringBuffer cbPlaceholder("$%s", name);
  594. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  595. if (!status.success())
  596. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  597. }
  598. void CouchbaseEmbedFunctionContext::bindStringParam(const char *name, size32_t len, const char *val)
  599. {
  600. checkNextParam(name);
  601. VStringBuffer cbPlaceholder("$%s", name);
  602. size32_t utf8chars;
  603. char *utf8;
  604. rtlStrToUtf8X(utf8chars, utf8, len, val);
  605. auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8);
  606. if (!status.success())
  607. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  608. }
  609. void CouchbaseEmbedFunctionContext::bindVStringParam(const char *name, const char *val)
  610. {
  611. checkNextParam(name);
  612. bindStringParam(name, strlen(val), val);
  613. }
  614. void CouchbaseEmbedFunctionContext::bindUTF8Param(const char *name, size32_t chars, const char *val)
  615. {
  616. checkNextParam(name);
  617. bindStringParam(name, strlen(val), val);
  618. }
  619. void CouchbaseEmbedFunctionContext::bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  620. {
  621. checkNextParam(name);
  622. VStringBuffer cbPlaceholder("$%s", name);
  623. size32_t utf8chars;
  624. char *utf8;
  625. rtlUnicodeToUtf8X(utf8chars, utf8, chars, val);
  626. auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8);
  627. if (!status.success())
  628. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  629. }
  630. void CouchbaseEmbedFunctionContext::compileEmbeddedScript(size32_t chars, const char *script)
  631. {
  632. if (script && *script)
  633. {
  634. m_pQcmd = new Couchbase::QueryCommand(script);
  635. if ((m_scriptFlags & EFnoparams) == 0)
  636. m_numParams = countParameterPlaceholders(script);
  637. else
  638. m_numParams = 0;
  639. }
  640. else
  641. failx("Empty N1QL query detected");
  642. }
  643. void CouchbaseEmbedFunctionContext::callFunction()
  644. {
  645. execute();
  646. }
  647. void CouchbaseEmbedFunctionContext::execute()
  648. {
  649. if (m_oInputStream)
  650. m_oInputStream->executeAll(m_oCBConnection);
  651. else
  652. {
  653. m_pQuery = m_oCBConnection->query(m_pQcmd);
  654. reportIfQueryFailure(m_pQuery);
  655. }
  656. }
  657. unsigned CouchbaseEmbedFunctionContext::checkNextParam(const char *name)
  658. {
  659. if (m_nextParam == m_numParams)
  660. failx("Too many parameters supplied: No matching $<name> placeholder for parameter %s", name);
  661. return m_nextParam++;
  662. }
  663. bool CouchbaseRowBuilder::getBooleanResult(const RtlFieldInfo *field)
  664. {
  665. const char * value = nextField(field);
  666. if (!value || !*value)
  667. {
  668. NullFieldProcessor p(field);
  669. return p.boolResult;
  670. }
  671. bool mybool;
  672. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mybool), "bool", value);
  673. return mybool;
  674. }
  675. void CouchbaseRowBuilder::getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
  676. {
  677. const char * value = nextField(field);
  678. if (!value || !*value)
  679. {
  680. NullFieldProcessor p(field);
  681. rtlStrToDataX(len, result, p.resultChars, p.stringResult);
  682. return;
  683. }
  684. rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want
  685. }
  686. double CouchbaseRowBuilder::getRealResult(const RtlFieldInfo *field)
  687. {
  688. const char * value = nextField(field);
  689. if (!value || !*value)
  690. {
  691. NullFieldProcessor p(field);
  692. return p.doubleResult;
  693. }
  694. double mydouble = 0.0;
  695. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value);
  696. return mydouble;
  697. }
  698. __int64 CouchbaseRowBuilder::getSignedResult(const RtlFieldInfo *field)
  699. {
  700. const char * value = nextField(field);
  701. if (!value || !*value)
  702. {
  703. NullFieldProcessor p(field);
  704. return p.uintResult;
  705. }
  706. __int64 myint64 = 0;
  707. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value);
  708. return myint64;
  709. }
  710. unsigned __int64 CouchbaseRowBuilder::getUnsignedResult(const RtlFieldInfo *field)
  711. {
  712. const char * value = nextField(field);
  713. if (!value || !*value)
  714. {
  715. NullFieldProcessor p(field);
  716. return p.uintResult;
  717. }
  718. unsigned __int64 myuint64 = 0;
  719. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value);
  720. return myuint64;
  721. }
  722. void CouchbaseRowBuilder::getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
  723. {
  724. const char * value = nextField(field);
  725. if (!value || !*value)
  726. {
  727. NullFieldProcessor p(field);
  728. rtlStrToStrX(chars, result, p.resultChars, p.stringResult);
  729. return;
  730. }
  731. unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
  732. rtlUtf8ToStrX(chars, result, numchars, value);
  733. return;
  734. }
  735. void CouchbaseRowBuilder::getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
  736. {
  737. getStringResult(field, chars, result);
  738. return;
  739. }
  740. void CouchbaseRowBuilder::getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
  741. {
  742. const char * value = nextField(field);
  743. if (!value || !*value)
  744. {
  745. NullFieldProcessor p(field);
  746. rtlUnicodeToUnicodeX(chars, result, p.resultChars, p.unicodeResult);
  747. return;
  748. }
  749. unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
  750. rtlUtf8ToUnicodeX(chars, result, numchars, value);
  751. return;
  752. }
  753. void CouchbaseRowBuilder::getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  754. {
  755. const char * dvalue = nextField(field);
  756. if (!dvalue || !*dvalue)
  757. {
  758. NullFieldProcessor p(field);
  759. value.set(p.decimalResult);
  760. return;
  761. }
  762. size32_t chars;
  763. rtlDataAttr result;
  764. value.setString(strlen(dvalue), dvalue);
  765. if (field)
  766. {
  767. RtlDecimalTypeInfo *dtype = (RtlDecimalTypeInfo *) field->type;
  768. value.setPrecision(dtype->getDecimalDigits(), dtype->getDecimalPrecision());
  769. }
  770. }
  771. void CouchbaseRowBuilder::processBeginSet(const RtlFieldInfo * field, bool &isAll)
  772. {
  773. isAll = false; // ALL not supported
  774. StringBuffer xpath;
  775. xpathOrName(xpath, field);
  776. if (!xpath.isEmpty())
  777. {
  778. PathTracker newPathNode(xpath, CPNTSet);
  779. StringBuffer newXPath;
  780. constructNewXPath(newXPath, xpath.str());
  781. newPathNode.childCount = m_oResultRow->getCount(newXPath);
  782. m_pathStack.push_back(newPathNode);
  783. }
  784. else
  785. {
  786. failx("processBeginSet: Field name or xpath missing");
  787. }
  788. }
  789. bool CouchbaseRowBuilder::processNextSet(const RtlFieldInfo * field)
  790. {
  791. return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount;
  792. }
  793. void CouchbaseRowBuilder::processBeginDataset(const RtlFieldInfo * field)
  794. {
  795. StringBuffer xpath;
  796. xpathOrName(xpath, field);
  797. if (!xpath.isEmpty())
  798. {
  799. PathTracker newPathNode(xpath, CPNTDataset);
  800. StringBuffer newXPath;
  801. constructNewXPath(newXPath, xpath.str());
  802. newPathNode.childCount = m_oResultRow->getCount(newXPath);
  803. m_pathStack.push_back(newPathNode);
  804. }
  805. else
  806. {
  807. failx("processBeginDataset: Field name or xpath missing");
  808. }
  809. }
  810. void CouchbaseRowBuilder::processBeginRow(const RtlFieldInfo * field)
  811. {
  812. StringBuffer xpath;
  813. xpathOrName(xpath, field);
  814. if (!xpath.isEmpty())
  815. {
  816. if (strncmp(xpath.str(), "<nested row>", 12) == 0)
  817. {
  818. // Row within child dataset
  819. if (m_pathStack.back().nodeType == CPNTDataset)
  820. {
  821. m_pathStack.back().currentChildIndex++;
  822. }
  823. else
  824. {
  825. failx("<nested row> received with no outer dataset designated");
  826. }
  827. }
  828. else
  829. {
  830. m_pathStack.push_back(PathTracker(xpath, CPNTScalar));
  831. }
  832. }
  833. else
  834. {
  835. failx("processBeginRow: Field name or xpath missing");
  836. }
  837. }
  838. bool CouchbaseRowBuilder::processNextRow(const RtlFieldInfo * field)
  839. {
  840. return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount;
  841. }
  842. void CouchbaseRowBuilder::processEndSet(const RtlFieldInfo * field)
  843. {
  844. StringBuffer xpath;
  845. xpathOrName(xpath, field);
  846. if (!xpath.isEmpty() && !m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  847. {
  848. m_pathStack.pop_back();
  849. }
  850. }
  851. void CouchbaseRowBuilder::processEndDataset(const RtlFieldInfo * field)
  852. {
  853. StringBuffer xpath;
  854. xpathOrName(xpath, field);
  855. if (!xpath.isEmpty())
  856. {
  857. if (!m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  858. {
  859. m_pathStack.pop_back();
  860. }
  861. }
  862. else
  863. {
  864. failx("processEndDataset: Field name or xpath missing");
  865. }
  866. }
  867. void CouchbaseRowBuilder::processEndRow(const RtlFieldInfo * field)
  868. {
  869. StringBuffer xpath;
  870. xpathOrName(xpath, field);
  871. if (!xpath.isEmpty())
  872. {
  873. if (!m_pathStack.empty())
  874. {
  875. if (m_pathStack.back().nodeType == CPNTDataset)
  876. {
  877. m_pathStack.back().childrenProcessed++;
  878. }
  879. else if (strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  880. {
  881. m_pathStack.pop_back();
  882. }
  883. }
  884. }
  885. else
  886. {
  887. failx("processEndRow: Field name or xpath missing");
  888. }
  889. }
  890. const char * CouchbaseRowBuilder::nextField(const RtlFieldInfo * field)
  891. {
  892. StringBuffer xpath;
  893. xpathOrName(xpath, field);
  894. if (xpath.isEmpty())
  895. {
  896. failx("nextField: Field name or xpath missing");
  897. }
  898. StringBuffer fullXPath;
  899. if (!m_pathStack.empty() && m_pathStack.back().nodeType == CPNTSet && strncmp(xpath.str(), "<set element>", 13) == 0)
  900. {
  901. m_pathStack.back().currentChildIndex++;
  902. constructNewXPath(fullXPath, NULL);
  903. m_pathStack.back().childrenProcessed++;
  904. }
  905. else
  906. {
  907. constructNewXPath(fullXPath, xpath.str());
  908. }
  909. return m_oResultRow->queryProp(fullXPath.str());
  910. }
  911. void CouchbaseRowBuilder::xpathOrName(StringBuffer & outXPath, const RtlFieldInfo * field) const
  912. {
  913. outXPath.clear();
  914. if (field->xpath)
  915. {
  916. if (field->xpath[0] == xpathCompoundSeparatorChar)
  917. {
  918. outXPath.append(field->xpath + 1);
  919. }
  920. else
  921. {
  922. const char * sep = strchr(field->xpath, xpathCompoundSeparatorChar);
  923. if (!sep)
  924. {
  925. outXPath.append(field->xpath);
  926. }
  927. else
  928. {
  929. outXPath.append(field->xpath, 0, static_cast<size32_t>(sep - field->xpath));
  930. }
  931. }
  932. }
  933. else
  934. {
  935. outXPath.append(field->name);
  936. }
  937. }
  938. void CouchbaseRowBuilder::constructNewXPath(StringBuffer& outXPath, const char * nextNode) const
  939. {
  940. bool nextNodeIsFromRoot = (nextNode && *nextNode == '/');
  941. outXPath.clear();
  942. if (!nextNodeIsFromRoot)
  943. {
  944. // Build up full parent xpath using our previous components
  945. for (std::vector<PathTracker>::const_iterator iter = m_pathStack.begin(); iter != m_pathStack.end(); iter++)
  946. {
  947. if (strncmp(iter->nodeName, "<row>", 5) != 0)
  948. {
  949. if (!outXPath.isEmpty())
  950. {
  951. outXPath.append("/");
  952. }
  953. outXPath.append(iter->nodeName);
  954. if (iter->nodeType == CPNTDataset || iter->nodeType == CPNTSet)
  955. {
  956. outXPath.appendf("[%d]", iter->currentChildIndex);
  957. }
  958. }
  959. }
  960. }
  961. if (nextNode && *nextNode)
  962. {
  963. if (!outXPath.isEmpty())
  964. {
  965. outXPath.append("/");
  966. }
  967. outXPath.append(nextNode);
  968. }
  969. }
  970. class CouchbaseEmbedContext : public CInterfaceOf<IEmbedContext>
  971. {
  972. public:
  973. virtual IEmbedFunctionContext * createFunctionContext(unsigned flags, const char *options)
  974. {
  975. return createFunctionContextEx(NULL, flags, options);
  976. }
  977. virtual IEmbedFunctionContext * createFunctionContextEx(ICodeContext * ctx, unsigned flags, const char *options)
  978. {
  979. if (flags & EFimport)
  980. {
  981. UNSUPPORTED("IMPORT");
  982. return nullptr;
  983. }
  984. else
  985. return new CouchbaseEmbedFunctionContext(ctx ? ctx->queryContextLogger() : queryDummyContextLogger(), options, flags);
  986. }
  987. virtual IEmbedServiceContext * createServiceContext(const char *service, unsigned flags, const char *options)
  988. {
  989. throwUnexpected();
  990. return nullptr;
  991. }
  992. };
  993. extern DECL_EXPORT IEmbedContext* getEmbedContext()
  994. {
  995. return new CouchbaseEmbedContext();
  996. }
  997. extern DECL_EXPORT bool syntaxCheck(const char *script)
  998. {
  999. return true; // TO-DO
  1000. }
  1001. } // namespace