id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1
value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
10,000 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | function(item, arr) {
for (var i = 0; i < arr[LEXICON.l]; i++)
//Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
try {
if (arr[i] === item)
return i;
}
catch(e) { }
return -1;
} | javascript | function(item, arr) {
for (var i = 0; i < arr[LEXICON.l]; i++)
//Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
try {
if (arr[i] === item)
return i;
}
catch(e) { }
return -1;
} | [
"function",
"(",
"item",
",",
"arr",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
"[",
"LEXICON",
".",
"l",
"]",
";",
"i",
"++",
")",
"//Sometiems in IE a \"SCRIPT70\" Permission denied error occurs if HTML elements in a iFrame are compared",
... | Checks whether a item is in the given array and returns its index.
@param item The item of which the position in the array shall be determined.
@param arr The array.
@returns {number} The zero based index of the item or -1 if the item isn't in the array. | [
"Checks",
"whether",
"a",
"item",
"is",
"in",
"the",
"given",
"array",
"and",
"returns",
"its",
"index",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L249-L258 | |
10,001 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | function(arr) {
var def = Array.isArray;
return def ? def(arr) : this.type(arr) == TYPES.a;
} | javascript | function(arr) {
var def = Array.isArray;
return def ? def(arr) : this.type(arr) == TYPES.a;
} | [
"function",
"(",
"arr",
")",
"{",
"var",
"def",
"=",
"Array",
".",
"isArray",
";",
"return",
"def",
"?",
"def",
"(",
"arr",
")",
":",
"this",
".",
"type",
"(",
"arr",
")",
"==",
"TYPES",
".",
"a",
";",
"}"
] | Returns true if the given value is a array.
@param arr The potential array.
@returns {boolean} True if the given value is a array, false otherwise. | [
"Returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"array",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L265-L268 | |
10,002 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | initOverlayScrollbarsStatics | function initOverlayScrollbarsStatics() {
if(!_pluginsGlobals)
_pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
if(!_pluginsAutoUpdateLoop)
_pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
} | javascript | function initOverlayScrollbarsStatics() {
if(!_pluginsGlobals)
_pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
if(!_pluginsAutoUpdateLoop)
_pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
} | [
"function",
"initOverlayScrollbarsStatics",
"(",
")",
"{",
"if",
"(",
"!",
"_pluginsGlobals",
")",
"_pluginsGlobals",
"=",
"new",
"OverlayScrollbarsGlobals",
"(",
"_pluginsOptions",
".",
"_defaults",
")",
";",
"if",
"(",
"!",
"_pluginsAutoUpdateLoop",
")",
"_plugins... | Initializes the object which contains global information about the plugin and each instance of it. | [
"Initializes",
"the",
"object",
"which",
"contains",
"global",
"information",
"about",
"the",
"plugin",
"and",
"each",
"instance",
"of",
"it",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L1647-L1652 |
10,003 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | function() {
if(_loopingInstances[_strLength] > 0 && _loopIsActive) {
_loopID = COMPATIBILITY.rAF()(function () {
loop();
});
var timeNew = COMPATIBILITY.now();
var timeDelta = timeNew - _loopTimeOld;
var lowestInterval;
var instance;
var instanceOptions;
var instanceAutoUpdateAllowed;
var instanceAutoUpdateInterval;
var now;
if (timeDelta > _loopInterval) {
_loopTimeOld = timeNew - (timeDelta % _loopInterval);
lowestInterval = _loopIntervalDefault;
for(var i = 0; i < _loopingInstances[_strLength]; i++) {
instance = _loopingInstances[i];
if (instance !== undefined) {
instanceOptions = instance.options();
instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
now = COMPATIBILITY.now();
if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
instance.update('auto');
_loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
}
lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
}
}
_loopInterval = lowestInterval;
}
} else {
_loopInterval = _loopIntervalDefault;
}
} | javascript | function() {
if(_loopingInstances[_strLength] > 0 && _loopIsActive) {
_loopID = COMPATIBILITY.rAF()(function () {
loop();
});
var timeNew = COMPATIBILITY.now();
var timeDelta = timeNew - _loopTimeOld;
var lowestInterval;
var instance;
var instanceOptions;
var instanceAutoUpdateAllowed;
var instanceAutoUpdateInterval;
var now;
if (timeDelta > _loopInterval) {
_loopTimeOld = timeNew - (timeDelta % _loopInterval);
lowestInterval = _loopIntervalDefault;
for(var i = 0; i < _loopingInstances[_strLength]; i++) {
instance = _loopingInstances[i];
if (instance !== undefined) {
instanceOptions = instance.options();
instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
now = COMPATIBILITY.now();
if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
instance.update('auto');
_loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
}
lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
}
}
_loopInterval = lowestInterval;
}
} else {
_loopInterval = _loopIntervalDefault;
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"_loopingInstances",
"[",
"_strLength",
"]",
">",
"0",
"&&",
"_loopIsActive",
")",
"{",
"_loopID",
"=",
"COMPATIBILITY",
".",
"rAF",
"(",
")",
"(",
"function",
"(",
")",
"{",
"loop",
"(",
")",
";",
"}",
")",
";... | The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds. | [
"The",
"auto",
"update",
"loop",
"which",
"will",
"run",
"every",
"50",
"milliseconds",
"or",
"less",
"if",
"the",
"update",
"interval",
"of",
"a",
"instance",
"is",
"lower",
"than",
"50",
"milliseconds",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L1879-L1917 | |
10,004 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | removePassiveEventListener | function removePassiveEventListener(element, eventNames, listener) {
var events = eventNames.split(_strSpace);
for (var i = 0; i < events.length; i++)
element[0].removeEventListener(events[i], listener, {passive: true});
} | javascript | function removePassiveEventListener(element, eventNames, listener) {
var events = eventNames.split(_strSpace);
for (var i = 0; i < events.length; i++)
element[0].removeEventListener(events[i], listener, {passive: true});
} | [
"function",
"removePassiveEventListener",
"(",
"element",
",",
"eventNames",
",",
"listener",
")",
"{",
"var",
"events",
"=",
"eventNames",
".",
"split",
"(",
"_strSpace",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length"... | Removes a passive event listener to the given element.
@param element The element from which the event listener shall be removed.
@param eventNames The name(s) of the event listener.
@param listener The listener method which shall be removed. | [
"Removes",
"a",
"passive",
"event",
"listener",
"to",
"the",
"given",
"element",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2257-L2261 |
10,005 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | function () {
/*
var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var expandChildCSS = {};
expandChildCSS[_strWidth] = sizeResetWidth;
expandChildCSS[_strHeight] = sizeResetHeight;
expandElementChild.css(expandChildCSS);
expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
*/
expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
} | javascript | function () {
/*
var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var expandChildCSS = {};
expandChildCSS[_strWidth] = sizeResetWidth;
expandChildCSS[_strHeight] = sizeResetHeight;
expandElementChild.css(expandChildCSS);
expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
*/
expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
} | [
"function",
"(",
")",
"{",
"/*\n var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;\n var sizeResetHeight = observerE... | care don't make changes to this object!!! | [
"care",
"don",
"t",
"make",
"changes",
"to",
"this",
"object!!!"
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2312-L2327 | |
10,006 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | removeResizeObserver | function removeResizeObserver(targetElement) {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].disconnect();
delete element[_strResizeObserverProperty];
}
else {
remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
}
} | javascript | function removeResizeObserver(targetElement) {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].disconnect();
delete element[_strResizeObserverProperty];
}
else {
remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
}
} | [
"function",
"removeResizeObserver",
"(",
"targetElement",
")",
"{",
"if",
"(",
"_supportResizeObserver",
")",
"{",
"var",
"element",
"=",
"targetElement",
".",
"contents",
"(",
")",
"[",
"0",
"]",
";",
"element",
"[",
"_strResizeObserverProperty",
"]",
".",
"d... | Removes a resize observer from the given element.
@param targetElement The element to which the target resize observer is applied. | [
"Removes",
"a",
"resize",
"observer",
"from",
"the",
"given",
"element",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2446-L2455 |
10,007 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | connectMutationObservers | function connectMutationObservers() {
if (_supportMutationObserver && !_mutationObserversConnected) {
_mutationObserverHost.observe(_hostElementNative, {
attributes: true,
attributeOldValue: true,
attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
attributes: true,
attributeOldValue: true,
subtree: !_isTextarea,
childList: !_isTextarea,
characterData: !_isTextarea,
attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserversConnected = true;
}
} | javascript | function connectMutationObservers() {
if (_supportMutationObserver && !_mutationObserversConnected) {
_mutationObserverHost.observe(_hostElementNative, {
attributes: true,
attributeOldValue: true,
attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
attributes: true,
attributeOldValue: true,
subtree: !_isTextarea,
childList: !_isTextarea,
characterData: !_isTextarea,
attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserversConnected = true;
}
} | [
"function",
"connectMutationObservers",
"(",
")",
"{",
"if",
"(",
"_supportMutationObserver",
"&&",
"!",
"_mutationObserversConnected",
")",
"{",
"_mutationObserverHost",
".",
"observe",
"(",
"_hostElementNative",
",",
"{",
"attributes",
":",
"true",
",",
"attributeOl... | Connects the MutationObservers if they are supported. | [
"Connects",
"the",
"MutationObservers",
"if",
"they",
"are",
"supported",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2587-L2606 |
10,008 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | hostOnMouseMove | function hostOnMouseMove() {
if (_scrollbarsAutoHideMove) {
refreshScrollbarsAutoHide(true);
clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
_scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
if (_scrollbarsAutoHideMove && !_destroyed)
refreshScrollbarsAutoHide(false);
}, 100);
}
} | javascript | function hostOnMouseMove() {
if (_scrollbarsAutoHideMove) {
refreshScrollbarsAutoHide(true);
clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
_scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
if (_scrollbarsAutoHideMove && !_destroyed)
refreshScrollbarsAutoHide(false);
}, 100);
}
} | [
"function",
"hostOnMouseMove",
"(",
")",
"{",
"if",
"(",
"_scrollbarsAutoHideMove",
")",
"{",
"refreshScrollbarsAutoHide",
"(",
"true",
")",
";",
"clearTimeout",
"(",
"_scrollbarsAutoHideMoveTimeoutId",
")",
";",
"_scrollbarsAutoHideMoveTimeoutId",
"=",
"setTimeout",
"(... | The mouse move event of the host element. This event is only needed for the autoHide "move" feature. | [
"The",
"mouse",
"move",
"event",
"of",
"the",
"host",
"element",
".",
"This",
"event",
"is",
"only",
"needed",
"for",
"the",
"autoHide",
"move",
"feature",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2668-L2677 |
10,009 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | isUnknownMutation | function isUnknownMutation(mutation) {
var attributeName = mutation.attributeName;
var mutationTarget = mutation.target;
var mutationType = mutation.type;
var strClosest = 'closest';
if (mutationTarget === _contentElementNative)
return attributeName === null;
if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
//ignore className changes by the plugin
if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c));
//only do it of browser support it natively
if (typeof mutationTarget[strClosest] != TYPES.f)
return true;
if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
return false;
}
return true;
} | javascript | function isUnknownMutation(mutation) {
var attributeName = mutation.attributeName;
var mutationTarget = mutation.target;
var mutationType = mutation.type;
var strClosest = 'closest';
if (mutationTarget === _contentElementNative)
return attributeName === null;
if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
//ignore className changes by the plugin
if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c));
//only do it of browser support it natively
if (typeof mutationTarget[strClosest] != TYPES.f)
return true;
if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
return false;
}
return true;
} | [
"function",
"isUnknownMutation",
"(",
"mutation",
")",
"{",
"var",
"attributeName",
"=",
"mutation",
".",
"attributeName",
";",
"var",
"mutationTarget",
"=",
"mutation",
".",
"target",
";",
"var",
"mutationType",
"=",
"mutation",
".",
"type",
";",
"var",
"strC... | Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown.
@param mutation The mutation which shall be checked.
@returns {boolean} True if the mutation is from a unknown element, false otherwise. | [
"Returns",
"true",
"if",
"the",
"given",
"mutation",
"is",
"not",
"from",
"a",
"from",
"the",
"plugin",
"generated",
"element",
".",
"If",
"the",
"target",
"element",
"is",
"a",
"textarea",
"the",
"mutation",
"is",
"always",
"unknown",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2801-L2823 |
10,010 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | updateAutoContentSizeChanged | function updateAutoContentSizeChanged() {
if (_isSleeping)
return false;
var float;
var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
var viewportScrollSize = { };
var css = { };
var bodyMinSizeC;
var changed;
var viewportScrollSizeChanged;
//fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true"
//it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring
if(_restrictedMeasuring) {
viewportScrollSize = {
x : _viewportElementNative[LEXICON.sW],
y : _viewportElementNative[LEXICON.sH]
}
}
if (setCSS) {
float = _contentElement.css(_strFloat);
css[_strFloat] = _isRTL ? _strRight : _strLeft;
css[_strWidth] = _strAuto;
_contentElement.css(css);
}
var contentElementScrollSize = {
w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength,
h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength
};
if (setCSS) {
css[_strFloat] = float;
css[_strWidth] = _strHundredPercent;
_contentElement.css(css);
}
bodyMinSizeC = bodyMinSizeChanged();
changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY);
_contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
_viewportScrollSizeCache = viewportScrollSize;
return changed || bodyMinSizeC || viewportScrollSizeChanged;
} | javascript | function updateAutoContentSizeChanged() {
if (_isSleeping)
return false;
var float;
var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
var viewportScrollSize = { };
var css = { };
var bodyMinSizeC;
var changed;
var viewportScrollSizeChanged;
//fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true"
//it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring
if(_restrictedMeasuring) {
viewportScrollSize = {
x : _viewportElementNative[LEXICON.sW],
y : _viewportElementNative[LEXICON.sH]
}
}
if (setCSS) {
float = _contentElement.css(_strFloat);
css[_strFloat] = _isRTL ? _strRight : _strLeft;
css[_strWidth] = _strAuto;
_contentElement.css(css);
}
var contentElementScrollSize = {
w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength,
h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength
};
if (setCSS) {
css[_strFloat] = float;
css[_strWidth] = _strHundredPercent;
_contentElement.css(css);
}
bodyMinSizeC = bodyMinSizeChanged();
changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY);
_contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
_viewportScrollSizeCache = viewportScrollSize;
return changed || bodyMinSizeC || viewportScrollSizeChanged;
} | [
"function",
"updateAutoContentSizeChanged",
"(",
")",
"{",
"if",
"(",
"_isSleeping",
")",
"return",
"false",
";",
"var",
"float",
";",
"var",
"textareaValueLength",
"=",
"_isTextarea",
"&&",
"_widthAutoCache",
"&&",
"!",
"_textareaAutoWrappingCache",
"?",
"_targetEl... | Returns true if the content size was changed since the last time this method was called.
@returns {boolean} True if the content size was changed, false otherwise. | [
"Returns",
"true",
"if",
"the",
"content",
"size",
"was",
"changed",
"since",
"the",
"last",
"time",
"this",
"method",
"was",
"called",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2829-L2874 |
10,011 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | isSizeAffectingCSSProperty | function isSizeAffectingCSSProperty(propertyName) {
if (!_initialized)
return true;
var flexGrow = 'flex-grow';
var flexShrink = 'flex-shrink';
var flexBasis = 'flex-basis';
var affectingPropsX = [
_strWidth,
_strMinMinus + _strWidth,
_strMaxMinus + _strWidth,
_strMarginMinus + _strLeft,
_strMarginMinus + _strRight,
_strLeft,
_strRight,
'font-weight',
'word-spacing',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsXContentBox = [
_strPaddingMinus + _strLeft,
_strPaddingMinus + _strRight,
_strBorderMinus + _strLeft + _strWidth,
_strBorderMinus + _strRight + _strWidth
];
var affectingPropsY = [
_strHeight,
_strMinMinus + _strHeight,
_strMaxMinus + _strHeight,
_strMarginMinus + _strTop,
_strMarginMinus + _strBottom,
_strTop,
_strBottom,
'line-height',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsYContentBox = [
_strPaddingMinus + _strTop,
_strPaddingMinus + _strBottom,
_strBorderMinus + _strTop + _strWidth,
_strBorderMinus + _strBottom + _strWidth
];
var _strS = 's';
var _strVS = 'v-s';
var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
var sizeIsAffected = false;
var checkPropertyName = function (arr, name) {
for (var i = 0; i < arr[LEXICON.l]; i++) {
if (arr[i] === name)
return true;
}
return false;
};
if (checkY) {
sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
}
if (checkX && !sizeIsAffected) {
sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
}
return sizeIsAffected;
} | javascript | function isSizeAffectingCSSProperty(propertyName) {
if (!_initialized)
return true;
var flexGrow = 'flex-grow';
var flexShrink = 'flex-shrink';
var flexBasis = 'flex-basis';
var affectingPropsX = [
_strWidth,
_strMinMinus + _strWidth,
_strMaxMinus + _strWidth,
_strMarginMinus + _strLeft,
_strMarginMinus + _strRight,
_strLeft,
_strRight,
'font-weight',
'word-spacing',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsXContentBox = [
_strPaddingMinus + _strLeft,
_strPaddingMinus + _strRight,
_strBorderMinus + _strLeft + _strWidth,
_strBorderMinus + _strRight + _strWidth
];
var affectingPropsY = [
_strHeight,
_strMinMinus + _strHeight,
_strMaxMinus + _strHeight,
_strMarginMinus + _strTop,
_strMarginMinus + _strBottom,
_strTop,
_strBottom,
'line-height',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsYContentBox = [
_strPaddingMinus + _strTop,
_strPaddingMinus + _strBottom,
_strBorderMinus + _strTop + _strWidth,
_strBorderMinus + _strBottom + _strWidth
];
var _strS = 's';
var _strVS = 'v-s';
var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
var sizeIsAffected = false;
var checkPropertyName = function (arr, name) {
for (var i = 0; i < arr[LEXICON.l]; i++) {
if (arr[i] === name)
return true;
}
return false;
};
if (checkY) {
sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
}
if (checkX && !sizeIsAffected) {
sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
}
return sizeIsAffected;
} | [
"function",
"isSizeAffectingCSSProperty",
"(",
"propertyName",
")",
"{",
"if",
"(",
"!",
"_initialized",
")",
"return",
"true",
";",
"var",
"flexGrow",
"=",
"'flex-grow'",
";",
"var",
"flexShrink",
"=",
"'flex-shrink'",
";",
"var",
"flexBasis",
"=",
"'flex-basis... | Checks is a CSS Property of a child element is affecting the scroll size of the content.
@param propertyName The CSS property name.
@returns {boolean} True if the property is affecting the content scroll size, false otherwise. | [
"Checks",
"is",
"a",
"CSS",
"Property",
"of",
"a",
"child",
"element",
"is",
"affecting",
"the",
"scroll",
"size",
"of",
"the",
"content",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L2917-L2986 |
10,012 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | refreshScrollbarAppearance | function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
if (shallBeVisible)
removeClass(_hostElement, scrollbarClassName);
else
addClass(_hostElement, scrollbarClassName);
if (canScroll)
removeClass(scrollbarElement, _classNameScrollbarUnusable);
else
addClass(scrollbarElement, _classNameScrollbarUnusable);
} | javascript | function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
if (shallBeVisible)
removeClass(_hostElement, scrollbarClassName);
else
addClass(_hostElement, scrollbarClassName);
if (canScroll)
removeClass(scrollbarElement, _classNameScrollbarUnusable);
else
addClass(scrollbarElement, _classNameScrollbarUnusable);
} | [
"function",
"refreshScrollbarAppearance",
"(",
"isHorizontal",
",",
"shallBeVisible",
",",
"canScroll",
")",
"{",
"var",
"scrollbarClassName",
"=",
"isHorizontal",
"?",
"_classNameHostScrollbarHorizontalHidden",
":",
"_classNameHostScrollbarVerticalHidden",
";",
"var",
"scrol... | Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not.
@param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target.
@param shallBeVisible True if the scrollbar shall be shown, false if hidden.
@param canScroll True if the scrollbar is scrollable, false otherwise. | [
"Shows",
"or",
"hides",
"the",
"given",
"scrollbar",
"and",
"applied",
"a",
"class",
"name",
"which",
"indicates",
"if",
"the",
"scrollbar",
"is",
"scrollable",
"or",
"not",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L4698-L4711 |
10,013 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | refreshScrollbarHandleLength | function refreshScrollbarHandleLength(isHorizontal) {
var handleCSS = {};
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var digit = 1000000;
//get and apply intended handle length
var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]);
handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit
if (!nativeOverlayScrollbarsAreActive())
scrollbarVars._handle.css(handleCSS);
//measure the handle length to respect min & max length
scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
scrollbarVarsInfo._handleLengthRatio = handleRatio;
} | javascript | function refreshScrollbarHandleLength(isHorizontal) {
var handleCSS = {};
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var digit = 1000000;
//get and apply intended handle length
var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]);
handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit
if (!nativeOverlayScrollbarsAreActive())
scrollbarVars._handle.css(handleCSS);
//measure the handle length to respect min & max length
scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
scrollbarVarsInfo._handleLengthRatio = handleRatio;
} | [
"function",
"refreshScrollbarHandleLength",
"(",
"isHorizontal",
")",
"{",
"var",
"handleCSS",
"=",
"{",
"}",
";",
"var",
"scrollbarVars",
"=",
"getScrollbarVars",
"(",
"isHorizontal",
")",
";",
"var",
"scrollbarVarsInfo",
"=",
"scrollbarVars",
".",
"_info",
";",
... | Refreshes the handle length of the given scrollbar.
@param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. | [
"Refreshes",
"the",
"handle",
"length",
"of",
"the",
"given",
"scrollbar",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L4749-L4764 |
10,014 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | refreshScrollbarsInteractive | function refreshScrollbarsInteractive(isTrack, value) {
var action = value ? 'removeClass' : 'addClass';
var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
element1[action](className);
element2[action](className);
} | javascript | function refreshScrollbarsInteractive(isTrack, value) {
var action = value ? 'removeClass' : 'addClass';
var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
element1[action](className);
element2[action](className);
} | [
"function",
"refreshScrollbarsInteractive",
"(",
"isTrack",
",",
"value",
")",
"{",
"var",
"action",
"=",
"value",
"?",
"'removeClass'",
":",
"'addClass'",
";",
"var",
"element1",
"=",
"isTrack",
"?",
"_scrollbarHorizontalTrackElement",
":",
"_scrollbarHorizontalHandl... | Refreshes the interactivity of the given scrollbar element.
@param isTrack True if the track element is the target, false if the handle element is the target.
@param value True for interactivity false for no interactivity. | [
"Refreshes",
"the",
"interactivity",
"of",
"the",
"given",
"scrollbar",
"element",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L4852-L4860 |
10,015 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | getScrollbarVars | function getScrollbarVars(isHorizontal) {
return {
_width_height: isHorizontal ? _strWidth : _strHeight,
_Width_Height: isHorizontal ? 'Width' : 'Height',
_left_top: isHorizontal ? _strLeft : _strTop,
_Left_Top: isHorizontal ? 'Left' : 'Top',
_x_y: isHorizontal ? _strX : _strY,
_X_Y: isHorizontal ? 'X' : 'Y',
_w_h: isHorizontal ? 'w' : 'h',
_l_t: isHorizontal ? 'l' : 't',
_track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
_handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
_scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
_info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
};
} | javascript | function getScrollbarVars(isHorizontal) {
return {
_width_height: isHorizontal ? _strWidth : _strHeight,
_Width_Height: isHorizontal ? 'Width' : 'Height',
_left_top: isHorizontal ? _strLeft : _strTop,
_Left_Top: isHorizontal ? 'Left' : 'Top',
_x_y: isHorizontal ? _strX : _strY,
_X_Y: isHorizontal ? 'X' : 'Y',
_w_h: isHorizontal ? 'w' : 'h',
_l_t: isHorizontal ? 'l' : 't',
_track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
_handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
_scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
_info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
};
} | [
"function",
"getScrollbarVars",
"(",
"isHorizontal",
")",
"{",
"return",
"{",
"_width_height",
":",
"isHorizontal",
"?",
"_strWidth",
":",
"_strHeight",
",",
"_Width_Height",
":",
"isHorizontal",
"?",
"'Width'",
":",
"'Height'",
",",
"_left_top",
":",
"isHorizonta... | Returns a object which is used for fast access for specific variables.
@param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed.
@returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}} | [
"Returns",
"a",
"object",
"which",
"is",
"used",
"for",
"fast",
"access",
"for",
"specific",
"variables",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L4867-L4882 |
10,016 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | setupScrollbarCornerEvents | function setupScrollbarCornerEvents() {
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var mouseDownPosition = { };
var mouseDownSize = { };
var mouseDownInvertedScale = { };
_resizeOnMouseTouchDown = function(event) {
if (onMouseTouchDownContinue(event)) {
if (_mutationObserversConnected) {
_resizeReconnectMutationObserver = true;
disconnectMutationObservers();
}
mouseDownPosition = getCoordinates(event);
mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
mouseDownInvertedScale = getHostElementInvertedScale();
_documentElement.on(_strSelectStartEvent, documentOnSelectStart)
.on(_strMouseTouchMoveEvent, documentDragMove)
.on(_strMouseTouchUpEvent, documentMouseTouchUp);
addClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.setCapture)
_scrollbarCornerElement.setCapture();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
};
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var pageOffset = getCoordinates(event);
var hostElementCSS = { };
if (_resizeHorizontal || _resizeBoth)
hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
if (_resizeVertical || _resizeBoth)
hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
_hostElement.css(hostElementCSS);
COMPATIBILITY.stpP(event);
}
else {
documentMouseTouchUp(event);
}
}
function documentMouseTouchUp(event) {
var eventIsTrusted = event !== undefined;
_documentElement.off(_strSelectStartEvent, documentOnSelectStart)
.off(_strMouseTouchMoveEvent, documentDragMove)
.off(_strMouseTouchUpEvent, documentMouseTouchUp);
removeClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.releaseCapture)
_scrollbarCornerElement.releaseCapture();
if (eventIsTrusted) {
if (_resizeReconnectMutationObserver)
connectMutationObservers();
_base.update(_strAuto);
}
_resizeReconnectMutationObserver = false;
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function getCoordinates(event) {
return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event);
}
} | javascript | function setupScrollbarCornerEvents() {
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var mouseDownPosition = { };
var mouseDownSize = { };
var mouseDownInvertedScale = { };
_resizeOnMouseTouchDown = function(event) {
if (onMouseTouchDownContinue(event)) {
if (_mutationObserversConnected) {
_resizeReconnectMutationObserver = true;
disconnectMutationObservers();
}
mouseDownPosition = getCoordinates(event);
mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
mouseDownInvertedScale = getHostElementInvertedScale();
_documentElement.on(_strSelectStartEvent, documentOnSelectStart)
.on(_strMouseTouchMoveEvent, documentDragMove)
.on(_strMouseTouchUpEvent, documentMouseTouchUp);
addClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.setCapture)
_scrollbarCornerElement.setCapture();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
};
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var pageOffset = getCoordinates(event);
var hostElementCSS = { };
if (_resizeHorizontal || _resizeBoth)
hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
if (_resizeVertical || _resizeBoth)
hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
_hostElement.css(hostElementCSS);
COMPATIBILITY.stpP(event);
}
else {
documentMouseTouchUp(event);
}
}
function documentMouseTouchUp(event) {
var eventIsTrusted = event !== undefined;
_documentElement.off(_strSelectStartEvent, documentOnSelectStart)
.off(_strMouseTouchMoveEvent, documentDragMove)
.off(_strMouseTouchUpEvent, documentMouseTouchUp);
removeClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.releaseCapture)
_scrollbarCornerElement.releaseCapture();
if (eventIsTrusted) {
if (_resizeReconnectMutationObserver)
connectMutationObservers();
_base.update(_strAuto);
}
_resizeReconnectMutationObserver = false;
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function getCoordinates(event) {
return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event);
}
} | [
"function",
"setupScrollbarCornerEvents",
"(",
")",
"{",
"var",
"insideIFrame",
"=",
"_windowElementNative",
".",
"top",
"!==",
"_windowElementNative",
";",
"var",
"mouseDownPosition",
"=",
"{",
"}",
";",
"var",
"mouseDownSize",
"=",
"{",
"}",
";",
"var",
"mouse... | Initializes all scrollbar corner interactivity events. | [
"Initializes",
"all",
"scrollbar",
"corner",
"interactivity",
"events",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L4904-L4976 |
10,017 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | setTopRightBottomLeft | function setTopRightBottomLeft(targetCSSObject, prefix, values) {
if (values === undefined)
values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
targetCSSObject[prefix + _strTop] = values[0];
targetCSSObject[prefix + _strRight] = values[1];
targetCSSObject[prefix + _strBottom] = values[2];
targetCSSObject[prefix + _strLeft] = values[3];
} | javascript | function setTopRightBottomLeft(targetCSSObject, prefix, values) {
if (values === undefined)
values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
targetCSSObject[prefix + _strTop] = values[0];
targetCSSObject[prefix + _strRight] = values[1];
targetCSSObject[prefix + _strBottom] = values[2];
targetCSSObject[prefix + _strLeft] = values[3];
} | [
"function",
"setTopRightBottomLeft",
"(",
"targetCSSObject",
",",
"prefix",
",",
"values",
")",
"{",
"if",
"(",
"values",
"===",
"undefined",
")",
"values",
"=",
"[",
"_strEmpty",
",",
"_strEmpty",
",",
"_strEmpty",
",",
"_strEmpty",
"]",
";",
"targetCSSObject... | Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object.
@param targetCSSObject The css object to which the values shall be applied.
@param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
@param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left].
If this argument is undefined the value '' (empty string) will be applied to all properties. | [
"Sets",
"the",
"top",
"right",
"bottom",
"left",
"properties",
"with",
"a",
"given",
"prefix",
"of",
"the",
"given",
"css",
"object",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5015-L5023 |
10,018 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | getCSSTransitionString | function getCSSTransitionString(element) {
var transitionStr = VENDORS._cssProperty('transition');
var assembledValue = element.css(transitionStr);
if(assembledValue)
return assembledValue;
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
var regExpMain = new RegExp(regExpString);
var regExpValidate = new RegExp('^(' + regExpString + ')+$');
var properties = 'property duration timing-function delay'.split(' ');
var result = [ ];
var strResult;
var valueArray;
var i = 0;
var j;
var splitCssStyleByComma = function(str) {
strResult = [ ];
if (!str.match(regExpValidate))
return str;
while (str.match(regExpMain)) {
strResult.push(RegExp.$1);
str = str.replace(regExpMain, _strEmpty);
}
return strResult;
};
for (; i < properties[LEXICON.l]; i++) {
valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
for (j = 0; j < valueArray[LEXICON.l]; j++)
result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
}
return result.join(', ');
} | javascript | function getCSSTransitionString(element) {
var transitionStr = VENDORS._cssProperty('transition');
var assembledValue = element.css(transitionStr);
if(assembledValue)
return assembledValue;
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
var regExpMain = new RegExp(regExpString);
var regExpValidate = new RegExp('^(' + regExpString + ')+$');
var properties = 'property duration timing-function delay'.split(' ');
var result = [ ];
var strResult;
var valueArray;
var i = 0;
var j;
var splitCssStyleByComma = function(str) {
strResult = [ ];
if (!str.match(regExpValidate))
return str;
while (str.match(regExpMain)) {
strResult.push(RegExp.$1);
str = str.replace(regExpMain, _strEmpty);
}
return strResult;
};
for (; i < properties[LEXICON.l]; i++) {
valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
for (j = 0; j < valueArray[LEXICON.l]; j++)
result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
}
return result.join(', ');
} | [
"function",
"getCSSTransitionString",
"(",
"element",
")",
"{",
"var",
"transitionStr",
"=",
"VENDORS",
".",
"_cssProperty",
"(",
"'transition'",
")",
";",
"var",
"assembledValue",
"=",
"element",
".",
"css",
"(",
"transitionStr",
")",
";",
"if",
"(",
"assembl... | Returns the computed CSS transition string from the given element.
@param element The element from which the transition string shall be returned.
@returns {string} The CSS transition string from the given element. | [
"Returns",
"the",
"computed",
"CSS",
"transition",
"string",
"from",
"the",
"given",
"element",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5030-L5061 |
10,019 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | isHTMLElement | function isHTMLElement(o) {
var strOwnerDocument = 'ownerDocument';
var strHTMLElement = 'HTMLElement';
var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
return (
typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
);
} | javascript | function isHTMLElement(o) {
var strOwnerDocument = 'ownerDocument';
var strHTMLElement = 'HTMLElement';
var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
return (
typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
);
} | [
"function",
"isHTMLElement",
"(",
"o",
")",
"{",
"var",
"strOwnerDocument",
"=",
"'ownerDocument'",
";",
"var",
"strHTMLElement",
"=",
"'HTMLElement'",
";",
"var",
"wnd",
"=",
"o",
"&&",
"o",
"[",
"strOwnerDocument",
"]",
"?",
"(",
"o",
"[",
"strOwnerDocumen... | Checks whether the given object is a HTMLElement.
@param o The object which shall be checked.
@returns {boolean} True the given object is a HTMLElement, false otherwise. | [
"Checks",
"whether",
"the",
"given",
"object",
"is",
"a",
"HTMLElement",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5080-L5088 |
10,020 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | getArrayDifferences | function getArrayDifferences(a1, a2) {
var a = [ ];
var diff = [ ];
var i;
var k;
for (i = 0; i < a1.length; i++)
a[a1[i]] = true;
for (i = 0; i < a2.length; i++) {
if (a[a2[i]])
delete a[a2[i]];
else
a[a2[i]] = true;
}
for (k in a)
diff.push(k);
return diff;
} | javascript | function getArrayDifferences(a1, a2) {
var a = [ ];
var diff = [ ];
var i;
var k;
for (i = 0; i < a1.length; i++)
a[a1[i]] = true;
for (i = 0; i < a2.length; i++) {
if (a[a2[i]])
delete a[a2[i]];
else
a[a2[i]] = true;
}
for (k in a)
diff.push(k);
return diff;
} | [
"function",
"getArrayDifferences",
"(",
"a1",
",",
"a2",
")",
"{",
"var",
"a",
"=",
"[",
"]",
";",
"var",
"diff",
"=",
"[",
"]",
";",
"var",
"i",
";",
"var",
"k",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"a1",
".",
"length",
";",
"i",... | Compares 2 arrays and returns the differences between them as a array.
@param a1 The first array which shall be compared.
@param a2 The second array which shall be compared.
@returns {Array} The differences between the two arrays. | [
"Compares",
"2",
"arrays",
"and",
"returns",
"the",
"differences",
"between",
"them",
"as",
"a",
"array",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5096-L5112 |
10,021 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | parseToZeroOrNumber | function parseToZeroOrNumber(value, toFloat) {
var num = toFloat ? parseFloat(value) : parseInt(value, 10);
return isNaN(num) ? 0 : num;
} | javascript | function parseToZeroOrNumber(value, toFloat) {
var num = toFloat ? parseFloat(value) : parseInt(value, 10);
return isNaN(num) ? 0 : num;
} | [
"function",
"parseToZeroOrNumber",
"(",
"value",
",",
"toFloat",
")",
"{",
"var",
"num",
"=",
"toFloat",
"?",
"parseFloat",
"(",
"value",
")",
":",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"return",
"isNaN",
"(",
"num",
")",
"?",
"0",
":",
"num... | Returns Zero or the number to which the value can be parsed.
@param value The value which shall be parsed.
@param toFloat Indicates whether the number shall be parsed to a float. | [
"Returns",
"Zero",
"or",
"the",
"number",
"to",
"which",
"the",
"value",
"can",
"be",
"parsed",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5119-L5122 |
10,022 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | getTextareaInfo | function getTextareaInfo() {
//read needed values
var textareaCursorPosition = _targetElementNative.selectionStart;
if (textareaCursorPosition === undefined)
return;
var strLength = 'length';
var textareaValue = _targetElement.val();
var textareaLength = textareaValue[strLength];
var textareaRowSplit = textareaValue.split("\n");
var textareaLastRow = textareaRowSplit[strLength];
var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split("\n");
var widestRow = 0;
var textareaLastCol = 0;
var cursorRow = textareaCurrentCursorRowSplit[strLength];
var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[strLength] - 1][strLength];
var rowCols;
var i;
//get widest Row and the last column of the textarea
for (i = 0; i < textareaRowSplit[strLength]; i++) {
rowCols = textareaRowSplit[i][strLength];
if (rowCols > textareaLastCol) {
widestRow = i + 1;
textareaLastCol = rowCols;
}
}
return {
_cursorRow: cursorRow, //cursorRow
_cursorColumn: cursorCol, //cursorCol
_rows: textareaLastRow, //rows
_columns: textareaLastCol, //cols
_widestRow: widestRow, //wRow
_cursorPosition: textareaCursorPosition, //pos
_cursorMax: textareaLength //max
};
} | javascript | function getTextareaInfo() {
//read needed values
var textareaCursorPosition = _targetElementNative.selectionStart;
if (textareaCursorPosition === undefined)
return;
var strLength = 'length';
var textareaValue = _targetElement.val();
var textareaLength = textareaValue[strLength];
var textareaRowSplit = textareaValue.split("\n");
var textareaLastRow = textareaRowSplit[strLength];
var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split("\n");
var widestRow = 0;
var textareaLastCol = 0;
var cursorRow = textareaCurrentCursorRowSplit[strLength];
var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[strLength] - 1][strLength];
var rowCols;
var i;
//get widest Row and the last column of the textarea
for (i = 0; i < textareaRowSplit[strLength]; i++) {
rowCols = textareaRowSplit[i][strLength];
if (rowCols > textareaLastCol) {
widestRow = i + 1;
textareaLastCol = rowCols;
}
}
return {
_cursorRow: cursorRow, //cursorRow
_cursorColumn: cursorCol, //cursorCol
_rows: textareaLastRow, //rows
_columns: textareaLastCol, //cols
_widestRow: widestRow, //wRow
_cursorPosition: textareaCursorPosition, //pos
_cursorMax: textareaLength //max
};
} | [
"function",
"getTextareaInfo",
"(",
")",
"{",
"//read needed values",
"var",
"textareaCursorPosition",
"=",
"_targetElementNative",
".",
"selectionStart",
";",
"if",
"(",
"textareaCursorPosition",
"===",
"undefined",
")",
"return",
";",
"var",
"strLength",
"=",
"'leng... | Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it.
@returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported. | [
"Gets",
"several",
"information",
"of",
"the",
"textarea",
"and",
"returns",
"them",
"as",
"a",
"object",
"or",
"undefined",
"if",
"the",
"browser",
"doesn",
"t",
"support",
"it",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5128-L5165 |
10,023 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | generateDiv | function generateDiv(classesOrAttrs, content) {
return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ?
'class="' + classesOrAttrs + '"' :
(function() {
var key;
var attrs = '';
if(FRAMEWORK.isPlainObject(classesOrAttrs)) {
for (key in classesOrAttrs)
attrs += (key === 'className' ? 'class' : key) + '="' + classesOrAttrs[key] + '" ';
}
return attrs;
})() :
_strEmpty) +
'>' +
(content ? content : _strEmpty) +
'</div>';
} | javascript | function generateDiv(classesOrAttrs, content) {
return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ?
'class="' + classesOrAttrs + '"' :
(function() {
var key;
var attrs = '';
if(FRAMEWORK.isPlainObject(classesOrAttrs)) {
for (key in classesOrAttrs)
attrs += (key === 'className' ? 'class' : key) + '="' + classesOrAttrs[key] + '" ';
}
return attrs;
})() :
_strEmpty) +
'>' +
(content ? content : _strEmpty) +
'</div>';
} | [
"function",
"generateDiv",
"(",
"classesOrAttrs",
",",
"content",
")",
"{",
"return",
"'<div '",
"+",
"(",
"classesOrAttrs",
"?",
"type",
"(",
"classesOrAttrs",
")",
"==",
"TYPES",
".",
"s",
"?",
"'class=\"'",
"+",
"classesOrAttrs",
"+",
"'\"'",
":",
"(",
... | Generates a string which represents a HTML div with the given classes or attributes.
@param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".)
@param content The content of the div as string.
@returns {string} The concated string which represents a HTML div and its content. | [
"Generates",
"a",
"string",
"which",
"represents",
"a",
"HTML",
"div",
"with",
"the",
"given",
"classes",
"or",
"attributes",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5189-L5205 |
10,024 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | getObjectPropVal | function getObjectPropVal(obj, path) {
var splits = path.split(_strDot);
var i = 0;
var val;
for(; i < splits.length; i++) {
if(!obj.hasOwnProperty(splits[i]))
return;
val = obj[splits[i]];
if(i < splits.length && type(val) == TYPES.o)
obj = val;
}
return val;
} | javascript | function getObjectPropVal(obj, path) {
var splits = path.split(_strDot);
var i = 0;
var val;
for(; i < splits.length; i++) {
if(!obj.hasOwnProperty(splits[i]))
return;
val = obj[splits[i]];
if(i < splits.length && type(val) == TYPES.o)
obj = val;
}
return val;
} | [
"function",
"getObjectPropVal",
"(",
"obj",
",",
"path",
")",
"{",
"var",
"splits",
"=",
"path",
".",
"split",
"(",
"_strDot",
")",
";",
"var",
"i",
"=",
"0",
";",
"var",
"val",
";",
"for",
"(",
";",
"i",
"<",
"splits",
".",
"length",
";",
"i",
... | Gets the value of the given property from the given object.
@param obj The object from which the property value shall be got.
@param path The property of which the value shall be got.
@returns {*} Returns the value of the searched property or undefined of the property wasn't found. | [
"Gets",
"the",
"value",
"of",
"the",
"given",
"property",
"from",
"the",
"given",
"object",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5213-L5225 |
10,025 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | setObjectPropVal | function setObjectPropVal(obj, path, val) {
var splits = path.split(_strDot);
var splitsLength = splits.length;
var i = 0;
var extendObj = { };
var extendObjRoot = extendObj;
for(; i < splitsLength; i++)
extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? { } : val;
FRAMEWORK.extend(obj, extendObjRoot, true);
} | javascript | function setObjectPropVal(obj, path, val) {
var splits = path.split(_strDot);
var splitsLength = splits.length;
var i = 0;
var extendObj = { };
var extendObjRoot = extendObj;
for(; i < splitsLength; i++)
extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? { } : val;
FRAMEWORK.extend(obj, extendObjRoot, true);
} | [
"function",
"setObjectPropVal",
"(",
"obj",
",",
"path",
",",
"val",
")",
"{",
"var",
"splits",
"=",
"path",
".",
"split",
"(",
"_strDot",
")",
";",
"var",
"splitsLength",
"=",
"splits",
".",
"length",
";",
"var",
"i",
"=",
"0",
";",
"var",
"extendOb... | Sets the value of the given property from the given object.
@param obj The object from which the property value shall be set.
@param path The property of which the value shall be set.
@param val The value of the property which shall be set. | [
"Sets",
"the",
"value",
"of",
"the",
"given",
"property",
"from",
"the",
"given",
"object",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5233-L5242 |
10,026 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | checkCacheDouble | function checkCacheDouble(current, cache, prop1, prop2, force) {
if (force === true)
return force;
if (prop2 === undefined && force === undefined) {
if (prop1 === true)
return prop1;
else
prop1 = undefined;
}
prop1 = prop1 === undefined ? 'w' : prop1;
prop2 = prop2 === undefined ? 'h' : prop2;
if (cache === undefined)
return true;
else if (current[prop1] !== cache[prop1] || current[prop2] !== cache[prop2])
return true;
return false;
} | javascript | function checkCacheDouble(current, cache, prop1, prop2, force) {
if (force === true)
return force;
if (prop2 === undefined && force === undefined) {
if (prop1 === true)
return prop1;
else
prop1 = undefined;
}
prop1 = prop1 === undefined ? 'w' : prop1;
prop2 = prop2 === undefined ? 'h' : prop2;
if (cache === undefined)
return true;
else if (current[prop1] !== cache[prop1] || current[prop2] !== cache[prop2])
return true;
return false;
} | [
"function",
"checkCacheDouble",
"(",
"current",
",",
"cache",
",",
"prop1",
",",
"prop2",
",",
"force",
")",
"{",
"if",
"(",
"force",
"===",
"true",
")",
"return",
"force",
";",
"if",
"(",
"prop2",
"===",
"undefined",
"&&",
"force",
"===",
"undefined",
... | Compares two objects with two properties and returns the result of the comparison as a boolean.
@param current The first object which shall be compared.
@param cache The second object which shall be compared.
@param prop1 The name of the first property of the objects which shall be compared.
@param prop2 The name of the second property of the objects which shall be compared.
@param force If true the returned value is always true.
@returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. | [
"Compares",
"two",
"objects",
"with",
"two",
"properties",
"and",
"returns",
"the",
"result",
"of",
"the",
"comparison",
"as",
"a",
"boolean",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5273-L5289 |
10,027 | KingSora/OverlayScrollbars | js/OverlayScrollbars.js | checkCacheTRBL | function checkCacheTRBL(current, cache) {
if (cache === undefined)
return true;
else if (current.t !== cache.t ||
current.r !== cache.r ||
current.b !== cache.b ||
current.l !== cache.l)
return true;
return false;
} | javascript | function checkCacheTRBL(current, cache) {
if (cache === undefined)
return true;
else if (current.t !== cache.t ||
current.r !== cache.r ||
current.b !== cache.b ||
current.l !== cache.l)
return true;
return false;
} | [
"function",
"checkCacheTRBL",
"(",
"current",
",",
"cache",
")",
"{",
"if",
"(",
"cache",
"===",
"undefined",
")",
"return",
"true",
";",
"else",
"if",
"(",
"current",
".",
"t",
"!==",
"cache",
".",
"t",
"||",
"current",
".",
"r",
"!==",
"cache",
"."... | Compares two objects which have four properties and returns the result of the comparison as a boolean.
@param current The first object with four properties.
@param cache The second object with four properties.
@returns {boolean} True if both objects aren't equal or some of them is undefined, false otherwise. | [
"Compares",
"two",
"objects",
"which",
"have",
"four",
"properties",
"and",
"returns",
"the",
"result",
"of",
"the",
"comparison",
"as",
"a",
"boolean",
"."
] | 8e658d46e2d034a2525269d7c873bbe844762307 | https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L5297-L5306 |
10,028 | ipfs/aegir | src/release/prerelease.js | validGh | function validGh (opts) {
if (!opts.ghrelease) {
return Promise.resolve(true)
}
if (!opts.ghtoken) {
return Promise.reject(new Error('Missing GitHub access token. ' +
'Have you set `AEGIR_GHTOKEN`?'))
}
return Promise.resolve()
} | javascript | function validGh (opts) {
if (!opts.ghrelease) {
return Promise.resolve(true)
}
if (!opts.ghtoken) {
return Promise.reject(new Error('Missing GitHub access token. ' +
'Have you set `AEGIR_GHTOKEN`?'))
}
return Promise.resolve()
} | [
"function",
"validGh",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"ghrelease",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"true",
")",
"}",
"if",
"(",
"!",
"opts",
".",
"ghtoken",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",... | Check if there are valid GitHub credentials for publishing this module | [
"Check",
"if",
"there",
"are",
"valid",
"GitHub",
"credentials",
"for",
"publishing",
"this",
"module"
] | 1cb8cf217bc03524f7f2caaa248b1b99d700d402 | https://github.com/ipfs/aegir/blob/1cb8cf217bc03524f7f2caaa248b1b99d700d402/src/release/prerelease.js#L7-L17 |
10,029 | ipfs/aegir | src/release/prerelease.js | isDirty | function isDirty () {
return pify(git.raw.bind(git))(['status', '-s'])
.then((out) => {
if (out && out.trim().length > 0) {
throw new Error('Dirty git repo, aborting')
}
})
} | javascript | function isDirty () {
return pify(git.raw.bind(git))(['status', '-s'])
.then((out) => {
if (out && out.trim().length > 0) {
throw new Error('Dirty git repo, aborting')
}
})
} | [
"function",
"isDirty",
"(",
")",
"{",
"return",
"pify",
"(",
"git",
".",
"raw",
".",
"bind",
"(",
"git",
")",
")",
"(",
"[",
"'status'",
",",
"'-s'",
"]",
")",
".",
"then",
"(",
"(",
"out",
")",
"=>",
"{",
"if",
"(",
"out",
"&&",
"out",
".",
... | Is the current git workspace dirty? | [
"Is",
"the",
"current",
"git",
"workspace",
"dirty?"
] | 1cb8cf217bc03524f7f2caaa248b1b99d700d402 | https://github.com/ipfs/aegir/blob/1cb8cf217bc03524f7f2caaa248b1b99d700d402/src/release/prerelease.js#L20-L27 |
10,030 | snowflakedb/snowflake-connector-nodejs | lib/agent/socket_util.js | isOcspValidationDisabled | function isOcspValidationDisabled(host)
{
// ocsp is disabled if insecure-connect is enabled, or if we've disabled ocsp
// for non-snowflake endpoints and the host is a non-snowflake endpoint
return GlobalConfig.isInsecureConnect() || (Parameters.getValue(
Parameters.names.JS_DRIVER_DISABLE_OCSP_FOR_NON_SF_ENDPOINTS) &&
!REGEX_SNOWFLAKE_ENDPOINT.test(host));
} | javascript | function isOcspValidationDisabled(host)
{
// ocsp is disabled if insecure-connect is enabled, or if we've disabled ocsp
// for non-snowflake endpoints and the host is a non-snowflake endpoint
return GlobalConfig.isInsecureConnect() || (Parameters.getValue(
Parameters.names.JS_DRIVER_DISABLE_OCSP_FOR_NON_SF_ENDPOINTS) &&
!REGEX_SNOWFLAKE_ENDPOINT.test(host));
} | [
"function",
"isOcspValidationDisabled",
"(",
"host",
")",
"{",
"// ocsp is disabled if insecure-connect is enabled, or if we've disabled ocsp",
"// for non-snowflake endpoints and the host is a non-snowflake endpoint",
"return",
"GlobalConfig",
".",
"isInsecureConnect",
"(",
")",
"||",
... | Determines if ocsp validation is disabled for a given host.
@param {String} host
@returns {boolean} | [
"Determines",
"if",
"ocsp",
"validation",
"is",
"disabled",
"for",
"a",
"given",
"host",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/agent/socket_util.js#L82-L89 |
10,031 | snowflakedb/snowflake-connector-nodejs | lib/agent/socket_util.js | validateCertChain | function validateCertChain(cert, cb)
{
// walk up the certificate chain and collect all the certificates in an array
var certs = [];
while (cert && cert.issuerCertificate &&
(cert.fingerprint !== cert.issuerCertificate.fingerprint))
{
certs.push(cert);
cert = cert.issuerCertificate;
}
// create an array to store any errors encountered
// while validating the certificate chain
var errors = new Array(certs.length);
/**
* Called for every certificate as we traverse the certificate chain and
* validate each one.
*
* @param certs
* @param index
*/
var eachCallback = function(certs, index)
{
var cert = certs[index];
validateCert(cert, function(err, data)
{
completed++;
errors[index] = err;
// if we have an ocsp response, cache it
if (data)
{
getOcspResponseCache().set(cert, data);
}
// if this is the last request to complete
if (completed === certs.length)
{
// if we saw one or more errors, invoke the callback with the first
// error we saw; otherwise invoke the callback without any error
for (var errorIndex = 0, length = errors.length;
errorIndex < length; errorIndex++)
{
var error = errors[errorIndex];
if (error)
{
break;
}
}
cb(error);
}
});
};
// fire off requests to validate all the certificates in the chain
var completed = 0;
for (var index = 0, length = certs.length; index < length; index++)
{
eachCallback(certs, index);
}
} | javascript | function validateCertChain(cert, cb)
{
// walk up the certificate chain and collect all the certificates in an array
var certs = [];
while (cert && cert.issuerCertificate &&
(cert.fingerprint !== cert.issuerCertificate.fingerprint))
{
certs.push(cert);
cert = cert.issuerCertificate;
}
// create an array to store any errors encountered
// while validating the certificate chain
var errors = new Array(certs.length);
/**
* Called for every certificate as we traverse the certificate chain and
* validate each one.
*
* @param certs
* @param index
*/
var eachCallback = function(certs, index)
{
var cert = certs[index];
validateCert(cert, function(err, data)
{
completed++;
errors[index] = err;
// if we have an ocsp response, cache it
if (data)
{
getOcspResponseCache().set(cert, data);
}
// if this is the last request to complete
if (completed === certs.length)
{
// if we saw one or more errors, invoke the callback with the first
// error we saw; otherwise invoke the callback without any error
for (var errorIndex = 0, length = errors.length;
errorIndex < length; errorIndex++)
{
var error = errors[errorIndex];
if (error)
{
break;
}
}
cb(error);
}
});
};
// fire off requests to validate all the certificates in the chain
var completed = 0;
for (var index = 0, length = certs.length; index < length; index++)
{
eachCallback(certs, index);
}
} | [
"function",
"validateCertChain",
"(",
"cert",
",",
"cb",
")",
"{",
"// walk up the certificate chain and collect all the certificates in an array",
"var",
"certs",
"=",
"[",
"]",
";",
"while",
"(",
"cert",
"&&",
"cert",
".",
"issuerCertificate",
"&&",
"(",
"cert",
"... | Validates a certificate chain using OCSP.
@param {Object} cert a top-level cert that represents the leaf of a
certificate chain.
@param {Function} cb the callback to invoke once the validation is complete. | [
"Validates",
"a",
"certificate",
"chain",
"using",
"OCSP",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/agent/socket_util.js#L118-L179 |
10,032 | snowflakedb/snowflake-connector-nodejs | lib/agent/socket_util.js | function(certs, index)
{
var cert = certs[index];
validateCert(cert, function(err, data)
{
completed++;
errors[index] = err;
// if we have an ocsp response, cache it
if (data)
{
getOcspResponseCache().set(cert, data);
}
// if this is the last request to complete
if (completed === certs.length)
{
// if we saw one or more errors, invoke the callback with the first
// error we saw; otherwise invoke the callback without any error
for (var errorIndex = 0, length = errors.length;
errorIndex < length; errorIndex++)
{
var error = errors[errorIndex];
if (error)
{
break;
}
}
cb(error);
}
});
} | javascript | function(certs, index)
{
var cert = certs[index];
validateCert(cert, function(err, data)
{
completed++;
errors[index] = err;
// if we have an ocsp response, cache it
if (data)
{
getOcspResponseCache().set(cert, data);
}
// if this is the last request to complete
if (completed === certs.length)
{
// if we saw one or more errors, invoke the callback with the first
// error we saw; otherwise invoke the callback without any error
for (var errorIndex = 0, length = errors.length;
errorIndex < length; errorIndex++)
{
var error = errors[errorIndex];
if (error)
{
break;
}
}
cb(error);
}
});
} | [
"function",
"(",
"certs",
",",
"index",
")",
"{",
"var",
"cert",
"=",
"certs",
"[",
"index",
"]",
";",
"validateCert",
"(",
"cert",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"completed",
"++",
";",
"errors",
"[",
"index",
"]",
"=",
"err",... | Called for every certificate as we traverse the certificate chain and
validate each one.
@param certs
@param index | [
"Called",
"for",
"every",
"certificate",
"as",
"we",
"traverse",
"the",
"certificate",
"chain",
"and",
"validate",
"each",
"one",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/agent/socket_util.js#L140-L171 | |
10,033 | snowflakedb/snowflake-connector-nodejs | lib/agent/socket_util.js | validateCert | function validateCert(cert, cb)
{
// if we already have an entry in the cache, use it
var ocspResponse = getOcspResponseCache().get(cert);
if (ocspResponse)
{
process.nextTick(function()
{
Logger.getInstance().trace('Returning OCSP status for certificate %s ' +
'from cache', cert.serialNumber);
cb(null, ocspResponse);
});
}
else
{
try
{
var decoded = CertUtil.decode(cert);
}
catch(e)
{
process.nextTick(function()
{
cb(e);
});
}
// issue a request to get the ocsp status
check(decoded, cb);
}
} | javascript | function validateCert(cert, cb)
{
// if we already have an entry in the cache, use it
var ocspResponse = getOcspResponseCache().get(cert);
if (ocspResponse)
{
process.nextTick(function()
{
Logger.getInstance().trace('Returning OCSP status for certificate %s ' +
'from cache', cert.serialNumber);
cb(null, ocspResponse);
});
}
else
{
try
{
var decoded = CertUtil.decode(cert);
}
catch(e)
{
process.nextTick(function()
{
cb(e);
});
}
// issue a request to get the ocsp status
check(decoded, cb);
}
} | [
"function",
"validateCert",
"(",
"cert",
",",
"cb",
")",
"{",
"// if we already have an entry in the cache, use it",
"var",
"ocspResponse",
"=",
"getOcspResponseCache",
"(",
")",
".",
"get",
"(",
"cert",
")",
";",
"if",
"(",
"ocspResponse",
")",
"{",
"process",
... | Validates a certificate using OCSP.
@param cert the certificate to validate.
@param cb the callback to invoke once the validation is complete. | [
"Validates",
"a",
"certificate",
"using",
"OCSP",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/agent/socket_util.js#L187-L218 |
10,034 | snowflakedb/snowflake-connector-nodejs | lib/util.js | function (url, paramName, paramValue)
{
// if the specified url is valid
var urlAsObject = Url.parse(url);
if (urlAsObject)
{
// if the url already has query parameters, use '&' as the separator
// when appending the additional query parameter, otherwise use '?'
url += (urlAsObject.search ? '&' : '?') + paramName + '=' + paramValue;
}
return url;
} | javascript | function (url, paramName, paramValue)
{
// if the specified url is valid
var urlAsObject = Url.parse(url);
if (urlAsObject)
{
// if the url already has query parameters, use '&' as the separator
// when appending the additional query parameter, otherwise use '?'
url += (urlAsObject.search ? '&' : '?') + paramName + '=' + paramValue;
}
return url;
} | [
"function",
"(",
"url",
",",
"paramName",
",",
"paramValue",
")",
"{",
"// if the specified url is valid",
"var",
"urlAsObject",
"=",
"Url",
".",
"parse",
"(",
"url",
")",
";",
"if",
"(",
"urlAsObject",
")",
"{",
"// if the url already has query parameters, use '&' ... | Appends a query parameter to a url. If an invalid url is specified, an
exception is thrown.
@param {String} url
@param {String} paramName the name of the query parameter.
@param {String} paramValue the value of the query parameter.
@returns {String} | [
"Appends",
"a",
"query",
"parameter",
"to",
"a",
"url",
".",
"If",
"an",
"invalid",
"url",
"is",
"specified",
"an",
"exception",
"is",
"thrown",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/util.js#L319-L331 | |
10,035 | snowflakedb/snowflake-connector-nodejs | lib/logger/browser.js | Logger | function Logger(options)
{
/**
* The array to which all log messages will be added.
*
* @type {String[]}
*/
var buffer = [];
/**
* Logs a message at a given level.
*
* @param {String} levelTag the tag associated with the level at which to log
* the message.
* @param {String} message the message to log.
* @param {Number} bufferMaxLength the maximum size to which the message
* buffer can grow.
*/
var logMessage = function(levelTag, message, bufferMaxLength)
{
// add the log level tag (e.g. info, warn, etc.) to the front of the message
message = Util.format('%s: %s', levelTag, message);
// if the buffer is full, evict old messages
while (buffer.length >= bufferMaxLength)
{
buffer.shift();
}
// add the new message to the buffer
buffer.push(message);
};
// create an inner implementation to which all our methods will be forwarded
var common = Core.createLogger(options, logMessage);
/**
* Configures this logger.
*
* @param {Object} options
*/
this.configure = function(options)
{
common.configure(options);
};
/**
* Returns the current log level.
*
* @returns {Number}
*/
this.getLevel = function()
{
return common.getLevelNumber();
};
/**
* Logs a given message at the error level.
*
* @param {String} message
*/
this.error = function(message)
{
common.error.apply(common, arguments);
};
/**
* Logs a given message at the warning level.
*
* @param {String} message
*/
this.warn = function(message)
{
common.warn.apply(common, arguments);
};
/**
* Logs a given message at the info level.
*
* @param {String} message
*/
this.info = function(message)
{
common.info.apply(common, arguments);
};
/**
* Logs a given message at the debug level.
*
* @param {String} message
*/
this.debug = function(message)
{
common.debug.apply(common, arguments);
};
/**
* Logs a given message at the trace level.
*
* @param {String} message
*/
this.trace = function(message)
{
common.trace.apply(common, arguments);
};
/**
* Returns the log buffer.
*
* @returns {String[]}
*/
this.getLogBuffer = function()
{
// return a copy of the buffer array; calling slice() shallow-copies the
// original array, but that's sufficient in this case because the array
// contains strings
return buffer.slice();
};
} | javascript | function Logger(options)
{
/**
* The array to which all log messages will be added.
*
* @type {String[]}
*/
var buffer = [];
/**
* Logs a message at a given level.
*
* @param {String} levelTag the tag associated with the level at which to log
* the message.
* @param {String} message the message to log.
* @param {Number} bufferMaxLength the maximum size to which the message
* buffer can grow.
*/
var logMessage = function(levelTag, message, bufferMaxLength)
{
// add the log level tag (e.g. info, warn, etc.) to the front of the message
message = Util.format('%s: %s', levelTag, message);
// if the buffer is full, evict old messages
while (buffer.length >= bufferMaxLength)
{
buffer.shift();
}
// add the new message to the buffer
buffer.push(message);
};
// create an inner implementation to which all our methods will be forwarded
var common = Core.createLogger(options, logMessage);
/**
* Configures this logger.
*
* @param {Object} options
*/
this.configure = function(options)
{
common.configure(options);
};
/**
* Returns the current log level.
*
* @returns {Number}
*/
this.getLevel = function()
{
return common.getLevelNumber();
};
/**
* Logs a given message at the error level.
*
* @param {String} message
*/
this.error = function(message)
{
common.error.apply(common, arguments);
};
/**
* Logs a given message at the warning level.
*
* @param {String} message
*/
this.warn = function(message)
{
common.warn.apply(common, arguments);
};
/**
* Logs a given message at the info level.
*
* @param {String} message
*/
this.info = function(message)
{
common.info.apply(common, arguments);
};
/**
* Logs a given message at the debug level.
*
* @param {String} message
*/
this.debug = function(message)
{
common.debug.apply(common, arguments);
};
/**
* Logs a given message at the trace level.
*
* @param {String} message
*/
this.trace = function(message)
{
common.trace.apply(common, arguments);
};
/**
* Returns the log buffer.
*
* @returns {String[]}
*/
this.getLogBuffer = function()
{
// return a copy of the buffer array; calling slice() shallow-copies the
// original array, but that's sufficient in this case because the array
// contains strings
return buffer.slice();
};
} | [
"function",
"Logger",
"(",
"options",
")",
"{",
"/**\n * The array to which all log messages will be added.\n *\n * @type {String[]}\n */",
"var",
"buffer",
"=",
"[",
"]",
";",
"/**\n * Logs a message at a given level.\n *\n * @param {String} levelTag the tag associated with ... | Creates a new Logger instance for when we're running in the browser.
@param {Object} [options]
@constructor | [
"Creates",
"a",
"new",
"Logger",
"instance",
"for",
"when",
"we",
"re",
"running",
"in",
"the",
"browser",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/logger/browser.js#L15-L133 |
10,036 | snowflakedb/snowflake-connector-nodejs | lib/connection/connection_context.js | ConnectionContext | function ConnectionContext(connectionConfig, httpClient, config)
{
// validate input
Errors.assertInternal(Util.isObject(connectionConfig));
Errors.assertInternal(Util.isObject(httpClient));
// if a config object was specified, verify
// that it has all the information we need
var sfServiceConfig;
if (Util.exists(config))
{
Errors.assertInternal(Util.isObject(config));
Errors.assertInternal(Util.isObject(config.services));
Errors.assertInternal(Util.isObject(config.services.sf));
sfServiceConfig = config.services.sf;
}
// create a map that contains all the services we'll be using
var services =
{
sf: new SfService(connectionConfig, httpClient, sfServiceConfig),
largeResultSet: new LargeResultSetService(connectionConfig, httpClient)
};
/**
* Returns the ConnectionConfig for use by the connection.
*
* @returns {ConnectionConfig}
*/
this.getConnectionConfig = function()
{
return connectionConfig;
};
/**
* Returns a map that contains all the available services.
*
* @returns {Object}
*/
this.getServices = function()
{
return services;
};
/**
* Returns a configuration object that can be passed as an optional argument
* to the ConnectionContext constructor to create a new object that has the
* same state as this ConnectionContext instance.
*
* @returns {Object}
*/
this.getConfig = function()
{
return {
services:
{
sf: services.sf.getConfig()
}
};
};
} | javascript | function ConnectionContext(connectionConfig, httpClient, config)
{
// validate input
Errors.assertInternal(Util.isObject(connectionConfig));
Errors.assertInternal(Util.isObject(httpClient));
// if a config object was specified, verify
// that it has all the information we need
var sfServiceConfig;
if (Util.exists(config))
{
Errors.assertInternal(Util.isObject(config));
Errors.assertInternal(Util.isObject(config.services));
Errors.assertInternal(Util.isObject(config.services.sf));
sfServiceConfig = config.services.sf;
}
// create a map that contains all the services we'll be using
var services =
{
sf: new SfService(connectionConfig, httpClient, sfServiceConfig),
largeResultSet: new LargeResultSetService(connectionConfig, httpClient)
};
/**
* Returns the ConnectionConfig for use by the connection.
*
* @returns {ConnectionConfig}
*/
this.getConnectionConfig = function()
{
return connectionConfig;
};
/**
* Returns a map that contains all the available services.
*
* @returns {Object}
*/
this.getServices = function()
{
return services;
};
/**
* Returns a configuration object that can be passed as an optional argument
* to the ConnectionContext constructor to create a new object that has the
* same state as this ConnectionContext instance.
*
* @returns {Object}
*/
this.getConfig = function()
{
return {
services:
{
sf: services.sf.getConfig()
}
};
};
} | [
"function",
"ConnectionContext",
"(",
"connectionConfig",
",",
"httpClient",
",",
"config",
")",
"{",
"// validate input",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"connectionConfig",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
... | Creates a new ConnectionContext.
@param {ConnectionConfig} connectionConfig
@param {Object} httpClient
@param {Object} config
@constructor | [
"Creates",
"a",
"new",
"ConnectionContext",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/connection_context.js#L19-L80 |
10,037 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/sf_timestamp.js | SfTimestamp | function SfTimestamp(epochSeconds, nanoSeconds, scale, timezone, format)
{
// pick reasonable defaults for the inputs if needed
epochSeconds = Util.isNumber(epochSeconds) ? epochSeconds : 0;
nanoSeconds = Util.isNumber(nanoSeconds) ? nanoSeconds : 0;
scale = Util.isNumber(scale) ? scale : 0;
format = Util.isString(format) ? format : '';
// save any information we'll need later
this.epochSeconds = epochSeconds;
this.nanoSeconds = nanoSeconds;
this.scale = scale;
this.timezone = timezone;
this.format = format;
// compute the epoch milliseconds and create a moment object from them
var moment = Moment((epochSeconds * 1000) + (nanoSeconds / 1000000));
// set the moment's timezone
if (Util.isString(timezone))
{
moment = moment.tz(timezone);
}
else if (Util.isNumber(timezone))
{
moment = moment.utcOffset(timezone);
}
// save the moment
this.moment = moment;
} | javascript | function SfTimestamp(epochSeconds, nanoSeconds, scale, timezone, format)
{
// pick reasonable defaults for the inputs if needed
epochSeconds = Util.isNumber(epochSeconds) ? epochSeconds : 0;
nanoSeconds = Util.isNumber(nanoSeconds) ? nanoSeconds : 0;
scale = Util.isNumber(scale) ? scale : 0;
format = Util.isString(format) ? format : '';
// save any information we'll need later
this.epochSeconds = epochSeconds;
this.nanoSeconds = nanoSeconds;
this.scale = scale;
this.timezone = timezone;
this.format = format;
// compute the epoch milliseconds and create a moment object from them
var moment = Moment((epochSeconds * 1000) + (nanoSeconds / 1000000));
// set the moment's timezone
if (Util.isString(timezone))
{
moment = moment.tz(timezone);
}
else if (Util.isNumber(timezone))
{
moment = moment.utcOffset(timezone);
}
// save the moment
this.moment = moment;
} | [
"function",
"SfTimestamp",
"(",
"epochSeconds",
",",
"nanoSeconds",
",",
"scale",
",",
"timezone",
",",
"format",
")",
"{",
"// pick reasonable defaults for the inputs if needed",
"epochSeconds",
"=",
"Util",
".",
"isNumber",
"(",
"epochSeconds",
")",
"?",
"epochSecon... | Creates a new SfTimestamp instance.
@param {Number} epochSeconds the epoch time in seconds.
@param {Number} nanoSeconds the number of nano seconds (incremental, not
epoch).
@param {Number} scale the precision for the fractional part of the timestamp.
@param {String | Number} [timezone] the timezone name as a string
(e.g. 'America/New_York') or the timezone offset in minutes (e.g. -240).
@param {String} [format] the SQL format to use to format the timestamp.
@constructor | [
"Creates",
"a",
"new",
"SfTimestamp",
"instance",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/sf_timestamp.js#L49-L79 |
10,038 | snowflakedb/snowflake-connector-nodejs | lib/core.js | Core | function Core(options)
{
// validate input
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(
Util.exists(options.httpClient || options.httpClientClass));
Errors.assertInternal(Util.exists(options.loggerClass));
// set the logger instance
Logger.setInstance(new (options.loggerClass)());
// if a connection class is specified, it must be an object or function
var connectionClass = options.connectionClass;
if (Util.exists(connectionClass))
{
Errors.assertInternal(
Util.isObject(connectionClass) || Util.isFunction(connectionClass));
}
else
{
// fall back to Connection
connectionClass = Connection;
}
var qaMode = options.qaMode;
var clientInfo = options.client;
/**
* Creates a new Connection instance.
*
* @param {Object} connectionOptions
* @param {Object} [config]
*
* @returns {Object}
*/
var createConnection = function createConnection(connectionOptions, config)
{
// create a new ConnectionConfig and skip credential-validation if a config
// object has been specified; this is because if a config object has been
// specified, we're trying to deserialize a connection and the account name,
// username and password don't need to be specified because the config
// object already contains the tokens we need
var connectionConfig =
new ConnectionConfig(connectionOptions, !config, qaMode, clientInfo);
// if an http client was specified in the options passed to the module, use
// it, otherwise create a new HttpClient
var httpClient = options.httpClient ||
new options.httpClientClass(connectionConfig);
return new connectionClass(
new ConnectionContext(connectionConfig, httpClient, config));
};
var instance =
{
/**
* Creates a connection object that can be used to communicate with
* Snowflake.
*
* @param {Object} options
*
* @returns {Object}
*/
createConnection: function(options)
{
return createConnection(options);
},
/**
* Deserializes a serialized connection.
*
* @param {Object} options
* @param {String} serializedConnection
*
* @returns {Object}
*/
deserializeConnection: function(options, serializedConnection)
{
// check for missing serializedConfig
Errors.checkArgumentExists(Util.exists(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_MISSING_CONFIG);
// check for invalid serializedConfig
Errors.checkArgumentValid(Util.isString(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_TYPE);
// try to json-parse serializedConfig
var config;
try
{
config = JSON.parse(serializedConnection);
}
catch (err) {}
finally
{
// if serializedConfig can't be parsed to json, throw an error
Errors.checkArgumentValid(Util.isObject(config),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_FORM);
}
return createConnection(options, config);
},
/**
* Serializes a given connection.
*
* @param {Object} connection
*
* @returns {String} a serialized version of the connection.
*/
serializeConnection: function(connection)
{
return connection ? connection.serialize() : connection;
},
/**
* Configures this instance of the Snowflake core module.
*
* @param {Object} options
*/
configure: function(options)
{
var logTag = options.logLevel;
if (Util.exists(logTag))
{
// check that the specified value is a valid tag
Errors.checkArgumentValid(LoggerCore.isValidLogTag(logTag),
ErrorCodes.ERR_GLOGAL_CONFIGURE_INVALID_LOG_LEVEL);
Logger.getInstance().configure(
{
level: LoggerCore.logTagToLevel(logTag)
});
}
var insecureConnect = options.insecureConnect;
if (Util.exists(insecureConnect))
{
// check that the specified value is a boolean
Errors.checkArgumentValid(Util.isBoolean(insecureConnect),
ErrorCodes.ERR_GLOBAL_CONFIGURE_INVALID_INSECURE_CONNECT);
GlobalConfig.setInsecureConnect(insecureConnect);
}
}
};
// add some read-only constants
var nativeTypeValues = DataTypes.NativeTypes.values;
Object.defineProperties(instance,
{
STRING : { value: nativeTypeValues.STRING },
BOOLEAN : { value: nativeTypeValues.BOOLEAN },
NUMBER : { value: nativeTypeValues.NUMBER },
DATE : { value: nativeTypeValues.DATE },
JSON : { value: nativeTypeValues.JSON }
});
return instance;
} | javascript | function Core(options)
{
// validate input
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(
Util.exists(options.httpClient || options.httpClientClass));
Errors.assertInternal(Util.exists(options.loggerClass));
// set the logger instance
Logger.setInstance(new (options.loggerClass)());
// if a connection class is specified, it must be an object or function
var connectionClass = options.connectionClass;
if (Util.exists(connectionClass))
{
Errors.assertInternal(
Util.isObject(connectionClass) || Util.isFunction(connectionClass));
}
else
{
// fall back to Connection
connectionClass = Connection;
}
var qaMode = options.qaMode;
var clientInfo = options.client;
/**
* Creates a new Connection instance.
*
* @param {Object} connectionOptions
* @param {Object} [config]
*
* @returns {Object}
*/
var createConnection = function createConnection(connectionOptions, config)
{
// create a new ConnectionConfig and skip credential-validation if a config
// object has been specified; this is because if a config object has been
// specified, we're trying to deserialize a connection and the account name,
// username and password don't need to be specified because the config
// object already contains the tokens we need
var connectionConfig =
new ConnectionConfig(connectionOptions, !config, qaMode, clientInfo);
// if an http client was specified in the options passed to the module, use
// it, otherwise create a new HttpClient
var httpClient = options.httpClient ||
new options.httpClientClass(connectionConfig);
return new connectionClass(
new ConnectionContext(connectionConfig, httpClient, config));
};
var instance =
{
/**
* Creates a connection object that can be used to communicate with
* Snowflake.
*
* @param {Object} options
*
* @returns {Object}
*/
createConnection: function(options)
{
return createConnection(options);
},
/**
* Deserializes a serialized connection.
*
* @param {Object} options
* @param {String} serializedConnection
*
* @returns {Object}
*/
deserializeConnection: function(options, serializedConnection)
{
// check for missing serializedConfig
Errors.checkArgumentExists(Util.exists(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_MISSING_CONFIG);
// check for invalid serializedConfig
Errors.checkArgumentValid(Util.isString(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_TYPE);
// try to json-parse serializedConfig
var config;
try
{
config = JSON.parse(serializedConnection);
}
catch (err) {}
finally
{
// if serializedConfig can't be parsed to json, throw an error
Errors.checkArgumentValid(Util.isObject(config),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_FORM);
}
return createConnection(options, config);
},
/**
* Serializes a given connection.
*
* @param {Object} connection
*
* @returns {String} a serialized version of the connection.
*/
serializeConnection: function(connection)
{
return connection ? connection.serialize() : connection;
},
/**
* Configures this instance of the Snowflake core module.
*
* @param {Object} options
*/
configure: function(options)
{
var logTag = options.logLevel;
if (Util.exists(logTag))
{
// check that the specified value is a valid tag
Errors.checkArgumentValid(LoggerCore.isValidLogTag(logTag),
ErrorCodes.ERR_GLOGAL_CONFIGURE_INVALID_LOG_LEVEL);
Logger.getInstance().configure(
{
level: LoggerCore.logTagToLevel(logTag)
});
}
var insecureConnect = options.insecureConnect;
if (Util.exists(insecureConnect))
{
// check that the specified value is a boolean
Errors.checkArgumentValid(Util.isBoolean(insecureConnect),
ErrorCodes.ERR_GLOBAL_CONFIGURE_INVALID_INSECURE_CONNECT);
GlobalConfig.setInsecureConnect(insecureConnect);
}
}
};
// add some read-only constants
var nativeTypeValues = DataTypes.NativeTypes.values;
Object.defineProperties(instance,
{
STRING : { value: nativeTypeValues.STRING },
BOOLEAN : { value: nativeTypeValues.BOOLEAN },
NUMBER : { value: nativeTypeValues.NUMBER },
DATE : { value: nativeTypeValues.DATE },
JSON : { value: nativeTypeValues.JSON }
});
return instance;
} | [
"function",
"Core",
"(",
"options",
")",
"{",
"// validate input",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"options",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"exists",
"(",
"options",
".",
"httpClient",
... | Creates a new instance of the Snowflake core module.
@param {Object} options
@returns {Object}
@constructor | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"Snowflake",
"core",
"module",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/core.js#L24-L184 |
10,039 | snowflakedb/snowflake-connector-nodejs | lib/core.js | function(options, serializedConnection)
{
// check for missing serializedConfig
Errors.checkArgumentExists(Util.exists(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_MISSING_CONFIG);
// check for invalid serializedConfig
Errors.checkArgumentValid(Util.isString(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_TYPE);
// try to json-parse serializedConfig
var config;
try
{
config = JSON.parse(serializedConnection);
}
catch (err) {}
finally
{
// if serializedConfig can't be parsed to json, throw an error
Errors.checkArgumentValid(Util.isObject(config),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_FORM);
}
return createConnection(options, config);
} | javascript | function(options, serializedConnection)
{
// check for missing serializedConfig
Errors.checkArgumentExists(Util.exists(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_MISSING_CONFIG);
// check for invalid serializedConfig
Errors.checkArgumentValid(Util.isString(serializedConnection),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_TYPE);
// try to json-parse serializedConfig
var config;
try
{
config = JSON.parse(serializedConnection);
}
catch (err) {}
finally
{
// if serializedConfig can't be parsed to json, throw an error
Errors.checkArgumentValid(Util.isObject(config),
ErrorCodes.ERR_CONN_DESERIALIZE_INVALID_CONFIG_FORM);
}
return createConnection(options, config);
} | [
"function",
"(",
"options",
",",
"serializedConnection",
")",
"{",
"// check for missing serializedConfig",
"Errors",
".",
"checkArgumentExists",
"(",
"Util",
".",
"exists",
"(",
"serializedConnection",
")",
",",
"ErrorCodes",
".",
"ERR_CONN_DESERIALIZE_MISSING_CONFIG",
"... | Deserializes a serialized connection.
@param {Object} options
@param {String} serializedConnection
@returns {Object} | [
"Deserializes",
"a",
"serialized",
"connection",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/core.js#L101-L126 | |
10,040 | snowflakedb/snowflake-connector-nodejs | lib/core.js | function(options)
{
var logTag = options.logLevel;
if (Util.exists(logTag))
{
// check that the specified value is a valid tag
Errors.checkArgumentValid(LoggerCore.isValidLogTag(logTag),
ErrorCodes.ERR_GLOGAL_CONFIGURE_INVALID_LOG_LEVEL);
Logger.getInstance().configure(
{
level: LoggerCore.logTagToLevel(logTag)
});
}
var insecureConnect = options.insecureConnect;
if (Util.exists(insecureConnect))
{
// check that the specified value is a boolean
Errors.checkArgumentValid(Util.isBoolean(insecureConnect),
ErrorCodes.ERR_GLOBAL_CONFIGURE_INVALID_INSECURE_CONNECT);
GlobalConfig.setInsecureConnect(insecureConnect);
}
} | javascript | function(options)
{
var logTag = options.logLevel;
if (Util.exists(logTag))
{
// check that the specified value is a valid tag
Errors.checkArgumentValid(LoggerCore.isValidLogTag(logTag),
ErrorCodes.ERR_GLOGAL_CONFIGURE_INVALID_LOG_LEVEL);
Logger.getInstance().configure(
{
level: LoggerCore.logTagToLevel(logTag)
});
}
var insecureConnect = options.insecureConnect;
if (Util.exists(insecureConnect))
{
// check that the specified value is a boolean
Errors.checkArgumentValid(Util.isBoolean(insecureConnect),
ErrorCodes.ERR_GLOBAL_CONFIGURE_INVALID_INSECURE_CONNECT);
GlobalConfig.setInsecureConnect(insecureConnect);
}
} | [
"function",
"(",
"options",
")",
"{",
"var",
"logTag",
"=",
"options",
".",
"logLevel",
";",
"if",
"(",
"Util",
".",
"exists",
"(",
"logTag",
")",
")",
"{",
"// check that the specified value is a valid tag",
"Errors",
".",
"checkArgumentValid",
"(",
"LoggerCore... | Configures this instance of the Snowflake core module.
@param {Object} options | [
"Configures",
"this",
"instance",
"of",
"the",
"Snowflake",
"core",
"module",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/core.js#L145-L169 | |
10,041 | snowflakedb/snowflake-connector-nodejs | lib/logger/node.js | Logger | function Logger(options)
{
var common;
var winstonLogger;
/**
* Logs a message at a given level.
*
* @param {String} levelTag the tag associated with the level at which to log
* the message.
* @param {String} message the message to log.
* @param {Number} bufferMaxLength the maximum size to which the message
* buffer can grow.
*/
var logMessage = function(levelTag, message, bufferMaxLength)
{
// initialize the winston logger if needed
if (!winstonLogger)
{
winstonLogger = new winston.createLogger(
{
transports:
[
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'snowflake.log' })
],
level: common.getLevelTag(),
levels: common.getLevelTagsMap()
});
}
// get the appropriate logging method using the level tag and use this
// method to log the message
winstonLogger[levelTag](message);
};
// create an inner implementation to which all our methods will be forwarded
common = Core.createLogger(options, logMessage);
/**
* Configures this logger.
*
* @param {Object} options
*/
this.configure = function(options)
{
common.configure(options);
};
/**
* Returns the current log level.
*
* @returns {Number}
*/
this.getLevel = function()
{
return common.getLevelNumber();
};
/**
* Logs a given message at the error level.
*
* @param {String} message
*/
this.error = function(message)
{
common.error.apply(common, arguments);
};
/**
* Logs a given message at the warning level.
*
* @param {String} message
*/
this.warn = function(message)
{
common.warn.apply(common, arguments);
};
/**
* Logs a given message at the info level.
*
* @param {String} message
*/
this.info = function(message)
{
common.info.apply(common, arguments);
};
/**
* Logs a given message at the debug level.
*
* @param {String} message
*/
this.debug = function(message)
{
common.debug.apply(common, arguments);
};
/**
* Logs a given message at the trace level.
*
* @param {String} message
*/
this.trace = function(message)
{
common.trace.apply(common, arguments);
};
/**
* Returns the log buffer.
*
* @returns {String[]}
*/
this.getLogBuffer = function()
{
return common.getLogBuffer();
};
} | javascript | function Logger(options)
{
var common;
var winstonLogger;
/**
* Logs a message at a given level.
*
* @param {String} levelTag the tag associated with the level at which to log
* the message.
* @param {String} message the message to log.
* @param {Number} bufferMaxLength the maximum size to which the message
* buffer can grow.
*/
var logMessage = function(levelTag, message, bufferMaxLength)
{
// initialize the winston logger if needed
if (!winstonLogger)
{
winstonLogger = new winston.createLogger(
{
transports:
[
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'snowflake.log' })
],
level: common.getLevelTag(),
levels: common.getLevelTagsMap()
});
}
// get the appropriate logging method using the level tag and use this
// method to log the message
winstonLogger[levelTag](message);
};
// create an inner implementation to which all our methods will be forwarded
common = Core.createLogger(options, logMessage);
/**
* Configures this logger.
*
* @param {Object} options
*/
this.configure = function(options)
{
common.configure(options);
};
/**
* Returns the current log level.
*
* @returns {Number}
*/
this.getLevel = function()
{
return common.getLevelNumber();
};
/**
* Logs a given message at the error level.
*
* @param {String} message
*/
this.error = function(message)
{
common.error.apply(common, arguments);
};
/**
* Logs a given message at the warning level.
*
* @param {String} message
*/
this.warn = function(message)
{
common.warn.apply(common, arguments);
};
/**
* Logs a given message at the info level.
*
* @param {String} message
*/
this.info = function(message)
{
common.info.apply(common, arguments);
};
/**
* Logs a given message at the debug level.
*
* @param {String} message
*/
this.debug = function(message)
{
common.debug.apply(common, arguments);
};
/**
* Logs a given message at the trace level.
*
* @param {String} message
*/
this.trace = function(message)
{
common.trace.apply(common, arguments);
};
/**
* Returns the log buffer.
*
* @returns {String[]}
*/
this.getLogBuffer = function()
{
return common.getLogBuffer();
};
} | [
"function",
"Logger",
"(",
"options",
")",
"{",
"var",
"common",
";",
"var",
"winstonLogger",
";",
"/**\n * Logs a message at a given level.\n *\n * @param {String} levelTag the tag associated with the level at which to log\n * the message.\n * @param {String} message the message... | Creates a new Logger instance for when we're running in node.
@param {Object} [options]
@constructor | [
"Creates",
"a",
"new",
"Logger",
"instance",
"for",
"when",
"we",
"re",
"running",
"in",
"node",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/logger/node.js#L16-L134 |
10,042 | snowflakedb/snowflake-connector-nodejs | lib/connection/connection_config.js | createParameters | function createParameters()
{
var isNonNegativeInteger = Util.number.isNonNegativeInteger.bind(Util.number);
var isPositiveInteger = Util.number.isPositiveInteger.bind(Util.number);
var isNonNegativeNumber = Util.number.isNonNegative.bind(Util.number);
return [
{
name : PARAM_TIMEOUT,
defaultValue : 90 * 1000,
external : true,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PREFETCH,
defaultValue : 2,
external : true,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_STREAM_INTERRUPTS,
defaultValue : 3,
validate : isPositiveInteger
},
// for now we set chunk cache size to 1, which is same as
// disabling the chunk cache. Otherwise, cache will explode
// memory when fetching large result set
{
name : PARAM_RESULT_CHUNK_CACHE_SIZE,
defaultValue : 1,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PROCESSING_BATCH_SIZE,
defaultValue : 1000,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PROCESSING_BATCH_DURATION,
defaultValue : 100,
validate : isPositiveInteger
},
{
name : PARAM_ROW_STREAM_HIGH_WATER_MARK,
defaultValue : 10,
validate : isPositiveInteger
},
{
name : PARAM_RETRY_LARGE_RESULT_SET_MAX_NUM_RETRIES,
defaultValue : 10,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_LARGE_RESULT_SET_MAX_SLEEP_TIME,
defaultValue : 16,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_SF_MAX_NUM_RETRIES,
defaultValue : 1000,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_SF_STARTING_SLEEP_TIME,
defaultValue : 0.25,
validate : isNonNegativeNumber
},
{
name : PARAM_RETRY_SF_MAX_SLEEP_TIME,
defaultValue : 16,
validate : isNonNegativeNumber
}
];
} | javascript | function createParameters()
{
var isNonNegativeInteger = Util.number.isNonNegativeInteger.bind(Util.number);
var isPositiveInteger = Util.number.isPositiveInteger.bind(Util.number);
var isNonNegativeNumber = Util.number.isNonNegative.bind(Util.number);
return [
{
name : PARAM_TIMEOUT,
defaultValue : 90 * 1000,
external : true,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PREFETCH,
defaultValue : 2,
external : true,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_STREAM_INTERRUPTS,
defaultValue : 3,
validate : isPositiveInteger
},
// for now we set chunk cache size to 1, which is same as
// disabling the chunk cache. Otherwise, cache will explode
// memory when fetching large result set
{
name : PARAM_RESULT_CHUNK_CACHE_SIZE,
defaultValue : 1,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PROCESSING_BATCH_SIZE,
defaultValue : 1000,
validate : isPositiveInteger
},
{
name : PARAM_RESULT_PROCESSING_BATCH_DURATION,
defaultValue : 100,
validate : isPositiveInteger
},
{
name : PARAM_ROW_STREAM_HIGH_WATER_MARK,
defaultValue : 10,
validate : isPositiveInteger
},
{
name : PARAM_RETRY_LARGE_RESULT_SET_MAX_NUM_RETRIES,
defaultValue : 10,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_LARGE_RESULT_SET_MAX_SLEEP_TIME,
defaultValue : 16,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_SF_MAX_NUM_RETRIES,
defaultValue : 1000,
validate : isNonNegativeInteger
},
{
name : PARAM_RETRY_SF_STARTING_SLEEP_TIME,
defaultValue : 0.25,
validate : isNonNegativeNumber
},
{
name : PARAM_RETRY_SF_MAX_SLEEP_TIME,
defaultValue : 16,
validate : isNonNegativeNumber
}
];
} | [
"function",
"createParameters",
"(",
")",
"{",
"var",
"isNonNegativeInteger",
"=",
"Util",
".",
"number",
".",
"isNonNegativeInteger",
".",
"bind",
"(",
"Util",
".",
"number",
")",
";",
"var",
"isPositiveInteger",
"=",
"Util",
".",
"number",
".",
"isPositiveIn... | Creates the list of known parameters. If a parameter is marked as external,
its value can be overridden by adding the appropriate name-value mapping to
the ConnectionConfig options.
@returns {Object[]} | [
"Creates",
"the",
"list",
"of",
"known",
"parameters",
".",
"If",
"a",
"parameter",
"is",
"marked",
"as",
"external",
"its",
"value",
"can",
"be",
"overridden",
"by",
"adding",
"the",
"appropriate",
"name",
"-",
"value",
"mapping",
"to",
"the",
"ConnectionCo... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/connection_config.js#L441-L514 |
10,043 | snowflakedb/snowflake-connector-nodejs | lib/logger/core.js | function(options)
{
var localIncludeTimestamp;
var localBufferMaxLength;
var localMessageMaxLength;
var localLevel;
// if an options argument is specified
if (Util.exists(options))
{
// make sure it's an object
Errors.assertInternal(Util.isObject(options));
localIncludeTimestamp = options.includeTimestamp;
localBufferMaxLength = options.bufferMaxLength;
localMessageMaxLength = options.messageMaxLength;
localLevel = options.level;
}
// if an includeTimestamp options is specified, convert it to a boolean
if (Util.exists(localIncludeTimestamp))
{
includeTimestamp = !!localIncludeTimestamp;
}
else if (!Util.exists(includeTimestamp))
{
// default to true
includeTimestamp = true;
}
// if a bufferMaxLength option is specified, make sure
// it's a positive integer before updating the logger option
if (Util.exists(localBufferMaxLength))
{
Errors.assertInternal(
Util.number.isPositiveInteger(localBufferMaxLength));
bufferMaxLength = localBufferMaxLength;
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(bufferMaxLength))
{
bufferMaxLength = DEFAULT_BUFFER_MAX_LENGTH;
}
// if a messageMaxLength option is specified, make sure
// it's a positive integer before updating the logger option
if (Util.exists(localMessageMaxLength))
{
Errors.assertInternal(
Util.number.isPositiveInteger(localMessageMaxLength));
messageMaxLength = localMessageMaxLength;
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(messageMaxLength))
{
messageMaxLength = DEFAULT_MESSAGE_MAX_LENGTH;
}
// if a level option is specified, make sure
// it's valid before updating the logger option
if (Util.exists(localLevel))
{
Errors.assertInternal(
MAP_LOG_LEVEL_TO_OBJECT.hasOwnProperty(localLevel));
currlevelObject = MAP_LOG_LEVEL_TO_OBJECT[localLevel];
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(currlevelObject))
{
currlevelObject = DEFAULT_LEVEL;
}
} | javascript | function(options)
{
var localIncludeTimestamp;
var localBufferMaxLength;
var localMessageMaxLength;
var localLevel;
// if an options argument is specified
if (Util.exists(options))
{
// make sure it's an object
Errors.assertInternal(Util.isObject(options));
localIncludeTimestamp = options.includeTimestamp;
localBufferMaxLength = options.bufferMaxLength;
localMessageMaxLength = options.messageMaxLength;
localLevel = options.level;
}
// if an includeTimestamp options is specified, convert it to a boolean
if (Util.exists(localIncludeTimestamp))
{
includeTimestamp = !!localIncludeTimestamp;
}
else if (!Util.exists(includeTimestamp))
{
// default to true
includeTimestamp = true;
}
// if a bufferMaxLength option is specified, make sure
// it's a positive integer before updating the logger option
if (Util.exists(localBufferMaxLength))
{
Errors.assertInternal(
Util.number.isPositiveInteger(localBufferMaxLength));
bufferMaxLength = localBufferMaxLength;
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(bufferMaxLength))
{
bufferMaxLength = DEFAULT_BUFFER_MAX_LENGTH;
}
// if a messageMaxLength option is specified, make sure
// it's a positive integer before updating the logger option
if (Util.exists(localMessageMaxLength))
{
Errors.assertInternal(
Util.number.isPositiveInteger(localMessageMaxLength));
messageMaxLength = localMessageMaxLength;
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(messageMaxLength))
{
messageMaxLength = DEFAULT_MESSAGE_MAX_LENGTH;
}
// if a level option is specified, make sure
// it's valid before updating the logger option
if (Util.exists(localLevel))
{
Errors.assertInternal(
MAP_LOG_LEVEL_TO_OBJECT.hasOwnProperty(localLevel));
currlevelObject = MAP_LOG_LEVEL_TO_OBJECT[localLevel];
}
// initialize logger option if configure() hasn't been called before
else if (!Util.exists(currlevelObject))
{
currlevelObject = DEFAULT_LEVEL;
}
} | [
"function",
"(",
"options",
")",
"{",
"var",
"localIncludeTimestamp",
";",
"var",
"localBufferMaxLength",
";",
"var",
"localMessageMaxLength",
";",
"var",
"localLevel",
";",
"// if an options argument is specified",
"if",
"(",
"Util",
".",
"exists",
"(",
"options",
... | Configures this logger.
@param {Object} options | [
"Configures",
"this",
"logger",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/logger/core.js#L113-L184 | |
10,044 | snowflakedb/snowflake-connector-nodejs | lib/parameters.js | Parameter | function Parameter(options)
{
// validate input
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isString(options.name));
Errors.assertInternal(Util.exists(options.value));
var name = options.name;
var value = options.value;
/**
* Returns the name of the parameter.
*
* @returns {String}
*/
this.getName = function ()
{
return name;
};
/**
* Returns the value of the parameter.
*
* @returns {*}
*/
this.getValue = function ()
{
return value;
};
/**
* Updates the value of the parameter.
*
* @param {*} targetValue
*/
this.setValue = function (targetValue)
{
value = targetValue;
};
} | javascript | function Parameter(options)
{
// validate input
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isString(options.name));
Errors.assertInternal(Util.exists(options.value));
var name = options.name;
var value = options.value;
/**
* Returns the name of the parameter.
*
* @returns {String}
*/
this.getName = function ()
{
return name;
};
/**
* Returns the value of the parameter.
*
* @returns {*}
*/
this.getValue = function ()
{
return value;
};
/**
* Updates the value of the parameter.
*
* @param {*} targetValue
*/
this.setValue = function (targetValue)
{
value = targetValue;
};
} | [
"function",
"Parameter",
"(",
"options",
")",
"{",
"// validate input",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"options",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isString",
"(",
"options",
".",
"name",
... | Creates a new Parameter.
@param {Object} options
@constructor | [
"Creates",
"a",
"new",
"Parameter",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/parameters.js#L14-L53 |
10,045 | snowflakedb/snowflake-connector-nodejs | lib/errors.js | createError | function createError(name, options)
{
// TODO: validate that name is a string and options is an object
// TODO: this code is a bit of a mess and needs to be cleaned up
// create a new error
var error = new Error();
// set its name
error.name = name;
// set the error code
var code;
error.code = code = options.code;
// if no error message was specified in the options
var message = options.message;
if (!message)
{
// use the error code to get the error message template
var messageTemplate = errorMessages[code];
// if some error message arguments were specified, substitute them into the
// error message template to get the full error message, otherwise just use
// the error message template as the error message
var messageArgs = options.messageArgs;
if (messageArgs)
{
messageArgs = messageArgs.slice();
messageArgs.unshift(messageTemplate);
message = Util.format.apply(Util, messageArgs);
}
else
{
message = messageTemplate;
}
}
error.message = message;
// if no sql state was specified in the options, use the error code to try to
// get the appropriate sql state
var sqlState = options.sqlState;
if (!sqlState)
{
sqlState = errCodeToSqlState[code];
}
error.sqlState = sqlState;
// set the error data
error.data = options.data;
// set the error response and response body
error.response = options.response;
error.responseBody = options.responseBody;
// set the error cause
error.cause = options.cause;
// set the error's fatal flag
error.isFatal = options.isFatal;
// if the error is not synchronous, add an externalize() method
if (!options.synchronous)
{
error.externalize = function(errorCode, errorMessageArgs, sqlState)
{
var propNames =
[
'name',
'code',
'message',
'sqlState',
'data',
'response',
'responseBody',
'cause',
'isFatal',
'stack'
];
var externalizedError = new Error();
var propName, propValue;
for (var index = 0, length = propNames.length; index < length; index++)
{
propName = propNames[index];
propValue = this[propName];
if (Util.exists(propValue))
{
externalizedError[propName] = propValue;
}
}
return externalizedError;
};
}
return error;
} | javascript | function createError(name, options)
{
// TODO: validate that name is a string and options is an object
// TODO: this code is a bit of a mess and needs to be cleaned up
// create a new error
var error = new Error();
// set its name
error.name = name;
// set the error code
var code;
error.code = code = options.code;
// if no error message was specified in the options
var message = options.message;
if (!message)
{
// use the error code to get the error message template
var messageTemplate = errorMessages[code];
// if some error message arguments were specified, substitute them into the
// error message template to get the full error message, otherwise just use
// the error message template as the error message
var messageArgs = options.messageArgs;
if (messageArgs)
{
messageArgs = messageArgs.slice();
messageArgs.unshift(messageTemplate);
message = Util.format.apply(Util, messageArgs);
}
else
{
message = messageTemplate;
}
}
error.message = message;
// if no sql state was specified in the options, use the error code to try to
// get the appropriate sql state
var sqlState = options.sqlState;
if (!sqlState)
{
sqlState = errCodeToSqlState[code];
}
error.sqlState = sqlState;
// set the error data
error.data = options.data;
// set the error response and response body
error.response = options.response;
error.responseBody = options.responseBody;
// set the error cause
error.cause = options.cause;
// set the error's fatal flag
error.isFatal = options.isFatal;
// if the error is not synchronous, add an externalize() method
if (!options.synchronous)
{
error.externalize = function(errorCode, errorMessageArgs, sqlState)
{
var propNames =
[
'name',
'code',
'message',
'sqlState',
'data',
'response',
'responseBody',
'cause',
'isFatal',
'stack'
];
var externalizedError = new Error();
var propName, propValue;
for (var index = 0, length = propNames.length; index < length; index++)
{
propName = propNames[index];
propValue = this[propName];
if (Util.exists(propValue))
{
externalizedError[propName] = propValue;
}
}
return externalizedError;
};
}
return error;
} | [
"function",
"createError",
"(",
"name",
",",
"options",
")",
"{",
"// TODO: validate that name is a string and options is an object",
"// TODO: this code is a bit of a mess and needs to be cleaned up",
"// create a new error",
"var",
"error",
"=",
"new",
"Error",
"(",
")",
";",
... | Creates a generic error.
@param {String} name
@param {Object} options
@returns {Error} | [
"Creates",
"a",
"generic",
"error",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/errors.js#L469-L568 |
10,046 | snowflakedb/snowflake-connector-nodejs | lib/agent/ocsp_response_cache.js | OcspResponseCache | function OcspResponseCache(capacity, maxAge)
{
// validate input
Errors.assertInternal(Util.number.isPositiveInteger(capacity));
Errors.assertInternal(Util.number.isPositiveInteger(maxAge));
// create a cache to store the responses
var cache = new SimpleCache({ maxSize: capacity });
/**
* Adds an entry to the cache.
*
* @param cert
* @param response
*/
this.set = function set(cert, response)
{
// for the value, use an object that contains the response
// as well as the time at which the response was saved
cache.set(CertUtil.buildCertId(cert),
{
response : response,
savedAt : Date.now()
});
};
/**
* Returns an entry from the cache.
*
* @param cert
* @returns {*}
*/
this.get = function get(cert)
{
// build the certificate id
var certId = CertUtil.buildCertId(cert);
// if we have an entry in the cache
var value = cache.get(certId);
if (value)
{
var response = value.response;
var savedAt = value.savedAt;
var now = Date.now();
// if the cache entry has expired, or if the current time doesn't fall
// within the response validity range, remove the entry from the cache
if (((now - savedAt) > maxAge) ||
(response.thisUpdate > now) || (response.nextUpdate < now))
{
cache.del(certId);
response = null;
}
}
return response;
};
} | javascript | function OcspResponseCache(capacity, maxAge)
{
// validate input
Errors.assertInternal(Util.number.isPositiveInteger(capacity));
Errors.assertInternal(Util.number.isPositiveInteger(maxAge));
// create a cache to store the responses
var cache = new SimpleCache({ maxSize: capacity });
/**
* Adds an entry to the cache.
*
* @param cert
* @param response
*/
this.set = function set(cert, response)
{
// for the value, use an object that contains the response
// as well as the time at which the response was saved
cache.set(CertUtil.buildCertId(cert),
{
response : response,
savedAt : Date.now()
});
};
/**
* Returns an entry from the cache.
*
* @param cert
* @returns {*}
*/
this.get = function get(cert)
{
// build the certificate id
var certId = CertUtil.buildCertId(cert);
// if we have an entry in the cache
var value = cache.get(certId);
if (value)
{
var response = value.response;
var savedAt = value.savedAt;
var now = Date.now();
// if the cache entry has expired, or if the current time doesn't fall
// within the response validity range, remove the entry from the cache
if (((now - savedAt) > maxAge) ||
(response.thisUpdate > now) || (response.nextUpdate < now))
{
cache.del(certId);
response = null;
}
}
return response;
};
} | [
"function",
"OcspResponseCache",
"(",
"capacity",
",",
"maxAge",
")",
"{",
"// validate input",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"number",
".",
"isPositiveInteger",
"(",
"capacity",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"Util",
... | Client-side cache for storing OCSP responses.
@param {Number} capacity
@param {Number} maxAge
@constructor | [
"Client",
"-",
"side",
"cache",
"for",
"storing",
"OCSP",
"responses",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/agent/ocsp_response_cache.js#L18-L76 |
10,047 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result_stream.js | ResultStream | function ResultStream(options)
{
// options should be an object
Errors.assertInternal(Util.isObject(options));
var chunks = options.chunks;
var prefetchSize = options.prefetchSize;
// chunks should be an array
Errors.assertInternal(Util.isArray(chunks));
// prefetch size should be non-negative
Errors.assertInternal(Util.isNumber(prefetchSize) && (prefetchSize >= 0));
// start with the first chunk
var start = 0;
var self = this;
/**
* Called when a chunk fires a 'loadcomplete' event.
*
* @param {Error} err
* @param {Chunk} chunk
*/
var onLoadComplete = function(err, chunk)
{
// unsubscribe from the 'loadcomplete' event
chunk.removeListener('loadcomplete', onLoadComplete);
// if the chunk load succeeded
if (!err)
{
// move on to the next chunk
start++;
// emit an event to signal that new data is available
self.emit('data', chunk);
}
else
{
// close the stream with an error; also, include a callback when emitting
// the event in case someone wants to fix the problem and ask us to
// continue from where we got interrupted
close(self, err, doLoad);
}
};
/**
* Identifies the next chunk to load and issues requests to fetch both its
* contents plus the contents of the next few chunks. If there are no more
* chunks to load, a 'close' event is fired on the stream to notify
* subscribers that all the chunks have been successfully read.
*/
var doLoad = function()
{
// get the array of chunks whose contents need to be fetched
var buffer = chunks.slice(start, start + prefetchSize + 1);
// the first chunk in the buffer is the next chunk we want to load
var nextChunk = buffer[0];
// if we don't have anymore chunks to load, we're done
if (!nextChunk)
{
self.asyncClose();
}
else
{
// fire off requests to load all the chunks in the buffer that aren't
// already loading
var chunk, index, length;
for (index = 0, length = buffer.length; index < length; index++)
{
chunk = buffer[index];
if (!chunk.isLoading())
{
chunk.load();
}
}
// subscribe to the loadcomplete event on the next chunk
nextChunk.on('loadcomplete', onLoadComplete);
}
};
/**
* Reads the next chunk of data in the result stream.
*/
this.read = function()
{
// TODO: if there are no more chunks to read, should we raise an error?
// TODO: what if we're already in the middle of a read?
// read the next chunk
doLoad();
};
} | javascript | function ResultStream(options)
{
// options should be an object
Errors.assertInternal(Util.isObject(options));
var chunks = options.chunks;
var prefetchSize = options.prefetchSize;
// chunks should be an array
Errors.assertInternal(Util.isArray(chunks));
// prefetch size should be non-negative
Errors.assertInternal(Util.isNumber(prefetchSize) && (prefetchSize >= 0));
// start with the first chunk
var start = 0;
var self = this;
/**
* Called when a chunk fires a 'loadcomplete' event.
*
* @param {Error} err
* @param {Chunk} chunk
*/
var onLoadComplete = function(err, chunk)
{
// unsubscribe from the 'loadcomplete' event
chunk.removeListener('loadcomplete', onLoadComplete);
// if the chunk load succeeded
if (!err)
{
// move on to the next chunk
start++;
// emit an event to signal that new data is available
self.emit('data', chunk);
}
else
{
// close the stream with an error; also, include a callback when emitting
// the event in case someone wants to fix the problem and ask us to
// continue from where we got interrupted
close(self, err, doLoad);
}
};
/**
* Identifies the next chunk to load and issues requests to fetch both its
* contents plus the contents of the next few chunks. If there are no more
* chunks to load, a 'close' event is fired on the stream to notify
* subscribers that all the chunks have been successfully read.
*/
var doLoad = function()
{
// get the array of chunks whose contents need to be fetched
var buffer = chunks.slice(start, start + prefetchSize + 1);
// the first chunk in the buffer is the next chunk we want to load
var nextChunk = buffer[0];
// if we don't have anymore chunks to load, we're done
if (!nextChunk)
{
self.asyncClose();
}
else
{
// fire off requests to load all the chunks in the buffer that aren't
// already loading
var chunk, index, length;
for (index = 0, length = buffer.length; index < length; index++)
{
chunk = buffer[index];
if (!chunk.isLoading())
{
chunk.load();
}
}
// subscribe to the loadcomplete event on the next chunk
nextChunk.on('loadcomplete', onLoadComplete);
}
};
/**
* Reads the next chunk of data in the result stream.
*/
this.read = function()
{
// TODO: if there are no more chunks to read, should we raise an error?
// TODO: what if we're already in the middle of a read?
// read the next chunk
doLoad();
};
} | [
"function",
"ResultStream",
"(",
"options",
")",
"{",
"// options should be an object",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"options",
")",
")",
";",
"var",
"chunks",
"=",
"options",
".",
"chunks",
";",
"var",
"prefetchSize",
"=... | Creates a stream-like object that can be used to read the contents of an
array of chunks with the ability to prefetch chunks as we go. Every time the
contents of a new chunk become available, a 'data' event is fired. When there
are no more chunks to read, a 'close' event is fired to indicate that the
read operation is complete. If no chunks are specified in the options, the
stream asynchronously fires a 'close' event after it is returned.
@param {Object} [options] An options object with the following properties:
{Object[]} chunks - The chunks to read.
{Number} prefetchSize - The number of chunks to prefetch every time a new
chunk is read.
@constructor | [
"Creates",
"a",
"stream",
"-",
"like",
"object",
"that",
"can",
"be",
"used",
"to",
"read",
"the",
"contents",
"of",
"an",
"array",
"of",
"chunks",
"with",
"the",
"ability",
"to",
"prefetch",
"chunks",
"as",
"we",
"go",
".",
"Every",
"time",
"the",
"co... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result_stream.js#L24-L121 |
10,048 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result_stream.js | function(err, chunk)
{
// unsubscribe from the 'loadcomplete' event
chunk.removeListener('loadcomplete', onLoadComplete);
// if the chunk load succeeded
if (!err)
{
// move on to the next chunk
start++;
// emit an event to signal that new data is available
self.emit('data', chunk);
}
else
{
// close the stream with an error; also, include a callback when emitting
// the event in case someone wants to fix the problem and ask us to
// continue from where we got interrupted
close(self, err, doLoad);
}
} | javascript | function(err, chunk)
{
// unsubscribe from the 'loadcomplete' event
chunk.removeListener('loadcomplete', onLoadComplete);
// if the chunk load succeeded
if (!err)
{
// move on to the next chunk
start++;
// emit an event to signal that new data is available
self.emit('data', chunk);
}
else
{
// close the stream with an error; also, include a callback when emitting
// the event in case someone wants to fix the problem and ask us to
// continue from where we got interrupted
close(self, err, doLoad);
}
} | [
"function",
"(",
"err",
",",
"chunk",
")",
"{",
"// unsubscribe from the 'loadcomplete' event",
"chunk",
".",
"removeListener",
"(",
"'loadcomplete'",
",",
"onLoadComplete",
")",
";",
"// if the chunk load succeeded",
"if",
"(",
"!",
"err",
")",
"{",
"// move on to th... | Called when a chunk fires a 'loadcomplete' event.
@param {Error} err
@param {Chunk} chunk | [
"Called",
"when",
"a",
"chunk",
"fires",
"a",
"loadcomplete",
"event",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result_stream.js#L49-L70 | |
10,049 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result_stream.js | function()
{
// get the array of chunks whose contents need to be fetched
var buffer = chunks.slice(start, start + prefetchSize + 1);
// the first chunk in the buffer is the next chunk we want to load
var nextChunk = buffer[0];
// if we don't have anymore chunks to load, we're done
if (!nextChunk)
{
self.asyncClose();
}
else
{
// fire off requests to load all the chunks in the buffer that aren't
// already loading
var chunk, index, length;
for (index = 0, length = buffer.length; index < length; index++)
{
chunk = buffer[index];
if (!chunk.isLoading())
{
chunk.load();
}
}
// subscribe to the loadcomplete event on the next chunk
nextChunk.on('loadcomplete', onLoadComplete);
}
} | javascript | function()
{
// get the array of chunks whose contents need to be fetched
var buffer = chunks.slice(start, start + prefetchSize + 1);
// the first chunk in the buffer is the next chunk we want to load
var nextChunk = buffer[0];
// if we don't have anymore chunks to load, we're done
if (!nextChunk)
{
self.asyncClose();
}
else
{
// fire off requests to load all the chunks in the buffer that aren't
// already loading
var chunk, index, length;
for (index = 0, length = buffer.length; index < length; index++)
{
chunk = buffer[index];
if (!chunk.isLoading())
{
chunk.load();
}
}
// subscribe to the loadcomplete event on the next chunk
nextChunk.on('loadcomplete', onLoadComplete);
}
} | [
"function",
"(",
")",
"{",
"// get the array of chunks whose contents need to be fetched",
"var",
"buffer",
"=",
"chunks",
".",
"slice",
"(",
"start",
",",
"start",
"+",
"prefetchSize",
"+",
"1",
")",
";",
"// the first chunk in the buffer is the next chunk we want to load"... | Identifies the next chunk to load and issues requests to fetch both its
contents plus the contents of the next few chunks. If there are no more
chunks to load, a 'close' event is fired on the stream to notify
subscribers that all the chunks have been successfully read. | [
"Identifies",
"the",
"next",
"chunk",
"to",
"load",
"and",
"issues",
"requests",
"to",
"fetch",
"both",
"its",
"contents",
"plus",
"the",
"contents",
"of",
"the",
"next",
"few",
"chunks",
".",
"If",
"there",
"are",
"no",
"more",
"chunks",
"to",
"load",
"... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result_stream.js#L78-L108 | |
10,050 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | invokeStatementComplete | function invokeStatementComplete(statement, context)
{
// find out if the result will be streamed;
// if a value is not specified, get it from the connection
var streamResult = context.streamResult;
if (!Util.exists(streamResult))
{
streamResult = context.connectionConfig.getStreamResult();
}
// if the result will be streamed later,
// invoke the complete callback right away
if (streamResult)
{
context.complete(Errors.externalize(context.resultError), statement);
}
else
{
process.nextTick(function()
{
// aggregate all the rows into an array and pass this
// array to the complete callback as the last argument
var rows = [];
statement.streamRows()
.on('data', function(row)
{
rows.push(row);
})
.on('end', function()
{
context.complete(null, statement, rows);
})
.on('error', function(err)
{
context.complete(Errors.externalize(err), statement);
});
});
}
} | javascript | function invokeStatementComplete(statement, context)
{
// find out if the result will be streamed;
// if a value is not specified, get it from the connection
var streamResult = context.streamResult;
if (!Util.exists(streamResult))
{
streamResult = context.connectionConfig.getStreamResult();
}
// if the result will be streamed later,
// invoke the complete callback right away
if (streamResult)
{
context.complete(Errors.externalize(context.resultError), statement);
}
else
{
process.nextTick(function()
{
// aggregate all the rows into an array and pass this
// array to the complete callback as the last argument
var rows = [];
statement.streamRows()
.on('data', function(row)
{
rows.push(row);
})
.on('end', function()
{
context.complete(null, statement, rows);
})
.on('error', function(err)
{
context.complete(Errors.externalize(err), statement);
});
});
}
} | [
"function",
"invokeStatementComplete",
"(",
"statement",
",",
"context",
")",
"{",
"// find out if the result will be streamed;",
"// if a value is not specified, get it from the connection",
"var",
"streamResult",
"=",
"context",
".",
"streamResult",
";",
"if",
"(",
"!",
"Ut... | Invokes the statement complete callback.
@param {Object} statement
@param {Object} context | [
"Invokes",
"the",
"statement",
"complete",
"callback",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L543-L581 |
10,051 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | createOnStatementRequestSuccRow | function createOnStatementRequestSuccRow(statement, context)
{
return function(body)
{
// if we don't already have a result
if (!context.result)
{
// build a result from the response
context.result = new Result(
{
response : body,
statement : statement,
services : context.services,
connectionConfig : context.connectionConfig
});
// save the statement id
context.statementId = context.result.getStatementId();
}
else
{
// refresh the existing result
context.result.refresh(body);
}
// only update the parameters if the statement isn't a post-exec statement
if (context.type !== statementTypes.ROW_POST_EXEC)
{
Parameters.update(context.result.getParametersArray());
}
};
} | javascript | function createOnStatementRequestSuccRow(statement, context)
{
return function(body)
{
// if we don't already have a result
if (!context.result)
{
// build a result from the response
context.result = new Result(
{
response : body,
statement : statement,
services : context.services,
connectionConfig : context.connectionConfig
});
// save the statement id
context.statementId = context.result.getStatementId();
}
else
{
// refresh the existing result
context.result.refresh(body);
}
// only update the parameters if the statement isn't a post-exec statement
if (context.type !== statementTypes.ROW_POST_EXEC)
{
Parameters.update(context.result.getParametersArray());
}
};
} | [
"function",
"createOnStatementRequestSuccRow",
"(",
"statement",
",",
"context",
")",
"{",
"return",
"function",
"(",
"body",
")",
"{",
"// if we don't already have a result",
"if",
"(",
"!",
"context",
".",
"result",
")",
"{",
"// build a result from the response",
"... | Creates a function that can be used by row statements to process the response
when the request is successful.
@param statement
@param context
@returns {Function} | [
"Creates",
"a",
"function",
"that",
"can",
"be",
"used",
"by",
"row",
"statements",
"to",
"process",
"the",
"response",
"when",
"the",
"request",
"is",
"successful",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L643-L674 |
10,052 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | FileStatementPreExec | function FileStatementPreExec(
statementOptions, context, services, connectionConfig)
{
// call super
BaseStatement.apply(this, arguments);
// add the result request headers to the context
context.resultRequestHeaders = buildResultRequestHeadersFile();
/**
* Called when the statement request is successful.
*
* @param {Object} body
*/
context.onStatementRequestSucc = function(body)
{
context.fileMetadata = body;
};
/**
* Returns the file metadata generated by the statement.
*
* @returns {Object}
*/
this.getFileMetadata = function()
{
return context.fileMetadata;
};
// send a request to execute the file statement
sendRequestPreExec(context, context.onStatementRequestComp);
} | javascript | function FileStatementPreExec(
statementOptions, context, services, connectionConfig)
{
// call super
BaseStatement.apply(this, arguments);
// add the result request headers to the context
context.resultRequestHeaders = buildResultRequestHeadersFile();
/**
* Called when the statement request is successful.
*
* @param {Object} body
*/
context.onStatementRequestSucc = function(body)
{
context.fileMetadata = body;
};
/**
* Returns the file metadata generated by the statement.
*
* @returns {Object}
*/
this.getFileMetadata = function()
{
return context.fileMetadata;
};
// send a request to execute the file statement
sendRequestPreExec(context, context.onStatementRequestComp);
} | [
"function",
"FileStatementPreExec",
"(",
"statementOptions",
",",
"context",
",",
"services",
",",
"connectionConfig",
")",
"{",
"// call super",
"BaseStatement",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"// add the result request headers to the context",
... | Creates a new FileStatementPreExec instance.
@param {Object} statementOptions
@param {Object} context
@param {Object} services
@param {Object} connectionConfig
@constructor | [
"Creates",
"a",
"new",
"FileStatementPreExec",
"instance",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L685-L716 |
10,053 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | RowStatementPostExec | function RowStatementPostExec(
statementOptions, context, services, connectionConfig)
{
// call super
BaseStatement.apply(this, arguments);
// add the result request headers to the context
context.resultRequestHeaders = buildResultRequestHeadersRow();
/**
* Called when the statement request is successful.
*
* @param {Object} body
*/
context.onStatementRequestSucc =
createOnStatementRequestSuccRow(this, context);
/**
* Fetches the rows in this statement's result and invokes the each()
* callback on each row. If startIndex and endIndex values are specified, the
* each() callback will only be invoked on rows in the requested range. The
* end() callback will be invoked when either all the requested rows have been
* successfully processed, or if an error was encountered while trying to
* fetch the requested rows.
*
* @param {Object} options
*/
this.fetchRows = createFnFetchRows(this, context);
/**
* Streams the rows in this statement's result. If start and end values are
* specified, only rows in the specified range are streamed.
*
* @param {Object} options
*/
this.streamRows = createFnStreamRows(this, context);
// send a request to fetch the result
sendRequestPostExec(context, context.onStatementRequestComp);
} | javascript | function RowStatementPostExec(
statementOptions, context, services, connectionConfig)
{
// call super
BaseStatement.apply(this, arguments);
// add the result request headers to the context
context.resultRequestHeaders = buildResultRequestHeadersRow();
/**
* Called when the statement request is successful.
*
* @param {Object} body
*/
context.onStatementRequestSucc =
createOnStatementRequestSuccRow(this, context);
/**
* Fetches the rows in this statement's result and invokes the each()
* callback on each row. If startIndex and endIndex values are specified, the
* each() callback will only be invoked on rows in the requested range. The
* end() callback will be invoked when either all the requested rows have been
* successfully processed, or if an error was encountered while trying to
* fetch the requested rows.
*
* @param {Object} options
*/
this.fetchRows = createFnFetchRows(this, context);
/**
* Streams the rows in this statement's result. If start and end values are
* specified, only rows in the specified range are streamed.
*
* @param {Object} options
*/
this.streamRows = createFnStreamRows(this, context);
// send a request to fetch the result
sendRequestPostExec(context, context.onStatementRequestComp);
} | [
"function",
"RowStatementPostExec",
"(",
"statementOptions",
",",
"context",
",",
"services",
",",
"connectionConfig",
")",
"{",
"// call super",
"BaseStatement",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"// add the result request headers to the context",
... | Creates a new RowStatementPostExec instance.
@param {Object} statementOptions
@param {Object} context
@param {Object} services
@param {Object} connectionConfig
@constructor | [
"Creates",
"a",
"new",
"RowStatementPostExec",
"instance",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L729-L768 |
10,054 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | createFnStreamRows | function createFnStreamRows(statement, context)
{
return function(options)
{
// if some options are specified
if (Util.exists(options))
{
// check for invalid options
Errors.checkArgumentValid(Util.isObject(options),
ErrorCodes.ERR_STMT_FETCH_ROWS_INVALID_OPTIONS);
// check for invalid start
if (Util.exists(options.start))
{
Errors.checkArgumentValid(Util.isNumber(options.start),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_START);
}
// check for invalid end
if (Util.exists(options.end))
{
Errors.checkArgumentValid(Util.isNumber(options.end),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_END);
}
// check for invalid fetchAsString
var fetchAsString = options.fetchAsString;
if (Util.exists(fetchAsString))
{
// check that the value is an array
Errors.checkArgumentValid(Util.isArray(fetchAsString),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_FETCH_AS_STRING);
// check that all the array elements are valid
var invalidValueIndex = NativeTypes.findInvalidValue(fetchAsString);
Errors.checkArgumentValid(invalidValueIndex === -1,
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_FETCH_AS_STRING_VALUES,
JSON.stringify(fetchAsString[invalidValueIndex]));
}
}
return new RowStream(statement, context, options);
};
} | javascript | function createFnStreamRows(statement, context)
{
return function(options)
{
// if some options are specified
if (Util.exists(options))
{
// check for invalid options
Errors.checkArgumentValid(Util.isObject(options),
ErrorCodes.ERR_STMT_FETCH_ROWS_INVALID_OPTIONS);
// check for invalid start
if (Util.exists(options.start))
{
Errors.checkArgumentValid(Util.isNumber(options.start),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_START);
}
// check for invalid end
if (Util.exists(options.end))
{
Errors.checkArgumentValid(Util.isNumber(options.end),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_END);
}
// check for invalid fetchAsString
var fetchAsString = options.fetchAsString;
if (Util.exists(fetchAsString))
{
// check that the value is an array
Errors.checkArgumentValid(Util.isArray(fetchAsString),
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_FETCH_AS_STRING);
// check that all the array elements are valid
var invalidValueIndex = NativeTypes.findInvalidValue(fetchAsString);
Errors.checkArgumentValid(invalidValueIndex === -1,
ErrorCodes.ERR_STMT_STREAM_ROWS_INVALID_FETCH_AS_STRING_VALUES,
JSON.stringify(fetchAsString[invalidValueIndex]));
}
}
return new RowStream(statement, context, options);
};
} | [
"function",
"createFnStreamRows",
"(",
"statement",
",",
"context",
")",
"{",
"return",
"function",
"(",
"options",
")",
"{",
"// if some options are specified",
"if",
"(",
"Util",
".",
"exists",
"(",
"options",
")",
")",
"{",
"// check for invalid options",
"Erro... | Creates a function that streams the rows in a statement's result. If start
and end values are specified, only rows in the specified range are streamed.
@param statement
@param context | [
"Creates",
"a",
"function",
"that",
"streams",
"the",
"rows",
"in",
"a",
"statement",
"s",
"result",
".",
"If",
"start",
"and",
"end",
"values",
"are",
"specified",
"only",
"rows",
"in",
"the",
"specified",
"range",
"are",
"streamed",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L865-L908 |
10,055 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | fetchRowsFromResult | function fetchRowsFromResult(options, statement, context)
{
var numInterrupts = 0;
// forward to the result to get a FetchRowsOperation object
var operation = context.result.fetchRows(options);
// subscribe to the operation's 'complete' event
operation.on('complete', function(err, continueCallback)
{
// we want to retry if the error is retryable and the
// result stream hasn't been closed too many times
if (Errors.isLargeResultSetError(err) && err.response &&
(err.response.statusCode === 403) &&
(numInterrupts <
context.connectionConfig.getResultStreamInterrupts()))
{
// increment the interrupt counter
numInterrupts++;
// issue a request to fetch the result again
sendRequestPostExec(context, function(err, body)
{
// refresh the result
context.onStatementRequestComp(err, body);
// if there was no error, continue from where we got interrupted
if (!err)
{
continueCallback();
}
});
}
else
{
endFetchRows(options, statement, context);
}
});
} | javascript | function fetchRowsFromResult(options, statement, context)
{
var numInterrupts = 0;
// forward to the result to get a FetchRowsOperation object
var operation = context.result.fetchRows(options);
// subscribe to the operation's 'complete' event
operation.on('complete', function(err, continueCallback)
{
// we want to retry if the error is retryable and the
// result stream hasn't been closed too many times
if (Errors.isLargeResultSetError(err) && err.response &&
(err.response.statusCode === 403) &&
(numInterrupts <
context.connectionConfig.getResultStreamInterrupts()))
{
// increment the interrupt counter
numInterrupts++;
// issue a request to fetch the result again
sendRequestPostExec(context, function(err, body)
{
// refresh the result
context.onStatementRequestComp(err, body);
// if there was no error, continue from where we got interrupted
if (!err)
{
continueCallback();
}
});
}
else
{
endFetchRows(options, statement, context);
}
});
} | [
"function",
"fetchRowsFromResult",
"(",
"options",
",",
"statement",
",",
"context",
")",
"{",
"var",
"numInterrupts",
"=",
"0",
";",
"// forward to the result to get a FetchRowsOperation object",
"var",
"operation",
"=",
"context",
".",
"result",
".",
"fetchRows",
"(... | Fetches rows from the statement's result.
@param {Object} options the options passed to fetchRows().
@param {Object} statement
@param {Object} context | [
"Fetches",
"rows",
"from",
"the",
"statement",
"s",
"result",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L929-L967 |
10,056 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | sendCancelStatement | function sendCancelStatement(statementContext, statement, callback)
{
var url;
var json;
// use different rest endpoints based on whether the statement id is available
if (statementContext.statementId)
{
url = '/queries/' + statementContext.statementId + '/abort-request';
}
else
{
url = '/queries/v1/abort-request';
json =
{
requestId: statementContext.requestId
};
}
// issue a request to cancel the statement
statementContext.services.sf.request(
{
method : 'POST',
url : url,
json : json,
callback : function(err)
{
// if a callback was specified, invoke it
if (Util.isFunction(callback))
{
callback(Errors.externalize(err), statement);
}
}
});
} | javascript | function sendCancelStatement(statementContext, statement, callback)
{
var url;
var json;
// use different rest endpoints based on whether the statement id is available
if (statementContext.statementId)
{
url = '/queries/' + statementContext.statementId + '/abort-request';
}
else
{
url = '/queries/v1/abort-request';
json =
{
requestId: statementContext.requestId
};
}
// issue a request to cancel the statement
statementContext.services.sf.request(
{
method : 'POST',
url : url,
json : json,
callback : function(err)
{
// if a callback was specified, invoke it
if (Util.isFunction(callback))
{
callback(Errors.externalize(err), statement);
}
}
});
} | [
"function",
"sendCancelStatement",
"(",
"statementContext",
",",
"statement",
",",
"callback",
")",
"{",
"var",
"url",
";",
"var",
"json",
";",
"// use different rest endpoints based on whether the statement id is available",
"if",
"(",
"statementContext",
".",
"statementId... | Issues a request to cancel a statement.
@param {Object} statementContext
@param {Object} statement
@param {Function} callback | [
"Issues",
"a",
"request",
"to",
"cancel",
"a",
"statement",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L976-L1010 |
10,057 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | sendRequestPreExec | function sendRequestPreExec(statementContext, onResultAvailable)
{
// get the request headers
var headers = statementContext.resultRequestHeaders;
// build the basic json for the request
var json =
{
disableOfflineChunks : false,
sqlText : statementContext.sqlText
};
// if binds are specified, build a binds map and include it in the request
if (Util.exists(statementContext.binds))
{
json.bindings = buildBindsMap(statementContext.binds);
}
// include statement parameters if a value was specified
if (Util.exists(statementContext.parameters))
{
json.parameters = statementContext.parameters;
}
// include the internal flag if a value was specified
if (Util.exists(statementContext.internal))
{
json.isInternal = statementContext.internal;
}
// use the snowflake service to issue the request
sendSfRequest(statementContext,
{
method : 'POST',
headers : headers,
url : Url.format(
{
pathname : '/queries/v1/query-request',
search : QueryString.stringify(
{
requestId: statementContext.requestId
})
}),
json: json,
callback: buildResultRequestCallback(
statementContext, headers, onResultAvailable)
},
true);
} | javascript | function sendRequestPreExec(statementContext, onResultAvailable)
{
// get the request headers
var headers = statementContext.resultRequestHeaders;
// build the basic json for the request
var json =
{
disableOfflineChunks : false,
sqlText : statementContext.sqlText
};
// if binds are specified, build a binds map and include it in the request
if (Util.exists(statementContext.binds))
{
json.bindings = buildBindsMap(statementContext.binds);
}
// include statement parameters if a value was specified
if (Util.exists(statementContext.parameters))
{
json.parameters = statementContext.parameters;
}
// include the internal flag if a value was specified
if (Util.exists(statementContext.internal))
{
json.isInternal = statementContext.internal;
}
// use the snowflake service to issue the request
sendSfRequest(statementContext,
{
method : 'POST',
headers : headers,
url : Url.format(
{
pathname : '/queries/v1/query-request',
search : QueryString.stringify(
{
requestId: statementContext.requestId
})
}),
json: json,
callback: buildResultRequestCallback(
statementContext, headers, onResultAvailable)
},
true);
} | [
"function",
"sendRequestPreExec",
"(",
"statementContext",
",",
"onResultAvailable",
")",
"{",
"// get the request headers",
"var",
"headers",
"=",
"statementContext",
".",
"resultRequestHeaders",
";",
"// build the basic json for the request",
"var",
"json",
"=",
"{",
"dis... | Issues a request to get the result of a statement that hasn't been previously
executed.
@param statementContext
@param onResultAvailable | [
"Issues",
"a",
"request",
"to",
"get",
"the",
"result",
"of",
"a",
"statement",
"that",
"hasn",
"t",
"been",
"previously",
"executed",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L1019-L1067 |
10,058 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | buildBindsMap | function buildBindsMap(bindsArray)
{
var bindsMap = {};
var isArrayBinding = bindsArray.length >0 && Util.isArray(bindsArray[0]);
var singleArray = isArrayBinding ? bindsArray[0] : bindsArray;
for (var index = 0, length = singleArray.length; index < length; index++)
{
var value = singleArray[index];
// pick the appropriate logical data type based on the bind value
var type;
if (Util.isBoolean(value))
{
type = 'BOOLEAN';
}
else if (Util.isObject(value) || Util.isArray(value))
{
type = 'VARIANT';
}
else if (Util.isNumber(value))
{
type = 'REAL';
}
else
{
type = 'TEXT';
}
// convert non-null values to a string if necessary; we don't convert null
// because the client might want to run something like
// sql text = update t set name = :1 where id = 1;, binds = [null]
// and converting null to a string would result in us executing
// sql text = update t set name = 'null' where id = 1;
// instead of
// sql text = update t set name = null where id = 1;
if (!isArrayBinding)
{
if (value !== null && !Util.isString(value))
{
value = JSON.stringify(value);
}
}
else
{
value = [];
for (var rowIndex = 0; rowIndex < bindsArray.length; rowIndex++)
{
var value0 = bindsArray[rowIndex][index];
if (value0 !== null && !Util.isString(value0))
{
value0 = JSON.stringify(value0);
}
value.push(value0);
}
}
// add an entry for the bind variable to the map
bindsMap[index + 1] =
{
type : type,
value : value
};
}
return bindsMap;
} | javascript | function buildBindsMap(bindsArray)
{
var bindsMap = {};
var isArrayBinding = bindsArray.length >0 && Util.isArray(bindsArray[0]);
var singleArray = isArrayBinding ? bindsArray[0] : bindsArray;
for (var index = 0, length = singleArray.length; index < length; index++)
{
var value = singleArray[index];
// pick the appropriate logical data type based on the bind value
var type;
if (Util.isBoolean(value))
{
type = 'BOOLEAN';
}
else if (Util.isObject(value) || Util.isArray(value))
{
type = 'VARIANT';
}
else if (Util.isNumber(value))
{
type = 'REAL';
}
else
{
type = 'TEXT';
}
// convert non-null values to a string if necessary; we don't convert null
// because the client might want to run something like
// sql text = update t set name = :1 where id = 1;, binds = [null]
// and converting null to a string would result in us executing
// sql text = update t set name = 'null' where id = 1;
// instead of
// sql text = update t set name = null where id = 1;
if (!isArrayBinding)
{
if (value !== null && !Util.isString(value))
{
value = JSON.stringify(value);
}
}
else
{
value = [];
for (var rowIndex = 0; rowIndex < bindsArray.length; rowIndex++)
{
var value0 = bindsArray[rowIndex][index];
if (value0 !== null && !Util.isString(value0))
{
value0 = JSON.stringify(value0);
}
value.push(value0);
}
}
// add an entry for the bind variable to the map
bindsMap[index + 1] =
{
type : type,
value : value
};
}
return bindsMap;
} | [
"function",
"buildBindsMap",
"(",
"bindsArray",
")",
"{",
"var",
"bindsMap",
"=",
"{",
"}",
";",
"var",
"isArrayBinding",
"=",
"bindsArray",
".",
"length",
">",
"0",
"&&",
"Util",
".",
"isArray",
"(",
"bindsArray",
"[",
"0",
"]",
")",
";",
"var",
"sing... | Converts a bind variables array to a map that can be included in the
POST-body when issuing a pre-exec statement request.
@param bindsArray
@returns {Object} | [
"Converts",
"a",
"bind",
"variables",
"array",
"to",
"a",
"map",
"that",
"can",
"be",
"included",
"in",
"the",
"POST",
"-",
"body",
"when",
"issuing",
"a",
"pre",
"-",
"exec",
"statement",
"request",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L1077-L1143 |
10,059 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | sendRequestPostExec | function sendRequestPostExec(statementContext, onResultAvailable)
{
// get the request headers
var headers = statementContext.resultRequestHeaders;
// use the snowflake service to issue the request
sendSfRequest(statementContext,
{
method : 'GET',
headers: headers,
url : Url.format(
{
pathname: '/queries/' + statementContext.statementId + '/result',
search : QueryString.stringify(
{
disableOfflineChunks: false
})
}),
callback: buildResultRequestCallback(
statementContext, headers, onResultAvailable)
});
} | javascript | function sendRequestPostExec(statementContext, onResultAvailable)
{
// get the request headers
var headers = statementContext.resultRequestHeaders;
// use the snowflake service to issue the request
sendSfRequest(statementContext,
{
method : 'GET',
headers: headers,
url : Url.format(
{
pathname: '/queries/' + statementContext.statementId + '/result',
search : QueryString.stringify(
{
disableOfflineChunks: false
})
}),
callback: buildResultRequestCallback(
statementContext, headers, onResultAvailable)
});
} | [
"function",
"sendRequestPostExec",
"(",
"statementContext",
",",
"onResultAvailable",
")",
"{",
"// get the request headers",
"var",
"headers",
"=",
"statementContext",
".",
"resultRequestHeaders",
";",
"// use the snowflake service to issue the request",
"sendSfRequest",
"(",
... | Issues a request to get the result of a statement that has been previously
executed.
@param statementContext
@param onResultAvailable | [
"Issues",
"a",
"request",
"to",
"get",
"the",
"result",
"of",
"a",
"statement",
"that",
"has",
"been",
"previously",
"executed",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L1152-L1173 |
10,060 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | sendSfRequest | function sendSfRequest(statementContext, options, appendQueryParamOnRetry)
{
var sf = statementContext.services.sf;
var connectionConfig = statementContext.connectionConfig;
// clone the options
options = Util.apply({}, options);
// get the original url and callback
var urlOrig = options.url;
var callbackOrig = options.callback;
var numRetries = 0;
var maxNumRetries = connectionConfig.getRetrySfMaxNumRetries();
var sleep = connectionConfig.getRetrySfStartingSleepTime();
// create a function to send the request
var sendRequest = function sendRequest()
{
// if this is a retry and a query parameter should be appended to the url on
// retry, update the url
if ((numRetries > 0) && appendQueryParamOnRetry)
{
options.url = Util.url.appendParam(urlOrig, 'retry', true);
}
sf.request(options);
};
// replace the specified callback with a new one that retries
options.callback = function(err)
{
// if we haven't exceeded the maximum number of retries yet and the server
// came back with a retryable error code
if (numRetries < maxNumRetries &&
err && Util.isRetryableHttpError(
err.response, false // no retry for HTTP 403
))
{
// increment the retry count
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time.
var cap = connectionConfig.getRetrySfMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
Logger.getInstance().debug(
'Retrying statement with request id %s, retry count = %s',
statementContext.requestId, numRetries);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// invoke the original callback
callbackOrig.apply(this, arguments);
}
};
// issue the request
sendRequest();
} | javascript | function sendSfRequest(statementContext, options, appendQueryParamOnRetry)
{
var sf = statementContext.services.sf;
var connectionConfig = statementContext.connectionConfig;
// clone the options
options = Util.apply({}, options);
// get the original url and callback
var urlOrig = options.url;
var callbackOrig = options.callback;
var numRetries = 0;
var maxNumRetries = connectionConfig.getRetrySfMaxNumRetries();
var sleep = connectionConfig.getRetrySfStartingSleepTime();
// create a function to send the request
var sendRequest = function sendRequest()
{
// if this is a retry and a query parameter should be appended to the url on
// retry, update the url
if ((numRetries > 0) && appendQueryParamOnRetry)
{
options.url = Util.url.appendParam(urlOrig, 'retry', true);
}
sf.request(options);
};
// replace the specified callback with a new one that retries
options.callback = function(err)
{
// if we haven't exceeded the maximum number of retries yet and the server
// came back with a retryable error code
if (numRetries < maxNumRetries &&
err && Util.isRetryableHttpError(
err.response, false // no retry for HTTP 403
))
{
// increment the retry count
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time.
var cap = connectionConfig.getRetrySfMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
Logger.getInstance().debug(
'Retrying statement with request id %s, retry count = %s',
statementContext.requestId, numRetries);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// invoke the original callback
callbackOrig.apply(this, arguments);
}
};
// issue the request
sendRequest();
} | [
"function",
"sendSfRequest",
"(",
"statementContext",
",",
"options",
",",
"appendQueryParamOnRetry",
")",
"{",
"var",
"sf",
"=",
"statementContext",
".",
"services",
".",
"sf",
";",
"var",
"connectionConfig",
"=",
"statementContext",
".",
"connectionConfig",
";",
... | Issues a statement-related request using the Snowflake service.
@param {Object} statementContext the statement context.
@param {Object} options the request options.
@param {Boolean} [appendQueryParamOnRetry] whether retry=true should be
appended to the url if the request is retried. | [
"Issues",
"a",
"statement",
"-",
"related",
"request",
"using",
"the",
"Snowflake",
"service",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L1183-L1246 |
10,061 | snowflakedb/snowflake-connector-nodejs | lib/connection/statement.js | buildResultRequestCallback | function buildResultRequestCallback(
statementContext, headers, onResultAvailable)
{
var callback = function(err, body)
{
// if the result is not ready yet, extract the result url from the response
// and issue a GET request to try to fetch the result again
if (!err && body && (body.code === '333333' || body.code === '333334'))
{
// extract the statement id from the response and save it
statementContext.statementId = body.data.queryId;
// extract the result url from the response and try to get the result
// again
sendSfRequest(statementContext,
{
method : 'GET',
headers : headers,
url : body.data.getResultUrl,
callback : callback
});
}
else
{
onResultAvailable.call(null, err, body);
}
};
return callback;
} | javascript | function buildResultRequestCallback(
statementContext, headers, onResultAvailable)
{
var callback = function(err, body)
{
// if the result is not ready yet, extract the result url from the response
// and issue a GET request to try to fetch the result again
if (!err && body && (body.code === '333333' || body.code === '333334'))
{
// extract the statement id from the response and save it
statementContext.statementId = body.data.queryId;
// extract the result url from the response and try to get the result
// again
sendSfRequest(statementContext,
{
method : 'GET',
headers : headers,
url : body.data.getResultUrl,
callback : callback
});
}
else
{
onResultAvailable.call(null, err, body);
}
};
return callback;
} | [
"function",
"buildResultRequestCallback",
"(",
"statementContext",
",",
"headers",
",",
"onResultAvailable",
")",
"{",
"var",
"callback",
"=",
"function",
"(",
"err",
",",
"body",
")",
"{",
"// if the result is not ready yet, extract the result url from the response",
"// a... | Builds a callback for use in an exec-statement or fetch-result request.
@param statementContext
@param headers
@param onResultAvailable
@returns {Function} | [
"Builds",
"a",
"callback",
"for",
"use",
"in",
"an",
"exec",
"-",
"statement",
"or",
"fetch",
"-",
"result",
"request",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/statement.js#L1257-L1286 |
10,062 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | Chunk | function Chunk(options)
{
// make sure the options object contains all the necessary information
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isObject(options.statement));
Errors.assertInternal(Util.isObject(options.services));
Errors.assertInternal(Util.isNumber(options.startIndex));
Errors.assertInternal(Util.isArray(options.columns));
Errors.assertInternal(Util.isObject(options.mapColumnNameToIndices));
Errors.assertInternal(Util.isObject(options.statementParameters));
Errors.assertInternal(Util.isString(options.resultVersion));
Errors.assertInternal(Util.isNumber(options.rowCount));
// if the result is small (i.e. not persisted on S3/Blob), there's no
// compressed and uncompressed size, so default to -1
this._compressedSize = options.compressedSize || -1;
this._uncompressedSize = options.uncompressedSize || -1;
// copy out other information from the options object and save it
this._statement = options.statement;
this._services = options.services;
this._startIndex = options.startIndex;
this._url = options.url;
this._columns = options.columns;
this._mapColumnNameToIndices = options.mapColumnNameToIndices;
this._chunkHeaders = options.chunkHeaders;
this._rowset = options.rowset;
// use the start index and row count to compute the end index
this._endIndex = this._startIndex + options.rowCount - 1;
// use the start and end index to build an id for this chunk
this._id = buildId(this._startIndex, this._endIndex);
} | javascript | function Chunk(options)
{
// make sure the options object contains all the necessary information
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isObject(options.statement));
Errors.assertInternal(Util.isObject(options.services));
Errors.assertInternal(Util.isNumber(options.startIndex));
Errors.assertInternal(Util.isArray(options.columns));
Errors.assertInternal(Util.isObject(options.mapColumnNameToIndices));
Errors.assertInternal(Util.isObject(options.statementParameters));
Errors.assertInternal(Util.isString(options.resultVersion));
Errors.assertInternal(Util.isNumber(options.rowCount));
// if the result is small (i.e. not persisted on S3/Blob), there's no
// compressed and uncompressed size, so default to -1
this._compressedSize = options.compressedSize || -1;
this._uncompressedSize = options.uncompressedSize || -1;
// copy out other information from the options object and save it
this._statement = options.statement;
this._services = options.services;
this._startIndex = options.startIndex;
this._url = options.url;
this._columns = options.columns;
this._mapColumnNameToIndices = options.mapColumnNameToIndices;
this._chunkHeaders = options.chunkHeaders;
this._rowset = options.rowset;
// use the start index and row count to compute the end index
this._endIndex = this._startIndex + options.rowCount - 1;
// use the start and end index to build an id for this chunk
this._id = buildId(this._startIndex, this._endIndex);
} | [
"function",
"Chunk",
"(",
"options",
")",
"{",
"// make sure the options object contains all the necessary information",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"options",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
... | Creates a new Chunk.
@param options
@constructor | [
"Creates",
"a",
"new",
"Chunk",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L15-L48 |
10,063 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | function(err)
{
// we're done loading
self._isLoading = false;
// emit an event to notify subscribers
self.emit('loadcomplete', err, self);
// invoke the callback if one was specified
if (Util.isFunction(callback))
{
callback(err, self);
}
} | javascript | function(err)
{
// we're done loading
self._isLoading = false;
// emit an event to notify subscribers
self.emit('loadcomplete', err, self);
// invoke the callback if one was specified
if (Util.isFunction(callback))
{
callback(err, self);
}
} | [
"function",
"(",
"err",
")",
"{",
"// we're done loading",
"self",
".",
"_isLoading",
"=",
"false",
";",
"// emit an event to notify subscribers",
"self",
".",
"emit",
"(",
"'loadcomplete'",
",",
"err",
",",
"self",
")",
";",
"// invoke the callback if one was specifi... | Completes the chunk load.
@param err | [
"Completes",
"the",
"chunk",
"load",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L229-L242 | |
10,064 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | convertRowsetToRows | function convertRowsetToRows(
statement,
startIndex,
rowset,
columns,
mapColumnNameToIndices)
{
// assert that rowset and columns are arrays
Errors.assertInternal(Util.isArray(rowset));
Errors.assertInternal(Util.isArray(columns));
///////////////////////////////////////////////////////////////////////////
//// Create functions that will be used as row methods ////
///////////////////////////////////////////////////////////////////////////
/**
* Returns the index of this row in the result.
*
* @returns {Number}
*/
var getRowIndex = function()
{
return this.rowIndex;
};
/**
* Returns the statement that produced this row.
*
* @returns {*}
*/
var getStatement = function getStatement()
{
return statement;
};
/**
* Returns the value of a column.
*
* @param {String | Number} columnIdentifier this can be either the column
* name or the column index.
*
* @returns {*}
*/
var getColumnValue = function getColumnValue(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValue(this) : undefined;
};
/**
* Returns the value of a column as a String.
*
* @param {String | Number} columnIdentifier this can be either the column
* name or the column index.
*
* @returns {*}
*/
var getColumnValueAsString = function getColumnValueAsString(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValueAsString(this) : undefined;
};
///////////////////////////////////////////////////////////////////////////
//// Convert the rowset to an array of row objects ////
///////////////////////////////////////////////////////////////////////////
// create a new array to store the processed rows
var length = rowset.length;
var rows = new Array(length);
for (var index = 0; index < length; index++)
{
// add a new item to the rows array
rows[index] =
{
_arrayProcessedColumns : [],
values : rowset[index],
rowIndex : startIndex + index,
getRowIndex : getRowIndex,
getStatement : getStatement,
getColumnValue : getColumnValue,
getColumnValueAsString : getColumnValueAsString
};
}
return rows;
} | javascript | function convertRowsetToRows(
statement,
startIndex,
rowset,
columns,
mapColumnNameToIndices)
{
// assert that rowset and columns are arrays
Errors.assertInternal(Util.isArray(rowset));
Errors.assertInternal(Util.isArray(columns));
///////////////////////////////////////////////////////////////////////////
//// Create functions that will be used as row methods ////
///////////////////////////////////////////////////////////////////////////
/**
* Returns the index of this row in the result.
*
* @returns {Number}
*/
var getRowIndex = function()
{
return this.rowIndex;
};
/**
* Returns the statement that produced this row.
*
* @returns {*}
*/
var getStatement = function getStatement()
{
return statement;
};
/**
* Returns the value of a column.
*
* @param {String | Number} columnIdentifier this can be either the column
* name or the column index.
*
* @returns {*}
*/
var getColumnValue = function getColumnValue(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValue(this) : undefined;
};
/**
* Returns the value of a column as a String.
*
* @param {String | Number} columnIdentifier this can be either the column
* name or the column index.
*
* @returns {*}
*/
var getColumnValueAsString = function getColumnValueAsString(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValueAsString(this) : undefined;
};
///////////////////////////////////////////////////////////////////////////
//// Convert the rowset to an array of row objects ////
///////////////////////////////////////////////////////////////////////////
// create a new array to store the processed rows
var length = rowset.length;
var rows = new Array(length);
for (var index = 0; index < length; index++)
{
// add a new item to the rows array
rows[index] =
{
_arrayProcessedColumns : [],
values : rowset[index],
rowIndex : startIndex + index,
getRowIndex : getRowIndex,
getStatement : getStatement,
getColumnValue : getColumnValue,
getColumnValueAsString : getColumnValueAsString
};
}
return rows;
} | [
"function",
"convertRowsetToRows",
"(",
"statement",
",",
"startIndex",
",",
"rowset",
",",
"columns",
",",
"mapColumnNameToIndices",
")",
"{",
"// assert that rowset and columns are arrays",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isArray",
"(",
"rowset",
... | Converts a rowset to an array of records.
@param statement
@param startIndex the chunk start index.
@param rowset
@param columns
@param mapColumnNameToIndices
@returns {Array}
@private | [
"Converts",
"a",
"rowset",
"to",
"an",
"array",
"of",
"records",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L298-L393 |
10,065 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | getColumnValue | function getColumnValue(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValue(this) : undefined;
} | javascript | function getColumnValue(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValue(this) : undefined;
} | [
"function",
"getColumnValue",
"(",
"columnIdentifier",
")",
"{",
"// resolve the column identifier to the correct column if possible",
"var",
"column",
"=",
"resolveColumnIdentifierToColumn",
"(",
"columns",
",",
"columnIdentifier",
",",
"mapColumnNameToIndices",
")",
";",
"ret... | Returns the value of a column.
@param {String | Number} columnIdentifier this can be either the column
name or the column index.
@returns {*} | [
"Returns",
"the",
"value",
"of",
"a",
"column",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L342-L349 |
10,066 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | getColumnValueAsString | function getColumnValueAsString(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValueAsString(this) : undefined;
} | javascript | function getColumnValueAsString(columnIdentifier)
{
// resolve the column identifier to the correct column if possible
var column = resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices);
return column ? column.getRowValueAsString(this) : undefined;
} | [
"function",
"getColumnValueAsString",
"(",
"columnIdentifier",
")",
"{",
"// resolve the column identifier to the correct column if possible",
"var",
"column",
"=",
"resolveColumnIdentifierToColumn",
"(",
"columns",
",",
"columnIdentifier",
",",
"mapColumnNameToIndices",
")",
";"... | Returns the value of a column as a String.
@param {String | Number} columnIdentifier this can be either the column
name or the column index.
@returns {*} | [
"Returns",
"the",
"value",
"of",
"a",
"column",
"as",
"a",
"String",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L359-L366 |
10,067 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/chunk.js | resolveColumnIdentifierToColumn | function resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices)
{
var columnIndex;
// if the column identifier is a string, treat it as a column
// name and use it to get the index of the specified column
if (Util.isString(columnIdentifier))
{
// if a valid column name was specified, get the index of the first column
// with the specified name
if (mapColumnNameToIndices.hasOwnProperty(columnIdentifier))
{
columnIndex = mapColumnNameToIndices[columnIdentifier][0];
}
}
// if the column identifier is a number, treat it as a column index
else if (Util.isNumber(columnIdentifier))
{
columnIndex = columnIdentifier;
}
return columns[columnIndex];
} | javascript | function resolveColumnIdentifierToColumn(
columns, columnIdentifier, mapColumnNameToIndices)
{
var columnIndex;
// if the column identifier is a string, treat it as a column
// name and use it to get the index of the specified column
if (Util.isString(columnIdentifier))
{
// if a valid column name was specified, get the index of the first column
// with the specified name
if (mapColumnNameToIndices.hasOwnProperty(columnIdentifier))
{
columnIndex = mapColumnNameToIndices[columnIdentifier][0];
}
}
// if the column identifier is a number, treat it as a column index
else if (Util.isNumber(columnIdentifier))
{
columnIndex = columnIdentifier;
}
return columns[columnIndex];
} | [
"function",
"resolveColumnIdentifierToColumn",
"(",
"columns",
",",
"columnIdentifier",
",",
"mapColumnNameToIndices",
")",
"{",
"var",
"columnIndex",
";",
"// if the column identifier is a string, treat it as a column",
"// name and use it to get the index of the specified column",
"i... | Resolves a column identifier to the corresponding column if possible. The
column identifier can be a column name or a column index. If an invalid
column identifier is specified, we return undefined.
@param {Object[]} columns
@param {String | Number} columnIdentifier
@param {Object} mapColumnNameToIndices
@returns {*} | [
"Resolves",
"a",
"column",
"identifier",
"to",
"the",
"corresponding",
"column",
"if",
"possible",
".",
"The",
"column",
"identifier",
"can",
"be",
"a",
"column",
"name",
"or",
"a",
"column",
"index",
".",
"If",
"an",
"invalid",
"column",
"identifier",
"is",... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/chunk.js#L406-L429 |
10,068 | snowflakedb/snowflake-connector-nodejs | lib/services/large_result_set.js | LargeResultSetService | function LargeResultSetService(connectionConfig, httpClient)
{
// validate input
Errors.assertInternal(Util.isObject(connectionConfig));
Errors.assertInternal(Util.isObject(httpClient));
function isRetryableError(response, err)
{
// https://aws.amazon.com/articles/1904 (Handling Errors)
// Note: 403's are retried because of a bug in S3/Blob
return Util.isRetryableHttpError(
response, true // retry HTTP 403
) || err && err.code === "ECONNRESET";
}
/**
* Issues a request to get an object from S3/Blob.
*
* @param {Object} options
*/
this.getObject = function getObject(options)
{
var numRetries = 0, sleep = 1;
// get the maximum number of retries
var maxNumRetries = options.maxNumRetries;
if (!Util.exists(maxNumRetries))
{
maxNumRetries = connectionConfig.getRetryLargeResultSetMaxNumRetries();
}
Errors.assertInternal(Util.isNumber(maxNumRetries) && maxNumRetries >= 0);
// invoked when the request completes
var callback = function callback(err, response, body)
{
if (err)
{
// if we haven't exceeded the maximum number of retries yet and the
// server came back with a retryable error code.
if (numRetries < maxNumRetries && isRetryableError(response, err))
{
// increment the number of retries
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time:
var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// wrap the error into a network error
err = Errors.createNetworkError(
ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
}
}
// if the response contains xml, build an S3/Blob error from the response
else if (response.getResponseHeader('Content-Type') ===
'application/xml')
{
err = Errors.createLargeResultSetError(
ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
}
// if we have an error, clear the body
if (err)
{
body = null;
}
// if a callback was specified, invoke it
if (Util.isFunction(options.callback))
{
options.callback(err, body);
}
};
var sendRequest = function sendRequest()
{
// issue a request to get the object from S3/Blob
httpClient.request(
{
method: 'GET',
url: options.url,
headers: options.headers,
gzip: true, // gunzip the response
appendRequestId: false,
callback: callback
});
};
sendRequest();
};
} | javascript | function LargeResultSetService(connectionConfig, httpClient)
{
// validate input
Errors.assertInternal(Util.isObject(connectionConfig));
Errors.assertInternal(Util.isObject(httpClient));
function isRetryableError(response, err)
{
// https://aws.amazon.com/articles/1904 (Handling Errors)
// Note: 403's are retried because of a bug in S3/Blob
return Util.isRetryableHttpError(
response, true // retry HTTP 403
) || err && err.code === "ECONNRESET";
}
/**
* Issues a request to get an object from S3/Blob.
*
* @param {Object} options
*/
this.getObject = function getObject(options)
{
var numRetries = 0, sleep = 1;
// get the maximum number of retries
var maxNumRetries = options.maxNumRetries;
if (!Util.exists(maxNumRetries))
{
maxNumRetries = connectionConfig.getRetryLargeResultSetMaxNumRetries();
}
Errors.assertInternal(Util.isNumber(maxNumRetries) && maxNumRetries >= 0);
// invoked when the request completes
var callback = function callback(err, response, body)
{
if (err)
{
// if we haven't exceeded the maximum number of retries yet and the
// server came back with a retryable error code.
if (numRetries < maxNumRetries && isRetryableError(response, err))
{
// increment the number of retries
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time:
var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// wrap the error into a network error
err = Errors.createNetworkError(
ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
}
}
// if the response contains xml, build an S3/Blob error from the response
else if (response.getResponseHeader('Content-Type') ===
'application/xml')
{
err = Errors.createLargeResultSetError(
ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
}
// if we have an error, clear the body
if (err)
{
body = null;
}
// if a callback was specified, invoke it
if (Util.isFunction(options.callback))
{
options.callback(err, body);
}
};
var sendRequest = function sendRequest()
{
// issue a request to get the object from S3/Blob
httpClient.request(
{
method: 'GET',
url: options.url,
headers: options.headers,
gzip: true, // gunzip the response
appendRequestId: false,
callback: callback
});
};
sendRequest();
};
} | [
"function",
"LargeResultSetService",
"(",
"connectionConfig",
",",
"httpClient",
")",
"{",
"// validate input",
"Errors",
".",
"assertInternal",
"(",
"Util",
".",
"isObject",
"(",
"connectionConfig",
")",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"Util",
"."... | Creates a new instance of an LargeResultSetService.
@param {Object} connectionConfig
@param {Object} httpClient
@constructor | [
"Creates",
"a",
"new",
"instance",
"of",
"an",
"LargeResultSetService",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/services/large_result_set.js#L17-L113 |
10,069 | snowflakedb/snowflake-connector-nodejs | lib/services/large_result_set.js | callback | function callback(err, response, body)
{
if (err)
{
// if we haven't exceeded the maximum number of retries yet and the
// server came back with a retryable error code.
if (numRetries < maxNumRetries && isRetryableError(response, err))
{
// increment the number of retries
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time:
var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// wrap the error into a network error
err = Errors.createNetworkError(
ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
}
}
// if the response contains xml, build an S3/Blob error from the response
else if (response.getResponseHeader('Content-Type') ===
'application/xml')
{
err = Errors.createLargeResultSetError(
ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
}
// if we have an error, clear the body
if (err)
{
body = null;
}
// if a callback was specified, invoke it
if (Util.isFunction(options.callback))
{
options.callback(err, body);
}
} | javascript | function callback(err, response, body)
{
if (err)
{
// if we haven't exceeded the maximum number of retries yet and the
// server came back with a retryable error code.
if (numRetries < maxNumRetries && isRetryableError(response, err))
{
// increment the number of retries
numRetries++;
// use exponential backoff with decorrelated jitter to compute the
// next sleep time:
var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
sleep = Util.nextSleepTime(1, cap, sleep);
// wait the appropriate amount of time before retrying the request
setTimeout(sendRequest, sleep * 1000);
}
else
{
// wrap the error into a network error
err = Errors.createNetworkError(
ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
}
}
// if the response contains xml, build an S3/Blob error from the response
else if (response.getResponseHeader('Content-Type') ===
'application/xml')
{
err = Errors.createLargeResultSetError(
ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
}
// if we have an error, clear the body
if (err)
{
body = null;
}
// if a callback was specified, invoke it
if (Util.isFunction(options.callback))
{
options.callback(err, body);
}
} | [
"function",
"callback",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"// if we haven't exceeded the maximum number of retries yet and the",
"// server came back with a retryable error code.",
"if",
"(",
"numRetries",
"<",
"maxNumRetries",
... | invoked when the request completes | [
"invoked",
"when",
"the",
"request",
"completes"
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/services/large_result_set.js#L50-L95 |
10,070 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawDate | function convertRawDate(rawColumnValue, column, context)
{
return new SfTimestamp(
Number(rawColumnValue) * 86400, // convert to seconds
0, // no nano seconds
0, // no scale required
'UTC', // use utc as the timezone
context.format).toSfDate();
} | javascript | function convertRawDate(rawColumnValue, column, context)
{
return new SfTimestamp(
Number(rawColumnValue) * 86400, // convert to seconds
0, // no nano seconds
0, // no scale required
'UTC', // use utc as the timezone
context.format).toSfDate();
} | [
"function",
"convertRawDate",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"return",
"new",
"SfTimestamp",
"(",
"Number",
"(",
"rawColumnValue",
")",
"*",
"86400",
",",
"// convert to seconds",
"0",
",",
"// no nano seconds",
"0",
",",
"// no ... | Converts a raw column value of type Date to a Snowflake Date.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Date} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"Date",
"to",
"a",
"Snowflake",
"Date",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L294-L302 |
10,071 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawTime | function convertRawTime(rawColumnValue, column, context)
{
var columnScale = column.getScale();
// the values might be big so use BigNumber to do arithmetic
var valFracSecsBig =
new BigNumber(rawColumnValue).times(Math.pow(10, columnScale));
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
'UTC',
context.format).toSfTime();
} | javascript | function convertRawTime(rawColumnValue, column, context)
{
var columnScale = column.getScale();
// the values might be big so use BigNumber to do arithmetic
var valFracSecsBig =
new BigNumber(rawColumnValue).times(Math.pow(10, columnScale));
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
'UTC',
context.format).toSfTime();
} | [
"function",
"convertRawTime",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"var",
"columnScale",
"=",
"column",
".",
"getScale",
"(",
")",
";",
"// the values might be big so use BigNumber to do arithmetic",
"var",
"valFracSecsBig",
"=",
"new",
"Big... | Converts a raw column value of type Time to a Snowflake Time.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Object} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"Time",
"to",
"a",
"Snowflake",
"Time",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L313-L326 |
10,072 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawTimestampLtz | function convertRawTimestampLtz(rawColumnValue, column, context)
{
var columnScale = column.getScale();
// the values might be big so use BigNumber to do arithmetic
var valFracSecsBig =
new BigNumber(rawColumnValue).times(Math.pow(10, columnScale));
// create a new snowflake date
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
context.statementParameters['TIMEZONE'],
context.format).toSfDate();
} | javascript | function convertRawTimestampLtz(rawColumnValue, column, context)
{
var columnScale = column.getScale();
// the values might be big so use BigNumber to do arithmetic
var valFracSecsBig =
new BigNumber(rawColumnValue).times(Math.pow(10, columnScale));
// create a new snowflake date
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
context.statementParameters['TIMEZONE'],
context.format).toSfDate();
} | [
"function",
"convertRawTimestampLtz",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"var",
"columnScale",
"=",
"column",
".",
"getScale",
"(",
")",
";",
"// the values might be big so use BigNumber to do arithmetic",
"var",
"valFracSecsBig",
"=",
"new"... | Converts a raw column value of type TIMESTAMP_LTZ to a Snowflake Date.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Date} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"TIMESTAMP_LTZ",
"to",
"a",
"Snowflake",
"Date",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L337-L351 |
10,073 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawTimestampTz | function convertRawTimestampTz(rawColumnValue, column, context)
{
var valFracSecsBig;
var valFracSecsWithTzBig;
var timezoneBig;
var timezone;
var timestampAndTZIndex;
// compute the scale factor
var columnScale = column.getScale();
var scaleFactor = Math.pow(10, columnScale);
var resultVersion = context.resultVersion;
if (resultVersion === '0' || resultVersion === undefined)
{
// the values might be big so use BigNumber to do arithmetic
valFracSecsBig =
new BigNumber(rawColumnValue).times(scaleFactor);
// for _tz, the timezone is baked into the value
valFracSecsWithTzBig = valFracSecsBig;
// extract everything but the lowest 14 bits to get the fractional seconds
valFracSecsBig =
valFracSecsWithTzBig.dividedBy(16384).floor();
// extract the lowest 14 bits to get the timezone
if (valFracSecsWithTzBig.greaterThanOrEqualTo(0))
{
timezoneBig = valFracSecsWithTzBig.modulo(16384);
}
else
{
timezoneBig =
valFracSecsWithTzBig.modulo(16384).plus(16384);
}
}
else
{
// split the value into number of seconds and timezone index
timestampAndTZIndex = rawColumnValue.split(' ');
// the values might be big so use BigNumber to do arithmetic
valFracSecsBig =
new BigNumber(timestampAndTZIndex[0]).times(scaleFactor);
timezoneBig = new BigNumber(timestampAndTZIndex[1]);
}
timezone = timezoneBig.toNumber();
// assert that timezone is valid
Errors.assertInternal(timezone >= 0 && timezone <= 2880);
// subtract 24 hours from the timezone to map [0, 48] to
// [-24, 24], and convert the result to a number
timezone = timezone - 1440;
// create a new snowflake date
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
timezone,
context.format).toSfDate();
} | javascript | function convertRawTimestampTz(rawColumnValue, column, context)
{
var valFracSecsBig;
var valFracSecsWithTzBig;
var timezoneBig;
var timezone;
var timestampAndTZIndex;
// compute the scale factor
var columnScale = column.getScale();
var scaleFactor = Math.pow(10, columnScale);
var resultVersion = context.resultVersion;
if (resultVersion === '0' || resultVersion === undefined)
{
// the values might be big so use BigNumber to do arithmetic
valFracSecsBig =
new BigNumber(rawColumnValue).times(scaleFactor);
// for _tz, the timezone is baked into the value
valFracSecsWithTzBig = valFracSecsBig;
// extract everything but the lowest 14 bits to get the fractional seconds
valFracSecsBig =
valFracSecsWithTzBig.dividedBy(16384).floor();
// extract the lowest 14 bits to get the timezone
if (valFracSecsWithTzBig.greaterThanOrEqualTo(0))
{
timezoneBig = valFracSecsWithTzBig.modulo(16384);
}
else
{
timezoneBig =
valFracSecsWithTzBig.modulo(16384).plus(16384);
}
}
else
{
// split the value into number of seconds and timezone index
timestampAndTZIndex = rawColumnValue.split(' ');
// the values might be big so use BigNumber to do arithmetic
valFracSecsBig =
new BigNumber(timestampAndTZIndex[0]).times(scaleFactor);
timezoneBig = new BigNumber(timestampAndTZIndex[1]);
}
timezone = timezoneBig.toNumber();
// assert that timezone is valid
Errors.assertInternal(timezone >= 0 && timezone <= 2880);
// subtract 24 hours from the timezone to map [0, 48] to
// [-24, 24], and convert the result to a number
timezone = timezone - 1440;
// create a new snowflake date
return convertRawTimestampHelper(
valFracSecsBig,
columnScale,
timezone,
context.format).toSfDate();
} | [
"function",
"convertRawTimestampTz",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"var",
"valFracSecsBig",
";",
"var",
"valFracSecsWithTzBig",
";",
"var",
"timezoneBig",
";",
"var",
"timezone",
";",
"var",
"timestampAndTZIndex",
";",
"// compute t... | Converts a raw column value of type TIMESTAMP_TZ to a Snowflake Date.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Date} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"TIMESTAMP_TZ",
"to",
"a",
"Snowflake",
"Date",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L387-L451 |
10,074 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawVariant | function convertRawVariant(rawColumnValue, column, context)
{
var ret;
// if the input is a non-empty string, convert it to a json object
if (Util.string.isNotNullOrEmpty(rawColumnValue))
{
try
{
ret = eval("(" + rawColumnValue + ")");
}
catch (parseError)
{
// TODO: log the error
// throw the error
throw parseError;
}
}
return ret;
} | javascript | function convertRawVariant(rawColumnValue, column, context)
{
var ret;
// if the input is a non-empty string, convert it to a json object
if (Util.string.isNotNullOrEmpty(rawColumnValue))
{
try
{
ret = eval("(" + rawColumnValue + ")");
}
catch (parseError)
{
// TODO: log the error
// throw the error
throw parseError;
}
}
return ret;
} | [
"function",
"convertRawVariant",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"var",
"ret",
";",
"// if the input is a non-empty string, convert it to a json object",
"if",
"(",
"Util",
".",
"string",
".",
"isNotNullOrEmpty",
"(",
"rawColumnValue",
")... | Converts a raw column value of type Variant to a JavaScript value.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Object | Array} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"Variant",
"to",
"a",
"JavaScript",
"value",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L498-L519 |
10,075 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | convertRawBinary | function convertRawBinary(rawColumnValue, column, context)
{
// Ensure the format is valid.
var format = context.format.toUpperCase();
Errors.assertInternal(format === "HEX" || format === "BASE64");
// Decode hex string sent by GS.
var buffer = Buffer.from(rawColumnValue, "HEX");
if (format === "HEX")
{
buffer.toStringSf = function()
{
// The raw value is already an uppercase hex string, so just return it.
// Note that buffer.toString("HEX") returns a lowercase hex string, but we
// want upper case.
return rawColumnValue;
}
}
else
{
buffer.toStringSf = function()
{
return this.toString("BASE64");
}
}
buffer.getFormat = function()
{
return format;
};
return buffer;
} | javascript | function convertRawBinary(rawColumnValue, column, context)
{
// Ensure the format is valid.
var format = context.format.toUpperCase();
Errors.assertInternal(format === "HEX" || format === "BASE64");
// Decode hex string sent by GS.
var buffer = Buffer.from(rawColumnValue, "HEX");
if (format === "HEX")
{
buffer.toStringSf = function()
{
// The raw value is already an uppercase hex string, so just return it.
// Note that buffer.toString("HEX") returns a lowercase hex string, but we
// want upper case.
return rawColumnValue;
}
}
else
{
buffer.toStringSf = function()
{
return this.toString("BASE64");
}
}
buffer.getFormat = function()
{
return format;
};
return buffer;
} | [
"function",
"convertRawBinary",
"(",
"rawColumnValue",
",",
"column",
",",
"context",
")",
"{",
"// Ensure the format is valid.",
"var",
"format",
"=",
"context",
".",
"format",
".",
"toUpperCase",
"(",
")",
";",
"Errors",
".",
"assertInternal",
"(",
"format",
"... | Converts a raw column value of type Binary to a Buffer.
@param {String} rawColumnValue
@param {Object} column
@param {Object} context
@returns {Buffer} | [
"Converts",
"a",
"raw",
"column",
"value",
"of",
"type",
"Binary",
"to",
"a",
"Buffer",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L530-L563 |
10,076 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/column.js | extractFromRow | function extractFromRow(row, context, asString)
{
var map = row._arrayProcessedColumns;
var values = row.values;
// get the value
var columnIndex = this.getIndex();
var ret = values[columnIndex];
// if we want the value as a string, and the column is of type variant, and we
// haven't already processed the value before, we don't need to process the
// value, so only process if none of the aforementioned conditions are true
if (!(asString && this.isVariant() && !map[columnIndex]))
{
// if the column value has not been processed yet, process it, put it back
// in the values array, and remember that the value has been processed
if (!map[columnIndex])
{
if (ret !== null)
{
ret = values[columnIndex] =
context.convert(values[columnIndex], this, context);
}
map[columnIndex] = true;
}
// use the appropriate extraction function depending on whether
// we want the value or a string representation of the value
var extractFn = !asString ? context.toValue : context.toString;
ret = extractFn(ret);
}
return ret;
} | javascript | function extractFromRow(row, context, asString)
{
var map = row._arrayProcessedColumns;
var values = row.values;
// get the value
var columnIndex = this.getIndex();
var ret = values[columnIndex];
// if we want the value as a string, and the column is of type variant, and we
// haven't already processed the value before, we don't need to process the
// value, so only process if none of the aforementioned conditions are true
if (!(asString && this.isVariant() && !map[columnIndex]))
{
// if the column value has not been processed yet, process it, put it back
// in the values array, and remember that the value has been processed
if (!map[columnIndex])
{
if (ret !== null)
{
ret = values[columnIndex] =
context.convert(values[columnIndex], this, context);
}
map[columnIndex] = true;
}
// use the appropriate extraction function depending on whether
// we want the value or a string representation of the value
var extractFn = !asString ? context.toValue : context.toString;
ret = extractFn(ret);
}
return ret;
} | [
"function",
"extractFromRow",
"(",
"row",
",",
"context",
",",
"asString",
")",
"{",
"var",
"map",
"=",
"row",
".",
"_arrayProcessedColumns",
";",
"var",
"values",
"=",
"row",
".",
"values",
";",
"// get the value",
"var",
"columnIndex",
"=",
"this",
".",
... | Extracts the value of a column from a given row.
@param {Object} row
@param {Object} context
@param {Boolean} asString
@returns {*} | [
"Extracts",
"the",
"value",
"of",
"a",
"column",
"from",
"a",
"given",
"row",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/column.js#L709-L742 |
10,077 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | Result | function Result(options)
{
var data;
var chunkHeaders;
var parametersMap;
var parametersArray;
var length;
var index;
var parameter;
var mapColumnNameToIndices;
var columns;
var column;
// assert that options is a valid object that contains a response, statement,
// services and connection config
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isObject(options.response));
Errors.assertInternal(Util.isObject(options.statement));
Errors.assertInternal(Util.isObject(options.services));
Errors.assertInternal(Util.isObject(options.connectionConfig));
// save the statement, services and connection config
this._statement = options.statement;
this._services = options.services;
this._connectionConfig = options.connectionConfig;
data = options.response.data;
this._statementId = data.queryId;
this._version = version = String(data.version); // don't rely on the version being a number
this._returnedRows = data.returned;
this._totalRows = data.total;
this._statementTypeId = data.statementTypeId;
// if no chunk headers were specified, but a query-result-master-key (qrmk)
// was specified, build the chunk headers from the qrmk
chunkHeaders = data.chunkHeaders;
if (!Util.isObject(chunkHeaders) && Util.isString(data.qrmk))
{
chunkHeaders =
{
'x-amz-server-side-encryption-customer-algorithm': 'AES256',
'x-amz-server-side-encryption-customer-key': data.qrmk
};
}
this._chunkHeaders = chunkHeaders;
// build a session state object from the response data; this can be used to
// get the values of the current role, current warehouse, current database,
// etc.
this._sessionState = createSessionState(data);
// convert the parameters array to a map
parametersMap = {};
parametersArray = data.parameters;
for (index = 0, length = parametersArray.length; index < length; index++)
{
parameter = parametersArray[index];
parametersMap[parameter.name] = parameter.value;
}
// save the parameters array
this._parametersArray = parametersArray;
// TODO: add timezone related information to columns
// create columns from the rowtype array returned in the result
var rowtype = data.rowtype;
var numColumns = rowtype.length;
this._columns = columns = new Array(numColumns);
// convert the rowtype array to an array of columns and build an inverted
// index map in which the keys are the column names and the values are the
// indices of the columns with the corresponding names
this._mapColumnNameToIndices = mapColumnNameToIndices = {};
for (index = 0; index < numColumns; index++)
{
// create a new column and add it to the columns array
columns[index] = column =
new Column(rowtype[index], index, parametersMap, version);
// if we don't already have an index array for a column with this name,
// create a new one, otherwise just append to the existing array of indices
mapColumnNameToIndices[column.getName()] =
mapColumnNameToIndices[column.getName()] || [];
mapColumnNameToIndices[column.getName()].push(index);
}
// create chunks
this._chunks = createChunks(
data.chunks,
data.rowset,
this._columns,
this._mapColumnNameToIndices,
this._chunkHeaders,
parametersMap,
this._version,
this._statement,
this._services);
// create a chunk cache and save a reference to it in case we need to
// TODO: should we be clearing the cache at some point, e.g. when the result
// is destroyed?
this._chunkCache = createChunkCache(
this._chunks,
this._connectionConfig.getResultChunkCacheSize());
} | javascript | function Result(options)
{
var data;
var chunkHeaders;
var parametersMap;
var parametersArray;
var length;
var index;
var parameter;
var mapColumnNameToIndices;
var columns;
var column;
// assert that options is a valid object that contains a response, statement,
// services and connection config
Errors.assertInternal(Util.isObject(options));
Errors.assertInternal(Util.isObject(options.response));
Errors.assertInternal(Util.isObject(options.statement));
Errors.assertInternal(Util.isObject(options.services));
Errors.assertInternal(Util.isObject(options.connectionConfig));
// save the statement, services and connection config
this._statement = options.statement;
this._services = options.services;
this._connectionConfig = options.connectionConfig;
data = options.response.data;
this._statementId = data.queryId;
this._version = version = String(data.version); // don't rely on the version being a number
this._returnedRows = data.returned;
this._totalRows = data.total;
this._statementTypeId = data.statementTypeId;
// if no chunk headers were specified, but a query-result-master-key (qrmk)
// was specified, build the chunk headers from the qrmk
chunkHeaders = data.chunkHeaders;
if (!Util.isObject(chunkHeaders) && Util.isString(data.qrmk))
{
chunkHeaders =
{
'x-amz-server-side-encryption-customer-algorithm': 'AES256',
'x-amz-server-side-encryption-customer-key': data.qrmk
};
}
this._chunkHeaders = chunkHeaders;
// build a session state object from the response data; this can be used to
// get the values of the current role, current warehouse, current database,
// etc.
this._sessionState = createSessionState(data);
// convert the parameters array to a map
parametersMap = {};
parametersArray = data.parameters;
for (index = 0, length = parametersArray.length; index < length; index++)
{
parameter = parametersArray[index];
parametersMap[parameter.name] = parameter.value;
}
// save the parameters array
this._parametersArray = parametersArray;
// TODO: add timezone related information to columns
// create columns from the rowtype array returned in the result
var rowtype = data.rowtype;
var numColumns = rowtype.length;
this._columns = columns = new Array(numColumns);
// convert the rowtype array to an array of columns and build an inverted
// index map in which the keys are the column names and the values are the
// indices of the columns with the corresponding names
this._mapColumnNameToIndices = mapColumnNameToIndices = {};
for (index = 0; index < numColumns; index++)
{
// create a new column and add it to the columns array
columns[index] = column =
new Column(rowtype[index], index, parametersMap, version);
// if we don't already have an index array for a column with this name,
// create a new one, otherwise just append to the existing array of indices
mapColumnNameToIndices[column.getName()] =
mapColumnNameToIndices[column.getName()] || [];
mapColumnNameToIndices[column.getName()].push(index);
}
// create chunks
this._chunks = createChunks(
data.chunks,
data.rowset,
this._columns,
this._mapColumnNameToIndices,
this._chunkHeaders,
parametersMap,
this._version,
this._statement,
this._services);
// create a chunk cache and save a reference to it in case we need to
// TODO: should we be clearing the cache at some point, e.g. when the result
// is destroyed?
this._chunkCache = createChunkCache(
this._chunks,
this._connectionConfig.getResultChunkCacheSize());
} | [
"function",
"Result",
"(",
"options",
")",
"{",
"var",
"data",
";",
"var",
"chunkHeaders",
";",
"var",
"parametersMap",
";",
"var",
"parametersArray",
";",
"var",
"length",
";",
"var",
"index",
";",
"var",
"parameter",
";",
"var",
"mapColumnNameToIndices",
"... | Creates a new Result.
@param {Object} options
@constructor | [
"Creates",
"a",
"new",
"Result",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L21-L128 |
10,078 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | createSessionState | function createSessionState(responseData)
{
var currentRole = responseData.finalRoleName;
var currentWarehouse = responseData.finalWarehouseName;
var currentDatabaseProvider = responseData.databaseProvider;
var currentDatabase = responseData.finalDatabaseName;
var currentSchema = responseData.finalSchemaName;
return {
getCurrentRole: function()
{
return currentRole;
},
getCurrentWarehouse: function()
{
return currentWarehouse;
},
getCurrentDatabaseProvider: function()
{
return currentDatabaseProvider;
},
getCurrentDatabase: function()
{
return currentDatabase;
},
getCurrentSchema: function()
{
return currentSchema;
}
};
} | javascript | function createSessionState(responseData)
{
var currentRole = responseData.finalRoleName;
var currentWarehouse = responseData.finalWarehouseName;
var currentDatabaseProvider = responseData.databaseProvider;
var currentDatabase = responseData.finalDatabaseName;
var currentSchema = responseData.finalSchemaName;
return {
getCurrentRole: function()
{
return currentRole;
},
getCurrentWarehouse: function()
{
return currentWarehouse;
},
getCurrentDatabaseProvider: function()
{
return currentDatabaseProvider;
},
getCurrentDatabase: function()
{
return currentDatabase;
},
getCurrentSchema: function()
{
return currentSchema;
}
};
} | [
"function",
"createSessionState",
"(",
"responseData",
")",
"{",
"var",
"currentRole",
"=",
"responseData",
".",
"finalRoleName",
";",
"var",
"currentWarehouse",
"=",
"responseData",
".",
"finalWarehouseName",
";",
"var",
"currentDatabaseProvider",
"=",
"responseData",
... | Creates a session state object from the values of the current role, current
warehouse, etc., returned in the result response.
@param responseData
@returns {Object} | [
"Creates",
"a",
"session",
"state",
"object",
"from",
"the",
"values",
"of",
"the",
"current",
"role",
"current",
"warehouse",
"etc",
".",
"returned",
"in",
"the",
"result",
"response",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L195-L225 |
10,079 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | createChunks | function createChunks(chunkCfgs,
rowset,
columns,
mapColumnNameToIndices,
chunkHeaders,
statementParameters,
resultVersion,
statement,
services)
{
var chunks;
var startIndex;
var length;
var index;
var chunkCfg;
// if we don't have any chunks, or if some records were returned inline,
// fabricate a config object for the first chunk
chunkCfgs = chunkCfgs || [];
if (!chunkCfgs || rowset.length > 0)
{
chunkCfgs.unshift(
{
rowCount: rowset.length,
url: null,
rowset: rowset
});
}
chunks = new Array(chunkCfgs.length);
// loop over the chunk config objects and build Chunk instances out of them
startIndex = 0;
length = chunkCfgs.length;
for (index = 0; index < length; index++)
{
chunkCfg = chunkCfgs[index];
// augment the chunk config object with additional information
chunkCfg.statement = statement;
chunkCfg.services = services;
chunkCfg.startIndex = startIndex;
chunkCfg.columns = columns;
chunkCfg.mapColumnNameToIndices = mapColumnNameToIndices;
chunkCfg.chunkHeaders = chunkHeaders;
chunkCfg.statementParameters = statementParameters;
chunkCfg.resultVersion = resultVersion;
// increment the start index for the next chunk
startIndex += chunkCfg.rowCount;
// create a new Chunk from the config object, and add it to the chunks array
chunks[index] = new Chunk(chunkCfg);
}
return chunks;
} | javascript | function createChunks(chunkCfgs,
rowset,
columns,
mapColumnNameToIndices,
chunkHeaders,
statementParameters,
resultVersion,
statement,
services)
{
var chunks;
var startIndex;
var length;
var index;
var chunkCfg;
// if we don't have any chunks, or if some records were returned inline,
// fabricate a config object for the first chunk
chunkCfgs = chunkCfgs || [];
if (!chunkCfgs || rowset.length > 0)
{
chunkCfgs.unshift(
{
rowCount: rowset.length,
url: null,
rowset: rowset
});
}
chunks = new Array(chunkCfgs.length);
// loop over the chunk config objects and build Chunk instances out of them
startIndex = 0;
length = chunkCfgs.length;
for (index = 0; index < length; index++)
{
chunkCfg = chunkCfgs[index];
// augment the chunk config object with additional information
chunkCfg.statement = statement;
chunkCfg.services = services;
chunkCfg.startIndex = startIndex;
chunkCfg.columns = columns;
chunkCfg.mapColumnNameToIndices = mapColumnNameToIndices;
chunkCfg.chunkHeaders = chunkHeaders;
chunkCfg.statementParameters = statementParameters;
chunkCfg.resultVersion = resultVersion;
// increment the start index for the next chunk
startIndex += chunkCfg.rowCount;
// create a new Chunk from the config object, and add it to the chunks array
chunks[index] = new Chunk(chunkCfg);
}
return chunks;
} | [
"function",
"createChunks",
"(",
"chunkCfgs",
",",
"rowset",
",",
"columns",
",",
"mapColumnNameToIndices",
",",
"chunkHeaders",
",",
"statementParameters",
",",
"resultVersion",
",",
"statement",
",",
"services",
")",
"{",
"var",
"chunks",
";",
"var",
"startIndex... | Creates an array of Chunk instances from the chunk-related information in the
result response.
@param chunkCfgs
@param rowset
@param columns
@param mapColumnNameToIndices
@param chunkHeaders
@param statementParameters
@param resultVersion
@param statement
@param services
@returns {Chunk} | [
"Creates",
"an",
"array",
"of",
"Chunk",
"instances",
"from",
"the",
"chunk",
"-",
"related",
"information",
"in",
"the",
"result",
"response",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L243-L299 |
10,080 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | function(chunk)
{
// get all the rows in the current chunk that overlap with the requested
// window
var chunkStart = chunk.getStartIndex();
var chunkEnd = chunk.getEndIndex();
var rows = chunk.getRows().slice(
Math.max(chunkStart, start) - chunkStart,
Math.min(chunkEnd, end) + 1 - chunkStart);
var rowIndex = 0;
var rowsLength = rows.length;
// create a function that can be called to batch-process rows
var processRows = function()
{
// get the start position and start time
var startIndex = rowIndex;
var startTime = Date.now();
var each = options.each;
while (rowIndex < rowsLength)
{
// invoke the each() callback on the current row
var ret = each(rows[rowIndex++]);
context.numRowsProcessed++;
// if the callback returned false, stop processing rows
if (ret === false)
{
var stoppedProcessingRows = true;
break;
}
// use the current position and current time to check if we've been
// processing rows for too long; if so, leave the rest for the next
// tick of the event loop
if ((rowIndex - startIndex) >= context.rowBatchSize &&
(Date.now() - startTime) > context.rowBatchDuration)
{
process.nextTick(processRows);
break;
}
}
// if there are no more rows for us to process in this chunk
if (!(rowIndex < rowsLength) || stoppedProcessingRows)
{
// if we exhausted all the rows in this chunk and we haven't yet
// processed all the rows we want to process, ask the result stream to
// do another read
if (!(rowIndex < rowsLength) &&
context.numRowsProcessed !== context.maxNumRowsToProcess)
{
resultStream.read();
}
else
{
// we've either processed all the rows we wanted to process or we
// were told to stop processing rows by the each() callback; either
// way, close the result stream to complete the operation
resultStream.asyncClose();
}
}
};
// start processing rows
processRows();
} | javascript | function(chunk)
{
// get all the rows in the current chunk that overlap with the requested
// window
var chunkStart = chunk.getStartIndex();
var chunkEnd = chunk.getEndIndex();
var rows = chunk.getRows().slice(
Math.max(chunkStart, start) - chunkStart,
Math.min(chunkEnd, end) + 1 - chunkStart);
var rowIndex = 0;
var rowsLength = rows.length;
// create a function that can be called to batch-process rows
var processRows = function()
{
// get the start position and start time
var startIndex = rowIndex;
var startTime = Date.now();
var each = options.each;
while (rowIndex < rowsLength)
{
// invoke the each() callback on the current row
var ret = each(rows[rowIndex++]);
context.numRowsProcessed++;
// if the callback returned false, stop processing rows
if (ret === false)
{
var stoppedProcessingRows = true;
break;
}
// use the current position and current time to check if we've been
// processing rows for too long; if so, leave the rest for the next
// tick of the event loop
if ((rowIndex - startIndex) >= context.rowBatchSize &&
(Date.now() - startTime) > context.rowBatchDuration)
{
process.nextTick(processRows);
break;
}
}
// if there are no more rows for us to process in this chunk
if (!(rowIndex < rowsLength) || stoppedProcessingRows)
{
// if we exhausted all the rows in this chunk and we haven't yet
// processed all the rows we want to process, ask the result stream to
// do another read
if (!(rowIndex < rowsLength) &&
context.numRowsProcessed !== context.maxNumRowsToProcess)
{
resultStream.read();
}
else
{
// we've either processed all the rows we wanted to process or we
// were told to stop processing rows by the each() callback; either
// way, close the result stream to complete the operation
resultStream.asyncClose();
}
}
};
// start processing rows
processRows();
} | [
"function",
"(",
"chunk",
")",
"{",
"// get all the rows in the current chunk that overlap with the requested",
"// window",
"var",
"chunkStart",
"=",
"chunk",
".",
"getStartIndex",
"(",
")",
";",
"var",
"chunkEnd",
"=",
"chunk",
".",
"getEndIndex",
"(",
")",
";",
"... | Processes the rows in a given chunk.
@param {Object} chunk | [
"Processes",
"the",
"rows",
"in",
"a",
"given",
"chunk",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L402-L471 | |
10,081 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | function()
{
// get the start position and start time
var startIndex = rowIndex;
var startTime = Date.now();
var each = options.each;
while (rowIndex < rowsLength)
{
// invoke the each() callback on the current row
var ret = each(rows[rowIndex++]);
context.numRowsProcessed++;
// if the callback returned false, stop processing rows
if (ret === false)
{
var stoppedProcessingRows = true;
break;
}
// use the current position and current time to check if we've been
// processing rows for too long; if so, leave the rest for the next
// tick of the event loop
if ((rowIndex - startIndex) >= context.rowBatchSize &&
(Date.now() - startTime) > context.rowBatchDuration)
{
process.nextTick(processRows);
break;
}
}
// if there are no more rows for us to process in this chunk
if (!(rowIndex < rowsLength) || stoppedProcessingRows)
{
// if we exhausted all the rows in this chunk and we haven't yet
// processed all the rows we want to process, ask the result stream to
// do another read
if (!(rowIndex < rowsLength) &&
context.numRowsProcessed !== context.maxNumRowsToProcess)
{
resultStream.read();
}
else
{
// we've either processed all the rows we wanted to process or we
// were told to stop processing rows by the each() callback; either
// way, close the result stream to complete the operation
resultStream.asyncClose();
}
}
} | javascript | function()
{
// get the start position and start time
var startIndex = rowIndex;
var startTime = Date.now();
var each = options.each;
while (rowIndex < rowsLength)
{
// invoke the each() callback on the current row
var ret = each(rows[rowIndex++]);
context.numRowsProcessed++;
// if the callback returned false, stop processing rows
if (ret === false)
{
var stoppedProcessingRows = true;
break;
}
// use the current position and current time to check if we've been
// processing rows for too long; if so, leave the rest for the next
// tick of the event loop
if ((rowIndex - startIndex) >= context.rowBatchSize &&
(Date.now() - startTime) > context.rowBatchDuration)
{
process.nextTick(processRows);
break;
}
}
// if there are no more rows for us to process in this chunk
if (!(rowIndex < rowsLength) || stoppedProcessingRows)
{
// if we exhausted all the rows in this chunk and we haven't yet
// processed all the rows we want to process, ask the result stream to
// do another read
if (!(rowIndex < rowsLength) &&
context.numRowsProcessed !== context.maxNumRowsToProcess)
{
resultStream.read();
}
else
{
// we've either processed all the rows we wanted to process or we
// were told to stop processing rows by the each() callback; either
// way, close the result stream to complete the operation
resultStream.asyncClose();
}
}
} | [
"function",
"(",
")",
"{",
"// get the start position and start time",
"var",
"startIndex",
"=",
"rowIndex",
";",
"var",
"startTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"each",
"=",
"options",
".",
"each",
";",
"while",
"(",
"rowIndex",
"<",
"r... | create a function that can be called to batch-process rows | [
"create",
"a",
"function",
"that",
"can",
"be",
"called",
"to",
"batch",
"-",
"process",
"rows"
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L416-L467 | |
10,082 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | findOverlappingChunks | function findOverlappingChunks(chunks, windowStart, windowEnd)
{
var overlappingChunks = [];
if (chunks.length !== 0)
{
// get the index of the first chunk that overlaps with the specified window
var index = findFirstOverlappingChunk(chunks, windowStart, windowEnd);
// iterate over the chunks starting with the first overlapping chunk and
// keep going until there's no overlap
for (var length = chunks.length; index < length; index++)
{
var chunk = chunks[index];
if (chunk.overlapsWithWindow(windowStart, windowEnd))
{
overlappingChunks.push(chunk);
}
else
{
// no future chunks will overlap because the chunks array is sorted
break;
}
}
}
return overlappingChunks;
} | javascript | function findOverlappingChunks(chunks, windowStart, windowEnd)
{
var overlappingChunks = [];
if (chunks.length !== 0)
{
// get the index of the first chunk that overlaps with the specified window
var index = findFirstOverlappingChunk(chunks, windowStart, windowEnd);
// iterate over the chunks starting with the first overlapping chunk and
// keep going until there's no overlap
for (var length = chunks.length; index < length; index++)
{
var chunk = chunks[index];
if (chunk.overlapsWithWindow(windowStart, windowEnd))
{
overlappingChunks.push(chunk);
}
else
{
// no future chunks will overlap because the chunks array is sorted
break;
}
}
}
return overlappingChunks;
} | [
"function",
"findOverlappingChunks",
"(",
"chunks",
",",
"windowStart",
",",
"windowEnd",
")",
"{",
"var",
"overlappingChunks",
"=",
"[",
"]",
";",
"if",
"(",
"chunks",
".",
"length",
"!==",
"0",
")",
"{",
"// get the index of the first chunk that overlaps with the ... | Given a sorted array of chunks, returns a sub-array that overlaps with a
specified window.
@param chunks
@param windowStart
@param windowEnd
@returns {Array} | [
"Given",
"a",
"sorted",
"array",
"of",
"chunks",
"returns",
"a",
"sub",
"-",
"array",
"that",
"overlaps",
"with",
"a",
"specified",
"window",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L492-L519 |
10,083 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/result.js | findFirstOverlappingChunk | function findFirstOverlappingChunk(chunks, windowStartIndex, windowEndIndex)
{
var helper = function(chunks,
chunkIndexLeft,
chunkIndexRight,
windowStartIndex,
windowEndIndex)
{
var result;
var chunkIndexMiddle;
var middleChunk;
var middleChunkEndIndex;
// initialize the return value to -1
result = -1;
// compute the index of the middle chunk and get the middle chunk
chunkIndexMiddle = Math.floor((chunkIndexLeft + chunkIndexRight) / 2);
middleChunk = chunks[chunkIndexMiddle];
// if we have two or fewer chunks
if ((chunkIndexMiddle === chunkIndexLeft) ||
(chunkIndexMiddle === chunkIndexRight))
{
// if we have just one chunk, and it overlaps with the specified window,
// we've found the chunk we were looking for
if (chunkIndexLeft === chunkIndexRight)
{
if (middleChunk.overlapsWithWindow(windowStartIndex, windowEndIndex))
{
result = chunkIndexLeft;
}
}
else // we just have two chunks left to check
{
// if the first chunk overlaps with the specified window, that's the
// chunk we were looking for
if (chunks[chunkIndexLeft].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
result = chunkIndexLeft;
}
// otherwise, if the second chunk overlaps with the specified window,
// that's the chunk we were looking for
else if (chunks[chunkIndexRight].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
result = chunkIndexRight;
}
}
return result;
}
// if the middle chunk does not overlap with the specified window
if (!middleChunk.overlapsWithWindow(windowStartIndex, windowEndIndex))
{
middleChunkEndIndex = middleChunk.getEndIndex();
// if the window is to the right of the middle chunk,
// recurse on the right half
if (windowStartIndex > middleChunkEndIndex)
{
return helper(
chunks,
chunkIndexMiddle,
chunkIndexRight,
windowStartIndex,
windowEndIndex);
}
else
{
// recurse on the left half
return helper(
chunks,
chunkIndexLeft,
chunkIndexMiddle,
windowStartIndex,
windowEndIndex);
}
}
else
{
// if the middle chunk overlaps but the chunk before it does not, the
// middle chunk is the one we were looking
if ((chunkIndexMiddle === 0) ||
!chunks[chunkIndexMiddle - 1].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
return chunkIndexMiddle;
}
else
{
// recurse on the left half
return helper(
chunks,
chunkIndexLeft,
chunkIndexMiddle,
windowStartIndex,
windowEndIndex);
}
}
};
return helper(chunks, 0, chunks.length - 1, windowStartIndex, windowEndIndex);
} | javascript | function findFirstOverlappingChunk(chunks, windowStartIndex, windowEndIndex)
{
var helper = function(chunks,
chunkIndexLeft,
chunkIndexRight,
windowStartIndex,
windowEndIndex)
{
var result;
var chunkIndexMiddle;
var middleChunk;
var middleChunkEndIndex;
// initialize the return value to -1
result = -1;
// compute the index of the middle chunk and get the middle chunk
chunkIndexMiddle = Math.floor((chunkIndexLeft + chunkIndexRight) / 2);
middleChunk = chunks[chunkIndexMiddle];
// if we have two or fewer chunks
if ((chunkIndexMiddle === chunkIndexLeft) ||
(chunkIndexMiddle === chunkIndexRight))
{
// if we have just one chunk, and it overlaps with the specified window,
// we've found the chunk we were looking for
if (chunkIndexLeft === chunkIndexRight)
{
if (middleChunk.overlapsWithWindow(windowStartIndex, windowEndIndex))
{
result = chunkIndexLeft;
}
}
else // we just have two chunks left to check
{
// if the first chunk overlaps with the specified window, that's the
// chunk we were looking for
if (chunks[chunkIndexLeft].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
result = chunkIndexLeft;
}
// otherwise, if the second chunk overlaps with the specified window,
// that's the chunk we were looking for
else if (chunks[chunkIndexRight].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
result = chunkIndexRight;
}
}
return result;
}
// if the middle chunk does not overlap with the specified window
if (!middleChunk.overlapsWithWindow(windowStartIndex, windowEndIndex))
{
middleChunkEndIndex = middleChunk.getEndIndex();
// if the window is to the right of the middle chunk,
// recurse on the right half
if (windowStartIndex > middleChunkEndIndex)
{
return helper(
chunks,
chunkIndexMiddle,
chunkIndexRight,
windowStartIndex,
windowEndIndex);
}
else
{
// recurse on the left half
return helper(
chunks,
chunkIndexLeft,
chunkIndexMiddle,
windowStartIndex,
windowEndIndex);
}
}
else
{
// if the middle chunk overlaps but the chunk before it does not, the
// middle chunk is the one we were looking
if ((chunkIndexMiddle === 0) ||
!chunks[chunkIndexMiddle - 1].overlapsWithWindow(
windowStartIndex, windowEndIndex))
{
return chunkIndexMiddle;
}
else
{
// recurse on the left half
return helper(
chunks,
chunkIndexLeft,
chunkIndexMiddle,
windowStartIndex,
windowEndIndex);
}
}
};
return helper(chunks, 0, chunks.length - 1, windowStartIndex, windowEndIndex);
} | [
"function",
"findFirstOverlappingChunk",
"(",
"chunks",
",",
"windowStartIndex",
",",
"windowEndIndex",
")",
"{",
"var",
"helper",
"=",
"function",
"(",
"chunks",
",",
"chunkIndexLeft",
",",
"chunkIndexRight",
",",
"windowStartIndex",
",",
"windowEndIndex",
")",
"{"... | Given a sorted array of chunks, returns the index of the first chunk in the
array that overlaps with a specified window.
@param chunks
@param windowStartIndex
@param windowEndIndex
@returns {number} | [
"Given",
"a",
"sorted",
"array",
"of",
"chunks",
"returns",
"the",
"index",
"of",
"the",
"first",
"chunk",
"in",
"the",
"array",
"that",
"overlaps",
"with",
"a",
"specified",
"window",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/result.js#L531-L637 |
10,084 | snowflakedb/snowflake-connector-nodejs | lib/services/sf.js | function(state, transitionContext)
{
// this check is necessary to make sure we don't re-enter a transient state
// like Renewing when we're already in it
if (currentState !== state)
{
// if we have a current state, exit it; the null check is necessary
// because the currentState is undefined at bootstrap time when we
// transition to the first state
if (currentState)
{
currentState.exit();
}
// update the current state
currentState = state;
// enter the new state
currentState.enter(transitionContext);
}
} | javascript | function(state, transitionContext)
{
// this check is necessary to make sure we don't re-enter a transient state
// like Renewing when we're already in it
if (currentState !== state)
{
// if we have a current state, exit it; the null check is necessary
// because the currentState is undefined at bootstrap time when we
// transition to the first state
if (currentState)
{
currentState.exit();
}
// update the current state
currentState = state;
// enter the new state
currentState.enter(transitionContext);
}
} | [
"function",
"(",
"state",
",",
"transitionContext",
")",
"{",
"// this check is necessary to make sure we don't re-enter a transient state",
"// like Renewing when we're already in it",
"if",
"(",
"currentState",
"!==",
"state",
")",
"{",
"// if we have a current state, exit it; the ... | Transitions to a given state.
@param {Object} state
@param {Object} [transitionContext] | [
"Transitions",
"to",
"a",
"given",
"state",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/services/sf.js#L106-L126 | |
10,085 | snowflakedb/snowflake-connector-nodejs | lib/services/sf.js | sendHttpRequest | function sendHttpRequest(requestOptions, httpClient)
{
return httpClient.request(
{
method : requestOptions.method,
headers : requestOptions.headers,
url : requestOptions.absoluteUrl,
gzip : requestOptions.gzip,
json : requestOptions.json,
callback : function(err, response, body)
{
// if we got an error, wrap it into a network error
if (err)
{
err = Errors.createNetworkError(
ErrorCodes.ERR_SF_NETWORK_COULD_NOT_CONNECT, err);
}
// if we didn't get a 200, the request failed
else if (!response || response.statusCode !== 200)
{
err = Errors.createRequestFailedError(
ErrorCodes.ERR_SF_RESPONSE_FAILURE, response);
}
else
{
// if the response body is a non-empty string and the response is
// supposed to contain json, try to json-parse the body
if (Util.isString(body) &&
response.getResponseHeader('Content-Type') === 'application/json')
{
try
{
body = JSON.parse(body);
}
catch (parseError)
{
// we expected to get json
err = Errors.createUnexpectedContentError(
ErrorCodes.ERR_SF_RESPONSE_NOT_JSON, response.body);
}
}
// if we were able to successfully json-parse the body and the success
// flag is false, the operation we tried to perform failed
if (body && !body.success)
{
var data = body.data;
err = Errors.createOperationFailedError(
body.code, data, body.message,
data && data.sqlState ? data.sqlState : undefined);
}
}
// if we have an error, clear the body
if (err)
{
body = undefined;
}
// if a callback was specified, invoke it
if (Util.isFunction(requestOptions.callback))
{
requestOptions.callback.apply(requestOptions.scope, [err, body]);
}
}
});
} | javascript | function sendHttpRequest(requestOptions, httpClient)
{
return httpClient.request(
{
method : requestOptions.method,
headers : requestOptions.headers,
url : requestOptions.absoluteUrl,
gzip : requestOptions.gzip,
json : requestOptions.json,
callback : function(err, response, body)
{
// if we got an error, wrap it into a network error
if (err)
{
err = Errors.createNetworkError(
ErrorCodes.ERR_SF_NETWORK_COULD_NOT_CONNECT, err);
}
// if we didn't get a 200, the request failed
else if (!response || response.statusCode !== 200)
{
err = Errors.createRequestFailedError(
ErrorCodes.ERR_SF_RESPONSE_FAILURE, response);
}
else
{
// if the response body is a non-empty string and the response is
// supposed to contain json, try to json-parse the body
if (Util.isString(body) &&
response.getResponseHeader('Content-Type') === 'application/json')
{
try
{
body = JSON.parse(body);
}
catch (parseError)
{
// we expected to get json
err = Errors.createUnexpectedContentError(
ErrorCodes.ERR_SF_RESPONSE_NOT_JSON, response.body);
}
}
// if we were able to successfully json-parse the body and the success
// flag is false, the operation we tried to perform failed
if (body && !body.success)
{
var data = body.data;
err = Errors.createOperationFailedError(
body.code, data, body.message,
data && data.sqlState ? data.sqlState : undefined);
}
}
// if we have an error, clear the body
if (err)
{
body = undefined;
}
// if a callback was specified, invoke it
if (Util.isFunction(requestOptions.callback))
{
requestOptions.callback.apply(requestOptions.scope, [err, body]);
}
}
});
} | [
"function",
"sendHttpRequest",
"(",
"requestOptions",
",",
"httpClient",
")",
"{",
"return",
"httpClient",
".",
"request",
"(",
"{",
"method",
":",
"requestOptions",
".",
"method",
",",
"headers",
":",
"requestOptions",
".",
"headers",
",",
"url",
":",
"reques... | Issues an http request to Snowflake.
@param {Object} requestOptions
@param {Object} httpClient
@returns {Object} the http request object. | [
"Issues",
"an",
"http",
"request",
"to",
"Snowflake",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/services/sf.js#L498-L564 |
10,086 | snowflakedb/snowflake-connector-nodejs | lib/services/sf.js | buildLoginUrl | function buildLoginUrl(connectionConfig)
{
var queryParams =
[
{ name: 'warehouse', value: connectionConfig.getWarehouse() },
{ name: 'databaseName', value: connectionConfig.getDatabase() },
{ name: 'schemaName', value: connectionConfig.getSchema() },
{ name: 'roleName', value: connectionConfig.getRole() }
];
var queryStringObject = {};
for (var index = 0, length = queryParams.length; index < length; index++)
{
var queryParam = queryParams[index];
if (Util.string.isNotNullOrEmpty(queryParam.value))
{
queryStringObject[queryParam.name] = queryParam.value;
}
}
return Url.format(
{
pathname : '/session/v1/login-request',
search : QueryString.stringify(queryStringObject)
});
} | javascript | function buildLoginUrl(connectionConfig)
{
var queryParams =
[
{ name: 'warehouse', value: connectionConfig.getWarehouse() },
{ name: 'databaseName', value: connectionConfig.getDatabase() },
{ name: 'schemaName', value: connectionConfig.getSchema() },
{ name: 'roleName', value: connectionConfig.getRole() }
];
var queryStringObject = {};
for (var index = 0, length = queryParams.length; index < length; index++)
{
var queryParam = queryParams[index];
if (Util.string.isNotNullOrEmpty(queryParam.value))
{
queryStringObject[queryParam.name] = queryParam.value;
}
}
return Url.format(
{
pathname : '/session/v1/login-request',
search : QueryString.stringify(queryStringObject)
});
} | [
"function",
"buildLoginUrl",
"(",
"connectionConfig",
")",
"{",
"var",
"queryParams",
"=",
"[",
"{",
"name",
":",
"'warehouse'",
",",
"value",
":",
"connectionConfig",
".",
"getWarehouse",
"(",
")",
"}",
",",
"{",
"name",
":",
"'databaseName'",
",",
"value",... | Builds the url for a login request.
@param connectionConfig
@returns {*} | [
"Builds",
"the",
"url",
"for",
"a",
"login",
"request",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/services/sf.js#L1028-L1053 |
10,087 | snowflakedb/snowflake-connector-nodejs | lib/http/base.js | HttpClient | function HttpClient(connectionConfig)
{
// save the connection config
this._connectionConfig = connectionConfig;
// check that we have a valid request module
var requestModule = this.getRequestModule();
Errors.assertInternal(
Util.isObject(requestModule) || Util.isFunction(requestModule));
} | javascript | function HttpClient(connectionConfig)
{
// save the connection config
this._connectionConfig = connectionConfig;
// check that we have a valid request module
var requestModule = this.getRequestModule();
Errors.assertInternal(
Util.isObject(requestModule) || Util.isFunction(requestModule));
} | [
"function",
"HttpClient",
"(",
"connectionConfig",
")",
"{",
"// save the connection config",
"this",
".",
"_connectionConfig",
"=",
"connectionConfig",
";",
"// check that we have a valid request module",
"var",
"requestModule",
"=",
"this",
".",
"getRequestModule",
"(",
"... | Creates a new HTTP client.
@param connectionConfig
@constructor | [
"Creates",
"a",
"new",
"HTTP",
"client",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/http/base.js#L18-L27 |
10,088 | snowflakedb/snowflake-connector-nodejs | lib/http/base.js | normalizeHeaders | function normalizeHeaders(headers)
{
var ret = headers;
if (Util.isObject(headers))
{
ret = {};
// shallow copy the headers object and convert some headers like 'Accept'
// and 'Content-Type' to lower case while copying; this is necessary
// because the browser-request module, which we use to make http requests in
// the browser, does not do case-insensitive checks when deciding whether to
// insert default values for the 'accept' and 'content-type' headers; in
// otherwise, if someone specifies an 'Accept': 'application/json' header,
// browser-request will inject its own 'accept': 'application/json' header
// and the browser XMLHttpRequest object will concatenate the two values and
// send 'Accept': 'application/json, application/json' with the request
var headerNameLowerCase;
for (var headerName in headers)
{
if (headers.hasOwnProperty(headerName))
{
headerNameLowerCase = headerName.toLowerCase();
if ((headerNameLowerCase === 'accept') ||
(headerNameLowerCase === 'content-type'))
{
ret[headerNameLowerCase] = headers[headerName];
}
else
{
ret[headerName] = headers[headerName];
}
}
}
}
return ret;
} | javascript | function normalizeHeaders(headers)
{
var ret = headers;
if (Util.isObject(headers))
{
ret = {};
// shallow copy the headers object and convert some headers like 'Accept'
// and 'Content-Type' to lower case while copying; this is necessary
// because the browser-request module, which we use to make http requests in
// the browser, does not do case-insensitive checks when deciding whether to
// insert default values for the 'accept' and 'content-type' headers; in
// otherwise, if someone specifies an 'Accept': 'application/json' header,
// browser-request will inject its own 'accept': 'application/json' header
// and the browser XMLHttpRequest object will concatenate the two values and
// send 'Accept': 'application/json, application/json' with the request
var headerNameLowerCase;
for (var headerName in headers)
{
if (headers.hasOwnProperty(headerName))
{
headerNameLowerCase = headerName.toLowerCase();
if ((headerNameLowerCase === 'accept') ||
(headerNameLowerCase === 'content-type'))
{
ret[headerNameLowerCase] = headers[headerName];
}
else
{
ret[headerName] = headers[headerName];
}
}
}
}
return ret;
} | [
"function",
"normalizeHeaders",
"(",
"headers",
")",
"{",
"var",
"ret",
"=",
"headers",
";",
"if",
"(",
"Util",
".",
"isObject",
"(",
"headers",
")",
")",
"{",
"ret",
"=",
"{",
"}",
";",
"// shallow copy the headers object and convert some headers like 'Accept'",
... | Normalizes a request headers object so that we get the same behavior
regardless of whether we're using request.js or browser-request.js.
@param {Object} headers
@returns {Object} | [
"Normalizes",
"a",
"request",
"headers",
"object",
"so",
"that",
"we",
"get",
"the",
"same",
"behavior",
"regardless",
"of",
"whether",
"we",
"re",
"using",
"request",
".",
"js",
"or",
"browser",
"-",
"request",
".",
"js",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/http/base.js#L199-L236 |
10,089 | snowflakedb/snowflake-connector-nodejs | lib/http/base.js | normalizeResponse | function normalizeResponse(response)
{
// if the response doesn't already have a getResponseHeader() method, add one
if (response && !response.getResponseHeader)
{
response.getResponseHeader = function(header)
{
return response.headers && response.headers[
Util.isString(header) ? header.toLowerCase() : header];
};
}
return response;
} | javascript | function normalizeResponse(response)
{
// if the response doesn't already have a getResponseHeader() method, add one
if (response && !response.getResponseHeader)
{
response.getResponseHeader = function(header)
{
return response.headers && response.headers[
Util.isString(header) ? header.toLowerCase() : header];
};
}
return response;
} | [
"function",
"normalizeResponse",
"(",
"response",
")",
"{",
"// if the response doesn't already have a getResponseHeader() method, add one",
"if",
"(",
"response",
"&&",
"!",
"response",
".",
"getResponseHeader",
")",
"{",
"response",
".",
"getResponseHeader",
"=",
"functio... | Normalizes the response object so that we can extract response headers from
it in a uniform way regardless of whether we're using request.js or
browser-request.js.
@param {Object} response
@return {Object} | [
"Normalizes",
"the",
"response",
"object",
"so",
"that",
"we",
"can",
"extract",
"response",
"headers",
"from",
"it",
"in",
"a",
"uniform",
"way",
"regardless",
"of",
"whether",
"we",
"re",
"using",
"request",
".",
"js",
"or",
"browser",
"-",
"request",
".... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/http/base.js#L247-L260 |
10,090 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | init | function init()
{
// the stream has now been initialized
initialized = true;
// if we have a result
if (context.result)
{
// if no value was specified for the start index or if the specified start
// index is negative, default to 0, otherwise truncate the fractional part
start = (!Util.isNumber(start) || (start < 0)) ? 0 : Math.floor(start);
// if no value was specified for the end index or if the end index is
// larger than the row index of the last row, default to the index of the
// last row, otherwise truncate the fractional part
var returnedRows = context.result.getReturnedRows();
end = (!Util.isNumber(end) || (end >= returnedRows)) ? returnedRows - 1 :
Math.floor(end);
// find all the chunks that overlap with the specified range
var overlappingChunks = context.result.findOverlappingChunks(start, end);
// if no chunks overlap or start is greater than end, we're done
if ((overlappingChunks.length === 0) || (start > end))
{
process.nextTick(close);
}
else
{
// create a result stream from the overlapping chunks
resultStream = new ResultStream(
{
chunks : overlappingChunks,
prefetchSize : context.connectionConfig.getResultPrefetch()
});
readNextRow();
}
}
else
{
close(context.resultError);
}
} | javascript | function init()
{
// the stream has now been initialized
initialized = true;
// if we have a result
if (context.result)
{
// if no value was specified for the start index or if the specified start
// index is negative, default to 0, otherwise truncate the fractional part
start = (!Util.isNumber(start) || (start < 0)) ? 0 : Math.floor(start);
// if no value was specified for the end index or if the end index is
// larger than the row index of the last row, default to the index of the
// last row, otherwise truncate the fractional part
var returnedRows = context.result.getReturnedRows();
end = (!Util.isNumber(end) || (end >= returnedRows)) ? returnedRows - 1 :
Math.floor(end);
// find all the chunks that overlap with the specified range
var overlappingChunks = context.result.findOverlappingChunks(start, end);
// if no chunks overlap or start is greater than end, we're done
if ((overlappingChunks.length === 0) || (start > end))
{
process.nextTick(close);
}
else
{
// create a result stream from the overlapping chunks
resultStream = new ResultStream(
{
chunks : overlappingChunks,
prefetchSize : context.connectionConfig.getResultPrefetch()
});
readNextRow();
}
}
else
{
close(context.resultError);
}
} | [
"function",
"init",
"(",
")",
"{",
"// the stream has now been initialized",
"initialized",
"=",
"true",
";",
"// if we have a result",
"if",
"(",
"context",
".",
"result",
")",
"{",
"// if no value was specified for the start index or if the specified start",
"// index is nega... | Initializes this stream. | [
"Initializes",
"this",
"stream",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L92-L135 |
10,091 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | processRowBuffer | function processRowBuffer()
{
// get the row to add to the read queue
var row = rowBuffer[rowIndex++];
// if we just read the last row in the row buffer, clear the row buffer and
// reset the row index so that we load the next chunk in the result stream
// when _read() is called
if (rowIndex === rowBuffer.length)
{
rowBuffer = null;
rowIndex = 0;
}
// initialize the columns and column-related maps if necessary
if (!columns)
{
columns = statement.getColumns();
}
if (!mapColumnIdToExtractFnName)
{
mapColumnIdToExtractFnName =
buildMapColumnExtractFnNames(columns, fetchAsString);
}
// add the next row to the read queue
process.nextTick(function()
{
self.push(externalizeRow(row, columns, mapColumnIdToExtractFnName));
});
} | javascript | function processRowBuffer()
{
// get the row to add to the read queue
var row = rowBuffer[rowIndex++];
// if we just read the last row in the row buffer, clear the row buffer and
// reset the row index so that we load the next chunk in the result stream
// when _read() is called
if (rowIndex === rowBuffer.length)
{
rowBuffer = null;
rowIndex = 0;
}
// initialize the columns and column-related maps if necessary
if (!columns)
{
columns = statement.getColumns();
}
if (!mapColumnIdToExtractFnName)
{
mapColumnIdToExtractFnName =
buildMapColumnExtractFnNames(columns, fetchAsString);
}
// add the next row to the read queue
process.nextTick(function()
{
self.push(externalizeRow(row, columns, mapColumnIdToExtractFnName));
});
} | [
"function",
"processRowBuffer",
"(",
")",
"{",
"// get the row to add to the read queue",
"var",
"row",
"=",
"rowBuffer",
"[",
"rowIndex",
"++",
"]",
";",
"// if we just read the last row in the row buffer, clear the row buffer and",
"// reset the row index so that we load the next c... | Processes the row buffer. | [
"Processes",
"the",
"row",
"buffer",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L140-L170 |
10,092 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | onResultStreamData | function onResultStreamData(chunk)
{
// unsubscribe from the result stream's 'data' and 'close' events
resultStream.removeListener('data', onResultStreamData);
resultStream.removeListener('close', onResultStreamClose);
// get all the rows in the chunk that overlap with the requested window,
// and use the resulting array as the new row buffer
var chunkStart = chunk.getStartIndex();
var chunkEnd = chunk.getEndIndex();
rowBuffer = chunk.getRows().slice(
Math.max(chunkStart, start) - chunkStart,
Math.min(chunkEnd, end) + 1 - chunkStart);
// reset the row index
rowIndex = 0;
// process the row buffer
processRowBuffer();
} | javascript | function onResultStreamData(chunk)
{
// unsubscribe from the result stream's 'data' and 'close' events
resultStream.removeListener('data', onResultStreamData);
resultStream.removeListener('close', onResultStreamClose);
// get all the rows in the chunk that overlap with the requested window,
// and use the resulting array as the new row buffer
var chunkStart = chunk.getStartIndex();
var chunkEnd = chunk.getEndIndex();
rowBuffer = chunk.getRows().slice(
Math.max(chunkStart, start) - chunkStart,
Math.min(chunkEnd, end) + 1 - chunkStart);
// reset the row index
rowIndex = 0;
// process the row buffer
processRowBuffer();
} | [
"function",
"onResultStreamData",
"(",
"chunk",
")",
"{",
"// unsubscribe from the result stream's 'data' and 'close' events",
"resultStream",
".",
"removeListener",
"(",
"'data'",
",",
"onResultStreamData",
")",
";",
"resultStream",
".",
"removeListener",
"(",
"'close'",
"... | Called when the result stream reads a new chunk.
@param {Chunk} chunk | [
"Called",
"when",
"the",
"result",
"stream",
"reads",
"a",
"new",
"chunk",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L177-L196 |
10,093 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | onResultStreamClose | function onResultStreamClose(err, continueCallback)
{
// if the error is retryable and
// the result stream hasn't been closed too many times
if (isResultStreamErrorRetryable(err) &&
(numResultStreamInterrupts <
context.connectionConfig.getResultStreamInterrupts()))
{
numResultStreamInterrupts++;
// fetch the statement result again
context.refresh(function()
{
if (context.resultError)
{
close(context.resultError);
}
else
{
continueCallback();
}
});
}
else
{
close(err);
}
} | javascript | function onResultStreamClose(err, continueCallback)
{
// if the error is retryable and
// the result stream hasn't been closed too many times
if (isResultStreamErrorRetryable(err) &&
(numResultStreamInterrupts <
context.connectionConfig.getResultStreamInterrupts()))
{
numResultStreamInterrupts++;
// fetch the statement result again
context.refresh(function()
{
if (context.resultError)
{
close(context.resultError);
}
else
{
continueCallback();
}
});
}
else
{
close(err);
}
} | [
"function",
"onResultStreamClose",
"(",
"err",
",",
"continueCallback",
")",
"{",
"// if the error is retryable and",
"// the result stream hasn't been closed too many times",
"if",
"(",
"isResultStreamErrorRetryable",
"(",
"err",
")",
"&&",
"(",
"numResultStreamInterrupts",
"<... | Called when there are no more chunks to read in the result stream or an
error is encountered while trying to read the next chunk.
@param err
@param continueCallback | [
"Called",
"when",
"there",
"are",
"no",
"more",
"chunks",
"to",
"read",
"in",
"the",
"result",
"stream",
"or",
"an",
"error",
"is",
"encountered",
"while",
"trying",
"to",
"read",
"the",
"next",
"chunk",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L205-L232 |
10,094 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | function(err)
{
// if we have a result stream, stop listening to events on it
if (resultStream)
{
resultStream.removeListener('data', onResultStreamData);
resultStream.removeListener('close', onResultStreamClose);
}
// we're done, so time to clean up
rowBuffer = null;
rowIndex = 0;
resultStream = null;
numResultStreamInterrupts = 0;
if (err)
{
emitError(err);
}
else
{
self.push(null);
}
} | javascript | function(err)
{
// if we have a result stream, stop listening to events on it
if (resultStream)
{
resultStream.removeListener('data', onResultStreamData);
resultStream.removeListener('close', onResultStreamClose);
}
// we're done, so time to clean up
rowBuffer = null;
rowIndex = 0;
resultStream = null;
numResultStreamInterrupts = 0;
if (err)
{
emitError(err);
}
else
{
self.push(null);
}
} | [
"function",
"(",
"err",
")",
"{",
"// if we have a result stream, stop listening to events on it",
"if",
"(",
"resultStream",
")",
"{",
"resultStream",
".",
"removeListener",
"(",
"'data'",
",",
"onResultStreamData",
")",
";",
"resultStream",
".",
"removeListener",
"(",... | Closes the row stream.
@param {Error} [err] | [
"Closes",
"the",
"row",
"stream",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L239-L262 | |
10,095 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | readNextRow | function readNextRow()
{
// if we have a row buffer, process it
if (rowBuffer)
{
processRowBuffer();
}
else
{
// subscribe to the result stream's 'data' and 'close' events
resultStream.on('data', onResultStreamData);
resultStream.on('close', onResultStreamClose);
// issue a request to fetch the next chunk in the result stream
resultStream.read();
}
} | javascript | function readNextRow()
{
// if we have a row buffer, process it
if (rowBuffer)
{
processRowBuffer();
}
else
{
// subscribe to the result stream's 'data' and 'close' events
resultStream.on('data', onResultStreamData);
resultStream.on('close', onResultStreamClose);
// issue a request to fetch the next chunk in the result stream
resultStream.read();
}
} | [
"function",
"readNextRow",
"(",
")",
"{",
"// if we have a row buffer, process it",
"if",
"(",
"rowBuffer",
")",
"{",
"processRowBuffer",
"(",
")",
";",
"}",
"else",
"{",
"// subscribe to the result stream's 'data' and 'close' events",
"resultStream",
".",
"on",
"(",
"'... | Called when we're ready to read the next row in the result. | [
"Called",
"when",
"we",
"re",
"ready",
"to",
"read",
"the",
"next",
"row",
"in",
"the",
"result",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L267-L283 |
10,096 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | isResultStreamErrorRetryable | function isResultStreamErrorRetryable(error)
{
return Errors.isLargeResultSetError(error) && error.response &&
(error.response.statusCode === 403);
} | javascript | function isResultStreamErrorRetryable(error)
{
return Errors.isLargeResultSetError(error) && error.response &&
(error.response.statusCode === 403);
} | [
"function",
"isResultStreamErrorRetryable",
"(",
"error",
")",
"{",
"return",
"Errors",
".",
"isLargeResultSetError",
"(",
"error",
")",
"&&",
"error",
".",
"response",
"&&",
"(",
"error",
".",
"response",
".",
"statusCode",
"===",
"403",
")",
";",
"}"
] | Determines if a result stream error is a retryable error.
@param {Error} error
@returns {Boolean} | [
"Determines",
"if",
"a",
"result",
"stream",
"error",
"is",
"a",
"retryable",
"error",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L316-L320 |
10,097 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | buildMapColumnExtractFnNames | function buildMapColumnExtractFnNames(columns, fetchAsString)
{
var fnNameGetColumnValue = 'getColumnValue';
var fnNameGetColumnValueAsString = 'getColumnValueAsString';
var index, length, column;
var mapColumnIdToExtractFnName = {};
// if no native types need to be retrieved as strings, extract values normally
if (!Util.exists(fetchAsString))
{
for (index = 0, length = columns.length; index < length; index++)
{
column = columns[index];
mapColumnIdToExtractFnName[column.getId()] = fnNameGetColumnValue;
}
}
else
{
// build a map that contains all the native types that need to be
// retrieved as strings when extracting column values from rows
var nativeTypesMap = {};
for (index = 0, length = fetchAsString.length; index < length; index++)
{
nativeTypesMap[fetchAsString[index].toUpperCase()] = true;
}
// for each column, pick the appropriate extract function
// based on whether the value needs to be retrieved as a string
for (index = 0, length = columns.length; index < length; index++)
{
column = columns[index];
mapColumnIdToExtractFnName[column.getId()] =
nativeTypesMap[DataTypes.toNativeType(column.getType())] ?
fnNameGetColumnValueAsString : fnNameGetColumnValue;
}
}
return mapColumnIdToExtractFnName;
} | javascript | function buildMapColumnExtractFnNames(columns, fetchAsString)
{
var fnNameGetColumnValue = 'getColumnValue';
var fnNameGetColumnValueAsString = 'getColumnValueAsString';
var index, length, column;
var mapColumnIdToExtractFnName = {};
// if no native types need to be retrieved as strings, extract values normally
if (!Util.exists(fetchAsString))
{
for (index = 0, length = columns.length; index < length; index++)
{
column = columns[index];
mapColumnIdToExtractFnName[column.getId()] = fnNameGetColumnValue;
}
}
else
{
// build a map that contains all the native types that need to be
// retrieved as strings when extracting column values from rows
var nativeTypesMap = {};
for (index = 0, length = fetchAsString.length; index < length; index++)
{
nativeTypesMap[fetchAsString[index].toUpperCase()] = true;
}
// for each column, pick the appropriate extract function
// based on whether the value needs to be retrieved as a string
for (index = 0, length = columns.length; index < length; index++)
{
column = columns[index];
mapColumnIdToExtractFnName[column.getId()] =
nativeTypesMap[DataTypes.toNativeType(column.getType())] ?
fnNameGetColumnValueAsString : fnNameGetColumnValue;
}
}
return mapColumnIdToExtractFnName;
} | [
"function",
"buildMapColumnExtractFnNames",
"(",
"columns",
",",
"fetchAsString",
")",
"{",
"var",
"fnNameGetColumnValue",
"=",
"'getColumnValue'",
";",
"var",
"fnNameGetColumnValueAsString",
"=",
"'getColumnValueAsString'",
";",
"var",
"index",
",",
"length",
",",
"col... | Builds a map in which the keys are column ids and the values are the names of
the extract functions to use when retrieving row values for the corresponding
columns.
@param {Object[]} columns
@param {String[]} fetchAsString the native types that should be retrieved as
strings.
@returns {Object} | [
"Builds",
"a",
"map",
"in",
"which",
"the",
"keys",
"are",
"column",
"ids",
"and",
"the",
"values",
"are",
"the",
"names",
"of",
"the",
"extract",
"functions",
"to",
"use",
"when",
"retrieving",
"row",
"values",
"for",
"the",
"corresponding",
"columns",
".... | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L333-L372 |
10,098 | snowflakedb/snowflake-connector-nodejs | lib/connection/result/row_stream.js | externalizeRow | function externalizeRow(row, columns, mapColumnIdToExtractFnName)
{
var externalizedRow = {};
for (var index = 0, length = columns.length; index < length; index++)
{
var column = columns[index];
var extractFnName = mapColumnIdToExtractFnName[column.getId()];
externalizedRow[column.getName()] = row[extractFnName](column.getId());
}
return externalizedRow;
} | javascript | function externalizeRow(row, columns, mapColumnIdToExtractFnName)
{
var externalizedRow = {};
for (var index = 0, length = columns.length; index < length; index++)
{
var column = columns[index];
var extractFnName = mapColumnIdToExtractFnName[column.getId()];
externalizedRow[column.getName()] = row[extractFnName](column.getId());
}
return externalizedRow;
} | [
"function",
"externalizeRow",
"(",
"row",
",",
"columns",
",",
"mapColumnIdToExtractFnName",
")",
"{",
"var",
"externalizedRow",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"index",
"=",
"0",
",",
"length",
"=",
"columns",
".",
"length",
";",
"index",
"<",
"l... | Converts an internal representation of a result row to a format appropriate
for consumption by the outside world.
@param {Object} row
@param {Object[]} columns
@param {Object} [mapColumnIdToExtractFnName]
@returns {Object} | [
"Converts",
"an",
"internal",
"representation",
"of",
"a",
"result",
"row",
"to",
"a",
"format",
"appropriate",
"for",
"consumption",
"by",
"the",
"outside",
"world",
"."
] | 7ad71410a3bb679a96021b6b2d5b9b515f790db8 | https://github.com/snowflakedb/snowflake-connector-nodejs/blob/7ad71410a3bb679a96021b6b2d5b9b515f790db8/lib/connection/result/row_stream.js#L384-L395 |
10,099 | PlatziDev/pulse-editor | src/utils/get-selection.js | getSelection | function getSelection (field) {
if (typeof field !== 'object') {
throw new TypeError('The field must be an object.')
}
return {
start: field.selectionStart,
end: field.selectionEnd
}
} | javascript | function getSelection (field) {
if (typeof field !== 'object') {
throw new TypeError('The field must be an object.')
}
return {
start: field.selectionStart,
end: field.selectionEnd
}
} | [
"function",
"getSelection",
"(",
"field",
")",
"{",
"if",
"(",
"typeof",
"field",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The field must be an object.'",
")",
"}",
"return",
"{",
"start",
":",
"field",
".",
"selectionStart",
",",
"en... | Get the element selection start and end values
@param {Element} field The DOM node element
@return {SelectionType} The selection start and end | [
"Get",
"the",
"element",
"selection",
"start",
"and",
"end",
"values"
] | 897bc0e91b365e305c06c038f0192a21e5f5fe4a | https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/utils/get-selection.js#L6-L15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.