couchbaseembed.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  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. #include <map>
  23. #include <mutex>
  24. #include <thread>
  25. static const char *g_moduleName = "couchbase";
  26. static const char *g_moduleDescription = "Couchbase Embed Helper";
  27. static const char *g_version = "Couchbase Embed Helper 1.0.0";
  28. static const char *g_compatibleVersions[] = { g_version, nullptr };
  29. static const NullFieldProcessor NULLFIELD(NULL);
  30. extern "C" COUCHBASEEMBED_PLUGIN_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  31. {
  32. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  33. {
  34. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  35. pbx->compatibleVersions = g_compatibleVersions;
  36. }
  37. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  38. return false;
  39. pb->magicVersion = PLUGIN_VERSION;
  40. pb->version = g_version;
  41. pb->moduleName = g_moduleName;
  42. pb->ECL = nullptr;
  43. pb->flags = PLUGIN_IMPLICIT_MODULE;
  44. pb->description = g_moduleDescription;
  45. return true;
  46. }
  47. namespace couchbaseembed
  48. {
  49. const time_t OBJECT_EXPIRE_TIMEOUT_SECONDS = 60 * 2; // Two minutes
  50. static std::once_flag connectionCacheInitFlag;
  51. //--------------------------------------------------------------------------
  52. // Plugin Classes
  53. //--------------------------------------------------------------------------
  54. void reportIfQueryFailure(Couchbase::Query * query)
  55. {
  56. auto status = query->meta().status();
  57. if (status.errcode())
  58. {
  59. if (status.isNetworkError())
  60. failx("NetworkErr: %s", status.description());
  61. else if (status.isDataError())
  62. failx("DataErr: %s", status.description());
  63. else if (status.isInputError())
  64. failx("InputErr: %s", status.description());
  65. else if (status.isTemporary())
  66. failx("TempErr: %s", status.description());
  67. else
  68. failx("Couchbase err: %s (%d)", status.description(), status.errcode());
  69. }
  70. //consider parsing json result
  71. if (strstr(query->meta().body().to_string().c_str(), "\"status\": \"errors\""))
  72. failx("Err: %s", query->meta().body().to_string().c_str());
  73. }
  74. CouchbaseRowStream::CouchbaseRowStream(IEngineRowAllocator* resultAllocator, Couchbase::Query * cbaseQuery)
  75. : m_resultAllocator(resultAllocator)
  76. {
  77. m_currentRow = 0;
  78. m_shouldRead = true;
  79. //iterating over result rows and copying them to stringarray
  80. //is there a way to independently step through original result rows?
  81. for (auto cbrow : *cbaseQuery)
  82. m_Rows.append(cbrow.json().to_string().c_str());
  83. reportIfQueryFailure(cbaseQuery);
  84. }
  85. CouchbaseRowStream::~CouchbaseRowStream() {}
  86. const void * CouchbaseRowStream::nextRow()
  87. {
  88. const void * result = nullptr;
  89. if (m_shouldRead && m_currentRow < m_Rows.length())
  90. {
  91. auto json = m_Rows.item(m_currentRow++);
  92. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json,ipt_caseInsensitive);
  93. if (contentTree)
  94. {
  95. CouchbaseRowBuilder cbRowBuilder(contentTree);
  96. RtlDynamicRowBuilder rowBuilder(m_resultAllocator);
  97. const RtlTypeInfo *typeInfo = m_resultAllocator->queryOutputMeta()->queryTypeInfo();
  98. assertex(typeInfo);
  99. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  100. size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, cbRowBuilder);
  101. return rowBuilder.finalizeRowClear(len);
  102. }
  103. else
  104. failx("Error processing result row");
  105. }
  106. return result;
  107. }
  108. void CouchbaseRowStream::stop()
  109. {
  110. m_resultAllocator.clear();
  111. m_shouldRead = false;
  112. }
  113. Couchbase::Query * CouchbaseConnection::query(Couchbase::QueryCommand * qcommand)
  114. {
  115. Couchbase::Status queryStatus;
  116. Couchbase::Query * pQuery = new Couchbase::Query(*m_pCouchbaseClient, *qcommand, queryStatus); // will be owned by method caller
  117. if (!queryStatus)
  118. failx("Couldn't issue query: %s", queryStatus.description());
  119. if (!pQuery->status())
  120. failx("Couldn't execute query, reason: %s\nBody is: ", pQuery->meta().body().data());
  121. if (pQuery->meta().status().errcode() != LCB_SUCCESS )//rows.length() == 0)
  122. failx("Query execution error: %s", pQuery->meta().body().data());
  123. return pQuery;
  124. }
  125. extern void UNSUPPORTED(const char *feature)
  126. {
  127. throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in %s", feature, g_version);
  128. }
  129. extern void failx(const char *message, ...)
  130. {
  131. va_list args;
  132. va_start(args,message);
  133. StringBuffer msg;
  134. msg.appendf("%s: ", g_moduleName).valist_appendf(message,args);
  135. va_end(args);
  136. rtlFail(0, msg.str());
  137. }
  138. extern void fail(const char *message)
  139. {
  140. StringBuffer msg;
  141. msg.appendf("%s: ", g_moduleName).append(message);
  142. rtlFail(0, msg.str());
  143. }
  144. void bindStringParam(unsigned len, const char *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  145. {
  146. VStringBuffer cbPlaceholder("$%s", field->name);
  147. if (pQcmd)
  148. {
  149. size32_t utf8chars;
  150. rtlDataAttr utf8;
  151. rtlStrToUtf8X(utf8chars, utf8.refstr(), len, value);
  152. auto status = pQcmd->named_param(cbPlaceholder.str(), utf8.getstr());
  153. if (!status.success())
  154. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8.getstr());
  155. }
  156. else
  157. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  158. }
  159. void bindBoolParam(bool value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  160. {
  161. VStringBuffer cbPlaceholder("$%s", field->name);
  162. if (pQcmd)
  163. {
  164. StringBuffer serialized;
  165. TokenSerializer tokenSerializer;
  166. tokenSerializer.serialize(value, serialized);
  167. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  168. if (!status.success())
  169. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  170. }
  171. else
  172. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  173. }
  174. void bindDataParam(unsigned len, const void *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  175. {
  176. VStringBuffer cbPlaceholder("$%s", field->name);
  177. if (pQcmd)
  178. {
  179. size32_t bytes;
  180. rtlDataAttr data;
  181. rtlStrToDataX(bytes, data.refdata(), len, value);
  182. auto status = pQcmd->named_param(cbPlaceholder.str(), data.getstr());
  183. if (!status.success())
  184. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), data.getstr());
  185. }
  186. else
  187. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  188. }
  189. void bindIntParam(__int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  190. {
  191. VStringBuffer cbPlaceholder("$%s", field->name);
  192. if (pQcmd)
  193. {
  194. StringBuffer serialized;
  195. TokenSerializer tokenSerializer;
  196. tokenSerializer.serialize(value, serialized);
  197. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  198. if (!status.success())
  199. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  200. }
  201. else
  202. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  203. }
  204. void bindUIntParam(unsigned __int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  205. {
  206. VStringBuffer cbPlaceholder("$%s", field->name);
  207. if (pQcmd)
  208. {
  209. StringBuffer serialized;
  210. TokenSerializer tokenSerializer;
  211. tokenSerializer.serialize(value, serialized);
  212. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  213. if (!status.success())
  214. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  215. }
  216. else
  217. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  218. }
  219. void bindRealParam(double value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  220. {
  221. VStringBuffer cbPlaceholder("$%s", field->name);
  222. if (pQcmd)
  223. {
  224. StringBuffer serialized;
  225. TokenSerializer tokenSerializer;
  226. tokenSerializer.serialize(value, serialized);
  227. auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  228. if (!status.success())
  229. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  230. }
  231. else
  232. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  233. }
  234. void bindUnicodeParam(unsigned chars, const UChar *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd)
  235. {
  236. VStringBuffer cbPlaceholder("$%s", field->name);
  237. if (pQcmd)
  238. {
  239. size32_t utf8chars;
  240. char *utf8;
  241. rtlUnicodeToUtf8X(utf8chars, utf8, chars, value);
  242. auto status = pQcmd->named_param(cbPlaceholder.str(), utf8);
  243. if (!status.success())
  244. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  245. }
  246. else
  247. failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str());
  248. }
  249. int CouchbaseRecordBinder::numFields()
  250. {
  251. int count = 0;
  252. const RtlFieldInfo * const *fields = typeInfo->queryFields();
  253. assertex(fields);
  254. while (*fields++)
  255. count++;
  256. return count;
  257. }
  258. void CouchbaseRecordBinder::processRow(const byte *row)
  259. {
  260. thisParam = firstParam;
  261. typeInfo->process(row, row, &dummyField, *this); // Bind the variables for the current row
  262. }
  263. void CouchbaseRecordBinder::processString(unsigned len, const char *value, const RtlFieldInfo * field)
  264. {
  265. checkNextParam(field);
  266. bindStringParam(len, value, field, m_pQcmd);
  267. }
  268. void CouchbaseRecordBinder::processBool(bool value, const RtlFieldInfo * field)
  269. {
  270. bindBoolParam(value, field, m_pQcmd);
  271. }
  272. void CouchbaseRecordBinder::processData(unsigned len, const void *value, const RtlFieldInfo * field)
  273. {
  274. bindDataParam(len, value, field, m_pQcmd);
  275. }
  276. void CouchbaseRecordBinder::processInt(__int64 value, const RtlFieldInfo * field)
  277. {
  278. bindIntParam(value, field, m_pQcmd);
  279. }
  280. void CouchbaseRecordBinder::processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  281. {
  282. bindUIntParam(value, field,m_pQcmd);
  283. }
  284. void CouchbaseRecordBinder::processReal(double value, const RtlFieldInfo * field)
  285. {
  286. bindRealParam(value, field, m_pQcmd);
  287. }
  288. void CouchbaseRecordBinder::processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  289. {
  290. Decimal val;
  291. size32_t bytes;
  292. rtlDataAttr decText;
  293. val.setDecimal(digits, precision, value);
  294. val.getStringX(bytes, decText.refstr());
  295. processUtf8(bytes, decText.getstr(), field);
  296. }
  297. void CouchbaseRecordBinder::processUnicode(unsigned chars, const UChar *value, const RtlFieldInfo * field)
  298. {
  299. bindUnicodeParam(chars, value, field, m_pQcmd);
  300. }
  301. void CouchbaseRecordBinder::processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  302. {
  303. size32_t charCount;
  304. rtlDataAttr text;
  305. rtlQStrToStrX(charCount, text.refstr(), len, value);
  306. processUtf8(charCount, text.getstr(), field);
  307. }
  308. void CouchbaseRecordBinder::processUtf8(unsigned chars, const char *value, const RtlFieldInfo * field)
  309. {
  310. bindStringParam(strlen(value), value, field, m_pQcmd);
  311. }
  312. unsigned CouchbaseRecordBinder::checkNextParam(const RtlFieldInfo * field)
  313. {
  314. if (logctx.queryTraceLevel() > 4)
  315. logctx.CTXLOG("Binding %s to %d", field->name, thisParam);
  316. return thisParam++;
  317. }
  318. static class ConnectionCacheObj
  319. {
  320. private:
  321. typedef std::vector<CouchbaseConnection*> ConnectionList;
  322. typedef std::map<hash64_t, ConnectionList> ObjMap;
  323. public:
  324. ConnectionCacheObj(int _traceLevel)
  325. : traceLevel(_traceLevel)
  326. {
  327. }
  328. ~ConnectionCacheObj()
  329. {
  330. deleteAll();
  331. }
  332. void deleteAll()
  333. {
  334. CriticalBlock block(cacheLock);
  335. // Delete all idle connection objects
  336. for (ObjMap::iterator keyIter = idleConnections.begin(); keyIter != idleConnections.end(); keyIter++)
  337. {
  338. for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++)
  339. {
  340. if (*connectionIter)
  341. {
  342. delete(*connectionIter);
  343. }
  344. }
  345. }
  346. idleConnections.clear();
  347. // Delete all active connection objects
  348. for (ObjMap::iterator keyIter = activeConnections.begin(); keyIter != activeConnections.end(); keyIter++)
  349. {
  350. for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++)
  351. {
  352. if (*connectionIter)
  353. {
  354. delete(*connectionIter);
  355. }
  356. }
  357. }
  358. activeConnections.clear();
  359. }
  360. void releaseActive(CouchbaseConnection* connectionPtr)
  361. {
  362. CriticalBlock block(cacheLock);
  363. // Find given connection in our active list and move it to our
  364. // idle list
  365. for (ObjMap::iterator keyIter = activeConnections.begin(); keyIter != activeConnections.end(); keyIter++)
  366. {
  367. for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++)
  368. {
  369. if (*connectionIter == connectionPtr)
  370. {
  371. connectionPtr->updateTimeTouched();
  372. keyIter->second.erase(connectionIter);
  373. idleConnections[keyIter->first].push_back(connectionPtr);
  374. if (traceLevel > 4)
  375. {
  376. DBGLOG("Couchbase: Released connection object %p", connectionPtr);
  377. }
  378. return;
  379. }
  380. }
  381. }
  382. }
  383. void expire()
  384. {
  385. if (!idleConnections.empty())
  386. {
  387. CriticalBlock block(cacheLock);
  388. time_t oldestAllowedTime = time(NULL) - OBJECT_EXPIRE_TIMEOUT_SECONDS;
  389. __int32 expireCount = 0;
  390. for (ObjMap::iterator keyIter = idleConnections.begin(); keyIter != idleConnections.end(); keyIter++)
  391. {
  392. ConnectionList::iterator connectionIter = keyIter->second.begin();
  393. while (connectionIter != keyIter->second.end())
  394. {
  395. if (*connectionIter)
  396. {
  397. if ((*connectionIter)->getTimeTouched() < oldestAllowedTime)
  398. {
  399. delete(*connectionIter);
  400. connectionIter = keyIter->second.erase(connectionIter);
  401. ++expireCount;
  402. }
  403. else
  404. {
  405. ++connectionIter;
  406. }
  407. }
  408. else
  409. {
  410. connectionIter = keyIter->second.erase(connectionIter);
  411. }
  412. }
  413. }
  414. if (traceLevel > 4 && expireCount > 0)
  415. {
  416. DBGLOG("Couchbase: Expired %d cached connection%s", expireCount, (expireCount == 1 ? "" : "s"));
  417. }
  418. }
  419. }
  420. CouchbaseConnection* getConnection(bool useSSL, const char * host, unsigned port, const char * bucketname, const char * password, const char * connOptions, unsigned int maxConnections, const char * user)
  421. {
  422. CouchbaseConnection* connectionObjPtr = nullptr;
  423. StringBuffer connectionString;
  424. CouchbaseConnection::makeConnectionString(useSSL, host, port, bucketname, connOptions, connectionString);
  425. // Use a hash of the connection string as the key to finding
  426. // any idle connection objects
  427. hash64_t key = rtlHash64VStr(connectionString.str(), 0);
  428. while (true)
  429. {
  430. {
  431. CriticalBlock block(cacheLock);
  432. ConnectionList& idleConnectionList = idleConnections[key];
  433. if (!idleConnectionList.empty())
  434. {
  435. // We have at least one idle connection; use that
  436. connectionObjPtr = idleConnectionList.back();
  437. idleConnectionList.pop_back();
  438. connectionObjPtr->updateTimeTouched();
  439. // Push the connection object onto our active list
  440. activeConnections[key].push_back(connectionObjPtr);
  441. if (traceLevel > 4)
  442. {
  443. DBGLOG("Couchbase: Using cached connection object %p: %s", connectionObjPtr, connectionString.str());
  444. }
  445. break;
  446. }
  447. else if (maxConnections == 0 || activeConnections[key].size() < maxConnections)
  448. {
  449. // No idle connections but we don't have to wait for
  450. // one; exit the loop and create a new connection
  451. break;
  452. }
  453. }
  454. // We can't exit the loop and allow a new connection to
  455. // be created because there are too many active
  456. // connections already; wait for a short while
  457. // and try again
  458. std::this_thread::sleep_for(std::chrono::microseconds(10));
  459. }
  460. if (!connectionObjPtr)
  461. {
  462. // An idle connection for that particular combination of
  463. // options does not exist so we need to create one;
  464. // use a small loop to retry connections if necessary
  465. unsigned int connectAttempt = 0;
  466. unsigned int MAX_ATTEMPTS = 10;
  467. useconds_t SLEEP_TIME = 100 + (fastRand() % 200); // Add jitter to sleep time
  468. while (true)
  469. {
  470. connectionObjPtr = new CouchbaseConnection(connectionString, password, user);
  471. connectionObjPtr->connect();
  472. if (connectionObjPtr->getConnectionStatus().success())
  473. {
  474. {
  475. // Push new connection object onto our active list
  476. CriticalBlock block(cacheLock);
  477. connectionObjPtr->updateTimeTouched();
  478. ConnectionList& activeConnectionList = activeConnections[key];
  479. activeConnectionList.push_back(connectionObjPtr);
  480. }
  481. if (traceLevel > 4)
  482. {
  483. DBGLOG("Couchbase: Created and cached new connection object %p: %s", connectionObjPtr, connectionString.str());
  484. }
  485. break;
  486. }
  487. else if (connectionObjPtr->getConnectionStatus().isTemporary())
  488. {
  489. ++connectAttempt;
  490. if (connectAttempt < MAX_ATTEMPTS)
  491. {
  492. // According to libcouchbase-cxx, we need
  493. // to destroy the connection object if
  494. // there has been a failure of any kind
  495. delete(connectionObjPtr);
  496. connectionObjPtr = nullptr;
  497. std::this_thread::sleep_for(std::chrono::microseconds(SLEEP_TIME));
  498. }
  499. else
  500. {
  501. // Capture the final failure reason and
  502. // destroy the connection object before
  503. // throwing an error
  504. std::string reason = connectionObjPtr->getConnectionStatus().description();
  505. delete(connectionObjPtr);
  506. connectionObjPtr = nullptr;
  507. failx("Failed to connect to couchbase instance: %s Reason: '%s'", connectionString.str(), reason.c_str());
  508. }
  509. }
  510. else
  511. {
  512. // Capture the final failure reason and
  513. // destroy the connection object before
  514. // throwing an error
  515. std::string reason = connectionObjPtr->getConnectionStatus().description();
  516. delete(connectionObjPtr);
  517. connectionObjPtr = nullptr;
  518. failx("Failed to connect to couchbase instance: %s Reason: '%s'", connectionString.str(), reason.c_str());
  519. }
  520. }
  521. }
  522. return connectionObjPtr;
  523. }
  524. private:
  525. ObjMap idleConnections; //!< std::map of created CouchbaseConnection object pointers
  526. ObjMap activeConnections; //!< std::map of created CouchbaseConnection object pointers
  527. CriticalSection cacheLock; //!< Mutex guarding modifications to connection pools
  528. int traceLevel; //!< The current logging level
  529. } *connectionCache;
  530. static class ConnectionCacheExpirerObj : public Thread
  531. {
  532. public:
  533. ConnectionCacheExpirerObj()
  534. : Thread("Couchbase::ConnectionCacheExpirer"),
  535. shouldRun(false)
  536. {
  537. }
  538. virtual void start()
  539. {
  540. if (!isAlive())
  541. {
  542. shouldRun = true;
  543. Thread::start();
  544. }
  545. }
  546. virtual void stop()
  547. {
  548. if (isAlive())
  549. {
  550. shouldRun = false;
  551. join();
  552. }
  553. }
  554. virtual int run()
  555. {
  556. // Periodically delete connections that have been idle too long
  557. while (shouldRun)
  558. {
  559. if (connectionCache)
  560. {
  561. connectionCache->expire();
  562. }
  563. std::this_thread::sleep_for(std::chrono::microseconds(1000));
  564. }
  565. return 0;
  566. }
  567. private:
  568. std::atomic_bool shouldRun; //!< If true, we should execute our thread's main event loop
  569. } *connectionCacheExpirer;
  570. static void setupConnectionCache(int traceLevel)
  571. {
  572. couchbaseembed::connectionCache = new couchbaseembed::ConnectionCacheObj(traceLevel);
  573. couchbaseembed::connectionCacheExpirer = new couchbaseembed::ConnectionCacheExpirerObj;
  574. couchbaseembed::connectionCacheExpirer->start();
  575. }
  576. CouchbaseEmbedFunctionContext::CouchbaseEmbedFunctionContext(const IContextLogger &_logctx, const char *options, unsigned _flags)
  577. : logctx(_logctx), m_NextRow(), m_nextParam(0), m_numParams(0), m_scriptFlags(_flags)
  578. {
  579. m_pQuery = nullptr;
  580. m_pQcmd = nullptr;
  581. const char *server = "localhost";
  582. const char *user = "";
  583. const char *password = "";
  584. const char *bucketname = "default";
  585. unsigned port = 8091;
  586. bool useSSL = false;
  587. StringBuffer connectionOptions;
  588. unsigned int maxConnections = 0;
  589. StringArray inputOptions;
  590. inputOptions.appendList(options, ",");
  591. ForEachItemIn(idx, inputOptions)
  592. {
  593. const char *opt = inputOptions.item(idx);
  594. const char *val = strchr(opt, '=');
  595. if (val)
  596. {
  597. StringBuffer optName(val-opt, opt);
  598. val++;
  599. if (stricmp(optName, "server")==0)
  600. server = val; // Note that lifetime of val is adequate for this to be safe
  601. else if (stricmp(optName, "port")==0)
  602. port = atoi(val);
  603. else if (stricmp(optName, "user")==0)
  604. user = val; // This is not used but retained for backwards-compatibility
  605. else if (stricmp(optName, "password")==0)
  606. password = val;
  607. else if (stricmp(optName, "bucket")==0)
  608. bucketname = val;
  609. else if (stricmp(optName, "useSSL")==0)
  610. useSSL = clipStrToBool(val);
  611. else if (stricmp(optName, "max_connections")==0)
  612. maxConnections = atoi(val);
  613. //Connection String options
  614. /*
  615. operation_timeout=SECONDS: Specify the operation timeout in seconds. This is the time the client will wait for an operation to complete before timing it out. The default is 2.5
  616. config_cache=PATH: Enables the client to make use of a file based configuration cache rather than connecting for the bootstrap operation. If the file does not exist, the client will first connect to the cluster and then cache the bootstrap information in the file.
  617. example "couchbases://127.0.0.1/default?certpath=../etc/x509-cert/SSLCA/clientdir/trust.pem"
  618. certpath=PATH: The path to the server's SSL certificate. This is typically required for SSL connectivity unless the certificate has already been added to the openssl installation on the system (only applicable with couchbases:// scheme)
  619. ssl=no_verify: Temporarily disable certificate verification for SSL (only applicable with couchbases:// scheme). This should only be used for quickly debugging SSL functionality.
  620. sasl_mech_force=MECHANISM: Force a specific SASL mechanism to be used when performing the initial connection. This should only need to be modified for debugging purposes. The currently supported mechanisms are PLAIN and CRAM-MD5
  621. bootstrap_on=<both,http,cccp>: Specify the bootstrap protocol the client should use when attempting to connect to the cluster. Options are: cccp: Bootstrap using the Memcached protocol (supported on clusters 2.5 and greater); http: Bootstrap using the HTTP REST protocol (supported on any cluster version); and both: First attempt bootstrap over the Memcached protocol, and use the HTTP protocol if Memcached bootstrap fails. The default is both
  622. operation_timeout (Timeout)
  623. The operation timeout is the maximum amount of time the library will wait for an operation to receive a response before invoking its callback with a failure status.
  624. An operation might time-out if:
  625. - A server is taking too long to respond
  626. - An updated cluster configuration has not been promptly received
  627. When an operation times out, it will fail with the LCB_ETIMEDOUT error code.
  628. Connection String Example
  629. operation_timeout=2.5
  630. config_total_timeout (Timeout)
  631. This is how long the client will wait to obtain the initial configuration. This affects the maximum amount of time that the call to lcb_wait() will take after having called lcb_connect(). If lcb_get_bootstrap_status is returning with LCB_ETIMEDOUT and you are running on a slow network, modifying this setting may increase the chances of success.
  632. See also config_node_timeout.
  633. Connection String Example
  634. config_total_timeout=5
  635. config_node_timeout (Timeout)
  636. The per-node configuration timeout sets the amount of time to wait for each node within the bootstrap/configuration process. This interval is a subset of the config_total_timeout option mentioned above and is intended to ensure that the bootstrap process does not wait too long for a given node.
  637. Nodes that are physically offline may never respond, and it may take a long time until they are detected as being offline. See CCBC-261 and CCBC-313 for more reasons.
  638. Connection String Example
  639. config_node_timeout=2
  640. views_timeout (Timeout)
  641. The I/O timeout for view operations.
  642. Connection String Example
  643. views_timeout=75
  644. n1ql_timeout (Timeout). Since 2.5.3
  645. The I/O timeout for N1QL queries.
  646. Connection String Example
  647. n1ql_timeout=75
  648. durabilty_timeout (Timeout)
  649. The default timeout for lcb_durability_poll() This is the time the client will spend sending repeated probes to a given key’s vBucket masters and replicas before they are deemed not to have satisfied the durability requirements.
  650. Connection String Example
  651. durability_timeout=5
  652. durabilty_interval (Timeout)
  653. This is the time the client will wait between repeated probes to a given server.
  654. Connection String Example
  655. durability_interval=0.0001
  656. ipv6= (enum)
  657. Controls whether hostname lookups should prefer IPv4 or IPv6. Can be set to allow, disable (the default), or only. See Enumeration Type Documentation for more info.
  658. randomize_nodes (Boolean)
  659. This option controls whether the connection attempts for configuration retrievals should be done in the supplied order or whether they should be randomized. This setting is off by default. To affect the order of the initial connection, this option must be supplied in the connection string.
  660. For the initial connection, the default order is the list of hosts provided in the structure. For subsequent connections, this is the order of nodes as received by the server.
  661. Connection String Example
  662. randomize_nodes=1
  663. config_cache (Path)
  664. The configuration cache allows bootstrapping from a cluster without using the initial bootstrap connection, considerably reducing latency. If the file passed does not exist, the normal bootstrap process is performed, and the file is written to with the current information.
  665. The leading directories for the file must exist. Otherwise, the file will never be created.
  666. Configuration cache is not supported for memcached buckets
  667. Connection String Example
  668. config_cache=/tmp/cb_config_cache
  669. config_cache_ro (Path). Since 2.4.8
  670. This is identical to the config_cache option, except that it guarantees that the library will never overwrite or otherwise modify the path specified.
  671. Connection String Example
  672. config_cache_ro=1
  673. detailed_errcodes (Boolean)
  674. Sets the behavior for reporting network errors. By default network errors are returned as LCB_NETWORK_ERROR. Return codes for compatibility reasons. More detailed error codes may be available by enabling this option that will return appropriate error codes with a category LCB_ERRTYPE_NETWORK.
  675. Using this option means your programming model is centered around the various LCB_EIF* macros (see <libcouchbase/error.h>) rather than individual codes.
  676. For users of higher level languages (wrapping the library), this may result in different exceptions being thrown, but may also help debug network issues.
  677. Connection String Example
  678. detailed_errcodes=1
  679. http_poolsize (Integer)
  680. Set the maximum pool size for pooled HTTP (view or N1QL request) sockets. A setting of 0 disables pooling.
  681. Connection String Example
  682. http_poolsize=0
  683. error_thresh_delay (Timeout)
  684. This option controls refreshing the configuration upon the receipt of errors. The client throttles how many requests for a new configuration it will send in a given interval—this is to avoid sending many successive requests in the event of a non-transient error condition.
  685. This setting controls the duration of this interval. The value can be adjusted upwards if operating in an environment where it is normal to receive many timeouts, such as in a resource-contented server or network. It can be adjusted downwards if timeouts are expected only in situations where the cluster has changed state.
  686. Connection String Example
  687. error_thresh_delay=7.5
  688. bootstrap_on (String; see description)
  689. Controls how the client attempts to retrieve the configuration from the cluster. By default, the client attempts to connect to the data (memcached) port of each node listed and attempts to retrieve the configuration from there. If the retrieval fails, the client attempts the same process using the HTTP REST API port (8091) of each node.
  690. This setting can be used to have the client forcefully use a single mode. This might be helpful for quick initialization of memcached buckets, which can only send configurations over HTTP. It can also be used in the case of potential issues encountered with either mode.
  691. Possible values for this setting are:
  692. http, to force bootstrap over HTTP only
  693. cccp, to force bootstrap over memcached only
  694. both, which attempts both (as above). This option can only be set from within the connection string.
  695. bootstrap_on=http
  696. fetch_mutation_tokens (Boolean). Since 2.5.2
  697. Whether the server should send an additional 16 bytes of metadata for each mutation response. This option is off by default but is required for Enhanced Durability. This option should be set either in the connection string, or immediately calling lcb_create(). For non-C applications, this must always be in the connection string.
  698. Connection String Example
  699. fetch_mutation_tokens=1
  700. dur_mutation_tokens (Boolean). Since 2.5.2
  701. Determines if Enhanced Durability is used automatically. It is enabled by default if fetch_synctokens is also enabled. Applications can take advantage of this new feature without modifying any code other than enabling these settings.
  702. If you are checking durability constraints across client instances, and fetch_synctokens is enabled, then this setting should be disabled. Otherwise, the client will fail to retrieve the lcb_SYNCTOKEN (see more about this in the Enhanced Durability section). Alternatively, you can supply the sync token directly in the command structure.
  703. dur_mutation_tokens=1
  704. */
  705. else if (stricmp(optName, "detailed_errcodes")==0
  706. || stricmp(optName, "operation_timeout")==0
  707. || stricmp(optName, "config_total_timeout")==0
  708. || stricmp(optName, "config_node_timeout")==0
  709. || stricmp(optName, "views_timeout")==0
  710. || stricmp(optName, "durabilty_timeout")==0
  711. || stricmp(optName, "durabilty_interval")==0
  712. || stricmp(optName, "ipv6")==0
  713. || stricmp(optName, "randomize_nodes")==0
  714. || stricmp(optName, "config_cache_ro")==0
  715. || stricmp(optName, "http_poolsize")==0
  716. || stricmp(optName, "error_thresh_delay")==0
  717. || stricmp(optName, "fetch_mutation_tokens")==0
  718. || stricmp(optName, "dur_mutation_tokens")==0
  719. || stricmp(optName, "http_poolsize")==0
  720. || stricmp(optName, "config_cache")==0
  721. || stricmp(optName, "certpath")==0
  722. || stricmp(optName, "sasl_mech_force")==0
  723. || stricmp(optName, "bootstrap_on")==0
  724. || stricmp(optName, "console_log_level")==0)
  725. connectionOptions.appendf("%s%s=%s", connectionOptions.length() == 0 ? "?" : "&", optName.str(), val);
  726. else
  727. failx("Unknown option %s", optName.str());
  728. }
  729. }
  730. std::call_once(connectionCacheInitFlag, setupConnectionCache, logctx.queryTraceLevel());
  731. // Get a cached idle connection or create a new one
  732. m_oCBConnection = connectionCache->getConnection(useSSL, server, port, bucketname, password, connectionOptions.str(), maxConnections, user);
  733. }
  734. CouchbaseEmbedFunctionContext::~CouchbaseEmbedFunctionContext()
  735. {
  736. if (m_pQcmd)
  737. {
  738. delete m_pQcmd;
  739. m_pQcmd = nullptr;
  740. }
  741. if (m_pQuery)
  742. {
  743. delete m_pQuery;
  744. m_pQuery = nullptr;
  745. }
  746. if (m_oCBConnection)
  747. {
  748. // When the context is deleted we should return any connection
  749. // object back to idle status
  750. connectionCache->releaseActive(m_oCBConnection);
  751. m_oCBConnection = nullptr;
  752. }
  753. }
  754. IPropertyTree * CouchbaseEmbedFunctionContext::nextResultRowTree()
  755. {
  756. if (m_pQuery)
  757. {
  758. reportIfQueryFailure(m_pQuery);
  759. // Only the first callback query is processed
  760. auto json = m_pQuery->begin()->json().to_string();
  761. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str());
  762. return contentTree.getLink();
  763. }
  764. return nullptr;
  765. }
  766. IPropertyTreeIterator * CouchbaseEmbedFunctionContext::nextResultRowIterator()
  767. {
  768. if (m_pQuery)
  769. {
  770. reportIfQueryFailure(m_pQuery);
  771. // Only the first callback query is processed
  772. auto json = m_pQuery->begin()->json().to_string();
  773. Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str());
  774. if (contentTree)
  775. return contentTree->getElements("./*");
  776. failx("Could not fetch next result row.");
  777. }
  778. return nullptr;
  779. }
  780. const char * CouchbaseEmbedFunctionContext::nextResultScalar()
  781. {
  782. m_resultrow.setown(nextResultRowIterator());
  783. if (m_resultrow)
  784. {
  785. m_resultrow->first();
  786. if(m_resultrow->isValid() == true)
  787. {
  788. if (m_resultrow->query().hasChildren())
  789. typeError("scalar", "");
  790. return m_resultrow->query().queryProp("");
  791. }
  792. else
  793. failx("Could not fetch next result column.");
  794. }
  795. else
  796. failx("Could not fetch next result row.");
  797. return nullptr;
  798. }
  799. bool CouchbaseEmbedFunctionContext::getBooleanResult()
  800. {
  801. bool mybool;
  802. auto scalar = nextResultScalar();
  803. handleDeserializeOutcome(m_tokenDeserializer.deserialize(scalar, mybool), "bool", scalar);
  804. return mybool;
  805. }
  806. void CouchbaseEmbedFunctionContext::getDataResult(size32_t &len, void * &result)
  807. {
  808. auto value = nextResultScalar();
  809. if (value && *value)
  810. {
  811. rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want
  812. }
  813. else
  814. {
  815. rtlStrToDataX(len, result, NULLFIELD.resultChars, NULLFIELD.stringResult);
  816. }
  817. }
  818. double CouchbaseEmbedFunctionContext::getRealResult()
  819. {
  820. double mydouble = 0.0;
  821. auto value = nextResultScalar();
  822. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value);
  823. return mydouble;
  824. }
  825. __int64 CouchbaseEmbedFunctionContext::getSignedResult()
  826. {
  827. __int64 myint64 = 0;
  828. auto value = nextResultScalar();
  829. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value);
  830. return myint64;
  831. }
  832. unsigned __int64 CouchbaseEmbedFunctionContext::getUnsignedResult()
  833. {
  834. unsigned __int64 myuint64 = 0;
  835. auto value = nextResultScalar();
  836. handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value);
  837. return myuint64;
  838. }
  839. void CouchbaseEmbedFunctionContext::getStringResult(size32_t &chars, char * &result)
  840. {
  841. auto value = nextResultScalar();
  842. if (value && *value)
  843. {
  844. unsigned numchars = rtlUtf8Length(strlen(value), value);
  845. rtlUtf8ToStrX(chars, result, numchars, value);
  846. }
  847. else
  848. {
  849. rtlStrToStrX(chars, result, NULLFIELD.resultChars, NULLFIELD.stringResult);
  850. }
  851. }
  852. void CouchbaseEmbedFunctionContext::getUTF8Result(size32_t &chars, char * &result)
  853. {
  854. getStringResult(chars, result);
  855. }
  856. void CouchbaseEmbedFunctionContext::getUnicodeResult(size32_t &chars, UChar * &result)
  857. {
  858. auto value = nextResultScalar();
  859. if (value && *value)
  860. {
  861. unsigned numchars = rtlUtf8Length(strlen(value), value);
  862. rtlUtf8ToUnicodeX(chars, result, numchars, value);
  863. }
  864. else
  865. {
  866. rtlUnicodeToUnicodeX(chars, result, NULLFIELD.resultChars, NULLFIELD.unicodeResult);
  867. }
  868. }
  869. void CouchbaseEmbedFunctionContext::getDecimalResult(Decimal &value)
  870. {
  871. auto text = nextResultScalar();
  872. if (text && *text)
  873. value.setString(rtlUtf8Length(strlen(text), text), text);
  874. else
  875. value.set(NULLFIELD.decimalResult);
  876. }
  877. IRowStream * CouchbaseEmbedFunctionContext::getDatasetResult(IEngineRowAllocator * _resultAllocator)
  878. {
  879. Owned<CouchbaseRowStream> cbaseRowStream;
  880. cbaseRowStream.setown(new CouchbaseRowStream(_resultAllocator, m_pQuery));
  881. return cbaseRowStream.getLink();
  882. }
  883. byte * CouchbaseEmbedFunctionContext::getRowResult(IEngineRowAllocator * _resultAllocator)
  884. {
  885. Owned<CouchbaseRowStream> cbaseRowStream;
  886. cbaseRowStream.setown(new CouchbaseRowStream(_resultAllocator, m_pQuery));
  887. return (byte *)cbaseRowStream->nextRow();
  888. }
  889. size32_t CouchbaseEmbedFunctionContext::getTransformResult(ARowBuilder & rowBuilder)
  890. {
  891. execute();
  892. auto resultrow = nextResultRowTree();
  893. if (!resultrow)
  894. fail("Failed to read row");
  895. if (resultrow->getCount("./*") != 1)
  896. typeError("row", "");
  897. CouchbaseRowBuilder couchbaseRowBuilder(resultrow);
  898. const RtlTypeInfo *typeInfo = rowBuilder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  899. assertex(typeInfo);
  900. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  901. return typeInfo->build(rowBuilder, 0, &dummyField, couchbaseRowBuilder);
  902. }
  903. void CouchbaseEmbedFunctionContext::bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val)
  904. {
  905. CouchbaseRecordBinder binder(logctx, metaVal.queryTypeInfo(), m_pQcmd, m_nextParam);
  906. binder.processRow(val);
  907. m_nextParam += binder.numFields();
  908. }
  909. void CouchbaseEmbedFunctionContext::bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  910. {
  911. // We only support a single dataset parameter...
  912. // MORE - look into batch?
  913. if (m_oInputStream)
  914. {
  915. fail("At most one dataset parameter supported");
  916. }
  917. m_oInputStream.setown(new CouchbaseDatasetBinder(logctx, LINK(val), metaVal.queryTypeInfo(), m_pQcmd, m_nextParam));
  918. m_nextParam += m_oInputStream->numFields();
  919. }
  920. void CouchbaseEmbedFunctionContext::bindBooleanParam(const char *name, bool val)
  921. {
  922. checkNextParam(name);
  923. StringBuffer serialized;
  924. m_tokenSerializer.serialize(val, serialized);
  925. VStringBuffer cbPlaceholder("$%s", name);
  926. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  927. if (!status.success())
  928. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  929. }
  930. void CouchbaseEmbedFunctionContext::bindDataParam(const char *name, size32_t len, const void *val)
  931. {
  932. checkNextParam(name);
  933. VStringBuffer cbPlaceholder("$%s", name);
  934. size32_t bytes;
  935. rtlDataAttr data;
  936. rtlStrToDataX(bytes, data.refdata(), len, val);
  937. auto status = m_pQcmd->named_param(cbPlaceholder.str(), data.getstr());
  938. if (!status.success())
  939. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), data.getstr());
  940. }
  941. void CouchbaseEmbedFunctionContext::bindFloatParam(const char *name, float val)
  942. {
  943. checkNextParam(name);
  944. StringBuffer serialized;
  945. m_tokenSerializer.serialize(val, serialized);
  946. VStringBuffer cbPlaceholder("$%s", name);
  947. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  948. if (!status.success())
  949. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  950. }
  951. void CouchbaseEmbedFunctionContext::bindRealParam(const char *name, double val)
  952. {
  953. checkNextParam(name);
  954. StringBuffer serialized;
  955. m_tokenSerializer.serialize(val, serialized);
  956. VStringBuffer cbPlaceholder("$%s", name);
  957. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  958. if (!status.success())
  959. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  960. }
  961. void CouchbaseEmbedFunctionContext::bindSignedSizeParam(const char *name, int size, __int64 val)
  962. {
  963. bindSignedParam(name, val);
  964. }
  965. void CouchbaseEmbedFunctionContext::bindSignedParam(const char *name, __int64 val)
  966. {
  967. checkNextParam(name);
  968. StringBuffer serialized;
  969. m_tokenSerializer.serialize(val, serialized);
  970. VStringBuffer cbPlaceholder("$%s", name);
  971. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  972. if (!status.success())
  973. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  974. }
  975. void CouchbaseEmbedFunctionContext::bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
  976. {
  977. bindUnsignedParam(name, val);
  978. }
  979. void CouchbaseEmbedFunctionContext::bindUnsignedParam(const char *name, unsigned __int64 val)
  980. {
  981. checkNextParam(name);
  982. StringBuffer serialized;
  983. m_tokenSerializer.serialize(val, serialized);
  984. VStringBuffer cbPlaceholder("$%s", name);
  985. auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str());
  986. if (!status.success())
  987. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str());
  988. }
  989. void CouchbaseEmbedFunctionContext::bindStringParam(const char *name, size32_t len, const char *val)
  990. {
  991. checkNextParam(name);
  992. VStringBuffer cbPlaceholder("$%s", name);
  993. size32_t utf8chars;
  994. rtlDataAttr utf8;
  995. rtlStrToUtf8X(utf8chars, utf8.refstr(), len, val);
  996. auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8.getstr());
  997. if (!status.success())
  998. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8.getstr());
  999. }
  1000. void CouchbaseEmbedFunctionContext::bindVStringParam(const char *name, const char *val)
  1001. {
  1002. checkNextParam(name);
  1003. bindStringParam(name, strlen(val), val);
  1004. }
  1005. void CouchbaseEmbedFunctionContext::bindUTF8Param(const char *name, size32_t chars, const char *val)
  1006. {
  1007. checkNextParam(name);
  1008. bindStringParam(name, strlen(val), val);
  1009. }
  1010. void CouchbaseEmbedFunctionContext::bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  1011. {
  1012. checkNextParam(name);
  1013. VStringBuffer cbPlaceholder("$%s", name);
  1014. size32_t utf8chars;
  1015. char *utf8;
  1016. rtlUnicodeToUtf8X(utf8chars, utf8, chars, val);
  1017. auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8);
  1018. if (!status.success())
  1019. failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8);
  1020. }
  1021. void CouchbaseEmbedFunctionContext::compileEmbeddedScript(size32_t chars, const char *script)
  1022. {
  1023. if (script && *script)
  1024. {
  1025. // Incoming script is not necessarily null terminated. Note that the chars refers to utf8 characters and not bytes.
  1026. size32_t len = rtlUtf8Size(chars, script);
  1027. if (len > 0)
  1028. {
  1029. StringAttr queryScript;
  1030. queryScript.set(script, len);
  1031. const char * terminatedScript = queryScript.get(); // Now null terminated
  1032. if (m_pQcmd)
  1033. delete m_pQcmd;
  1034. m_pQcmd = new Couchbase::QueryCommand(terminatedScript);
  1035. if ((m_scriptFlags & EFnoparams) == 0)
  1036. m_numParams = countParameterPlaceholders(terminatedScript);
  1037. else
  1038. m_numParams = 0;
  1039. }
  1040. else
  1041. failx("Empty N1QL query detected");
  1042. }
  1043. else
  1044. failx("Empty N1QL query detected");
  1045. }
  1046. void CouchbaseEmbedFunctionContext::callFunction()
  1047. {
  1048. execute();
  1049. }
  1050. void CouchbaseEmbedFunctionContext::execute()
  1051. {
  1052. if (m_oInputStream)
  1053. m_oInputStream->executeAll(m_oCBConnection);
  1054. else
  1055. {
  1056. if (m_pQuery)
  1057. delete m_pQuery;
  1058. m_pQuery = m_oCBConnection->query(m_pQcmd);
  1059. reportIfQueryFailure(m_pQuery);
  1060. }
  1061. }
  1062. unsigned CouchbaseEmbedFunctionContext::checkNextParam(const char *name)
  1063. {
  1064. if (m_nextParam == m_numParams)
  1065. failx("Too many parameters supplied: No matching $<name> placeholder for parameter %s", name);
  1066. return m_nextParam++;
  1067. }
  1068. bool CouchbaseRowBuilder::getBooleanResult(const RtlFieldInfo *field)
  1069. {
  1070. const char * value = nextField(field);
  1071. if (!value || !*value)
  1072. {
  1073. NullFieldProcessor p(field);
  1074. return p.boolResult;
  1075. }
  1076. bool mybool;
  1077. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mybool), "bool", value);
  1078. return mybool;
  1079. }
  1080. void CouchbaseRowBuilder::getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
  1081. {
  1082. const char * value = nextField(field);
  1083. if (!value || !*value)
  1084. {
  1085. NullFieldProcessor p(field);
  1086. rtlStrToDataX(len, result, p.resultChars, p.stringResult);
  1087. return;
  1088. }
  1089. rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want
  1090. }
  1091. double CouchbaseRowBuilder::getRealResult(const RtlFieldInfo *field)
  1092. {
  1093. const char * value = nextField(field);
  1094. if (!value || !*value)
  1095. {
  1096. NullFieldProcessor p(field);
  1097. return p.doubleResult;
  1098. }
  1099. double mydouble = 0.0;
  1100. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value);
  1101. return mydouble;
  1102. }
  1103. __int64 CouchbaseRowBuilder::getSignedResult(const RtlFieldInfo *field)
  1104. {
  1105. const char * value = nextField(field);
  1106. if (!value || !*value)
  1107. {
  1108. NullFieldProcessor p(field);
  1109. return p.uintResult;
  1110. }
  1111. __int64 myint64 = 0;
  1112. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value);
  1113. return myint64;
  1114. }
  1115. unsigned __int64 CouchbaseRowBuilder::getUnsignedResult(const RtlFieldInfo *field)
  1116. {
  1117. const char * value = nextField(field);
  1118. if (!value || !*value)
  1119. {
  1120. NullFieldProcessor p(field);
  1121. return p.uintResult;
  1122. }
  1123. unsigned __int64 myuint64 = 0;
  1124. couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value);
  1125. return myuint64;
  1126. }
  1127. void CouchbaseRowBuilder::getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
  1128. {
  1129. const char * value = nextField(field);
  1130. if (!value || !*value)
  1131. {
  1132. NullFieldProcessor p(field);
  1133. rtlStrToStrX(chars, result, p.resultChars, p.stringResult);
  1134. return;
  1135. }
  1136. unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
  1137. rtlUtf8ToStrX(chars, result, numchars, value);
  1138. return;
  1139. }
  1140. void CouchbaseRowBuilder::getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
  1141. {
  1142. getStringResult(field, chars, result);
  1143. return;
  1144. }
  1145. void CouchbaseRowBuilder::getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
  1146. {
  1147. const char * value = nextField(field);
  1148. if (!value || !*value)
  1149. {
  1150. NullFieldProcessor p(field);
  1151. rtlUnicodeToUnicodeX(chars, result, p.resultChars, p.unicodeResult);
  1152. return;
  1153. }
  1154. unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
  1155. rtlUtf8ToUnicodeX(chars, result, numchars, value);
  1156. return;
  1157. }
  1158. void CouchbaseRowBuilder::getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  1159. {
  1160. const char * dvalue = nextField(field);
  1161. if (!dvalue || !*dvalue)
  1162. {
  1163. NullFieldProcessor p(field);
  1164. value.set(p.decimalResult);
  1165. return;
  1166. }
  1167. size32_t chars;
  1168. rtlDataAttr result;
  1169. value.setString(strlen(dvalue), dvalue);
  1170. RtlDecimalTypeInfo *dtype = (RtlDecimalTypeInfo *) field->type;
  1171. value.setPrecision(dtype->getDecimalDigits(), dtype->getDecimalPrecision());
  1172. }
  1173. void CouchbaseRowBuilder::processBeginSet(const RtlFieldInfo * field, bool &isAll)
  1174. {
  1175. isAll = false; // ALL not supported
  1176. StringBuffer xpath;
  1177. xpathOrName(xpath, field);
  1178. if (!xpath.isEmpty())
  1179. {
  1180. PathTracker newPathNode(xpath, CPNTSet);
  1181. StringBuffer newXPath;
  1182. constructNewXPath(newXPath, xpath.str());
  1183. newPathNode.childCount = m_oResultRow->getCount(newXPath);
  1184. m_pathStack.push_back(newPathNode);
  1185. }
  1186. else
  1187. {
  1188. failx("processBeginSet: Field name or xpath missing");
  1189. }
  1190. }
  1191. bool CouchbaseRowBuilder::processNextSet(const RtlFieldInfo * field)
  1192. {
  1193. return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount;
  1194. }
  1195. void CouchbaseRowBuilder::processBeginDataset(const RtlFieldInfo * field)
  1196. {
  1197. StringBuffer xpath;
  1198. xpathOrName(xpath, field);
  1199. if (!xpath.isEmpty())
  1200. {
  1201. PathTracker newPathNode(xpath, CPNTDataset);
  1202. StringBuffer newXPath;
  1203. constructNewXPath(newXPath, xpath.str());
  1204. newPathNode.childCount = m_oResultRow->getCount(newXPath);
  1205. m_pathStack.push_back(newPathNode);
  1206. }
  1207. else
  1208. {
  1209. failx("processBeginDataset: Field name or xpath missing");
  1210. }
  1211. }
  1212. void CouchbaseRowBuilder::processBeginRow(const RtlFieldInfo * field)
  1213. {
  1214. StringBuffer xpath;
  1215. xpathOrName(xpath, field);
  1216. if (!xpath.isEmpty())
  1217. {
  1218. if (strncmp(xpath.str(), "<nested row>", 12) == 0)
  1219. {
  1220. // Row within child dataset
  1221. if (m_pathStack.back().nodeType == CPNTDataset)
  1222. {
  1223. m_pathStack.back().currentChildIndex++;
  1224. }
  1225. else
  1226. {
  1227. failx("<nested row> received with no outer dataset designated");
  1228. }
  1229. }
  1230. else
  1231. {
  1232. m_pathStack.push_back(PathTracker(xpath, CPNTScalar));
  1233. }
  1234. }
  1235. else
  1236. {
  1237. failx("processBeginRow: Field name or xpath missing");
  1238. }
  1239. }
  1240. bool CouchbaseRowBuilder::processNextRow(const RtlFieldInfo * field)
  1241. {
  1242. return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount;
  1243. }
  1244. void CouchbaseRowBuilder::processEndSet(const RtlFieldInfo * field)
  1245. {
  1246. StringBuffer xpath;
  1247. xpathOrName(xpath, field);
  1248. if (!xpath.isEmpty() && !m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  1249. {
  1250. m_pathStack.pop_back();
  1251. }
  1252. }
  1253. void CouchbaseRowBuilder::processEndDataset(const RtlFieldInfo * field)
  1254. {
  1255. StringBuffer xpath;
  1256. xpathOrName(xpath, field);
  1257. if (!xpath.isEmpty())
  1258. {
  1259. if (!m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  1260. {
  1261. m_pathStack.pop_back();
  1262. }
  1263. }
  1264. else
  1265. {
  1266. failx("processEndDataset: Field name or xpath missing");
  1267. }
  1268. }
  1269. void CouchbaseRowBuilder::processEndRow(const RtlFieldInfo * field)
  1270. {
  1271. StringBuffer xpath;
  1272. xpathOrName(xpath, field);
  1273. if (!xpath.isEmpty())
  1274. {
  1275. if (!m_pathStack.empty())
  1276. {
  1277. if (m_pathStack.back().nodeType == CPNTDataset)
  1278. {
  1279. m_pathStack.back().childrenProcessed++;
  1280. }
  1281. else if (strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0)
  1282. {
  1283. m_pathStack.pop_back();
  1284. }
  1285. }
  1286. }
  1287. else
  1288. {
  1289. failx("processEndRow: Field name or xpath missing");
  1290. }
  1291. }
  1292. const char * CouchbaseRowBuilder::nextField(const RtlFieldInfo * field)
  1293. {
  1294. StringBuffer xpath;
  1295. xpathOrName(xpath, field);
  1296. if (xpath.isEmpty())
  1297. {
  1298. failx("nextField: Field name or xpath missing");
  1299. }
  1300. StringBuffer fullXPath;
  1301. if (!m_pathStack.empty() && m_pathStack.back().nodeType == CPNTSet && strncmp(xpath.str(), "<set element>", 13) == 0)
  1302. {
  1303. m_pathStack.back().currentChildIndex++;
  1304. constructNewXPath(fullXPath, NULL);
  1305. m_pathStack.back().childrenProcessed++;
  1306. }
  1307. else
  1308. {
  1309. constructNewXPath(fullXPath, xpath.str());
  1310. }
  1311. return m_oResultRow->queryProp(fullXPath.str());
  1312. }
  1313. void CouchbaseRowBuilder::xpathOrName(StringBuffer & outXPath, const RtlFieldInfo * field) const
  1314. {
  1315. outXPath.clear();
  1316. if (field->xpath)
  1317. {
  1318. if (field->xpath[0] == xpathCompoundSeparatorChar)
  1319. {
  1320. outXPath.append(field->xpath + 1);
  1321. }
  1322. else
  1323. {
  1324. const char * sep = strchr(field->xpath, xpathCompoundSeparatorChar);
  1325. if (!sep)
  1326. {
  1327. outXPath.append(field->xpath);
  1328. }
  1329. else
  1330. {
  1331. outXPath.append(field->xpath, 0, static_cast<size32_t>(sep - field->xpath));
  1332. }
  1333. }
  1334. }
  1335. else
  1336. {
  1337. outXPath.append(field->name);
  1338. }
  1339. }
  1340. void CouchbaseRowBuilder::constructNewXPath(StringBuffer& outXPath, const char * nextNode) const
  1341. {
  1342. bool nextNodeIsFromRoot = (nextNode && *nextNode == '/');
  1343. outXPath.clear();
  1344. if (!nextNodeIsFromRoot)
  1345. {
  1346. // Build up full parent xpath using our previous components
  1347. for (std::vector<PathTracker>::const_iterator iter = m_pathStack.begin(); iter != m_pathStack.end(); iter++)
  1348. {
  1349. if (strncmp(iter->nodeName, "<row>", 5) != 0)
  1350. {
  1351. if (!outXPath.isEmpty())
  1352. {
  1353. outXPath.append("/");
  1354. }
  1355. outXPath.append(iter->nodeName);
  1356. if (iter->nodeType == CPNTDataset || iter->nodeType == CPNTSet)
  1357. {
  1358. outXPath.appendf("[%d]", iter->currentChildIndex);
  1359. }
  1360. }
  1361. }
  1362. }
  1363. if (nextNode && *nextNode)
  1364. {
  1365. if (!outXPath.isEmpty())
  1366. {
  1367. outXPath.append("/");
  1368. }
  1369. outXPath.append(nextNode);
  1370. }
  1371. }
  1372. class CouchbaseEmbedContext : public CInterfaceOf<IEmbedContext>
  1373. {
  1374. public:
  1375. virtual IEmbedFunctionContext * createFunctionContext(unsigned flags, const char *options) override
  1376. {
  1377. return createFunctionContextEx(nullptr, nullptr, flags, options);
  1378. }
  1379. virtual IEmbedFunctionContext * createFunctionContextEx(ICodeContext * ctx, const IThorActivityContext *activityCtx, unsigned flags, const char *options) override
  1380. {
  1381. if (flags & EFimport)
  1382. {
  1383. UNSUPPORTED("IMPORT");
  1384. return nullptr;
  1385. }
  1386. else
  1387. return new CouchbaseEmbedFunctionContext(ctx ? ctx->queryContextLogger() : queryDummyContextLogger(), options, flags);
  1388. }
  1389. virtual IEmbedServiceContext * createServiceContext(const char *service, unsigned flags, const char *options) override
  1390. {
  1391. throwUnexpected();
  1392. return nullptr;
  1393. }
  1394. };
  1395. extern DECL_EXPORT IEmbedContext* getEmbedContext()
  1396. {
  1397. return new CouchbaseEmbedContext();
  1398. }
  1399. extern DECL_EXPORT bool syntaxCheck(const char *script)
  1400. {
  1401. return true; // TO-DO
  1402. }
  1403. } // namespace
  1404. MODULE_INIT(INIT_PRIORITY_STANDARD)
  1405. {
  1406. couchbaseembed::connectionCache = nullptr;
  1407. couchbaseembed::connectionCacheExpirer = nullptr;
  1408. return true;
  1409. }
  1410. MODULE_EXIT()
  1411. {
  1412. // Delete the background thread expiring items from the CouchbaseConnection
  1413. // cache before deleting the connection cache
  1414. if (couchbaseembed::connectionCacheExpirer)
  1415. {
  1416. couchbaseembed::connectionCacheExpirer->stop();
  1417. delete(couchbaseembed::connectionCacheExpirer);
  1418. couchbaseembed::connectionCacheExpirer = nullptr;
  1419. }
  1420. if (couchbaseembed::connectionCache)
  1421. {
  1422. couchbaseembed::connectionCache->deleteAll();
  1423. delete(couchbaseembed::connectionCache);
  1424. couchbaseembed::connectionCache = nullptr;
  1425. }
  1426. }