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
25,100
froala/knockout-froala
src/knockout-froala.js
init
function init( element, value, bindings ) { var $el = $( element ); var model = value(); var allBindings = unwrap( bindings() ); var options = ko.toJS( allBindings.froalaOptions ); // initialize the editor $el.froalaEditor( options || {} ); // provide froala editor instance for flexibility if( allBindings.froalaInstance && ko.isWriteableObservable( allBindings.froalaInstance ) ) { allBindings.froalaInstance( $el.data( 'froala.editor' ) ); } // update underlying model whenever editor content changed var processUpdateEvent = function (e, editor) { if (ko.isWriteableObservable(model)) { var editorValue = editor.html.get(); var current = model(); if (current !== editorValue) { model(editorValue); } } } $el.on('froalaEditor.contentChanged', processUpdateEvent); $el.on('froalaEditor.paste.after', processUpdateEvent); // cleanup editor, when dom node is removed ko.utils.domNodeDisposal.addDisposeCallback( element, destroy( element ) ); // do not handle child nodes return { controlsDescendantBindings: true }; }
javascript
function init( element, value, bindings ) { var $el = $( element ); var model = value(); var allBindings = unwrap( bindings() ); var options = ko.toJS( allBindings.froalaOptions ); // initialize the editor $el.froalaEditor( options || {} ); // provide froala editor instance for flexibility if( allBindings.froalaInstance && ko.isWriteableObservable( allBindings.froalaInstance ) ) { allBindings.froalaInstance( $el.data( 'froala.editor' ) ); } // update underlying model whenever editor content changed var processUpdateEvent = function (e, editor) { if (ko.isWriteableObservable(model)) { var editorValue = editor.html.get(); var current = model(); if (current !== editorValue) { model(editorValue); } } } $el.on('froalaEditor.contentChanged', processUpdateEvent); $el.on('froalaEditor.paste.after', processUpdateEvent); // cleanup editor, when dom node is removed ko.utils.domNodeDisposal.addDisposeCallback( element, destroy( element ) ); // do not handle child nodes return { controlsDescendantBindings: true }; }
[ "function", "init", "(", "element", ",", "value", ",", "bindings", ")", "{", "var", "$el", "=", "$", "(", "element", ")", ";", "var", "model", "=", "value", "(", ")", ";", "var", "allBindings", "=", "unwrap", "(", "bindings", "(", ")", ")", ";", "var", "options", "=", "ko", ".", "toJS", "(", "allBindings", ".", "froalaOptions", ")", ";", "// initialize the editor", "$el", ".", "froalaEditor", "(", "options", "||", "{", "}", ")", ";", "// provide froala editor instance for flexibility", "if", "(", "allBindings", ".", "froalaInstance", "&&", "ko", ".", "isWriteableObservable", "(", "allBindings", ".", "froalaInstance", ")", ")", "{", "allBindings", ".", "froalaInstance", "(", "$el", ".", "data", "(", "'froala.editor'", ")", ")", ";", "}", "// update underlying model whenever editor content changed", "var", "processUpdateEvent", "=", "function", "(", "e", ",", "editor", ")", "{", "if", "(", "ko", ".", "isWriteableObservable", "(", "model", ")", ")", "{", "var", "editorValue", "=", "editor", ".", "html", ".", "get", "(", ")", ";", "var", "current", "=", "model", "(", ")", ";", "if", "(", "current", "!==", "editorValue", ")", "{", "model", "(", "editorValue", ")", ";", "}", "}", "}", "$el", ".", "on", "(", "'froalaEditor.contentChanged'", ",", "processUpdateEvent", ")", ";", "$el", ".", "on", "(", "'froalaEditor.paste.after'", ",", "processUpdateEvent", ")", ";", "// cleanup editor, when dom node is removed", "ko", ".", "utils", ".", "domNodeDisposal", ".", "addDisposeCallback", "(", "element", ",", "destroy", "(", "element", ")", ")", ";", "// do not handle child nodes", "return", "{", "controlsDescendantBindings", ":", "true", "}", ";", "}" ]
initiate froala editor, listen to its changes and updates the underlying observable model @param {element} element @param {object} value @param {object} bindings @api public
[ "initiate", "froala", "editor", "listen", "to", "its", "changes", "and", "updates", "the", "underlying", "observable", "model" ]
64d72223b48ca48d2f3257dc95302ce182e90b5f
https://github.com/froala/knockout-froala/blob/64d72223b48ca48d2f3257dc95302ce182e90b5f/src/knockout-froala.js#L21-L54
25,101
froala/knockout-froala
src/knockout-froala.js
function (e, editor) { if (ko.isWriteableObservable(model)) { var editorValue = editor.html.get(); var current = model(); if (current !== editorValue) { model(editorValue); } } }
javascript
function (e, editor) { if (ko.isWriteableObservable(model)) { var editorValue = editor.html.get(); var current = model(); if (current !== editorValue) { model(editorValue); } } }
[ "function", "(", "e", ",", "editor", ")", "{", "if", "(", "ko", ".", "isWriteableObservable", "(", "model", ")", ")", "{", "var", "editorValue", "=", "editor", ".", "html", ".", "get", "(", ")", ";", "var", "current", "=", "model", "(", ")", ";", "if", "(", "current", "!==", "editorValue", ")", "{", "model", "(", "editorValue", ")", ";", "}", "}", "}" ]
update underlying model whenever editor content changed
[ "update", "underlying", "model", "whenever", "editor", "content", "changed" ]
64d72223b48ca48d2f3257dc95302ce182e90b5f
https://github.com/froala/knockout-froala/blob/64d72223b48ca48d2f3257dc95302ce182e90b5f/src/knockout-froala.js#L36-L44
25,102
froala/knockout-froala
src/knockout-froala.js
update
function update( element, value ) { var $el = $( element ); var modelValue = unwrap( value() ); var editorInstance = $el.data( 'froala.editor' ); if( editorInstance == null ) { return; } var editorValue = editorInstance.html.get(); // avoid any un-necessary updates if( editorValue !== modelValue && (typeof modelValue === 'string' || modelValue === null)) { editorInstance.html.set( modelValue ); } }
javascript
function update( element, value ) { var $el = $( element ); var modelValue = unwrap( value() ); var editorInstance = $el.data( 'froala.editor' ); if( editorInstance == null ) { return; } var editorValue = editorInstance.html.get(); // avoid any un-necessary updates if( editorValue !== modelValue && (typeof modelValue === 'string' || modelValue === null)) { editorInstance.html.set( modelValue ); } }
[ "function", "update", "(", "element", ",", "value", ")", "{", "var", "$el", "=", "$", "(", "element", ")", ";", "var", "modelValue", "=", "unwrap", "(", "value", "(", ")", ")", ";", "var", "editorInstance", "=", "$el", ".", "data", "(", "'froala.editor'", ")", ";", "if", "(", "editorInstance", "==", "null", ")", "{", "return", ";", "}", "var", "editorValue", "=", "editorInstance", ".", "html", ".", "get", "(", ")", ";", "// avoid any un-necessary updates", "if", "(", "editorValue", "!==", "modelValue", "&&", "(", "typeof", "modelValue", "===", "'string'", "||", "modelValue", "===", "null", ")", ")", "{", "editorInstance", ".", "html", ".", "set", "(", "modelValue", ")", ";", "}", "}" ]
update froala editor whenever underlying observable model is updated @param {element} element @param {object} value @api public
[ "update", "froala", "editor", "whenever", "underlying", "observable", "model", "is", "updated" ]
64d72223b48ca48d2f3257dc95302ce182e90b5f
https://github.com/froala/knockout-froala/blob/64d72223b48ca48d2f3257dc95302ce182e90b5f/src/knockout-froala.js#L66-L81
25,103
joe-sky/flarej
dist/js/flarej.js
lazyDo
function lazyDo(fn, timeOut, doName, obj) { var sto = null; if (!obj) { obj = window; } if (timeOut == null) { timeOut = 25; } //If before the implementation of the operation has not exceeded the time,then make it cancel. if (doName && obj[doName]) { clearTimeout(obj[doName]); } //Delay for a period of time to perform the operation. sto = setTimeout(function () { fn.call(obj); }, timeOut); if (doName) { obj[doName] = sto; } return sto; }
javascript
function lazyDo(fn, timeOut, doName, obj) { var sto = null; if (!obj) { obj = window; } if (timeOut == null) { timeOut = 25; } //If before the implementation of the operation has not exceeded the time,then make it cancel. if (doName && obj[doName]) { clearTimeout(obj[doName]); } //Delay for a period of time to perform the operation. sto = setTimeout(function () { fn.call(obj); }, timeOut); if (doName) { obj[doName] = sto; } return sto; }
[ "function", "lazyDo", "(", "fn", ",", "timeOut", ",", "doName", ",", "obj", ")", "{", "var", "sto", "=", "null", ";", "if", "(", "!", "obj", ")", "{", "obj", "=", "window", ";", "}", "if", "(", "timeOut", "==", "null", ")", "{", "timeOut", "=", "25", ";", "}", "//If before the implementation of the operation has not exceeded the time,then make it cancel.", "if", "(", "doName", "&&", "obj", "[", "doName", "]", ")", "{", "clearTimeout", "(", "obj", "[", "doName", "]", ")", ";", "}", "//Delay for a period of time to perform the operation.", "sto", "=", "setTimeout", "(", "function", "(", ")", "{", "fn", ".", "call", "(", "obj", ")", ";", "}", ",", "timeOut", ")", ";", "if", "(", "doName", ")", "{", "obj", "[", "doName", "]", "=", "sto", ";", "}", "return", "sto", ";", "}" ]
Lazy to do something
[ "Lazy", "to", "do", "something" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L2873-L2898
25,104
joe-sky/flarej
dist/js/flarej.js
pollDo
function pollDo(fn, timeOut, doName, obj) { var siv = null; if (!obj) { obj = window; } if (timeOut == null) { timeOut = 100; } //If the previous poll operation is exist,then make it cancel. if (doName && obj[doName]) { clearInterval(obj[doName]); } //Polling execution operations every interval a period of time. siv = setInterval(function () { if (fn.call(obj) === false) { clearInterval(siv); } }, timeOut); if (doName) { obj[doName] = siv; } return siv; }
javascript
function pollDo(fn, timeOut, doName, obj) { var siv = null; if (!obj) { obj = window; } if (timeOut == null) { timeOut = 100; } //If the previous poll operation is exist,then make it cancel. if (doName && obj[doName]) { clearInterval(obj[doName]); } //Polling execution operations every interval a period of time. siv = setInterval(function () { if (fn.call(obj) === false) { clearInterval(siv); } }, timeOut); if (doName) { obj[doName] = siv; } return siv; }
[ "function", "pollDo", "(", "fn", ",", "timeOut", ",", "doName", ",", "obj", ")", "{", "var", "siv", "=", "null", ";", "if", "(", "!", "obj", ")", "{", "obj", "=", "window", ";", "}", "if", "(", "timeOut", "==", "null", ")", "{", "timeOut", "=", "100", ";", "}", "//If the previous poll operation is exist,then make it cancel.", "if", "(", "doName", "&&", "obj", "[", "doName", "]", ")", "{", "clearInterval", "(", "obj", "[", "doName", "]", ")", ";", "}", "//Polling execution operations every interval a period of time.", "siv", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "fn", ".", "call", "(", "obj", ")", "===", "false", ")", "{", "clearInterval", "(", "siv", ")", ";", "}", "}", ",", "timeOut", ")", ";", "if", "(", "doName", ")", "{", "obj", "[", "doName", "]", "=", "siv", ";", "}", "return", "siv", ";", "}" ]
Poll to do something
[ "Poll", "to", "do", "something" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L2901-L2928
25,105
joe-sky/flarej
dist/js/flarej.js
on
function on(name, fn, elem) { var useCapture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; return (elem || doc).addEventListener(name, fn, useCapture); }
javascript
function on(name, fn, elem) { var useCapture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; return (elem || doc).addEventListener(name, fn, useCapture); }
[ "function", "on", "(", "name", ",", "fn", ",", "elem", ")", "{", "var", "useCapture", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "false", ";", "return", "(", "elem", "||", "doc", ")", ".", "addEventListener", "(", "name", ",", "fn", ",", "useCapture", ")", ";", "}" ]
Add dom event
[ "Add", "dom", "event" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L4973-L4977
25,106
joe-sky/flarej
dist/js/flarej.js
off
function off(name, fn, elem) { var useCapture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; return (elem || doc).removeEventListener(name, fn, useCapture); }
javascript
function off(name, fn, elem) { var useCapture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; return (elem || doc).removeEventListener(name, fn, useCapture); }
[ "function", "off", "(", "name", ",", "fn", ",", "elem", ")", "{", "var", "useCapture", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "false", ";", "return", "(", "elem", "||", "doc", ")", ".", "removeEventListener", "(", "name", ",", "fn", ",", "useCapture", ")", ";", "}" ]
Remove dom event
[ "Remove", "dom", "event" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L4980-L4984
25,107
joe-sky/flarej
dist/js/flarej.js
pageWidth
function pageWidth() { return win.innerWidth != null ? win.innerWidth : doc.documentElement && doc.documentElement.clientWidth != null ? doc.documentElement.clientWidth : doc.body != null ? doc.body.clientWidth : null; }
javascript
function pageWidth() { return win.innerWidth != null ? win.innerWidth : doc.documentElement && doc.documentElement.clientWidth != null ? doc.documentElement.clientWidth : doc.body != null ? doc.body.clientWidth : null; }
[ "function", "pageWidth", "(", ")", "{", "return", "win", ".", "innerWidth", "!=", "null", "?", "win", ".", "innerWidth", ":", "doc", ".", "documentElement", "&&", "doc", ".", "documentElement", ".", "clientWidth", "!=", "null", "?", "doc", ".", "documentElement", ".", "clientWidth", ":", "doc", ".", "body", "!=", "null", "?", "doc", ".", "body", ".", "clientWidth", ":", "null", ";", "}" ]
Get current width of page
[ "Get", "current", "width", "of", "page" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L6864-L6866
25,108
joe-sky/flarej
dist/js/flarej.js
pageHeight
function pageHeight() { return win.innerHeight != null ? win.innerHeight : doc.documentElement && doc.documentElement.clientHeight != null ? doc.documentElement.clientHeight : doc.body != null ? doc.body.clientHeight : null; }
javascript
function pageHeight() { return win.innerHeight != null ? win.innerHeight : doc.documentElement && doc.documentElement.clientHeight != null ? doc.documentElement.clientHeight : doc.body != null ? doc.body.clientHeight : null; }
[ "function", "pageHeight", "(", ")", "{", "return", "win", ".", "innerHeight", "!=", "null", "?", "win", ".", "innerHeight", ":", "doc", ".", "documentElement", "&&", "doc", ".", "documentElement", ".", "clientHeight", "!=", "null", "?", "doc", ".", "documentElement", ".", "clientHeight", ":", "doc", ".", "body", "!=", "null", "?", "doc", ".", "body", ".", "clientHeight", ":", "null", ";", "}" ]
Get current height of page
[ "Get", "current", "height", "of", "page" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L6872-L6874
25,109
joe-sky/flarej
dist/js/flarej.js
clone
function clone(item) { if (!foundFirst && selectedKeys.indexOf(item.key) !== -1 || !foundFirst && !selectedKeys.length && firstActiveValue.indexOf(item.key) !== -1) { foundFirst = true; return Object(__WEBPACK_IMPORTED_MODULE_4_react__["cloneElement"])(item, { ref: function ref(_ref) { _this2.firstActiveItem = _ref; } }); } return item; }
javascript
function clone(item) { if (!foundFirst && selectedKeys.indexOf(item.key) !== -1 || !foundFirst && !selectedKeys.length && firstActiveValue.indexOf(item.key) !== -1) { foundFirst = true; return Object(__WEBPACK_IMPORTED_MODULE_4_react__["cloneElement"])(item, { ref: function ref(_ref) { _this2.firstActiveItem = _ref; } }); } return item; }
[ "function", "clone", "(", "item", ")", "{", "if", "(", "!", "foundFirst", "&&", "selectedKeys", ".", "indexOf", "(", "item", ".", "key", ")", "!==", "-", "1", "||", "!", "foundFirst", "&&", "!", "selectedKeys", ".", "length", "&&", "firstActiveValue", ".", "indexOf", "(", "item", ".", "key", ")", "!==", "-", "1", ")", "{", "foundFirst", "=", "true", ";", "return", "Object", "(", "__WEBPACK_IMPORTED_MODULE_4_react__", "[", "\"cloneElement\"", "]", ")", "(", "item", ",", "{", "ref", ":", "function", "ref", "(", "_ref", ")", "{", "_this2", ".", "firstActiveItem", "=", "_ref", ";", "}", "}", ")", ";", "}", "return", "item", ";", "}" ]
set firstActiveItem via cloning menus for scroll into view
[ "set", "firstActiveItem", "via", "cloning", "menus", "for", "scroll", "into", "view" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L33036-L33046
25,110
joe-sky/flarej
dist/js/flarej.js
matches
function matches(elem, selector) { // Vendor-specific implementations of `Element.prototype.matches()`. var proto = window.Element.prototype; var nativeMatches = proto.matches || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; if (!elem || elem.nodeType !== 1) { return false; } var parentElem = elem.parentNode; // use native 'matches' if (nativeMatches) { return nativeMatches.call(elem, selector); } // native support for `matches` is missing and a fallback is required var nodes = parentElem.querySelectorAll(selector); var len = nodes.length; for (var i = 0; i < len; i++) { if (nodes[i] === elem) { return true; } } return false; }
javascript
function matches(elem, selector) { // Vendor-specific implementations of `Element.prototype.matches()`. var proto = window.Element.prototype; var nativeMatches = proto.matches || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; if (!elem || elem.nodeType !== 1) { return false; } var parentElem = elem.parentNode; // use native 'matches' if (nativeMatches) { return nativeMatches.call(elem, selector); } // native support for `matches` is missing and a fallback is required var nodes = parentElem.querySelectorAll(selector); var len = nodes.length; for (var i = 0; i < len; i++) { if (nodes[i] === elem) { return true; } } return false; }
[ "function", "matches", "(", "elem", ",", "selector", ")", "{", "// Vendor-specific implementations of `Element.prototype.matches()`.", "var", "proto", "=", "window", ".", "Element", ".", "prototype", ";", "var", "nativeMatches", "=", "proto", ".", "matches", "||", "proto", ".", "mozMatchesSelector", "||", "proto", ".", "msMatchesSelector", "||", "proto", ".", "oMatchesSelector", "||", "proto", ".", "webkitMatchesSelector", ";", "if", "(", "!", "elem", "||", "elem", ".", "nodeType", "!==", "1", ")", "{", "return", "false", ";", "}", "var", "parentElem", "=", "elem", ".", "parentNode", ";", "// use native 'matches'", "if", "(", "nativeMatches", ")", "{", "return", "nativeMatches", ".", "call", "(", "elem", ",", "selector", ")", ";", "}", "// native support for `matches` is missing and a fallback is required", "var", "nodes", "=", "parentElem", ".", "querySelectorAll", "(", "selector", ")", ";", "var", "len", "=", "nodes", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "nodes", "[", "i", "]", "===", "elem", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if a DOM element matches a CSS selector @param {Element} elem @param {String} selector @return {Boolean} @api public
[ "Determine", "if", "a", "DOM", "element", "matches", "a", "CSS", "selector" ]
d1dd8bf8e34f9110869e4ce3f40d8f93a8030168
https://github.com/joe-sky/flarej/blob/d1dd8bf8e34f9110869e4ce3f40d8f93a8030168/dist/js/flarej.js#L33983-L34014
25,111
afeld/backbone-nested
vendor/DocumentUp/documentup.js
insert
function insert(target, host, fn) { var i = 0, self = host || this, r = [] // target nodes could be a css selector if it's a string and a selector engine is present // otherwise, just use target , nodes = query && typeof target == 'string' && target.charAt(0) != '<' ? query(target) : target // normalize each node in case it's still a string and we need to create nodes on the fly each(normalize(nodes), function (t) { each(self, function (el) { var n = !el[parentNode] || (el[parentNode] && !el[parentNode][parentNode]) ? function () { var c = el.cloneNode(true) // check for existence of an event cloner // preferably https://github.com/fat/bean // otherwise Bonzo won't do this for you self.$ && self.cloneEvents && self.$(c).cloneEvents(el) return c }() : el fn(t, n) r[i] = n i++ }) }, this) each(r, function (e, i) { self[i] = e }) self.length = i return self }
javascript
function insert(target, host, fn) { var i = 0, self = host || this, r = [] // target nodes could be a css selector if it's a string and a selector engine is present // otherwise, just use target , nodes = query && typeof target == 'string' && target.charAt(0) != '<' ? query(target) : target // normalize each node in case it's still a string and we need to create nodes on the fly each(normalize(nodes), function (t) { each(self, function (el) { var n = !el[parentNode] || (el[parentNode] && !el[parentNode][parentNode]) ? function () { var c = el.cloneNode(true) // check for existence of an event cloner // preferably https://github.com/fat/bean // otherwise Bonzo won't do this for you self.$ && self.cloneEvents && self.$(c).cloneEvents(el) return c }() : el fn(t, n) r[i] = n i++ }) }, this) each(r, function (e, i) { self[i] = e }) self.length = i return self }
[ "function", "insert", "(", "target", ",", "host", ",", "fn", ")", "{", "var", "i", "=", "0", ",", "self", "=", "host", "||", "this", ",", "r", "=", "[", "]", "// target nodes could be a css selector if it's a string and a selector engine is present", "// otherwise, just use target", ",", "nodes", "=", "query", "&&", "typeof", "target", "==", "'string'", "&&", "target", ".", "charAt", "(", "0", ")", "!=", "'<'", "?", "query", "(", "target", ")", ":", "target", "// normalize each node in case it's still a string and we need to create nodes on the fly", "each", "(", "normalize", "(", "nodes", ")", ",", "function", "(", "t", ")", "{", "each", "(", "self", ",", "function", "(", "el", ")", "{", "var", "n", "=", "!", "el", "[", "parentNode", "]", "||", "(", "el", "[", "parentNode", "]", "&&", "!", "el", "[", "parentNode", "]", "[", "parentNode", "]", ")", "?", "function", "(", ")", "{", "var", "c", "=", "el", ".", "cloneNode", "(", "true", ")", "// check for existence of an event cloner", "// preferably https://github.com/fat/bean", "// otherwise Bonzo won't do this for you", "self", ".", "$", "&&", "self", ".", "cloneEvents", "&&", "self", ".", "$", "(", "c", ")", ".", "cloneEvents", "(", "el", ")", "return", "c", "}", "(", ")", ":", "el", "fn", "(", "t", ",", "n", ")", "r", "[", "i", "]", "=", "n", "i", "++", "}", ")", "}", ",", "this", ")", "each", "(", "r", ",", "function", "(", "e", ",", "i", ")", "{", "self", "[", "i", "]", "=", "e", "}", ")", "self", ".", "length", "=", "i", "return", "self", "}" ]
this insert method is intense
[ "this", "insert", "method", "is", "intense" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L329-L356
25,112
afeld/backbone-nested
vendor/DocumentUp/documentup.js
each
function each(a, fn) { var i = 0, l = a.length for (; i < l; i++) fn.call(null, a[i]) }
javascript
function each(a, fn) { var i = 0, l = a.length for (; i < l; i++) fn.call(null, a[i]) }
[ "function", "each", "(", "a", ",", "fn", ")", "{", "var", "i", "=", "0", ",", "l", "=", "a", ".", "length", "for", "(", ";", "i", "<", "l", ";", "i", "++", ")", "fn", ".", "call", "(", "null", ",", "a", "[", "i", "]", ")", "}" ]
not quite as fast as inline loops in older browsers so don't use liberally
[ "not", "quite", "as", "fast", "as", "inline", "loops", "in", "older", "browsers", "so", "don", "t", "use", "liberally" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L1164-L1167
25,113
afeld/backbone-nested
vendor/DocumentUp/documentup.js
_qwery
function _qwery(selector, _root) { var r = [], ret = [], i, l, m, token, tag, els, intr, item, root = _root , tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr)) , dividedTokens = selector.match(dividers) if (!tokens.length) return r token = (tokens = tokens.slice(0)).pop() // copy cached tokens, take the last one if (tokens.length && (m = tokens[tokens.length - 1].match(idOnly))) root = byId(_root, m[1]) if (!root) return r intr = q(token) // collect base candidates to filter els = root !== _root && root.nodeType !== 9 && dividedTokens && /^[+~]$/.test(dividedTokens[dividedTokens.length - 1]) ? function (r) { while (root = root.nextSibling) { root.nodeType == 1 && (intr[1] ? intr[1] == root.tagName.toLowerCase() : 1) && (r[r.length] = root) } return r }([]) : root[byTag](intr[1] || '*') // filter elements according to the right-most part of the selector for (i = 0, l = els.length; i < l; i++) { if (item = interpret.apply(els[i], intr)) r[r.length] = item } if (!tokens.length) return r // filter further according to the rest of the selector (the left side) each(r, function(e) { if (ancestorMatch(e, tokens, dividedTokens)) ret[ret.length] = e }) return ret }
javascript
function _qwery(selector, _root) { var r = [], ret = [], i, l, m, token, tag, els, intr, item, root = _root , tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr)) , dividedTokens = selector.match(dividers) if (!tokens.length) return r token = (tokens = tokens.slice(0)).pop() // copy cached tokens, take the last one if (tokens.length && (m = tokens[tokens.length - 1].match(idOnly))) root = byId(_root, m[1]) if (!root) return r intr = q(token) // collect base candidates to filter els = root !== _root && root.nodeType !== 9 && dividedTokens && /^[+~]$/.test(dividedTokens[dividedTokens.length - 1]) ? function (r) { while (root = root.nextSibling) { root.nodeType == 1 && (intr[1] ? intr[1] == root.tagName.toLowerCase() : 1) && (r[r.length] = root) } return r }([]) : root[byTag](intr[1] || '*') // filter elements according to the right-most part of the selector for (i = 0, l = els.length; i < l; i++) { if (item = interpret.apply(els[i], intr)) r[r.length] = item } if (!tokens.length) return r // filter further according to the rest of the selector (the left side) each(r, function(e) { if (ancestorMatch(e, tokens, dividedTokens)) ret[ret.length] = e }) return ret }
[ "function", "_qwery", "(", "selector", ",", "_root", ")", "{", "var", "r", "=", "[", "]", ",", "ret", "=", "[", "]", ",", "i", ",", "l", ",", "m", ",", "token", ",", "tag", ",", "els", ",", "intr", ",", "item", ",", "root", "=", "_root", ",", "tokens", "=", "tokenCache", ".", "g", "(", "selector", ")", "||", "tokenCache", ".", "s", "(", "selector", ",", "selector", ".", "split", "(", "tokenizr", ")", ")", ",", "dividedTokens", "=", "selector", ".", "match", "(", "dividers", ")", "if", "(", "!", "tokens", ".", "length", ")", "return", "r", "token", "=", "(", "tokens", "=", "tokens", ".", "slice", "(", "0", ")", ")", ".", "pop", "(", ")", "// copy cached tokens, take the last one", "if", "(", "tokens", ".", "length", "&&", "(", "m", "=", "tokens", "[", "tokens", ".", "length", "-", "1", "]", ".", "match", "(", "idOnly", ")", ")", ")", "root", "=", "byId", "(", "_root", ",", "m", "[", "1", "]", ")", "if", "(", "!", "root", ")", "return", "r", "intr", "=", "q", "(", "token", ")", "// collect base candidates to filter", "els", "=", "root", "!==", "_root", "&&", "root", ".", "nodeType", "!==", "9", "&&", "dividedTokens", "&&", "/", "^[+~]$", "/", ".", "test", "(", "dividedTokens", "[", "dividedTokens", ".", "length", "-", "1", "]", ")", "?", "function", "(", "r", ")", "{", "while", "(", "root", "=", "root", ".", "nextSibling", ")", "{", "root", ".", "nodeType", "==", "1", "&&", "(", "intr", "[", "1", "]", "?", "intr", "[", "1", "]", "==", "root", ".", "tagName", ".", "toLowerCase", "(", ")", ":", "1", ")", "&&", "(", "r", "[", "r", ".", "length", "]", "=", "root", ")", "}", "return", "r", "}", "(", "[", "]", ")", ":", "root", "[", "byTag", "]", "(", "intr", "[", "1", "]", "||", "'*'", ")", "// filter elements according to the right-most part of the selector", "for", "(", "i", "=", "0", ",", "l", "=", "els", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "item", "=", "interpret", ".", "apply", "(", "els", "[", "i", "]", ",", "intr", ")", ")", "r", "[", "r", ".", "length", "]", "=", "item", "}", "if", "(", "!", "tokens", ".", "length", ")", "return", "r", "// filter further according to the rest of the selector (the left side)", "each", "(", "r", ",", "function", "(", "e", ")", "{", "if", "(", "ancestorMatch", "(", "e", ",", "tokens", ",", "dividedTokens", ")", ")", "ret", "[", "ret", ".", "length", "]", "=", "e", "}", ")", "return", "ret", "}" ]
given a selector, first check for simple cases then collect all base candidate matches and filter
[ "given", "a", "selector", "first", "check", "for", "simple", "cases", "then", "collect", "all", "base", "candidate", "matches", "and", "filter" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L1243-L1273
25,114
afeld/backbone-nested
vendor/DocumentUp/documentup.js
crawl
function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } }
javascript
function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } }
[ "function", "crawl", "(", "e", ",", "i", ",", "p", ")", "{", "while", "(", "p", "=", "walker", "[", "dividedTokens", "[", "i", "]", "]", "(", "p", ",", "e", ")", ")", "{", "if", "(", "isNode", "(", "p", ")", "&&", "(", "interpret", ".", "apply", "(", "p", ",", "q", "(", "tokens", "[", "i", "]", ")", ")", ")", ")", "{", "if", "(", "i", ")", "{", "if", "(", "cand", "=", "crawl", "(", "p", ",", "i", "-", "1", ",", "p", ")", ")", "return", "cand", "}", "else", "return", "p", "}", "}", "}" ]
recursively work backwards through the tokens and up the dom, covering all options
[ "recursively", "work", "backwards", "through", "the", "tokens", "and", "up", "the", "dom", "covering", "all", "options" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L1296-L1304
25,115
afeld/backbone-nested
vendor/DocumentUp/documentup.js
function (checkNamespaces) { var i, j if (!checkNamespaces) return true if (!this.namespaces) return false for (i = checkNamespaces.length; i--;) { for (j = this.namespaces.length; j--;) { if (checkNamespaces[i] === this.namespaces[j]) return true } } return false }
javascript
function (checkNamespaces) { var i, j if (!checkNamespaces) return true if (!this.namespaces) return false for (i = checkNamespaces.length; i--;) { for (j = this.namespaces.length; j--;) { if (checkNamespaces[i] === this.namespaces[j]) return true } } return false }
[ "function", "(", "checkNamespaces", ")", "{", "var", "i", ",", "j", "if", "(", "!", "checkNamespaces", ")", "return", "true", "if", "(", "!", "this", ".", "namespaces", ")", "return", "false", "for", "(", "i", "=", "checkNamespaces", ".", "length", ";", "i", "--", ";", ")", "{", "for", "(", "j", "=", "this", ".", "namespaces", ".", "length", ";", "j", "--", ";", ")", "{", "if", "(", "checkNamespaces", "[", "i", "]", "===", "this", ".", "namespaces", "[", "j", "]", ")", "return", "true", "}", "}", "return", "false", "}" ]
given a list of namespaces, is our entry in any of them?
[ "given", "a", "list", "of", "namespaces", "is", "our", "entry", "in", "any", "of", "them?" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L1730-L1743
25,116
afeld/backbone-nested
vendor/DocumentUp/documentup.js
function () { var i, entries = registry.entries() for (i in entries) { if (entries[i].type && entries[i].type !== 'unload') remove(entries[i].element, entries[i].type) } win[detachEvent]('onunload', cleanup) win.CollectGarbage && win.CollectGarbage() }
javascript
function () { var i, entries = registry.entries() for (i in entries) { if (entries[i].type && entries[i].type !== 'unload') remove(entries[i].element, entries[i].type) } win[detachEvent]('onunload', cleanup) win.CollectGarbage && win.CollectGarbage() }
[ "function", "(", ")", "{", "var", "i", ",", "entries", "=", "registry", ".", "entries", "(", ")", "for", "(", "i", "in", "entries", ")", "{", "if", "(", "entries", "[", "i", "]", ".", "type", "&&", "entries", "[", "i", "]", ".", "type", "!==", "'unload'", ")", "remove", "(", "entries", "[", "i", "]", ".", "element", ",", "entries", "[", "i", "]", ".", "type", ")", "}", "win", "[", "detachEvent", "]", "(", "'onunload'", ",", "cleanup", ")", "win", ".", "CollectGarbage", "&&", "win", ".", "CollectGarbage", "(", ")", "}" ]
for IE, clean up on unload to avoid leaks
[ "for", "IE", "clean", "up", "on", "unload", "to", "avoid", "leaks" ]
7d69a1178056f99c69be4c381e4e3bdf016739ce
https://github.com/afeld/backbone-nested/blob/7d69a1178056f99c69be4c381e4e3bdf016739ce/vendor/DocumentUp/documentup.js#L2032-L2040
25,117
C2FO/patio
lib/plugins/columnMapper.js
function (name, table, condition, opts) { opts = opts || {}; if (name) { name = sql.stringToIdentifier(name); if (table && condition) { opts = comb.merge({joinType: "left", table: table, condition: condition, column: name}, opts); this._mappedColumns[name] = opts; } else { throw new ModelError("mapped column requires a table and join condition"); } } return this; }
javascript
function (name, table, condition, opts) { opts = opts || {}; if (name) { name = sql.stringToIdentifier(name); if (table && condition) { opts = comb.merge({joinType: "left", table: table, condition: condition, column: name}, opts); this._mappedColumns[name] = opts; } else { throw new ModelError("mapped column requires a table and join condition"); } } return this; }
[ "function", "(", "name", ",", "table", ",", "condition", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "name", ")", "{", "name", "=", "sql", ".", "stringToIdentifier", "(", "name", ")", ";", "if", "(", "table", "&&", "condition", ")", "{", "opts", "=", "comb", ".", "merge", "(", "{", "joinType", ":", "\"left\"", ",", "table", ":", "table", ",", "condition", ":", "condition", ",", "column", ":", "name", "}", ",", "opts", ")", ";", "this", ".", "_mappedColumns", "[", "name", "]", "=", "opts", ";", "}", "else", "{", "throw", "new", "ModelError", "(", "\"mapped column requires a table and join condition\"", ")", ";", "}", "}", "return", "this", ";", "}" ]
Add a mapped column from another table. This is useful if there columns on another table but you do not want to load the association every time. For example assume we have an employee and works table. Well we might want the salary from the works table, but do not want to add it to the employee table. <b>NOTE:</b> mapped columns are READ ONLY. {@code patio.addModel("employee") .oneToOne("works") .mappedColumn("salary", "works", {employeeId : patio.sql.identifier("id")}); } You can also change the name of the of the column {@code patio.addModel("employee") .oneToOne("works") .mappedColumn("mySalary", "works", {employeeId : patio.sql.identifier("id")}, { column : "salary" }); } If you want to prevent the mapped columns from being reloaded after a save or update you can set the <code>fetchMappedColumnsOnUpdate</code> or <code>fetchMappedColumnsOnSave</code> to false. {@code var Employee = patio.addModel("employee") .oneToOne("works") .mappedColumn("mySalary", "works", {employeeId : patio.sql.identifier("id")}, { column : "salary" }); //prevent the mapped columns from being fetched after a save. Employee.fetchMappedColumnsOnSave = false; //prevent the mapped columns from being re-fetched after an update. Employee.fetchMappedColumnsOnUpdate = false; } You can also override prevent the properties from being reloaded by setting the <code>reload</code> or <code>reloadMapped</code> options when saving or updating. {@code //prevents entire model from being reloaded including mapped columns employee.save(null, {reload : false}); employee.update(null, {reload : false}); //just prevents just the mapped columns from being reloaded employee.save(null, {reloadMapped : false}); employee.update(null, {reloadMapped : false}); } @param {String} name the name you want the column represented as on the model. @param {String|patio.Model} table the table or model you want the property mapped from @param condition the join condition. See {@link patio.Dataset#joinTable}. @param {Object} [opts={}] additional options @param {String} [opts.joinType="left"] the join type to use when gathering the properties. @param {String|patio.sql.Identifer} [opts.column=null] the column on the remote table that should be used as the local copy. @return {patio.Model} returns the model for chaining.
[ "Add", "a", "mapped", "column", "from", "another", "table", ".", "This", "is", "useful", "if", "there", "columns", "on", "another", "table", "but", "you", "do", "not", "want", "to", "load", "the", "association", "every", "time", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/columnMapper.js#L113-L125
25,118
C2FO/patio
lib/adapters/postgres.js
function () { if (!this.__serverVersion) { var self = this; this.__serverVersion = this.get(identifier("version").sqlFunction).chain(function (version) { var m = version.match(/PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/); version = (parseInt(m[1], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[3], 10); self._serverVersion = version; return version; }); } return this.__serverVersion.promise(); }
javascript
function () { if (!this.__serverVersion) { var self = this; this.__serverVersion = this.get(identifier("version").sqlFunction).chain(function (version) { var m = version.match(/PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/); version = (parseInt(m[1], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[3], 10); self._serverVersion = version; return version; }); } return this.__serverVersion.promise(); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "__serverVersion", ")", "{", "var", "self", "=", "this", ";", "this", ".", "__serverVersion", "=", "this", ".", "get", "(", "identifier", "(", "\"version\"", ")", ".", "sqlFunction", ")", ".", "chain", "(", "function", "(", "version", ")", "{", "var", "m", "=", "version", ".", "match", "(", "/", "PostgreSQL (\\d+)\\.(\\d+)(?:(?:rc\\d+)|\\.(\\d+))?", "/", ")", ";", "version", "=", "(", "parseInt", "(", "m", "[", "1", "]", ",", "10", ")", "*", "10000", ")", "+", "(", "parseInt", "(", "m", "[", "2", "]", ",", "10", ")", "*", "100", ")", "+", "parseInt", "(", "m", "[", "3", "]", ",", "10", ")", ";", "self", ".", "_serverVersion", "=", "version", ";", "return", "version", ";", "}", ")", ";", "}", "return", "this", ".", "__serverVersion", ".", "promise", "(", ")", ";", "}" ]
Get version of postgres server, used for determined capabilities.
[ "Get", "version", "of", "postgres", "server", "used", "for", "determined", "capabilities", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/postgres.js#L679-L690
25,119
C2FO/patio
lib/adapters/postgres.js
function (type, opts, cb) { var ret; var ds = this.metadataDataset.from("pg_class") .filter({relkind: type}).select("relname") .exclude({relname: {like: this.SYSTEM_TABLE_REGEXP}}) .join("pg_namespace", {oid: identifier("relnamespace")}); ds = this.__filterSchema(ds, opts); var m = this.outputIdentifierFunc; if (cb) { ret = when(cb(ds)); } else { ret = ds.map(function (r) { return m(r.relname); }); } return ret.promise(); }
javascript
function (type, opts, cb) { var ret; var ds = this.metadataDataset.from("pg_class") .filter({relkind: type}).select("relname") .exclude({relname: {like: this.SYSTEM_TABLE_REGEXP}}) .join("pg_namespace", {oid: identifier("relnamespace")}); ds = this.__filterSchema(ds, opts); var m = this.outputIdentifierFunc; if (cb) { ret = when(cb(ds)); } else { ret = ds.map(function (r) { return m(r.relname); }); } return ret.promise(); }
[ "function", "(", "type", ",", "opts", ",", "cb", ")", "{", "var", "ret", ";", "var", "ds", "=", "this", ".", "metadataDataset", ".", "from", "(", "\"pg_class\"", ")", ".", "filter", "(", "{", "relkind", ":", "type", "}", ")", ".", "select", "(", "\"relname\"", ")", ".", "exclude", "(", "{", "relname", ":", "{", "like", ":", "this", ".", "SYSTEM_TABLE_REGEXP", "}", "}", ")", ".", "join", "(", "\"pg_namespace\"", ",", "{", "oid", ":", "identifier", "(", "\"relnamespace\"", ")", "}", ")", ";", "ds", "=", "this", ".", "__filterSchema", "(", "ds", ",", "opts", ")", ";", "var", "m", "=", "this", ".", "outputIdentifierFunc", ";", "if", "(", "cb", ")", "{", "ret", "=", "when", "(", "cb", "(", "ds", ")", ")", ";", "}", "else", "{", "ret", "=", "ds", ".", "map", "(", "function", "(", "r", ")", "{", "return", "m", "(", "r", ".", "relname", ")", ";", "}", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Backbone of the tables and views support.
[ "Backbone", "of", "the", "tables", "and", "views", "support", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/postgres.js#L858-L874
25,120
C2FO/patio
lib/adapters/postgres.js
function (column) { if (column.fixed) { return ["char(", column.size || 255, ")"].join(""); } else if (column.text === false || column.size) { return ["varchar(", column.size || 255, ")"].join(""); } else { return 'text'; } }
javascript
function (column) { if (column.fixed) { return ["char(", column.size || 255, ")"].join(""); } else if (column.text === false || column.size) { return ["varchar(", column.size || 255, ")"].join(""); } else { return 'text'; } }
[ "function", "(", "column", ")", "{", "if", "(", "column", ".", "fixed", ")", "{", "return", "[", "\"char(\"", ",", "column", ".", "size", "||", "255", ",", "\")\"", "]", ".", "join", "(", "\"\"", ")", ";", "}", "else", "if", "(", "column", ".", "text", "===", "false", "||", "column", ".", "size", ")", "{", "return", "[", "\"varchar(\"", ",", "column", ".", "size", "||", "255", ",", "\")\"", "]", ".", "join", "(", "\"\"", ")", ";", "}", "else", "{", "return", "'text'", ";", "}", "}" ]
PostgreSQL prefers the text datatype. If a fixed size is requested, the char type is used. If the text type is specifically disallowed or there is a size specified, use the varchar type. Otherwise use the type type.
[ "PostgreSQL", "prefers", "the", "text", "datatype", ".", "If", "a", "fixed", "size", "is", "requested", "the", "char", "type", "is", "used", ".", "If", "the", "text", "type", "is", "specifically", "disallowed", "or", "there", "is", "a", "size", "specified", "use", "the", "varchar", "type", ".", "Otherwise", "use", "the", "type", "type", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/postgres.js#L1005-L1014
25,121
C2FO/patio
lib/associations/_Association.js
function (parent) { var options = this.__opts || {}; var ds, self = this; if (!isUndefined((ds = options.dataset)) && isFunction(ds)) { ds = ds.apply(parent, [parent]); } if (!ds) { var q = {}; this._setAssociationKeys(parent, q); ds = this.model.dataset.naked().filter(q); var recip = this.model._findAssociation(this); recip && (recip = recip[1]); ds.rowCb = function (item) { var model = self._toModel(item, true); recip && recip.__setValue(model, parent); //call hook to finish other model associations return model._hook("post", "load").chain(function () { return model; }); }; } else if (!ds.rowCb && this.model) { ds.rowCb = function (item) { var model = self._toModel(item, true); //call hook to finish other model associations return model._hook("post", "load").chain(function () { return model; }); }; } return this._setDatasetOptions(ds); }
javascript
function (parent) { var options = this.__opts || {}; var ds, self = this; if (!isUndefined((ds = options.dataset)) && isFunction(ds)) { ds = ds.apply(parent, [parent]); } if (!ds) { var q = {}; this._setAssociationKeys(parent, q); ds = this.model.dataset.naked().filter(q); var recip = this.model._findAssociation(this); recip && (recip = recip[1]); ds.rowCb = function (item) { var model = self._toModel(item, true); recip && recip.__setValue(model, parent); //call hook to finish other model associations return model._hook("post", "load").chain(function () { return model; }); }; } else if (!ds.rowCb && this.model) { ds.rowCb = function (item) { var model = self._toModel(item, true); //call hook to finish other model associations return model._hook("post", "load").chain(function () { return model; }); }; } return this._setDatasetOptions(ds); }
[ "function", "(", "parent", ")", "{", "var", "options", "=", "this", ".", "__opts", "||", "{", "}", ";", "var", "ds", ",", "self", "=", "this", ";", "if", "(", "!", "isUndefined", "(", "(", "ds", "=", "options", ".", "dataset", ")", ")", "&&", "isFunction", "(", "ds", ")", ")", "{", "ds", "=", "ds", ".", "apply", "(", "parent", ",", "[", "parent", "]", ")", ";", "}", "if", "(", "!", "ds", ")", "{", "var", "q", "=", "{", "}", ";", "this", ".", "_setAssociationKeys", "(", "parent", ",", "q", ")", ";", "ds", "=", "this", ".", "model", ".", "dataset", ".", "naked", "(", ")", ".", "filter", "(", "q", ")", ";", "var", "recip", "=", "this", ".", "model", ".", "_findAssociation", "(", "this", ")", ";", "recip", "&&", "(", "recip", "=", "recip", "[", "1", "]", ")", ";", "ds", ".", "rowCb", "=", "function", "(", "item", ")", "{", "var", "model", "=", "self", ".", "_toModel", "(", "item", ",", "true", ")", ";", "recip", "&&", "recip", ".", "__setValue", "(", "model", ",", "parent", ")", ";", "//call hook to finish other model associations", "return", "model", ".", "_hook", "(", "\"post\"", ",", "\"load\"", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "model", ";", "}", ")", ";", "}", ";", "}", "else", "if", "(", "!", "ds", ".", "rowCb", "&&", "this", ".", "model", ")", "{", "ds", ".", "rowCb", "=", "function", "(", "item", ")", "{", "var", "model", "=", "self", ".", "_toModel", "(", "item", ",", "true", ")", ";", "//call hook to finish other model associations", "return", "model", ".", "_hook", "(", "\"post\"", ",", "\"load\"", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "model", ";", "}", ")", ";", "}", ";", "}", "return", "this", ".", "_setDatasetOptions", "(", "ds", ")", ";", "}" ]
Filters our associated dataset to load our association. @return {Dataset} the dataset with all filters applied.
[ "Filters", "our", "associated", "dataset", "to", "load", "our", "association", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/_Association.js#L238-L269
25,122
C2FO/patio
lib/associations/_Association.js
function (model) { //if we have them return them; if (this.associationLoaded(model)) { var assoc = this.getAssociation(model); return this.isEager() ? assoc : when(assoc); } else if (model.isNew) { return null; } else { return this.fetch(model); } }
javascript
function (model) { //if we have them return them; if (this.associationLoaded(model)) { var assoc = this.getAssociation(model); return this.isEager() ? assoc : when(assoc); } else if (model.isNew) { return null; } else { return this.fetch(model); } }
[ "function", "(", "model", ")", "{", "//if we have them return them;", "if", "(", "this", ".", "associationLoaded", "(", "model", ")", ")", "{", "var", "assoc", "=", "this", ".", "getAssociation", "(", "model", ")", ";", "return", "this", ".", "isEager", "(", ")", "?", "assoc", ":", "when", "(", "assoc", ")", ";", "}", "else", "if", "(", "model", ".", "isNew", ")", "{", "return", "null", ";", "}", "else", "{", "return", "this", ".", "fetch", "(", "model", ")", ";", "}", "}" ]
Alias used to explicitly get an association on a model. @param {_Association} self reference to the Association that is being called.
[ "Alias", "used", "to", "explicitly", "get", "an", "association", "on", "a", "model", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/_Association.js#L413-L423
25,123
C2FO/patio
lib/associations/_Association.js
function (parent, name) { this.name = name; var self = this; this.parent = parent; var parentProto = parent.prototype; parentProto["__defineGetter__"](name, function () { return self._getter(this); }); parentProto["__defineGetter__"](this.associatedDatasetName, function () { return self._filter(this); }); if (!this.readOnly && this.createSetter) { //define a setter because we arent read only parentProto["__defineSetter__"](name, function (vals) { self._setter(vals, this); }); } //set up all callbacks ["pre", "post"].forEach(function (op) { ["save", "update", "remove", "load"].forEach(function (type) { parent[op](type, function (next) { return self["_" + op + type.charAt(0).toUpperCase() + type.slice(1)](next, this); }); }, this); }, this); }
javascript
function (parent, name) { this.name = name; var self = this; this.parent = parent; var parentProto = parent.prototype; parentProto["__defineGetter__"](name, function () { return self._getter(this); }); parentProto["__defineGetter__"](this.associatedDatasetName, function () { return self._filter(this); }); if (!this.readOnly && this.createSetter) { //define a setter because we arent read only parentProto["__defineSetter__"](name, function (vals) { self._setter(vals, this); }); } //set up all callbacks ["pre", "post"].forEach(function (op) { ["save", "update", "remove", "load"].forEach(function (type) { parent[op](type, function (next) { return self["_" + op + type.charAt(0).toUpperCase() + type.slice(1)](next, this); }); }, this); }, this); }
[ "function", "(", "parent", ",", "name", ")", "{", "this", ".", "name", "=", "name", ";", "var", "self", "=", "this", ";", "this", ".", "parent", "=", "parent", ";", "var", "parentProto", "=", "parent", ".", "prototype", ";", "parentProto", "[", "\"__defineGetter__\"", "]", "(", "name", ",", "function", "(", ")", "{", "return", "self", ".", "_getter", "(", "this", ")", ";", "}", ")", ";", "parentProto", "[", "\"__defineGetter__\"", "]", "(", "this", ".", "associatedDatasetName", ",", "function", "(", ")", "{", "return", "self", ".", "_filter", "(", "this", ")", ";", "}", ")", ";", "if", "(", "!", "this", ".", "readOnly", "&&", "this", ".", "createSetter", ")", "{", "//define a setter because we arent read only", "parentProto", "[", "\"__defineSetter__\"", "]", "(", "name", ",", "function", "(", "vals", ")", "{", "self", ".", "_setter", "(", "vals", ",", "this", ")", ";", "}", ")", ";", "}", "//set up all callbacks", "[", "\"pre\"", ",", "\"post\"", "]", ".", "forEach", "(", "function", "(", "op", ")", "{", "[", "\"save\"", ",", "\"update\"", ",", "\"remove\"", ",", "\"load\"", "]", ".", "forEach", "(", "function", "(", "type", ")", "{", "parent", "[", "op", "]", "(", "type", ",", "function", "(", "next", ")", "{", "return", "self", "[", "\"_\"", "+", "op", "+", "type", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "]", "(", "next", ",", "this", ")", ";", "}", ")", ";", "}", ",", "this", ")", ";", "}", ",", "this", ")", ";", "}" ]
Method to inject functionality into a model. This method alters the model to prepare it for associations, and initializes all required middleware calls to fulfill requirements needed to loaded the associations. @param {Model} parent the model that is having an associtaion set on it. @param {String} name the name of the association.
[ "Method", "to", "inject", "functionality", "into", "a", "model", ".", "This", "method", "alters", "the", "model", "to", "prepare", "it", "for", "associations", "and", "initializes", "all", "required", "middleware", "calls", "to", "fulfill", "requirements", "needed", "to", "loaded", "the", "associations", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/_Association.js#L445-L472
25,124
C2FO/patio
lib/plugins/inheritance.js
function () { var q = this._getPrimaryKeyQuery(); return new PromiseList(this._static.__ctiTables.slice().reverse().map(function (table) { return this.db.from(table).filter(q).remove(); }, this), true).promise(); }
javascript
function () { var q = this._getPrimaryKeyQuery(); return new PromiseList(this._static.__ctiTables.slice().reverse().map(function (table) { return this.db.from(table).filter(q).remove(); }, this), true).promise(); }
[ "function", "(", ")", "{", "var", "q", "=", "this", ".", "_getPrimaryKeyQuery", "(", ")", ";", "return", "new", "PromiseList", "(", "this", ".", "_static", ".", "__ctiTables", ".", "slice", "(", ")", ".", "reverse", "(", ")", ".", "map", "(", "function", "(", "table", ")", "{", "return", "this", ".", "db", ".", "from", "(", "table", ")", ".", "filter", "(", "q", ")", ".", "remove", "(", ")", ";", "}", ",", "this", ")", ",", "true", ")", ".", "promise", "(", ")", ";", "}" ]
Delete the row from all backing tables, starting from the most recent table and going through all superclasses.
[ "Delete", "the", "row", "from", "all", "backing", "tables", "starting", "from", "the", "most", "recent", "table", "and", "going", "through", "all", "superclasses", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/inheritance.js#L127-L132
25,125
C2FO/patio
lib/plugins/inheritance.js
function () { var Self = this._static, ret; if (Self === Self.__ctiBaseModel) { ret = this._super(arguments); } else { var pk = this.primaryKey[0], tables = Self.__ctiTables, ctiColumns = Self.__ctiColumns, self = this, isRestricted = Self.isRestrictedPrimaryKey, db = this.db; ret = asyncArray.forEach(tables,function (table, index) { var cols = ctiColumns[table], insert = {}, val, i = -1, colLength = cols.length, c; while (++i < colLength) { c = cols[i]; if ((index !== 0 || (index === 0 && (!isRestricted || pk.indexOf(c) === -1))) && !comb.isUndefined(val = self[c])) { insert[c] = val; } } return db.from(table).insert(insert).chain(function (id) { if (comb.isUndefined(self.primaryKeyValue) && !comb.isUndefined(id) && index === 0) { self.__ignore = true; //how to handle composite keys. self[pk] = id; self.__ignore = false; } }); }, 1).chain(function () { self.__isNew = false; self.__isChanged = false; return self._saveReload(); }); } return ret.promise(); }
javascript
function () { var Self = this._static, ret; if (Self === Self.__ctiBaseModel) { ret = this._super(arguments); } else { var pk = this.primaryKey[0], tables = Self.__ctiTables, ctiColumns = Self.__ctiColumns, self = this, isRestricted = Self.isRestrictedPrimaryKey, db = this.db; ret = asyncArray.forEach(tables,function (table, index) { var cols = ctiColumns[table], insert = {}, val, i = -1, colLength = cols.length, c; while (++i < colLength) { c = cols[i]; if ((index !== 0 || (index === 0 && (!isRestricted || pk.indexOf(c) === -1))) && !comb.isUndefined(val = self[c])) { insert[c] = val; } } return db.from(table).insert(insert).chain(function (id) { if (comb.isUndefined(self.primaryKeyValue) && !comb.isUndefined(id) && index === 0) { self.__ignore = true; //how to handle composite keys. self[pk] = id; self.__ignore = false; } }); }, 1).chain(function () { self.__isNew = false; self.__isChanged = false; return self._saveReload(); }); } return ret.promise(); }
[ "function", "(", ")", "{", "var", "Self", "=", "this", ".", "_static", ",", "ret", ";", "if", "(", "Self", "===", "Self", ".", "__ctiBaseModel", ")", "{", "ret", "=", "this", ".", "_super", "(", "arguments", ")", ";", "}", "else", "{", "var", "pk", "=", "this", ".", "primaryKey", "[", "0", "]", ",", "tables", "=", "Self", ".", "__ctiTables", ",", "ctiColumns", "=", "Self", ".", "__ctiColumns", ",", "self", "=", "this", ",", "isRestricted", "=", "Self", ".", "isRestrictedPrimaryKey", ",", "db", "=", "this", ".", "db", ";", "ret", "=", "asyncArray", ".", "forEach", "(", "tables", ",", "function", "(", "table", ",", "index", ")", "{", "var", "cols", "=", "ctiColumns", "[", "table", "]", ",", "insert", "=", "{", "}", ",", "val", ",", "i", "=", "-", "1", ",", "colLength", "=", "cols", ".", "length", ",", "c", ";", "while", "(", "++", "i", "<", "colLength", ")", "{", "c", "=", "cols", "[", "i", "]", ";", "if", "(", "(", "index", "!==", "0", "||", "(", "index", "===", "0", "&&", "(", "!", "isRestricted", "||", "pk", ".", "indexOf", "(", "c", ")", "===", "-", "1", ")", ")", ")", "&&", "!", "comb", ".", "isUndefined", "(", "val", "=", "self", "[", "c", "]", ")", ")", "{", "insert", "[", "c", "]", "=", "val", ";", "}", "}", "return", "db", ".", "from", "(", "table", ")", ".", "insert", "(", "insert", ")", ".", "chain", "(", "function", "(", "id", ")", "{", "if", "(", "comb", ".", "isUndefined", "(", "self", ".", "primaryKeyValue", ")", "&&", "!", "comb", ".", "isUndefined", "(", "id", ")", "&&", "index", "===", "0", ")", "{", "self", ".", "__ignore", "=", "true", ";", "//how to handle composite keys.", "self", "[", "pk", "]", "=", "id", ";", "self", ".", "__ignore", "=", "false", ";", "}", "}", ")", ";", "}", ",", "1", ")", ".", "chain", "(", "function", "(", ")", "{", "self", ".", "__isNew", "=", "false", ";", "self", ".", "__isChanged", "=", "false", ";", "return", "self", ".", "_saveReload", "(", ")", ";", "}", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Save each column according to the columns in each table
[ "Save", "each", "column", "according", "to", "the", "columns", "in", "each", "table" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/inheritance.js#L135-L165
25,126
C2FO/patio
lib/plugins/inheritance.js
function () { var q = this._getPrimaryKeyQuery(), changed = this.__changed; var modelStatic = this._static, ctiColumns = modelStatic.__ctiColumns, tables = modelStatic.__ctiTables, self = this; return new PromiseList(tables.map(function (table) { var cols = ctiColumns[table], update = {}; cols.forEach(function (c) { if (!comb.isUndefined(changed[c])) { update[c] = changed[c]; } }); return comb.isEmpty(update) ? new Promise().callback() : self.db.from(table).filter(q).update(update); }), true) .chain(function () { return self._updateReload(); }) .promise(); }
javascript
function () { var q = this._getPrimaryKeyQuery(), changed = this.__changed; var modelStatic = this._static, ctiColumns = modelStatic.__ctiColumns, tables = modelStatic.__ctiTables, self = this; return new PromiseList(tables.map(function (table) { var cols = ctiColumns[table], update = {}; cols.forEach(function (c) { if (!comb.isUndefined(changed[c])) { update[c] = changed[c]; } }); return comb.isEmpty(update) ? new Promise().callback() : self.db.from(table).filter(q).update(update); }), true) .chain(function () { return self._updateReload(); }) .promise(); }
[ "function", "(", ")", "{", "var", "q", "=", "this", ".", "_getPrimaryKeyQuery", "(", ")", ",", "changed", "=", "this", ".", "__changed", ";", "var", "modelStatic", "=", "this", ".", "_static", ",", "ctiColumns", "=", "modelStatic", ".", "__ctiColumns", ",", "tables", "=", "modelStatic", ".", "__ctiTables", ",", "self", "=", "this", ";", "return", "new", "PromiseList", "(", "tables", ".", "map", "(", "function", "(", "table", ")", "{", "var", "cols", "=", "ctiColumns", "[", "table", "]", ",", "update", "=", "{", "}", ";", "cols", ".", "forEach", "(", "function", "(", "c", ")", "{", "if", "(", "!", "comb", ".", "isUndefined", "(", "changed", "[", "c", "]", ")", ")", "{", "update", "[", "c", "]", "=", "changed", "[", "c", "]", ";", "}", "}", ")", ";", "return", "comb", ".", "isEmpty", "(", "update", ")", "?", "new", "Promise", "(", ")", ".", "callback", "(", ")", ":", "self", ".", "db", ".", "from", "(", "table", ")", ".", "filter", "(", "q", ")", ".", "update", "(", "update", ")", ";", "}", ")", ",", "true", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "self", ".", "_updateReload", "(", ")", ";", "}", ")", ".", "promise", "(", ")", ";", "}" ]
update each column according to the columns in each table
[ "update", "each", "column", "according", "to", "the", "columns", "in", "each", "table" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/inheritance.js#L168-L187
25,127
C2FO/patio
lib/dataset/sql.js
function (tableAlias) { tableAlias = this._toTableName(tableAlias); var usedAliases = [], from, join; if ((from = this.__opts.from) != null) { usedAliases = usedAliases.concat(from.map(function (n) { return this._toTableName(n); }, this)); } if ((join = this.__opts.join) != null) { usedAliases = usedAliases.concat(join.map(function (join) { if (join.tableAlias) { return this.__toAliasedTableName(join.tableAlias); } else { return this._toTableName(join.table); } }, this)); } if (usedAliases.indexOf(tableAlias) !== -1) { var base = tableAlias, i = 0; do { tableAlias = string.format("%s%d", base, i++); } while (usedAliases.indexOf(tableAlias) !== -1); } return tableAlias; }
javascript
function (tableAlias) { tableAlias = this._toTableName(tableAlias); var usedAliases = [], from, join; if ((from = this.__opts.from) != null) { usedAliases = usedAliases.concat(from.map(function (n) { return this._toTableName(n); }, this)); } if ((join = this.__opts.join) != null) { usedAliases = usedAliases.concat(join.map(function (join) { if (join.tableAlias) { return this.__toAliasedTableName(join.tableAlias); } else { return this._toTableName(join.table); } }, this)); } if (usedAliases.indexOf(tableAlias) !== -1) { var base = tableAlias, i = 0; do { tableAlias = string.format("%s%d", base, i++); } while (usedAliases.indexOf(tableAlias) !== -1); } return tableAlias; }
[ "function", "(", "tableAlias", ")", "{", "tableAlias", "=", "this", ".", "_toTableName", "(", "tableAlias", ")", ";", "var", "usedAliases", "=", "[", "]", ",", "from", ",", "join", ";", "if", "(", "(", "from", "=", "this", ".", "__opts", ".", "from", ")", "!=", "null", ")", "{", "usedAliases", "=", "usedAliases", ".", "concat", "(", "from", ".", "map", "(", "function", "(", "n", ")", "{", "return", "this", ".", "_toTableName", "(", "n", ")", ";", "}", ",", "this", ")", ")", ";", "}", "if", "(", "(", "join", "=", "this", ".", "__opts", ".", "join", ")", "!=", "null", ")", "{", "usedAliases", "=", "usedAliases", ".", "concat", "(", "join", ".", "map", "(", "function", "(", "join", ")", "{", "if", "(", "join", ".", "tableAlias", ")", "{", "return", "this", ".", "__toAliasedTableName", "(", "join", ".", "tableAlias", ")", ";", "}", "else", "{", "return", "this", ".", "_toTableName", "(", "join", ".", "table", ")", ";", "}", "}", ",", "this", ")", ")", ";", "}", "if", "(", "usedAliases", ".", "indexOf", "(", "tableAlias", ")", "!==", "-", "1", ")", "{", "var", "base", "=", "tableAlias", ",", "i", "=", "0", ";", "do", "{", "tableAlias", "=", "string", ".", "format", "(", "\"%s%d\"", ",", "base", ",", "i", "++", ")", ";", "}", "while", "(", "usedAliases", ".", "indexOf", "(", "tableAlias", ")", "!==", "-", "1", ")", ";", "}", "return", "tableAlias", ";", "}" ]
Creates a unique table alias that hasn't already been used in this dataset. @example DB.from("table").unusedTableAlias("t"); //=> "t" DB.from("table").unusedTableAlias("table"); //=> "table0" DB.from("table", "table0"]).unusedTableAlias("table"); //=> "table1" @param {String|patio.sql.Identifier} tableAlias the table to get an unused alias for. @return {String} the implicit alias that is in tableAlias with a possible "N" if the alias has already been used, where N is an integer starting at 0.
[ "Creates", "a", "unique", "table", "alias", "that", "hasn", "t", "already", "been", "used", "in", "this", "dataset", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L358-L382
25,128
C2FO/patio
lib/dataset/sql.js
function (v) { if (isInstanceOf(v, Json, JsonArray)) { return this._literalJson(v); } else if (isInstanceOf(v, LiteralString)) { return "" + v; } else if (isString(v)) { return this._literalString(v); } else if (isNumber(v)) { return this._literalNumber(v); } else if (isInstanceOf(v, Expression)) { return this._literalExpression(v); } else if (isInstanceOf(v, Dataset)) { return this._literalDataset(v); } else if (isArray(v)) { return this._literalArray(v); } else if (isInstanceOf(v, sql.Year)) { return this._literalYear(v); } else if (isInstanceOf(v, sql.TimeStamp, sql.DateTime)) { return this._literalTimestamp(v); } else if (isDate(v)) { return this._literalDate(v); } else if (isInstanceOf(v, sql.Time)) { return this._literalTime(v); } else if (Buffer.isBuffer(v)) { return this._literalBuffer(v); } else if (isNull(v)) { return this._literalNull(); } else if (isBoolean(v)) { return this._literalBoolean(v); } else if (isHash(v)) { return this._literalObject(v); } else { return this._literalOther(v); } }
javascript
function (v) { if (isInstanceOf(v, Json, JsonArray)) { return this._literalJson(v); } else if (isInstanceOf(v, LiteralString)) { return "" + v; } else if (isString(v)) { return this._literalString(v); } else if (isNumber(v)) { return this._literalNumber(v); } else if (isInstanceOf(v, Expression)) { return this._literalExpression(v); } else if (isInstanceOf(v, Dataset)) { return this._literalDataset(v); } else if (isArray(v)) { return this._literalArray(v); } else if (isInstanceOf(v, sql.Year)) { return this._literalYear(v); } else if (isInstanceOf(v, sql.TimeStamp, sql.DateTime)) { return this._literalTimestamp(v); } else if (isDate(v)) { return this._literalDate(v); } else if (isInstanceOf(v, sql.Time)) { return this._literalTime(v); } else if (Buffer.isBuffer(v)) { return this._literalBuffer(v); } else if (isNull(v)) { return this._literalNull(); } else if (isBoolean(v)) { return this._literalBoolean(v); } else if (isHash(v)) { return this._literalObject(v); } else { return this._literalOther(v); } }
[ "function", "(", "v", ")", "{", "if", "(", "isInstanceOf", "(", "v", ",", "Json", ",", "JsonArray", ")", ")", "{", "return", "this", ".", "_literalJson", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "LiteralString", ")", ")", "{", "return", "\"\"", "+", "v", ";", "}", "else", "if", "(", "isString", "(", "v", ")", ")", "{", "return", "this", ".", "_literalString", "(", "v", ")", ";", "}", "else", "if", "(", "isNumber", "(", "v", ")", ")", "{", "return", "this", ".", "_literalNumber", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "Expression", ")", ")", "{", "return", "this", ".", "_literalExpression", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "Dataset", ")", ")", "{", "return", "this", ".", "_literalDataset", "(", "v", ")", ";", "}", "else", "if", "(", "isArray", "(", "v", ")", ")", "{", "return", "this", ".", "_literalArray", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "sql", ".", "Year", ")", ")", "{", "return", "this", ".", "_literalYear", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "sql", ".", "TimeStamp", ",", "sql", ".", "DateTime", ")", ")", "{", "return", "this", ".", "_literalTimestamp", "(", "v", ")", ";", "}", "else", "if", "(", "isDate", "(", "v", ")", ")", "{", "return", "this", ".", "_literalDate", "(", "v", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "v", ",", "sql", ".", "Time", ")", ")", "{", "return", "this", ".", "_literalTime", "(", "v", ")", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "v", ")", ")", "{", "return", "this", ".", "_literalBuffer", "(", "v", ")", ";", "}", "else", "if", "(", "isNull", "(", "v", ")", ")", "{", "return", "this", ".", "_literalNull", "(", ")", ";", "}", "else", "if", "(", "isBoolean", "(", "v", ")", ")", "{", "return", "this", ".", "_literalBoolean", "(", "v", ")", ";", "}", "else", "if", "(", "isHash", "(", "v", ")", ")", "{", "return", "this", ".", "_literalObject", "(", "v", ")", ";", "}", "else", "{", "return", "this", ".", "_literalOther", "(", "v", ")", ";", "}", "}" ]
Returns a literal representation of a value to be used as part of an SQL expression. @example DB.from("items").literal("abc'def\\") //=> "'abc''def\\\\'" DB.from("items").literal("items__id") //=> "items.id" DB.from("items").literal([1, 2, 3]) //=> "(1, 2, 3)" DB.from("items").literal(DB.from("items")) //=> "(SELECT * FROM items)" DB.from("items").literal(sql.x.plus(1).gt("y")); //=> "((x + 1) > y)" @throws {patio.QueryError} If an unsupported object is given. @param {*} v the value to convert the the SQL literal representation @return {String} a literal representation of the value.
[ "Returns", "a", "literal", "representation", "of", "a", "value", "to", "be", "used", "as", "part", "of", "an", "SQL", "expression", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L401-L435
25,129
C2FO/patio
lib/dataset/sql.js
function (name) { var ret; if (isString(name)) { var parts = this._splitString(name); var schema = parts[0], table = parts[1], alias = parts[2]; ret = (schema || alias) ? alias || table : table; } else if (isInstanceOf(name, Identifier)) { ret = name.value; } else if (isInstanceOf(name, QualifiedIdentifier)) { ret = this._toTableName(name.column); } else if (isInstanceOf(name, AliasedExpression)) { ret = this.__toAliasedTableName(name.alias); } else { throw new QueryError("Invalid object to retrieve the table name from"); } return ret; }
javascript
function (name) { var ret; if (isString(name)) { var parts = this._splitString(name); var schema = parts[0], table = parts[1], alias = parts[2]; ret = (schema || alias) ? alias || table : table; } else if (isInstanceOf(name, Identifier)) { ret = name.value; } else if (isInstanceOf(name, QualifiedIdentifier)) { ret = this._toTableName(name.column); } else if (isInstanceOf(name, AliasedExpression)) { ret = this.__toAliasedTableName(name.alias); } else { throw new QueryError("Invalid object to retrieve the table name from"); } return ret; }
[ "function", "(", "name", ")", "{", "var", "ret", ";", "if", "(", "isString", "(", "name", ")", ")", "{", "var", "parts", "=", "this", ".", "_splitString", "(", "name", ")", ";", "var", "schema", "=", "parts", "[", "0", "]", ",", "table", "=", "parts", "[", "1", "]", ",", "alias", "=", "parts", "[", "2", "]", ";", "ret", "=", "(", "schema", "||", "alias", ")", "?", "alias", "||", "table", ":", "table", ";", "}", "else", "if", "(", "isInstanceOf", "(", "name", ",", "Identifier", ")", ")", "{", "ret", "=", "name", ".", "value", ";", "}", "else", "if", "(", "isInstanceOf", "(", "name", ",", "QualifiedIdentifier", ")", ")", "{", "ret", "=", "this", ".", "_toTableName", "(", "name", ".", "column", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "name", ",", "AliasedExpression", ")", ")", "{", "ret", "=", "this", ".", "__toAliasedTableName", "(", "name", ".", "alias", ")", ";", "}", "else", "{", "throw", "new", "QueryError", "(", "\"Invalid object to retrieve the table name from\"", ")", ";", "}", "return", "ret", ";", "}" ]
Returns a string that is the name of the table. @throws {patio.QueryError} If the name is not a String {@link patio.sql.Identifier}, {@link patio.sql.QualifiedIdentifier} or {@link patio.sql.AliasedExpression}. @param {String|patio.sql.Identifier|patio.sql.QualifiedIdentifier|patio.sql.AliasedExpression} name the object to get the table name from. @return {String} the name of the table.
[ "Returns", "a", "string", "that", "is", "the", "name", "of", "the", "table", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L512-L528
25,130
C2FO/patio
lib/dataset/sql.js
function (type) { var sql = [("" + type).toUpperCase()]; try { this._static[sql + "_CLAUSE_METHODS"].forEach(function (m) { if (m.match("With")) { this[m](sql); } else { var sqlRet = this[m](); if (sqlRet) { sql.push(sqlRet); } } }, this); } catch (e) { throw e; } return sql.join(""); }
javascript
function (type) { var sql = [("" + type).toUpperCase()]; try { this._static[sql + "_CLAUSE_METHODS"].forEach(function (m) { if (m.match("With")) { this[m](sql); } else { var sqlRet = this[m](); if (sqlRet) { sql.push(sqlRet); } } }, this); } catch (e) { throw e; } return sql.join(""); }
[ "function", "(", "type", ")", "{", "var", "sql", "=", "[", "(", "\"\"", "+", "type", ")", ".", "toUpperCase", "(", ")", "]", ";", "try", "{", "this", ".", "_static", "[", "sql", "+", "\"_CLAUSE_METHODS\"", "]", ".", "forEach", "(", "function", "(", "m", ")", "{", "if", "(", "m", ".", "match", "(", "\"With\"", ")", ")", "{", "this", "[", "m", "]", "(", "sql", ")", ";", "}", "else", "{", "var", "sqlRet", "=", "this", "[", "m", "]", "(", ")", ";", "if", "(", "sqlRet", ")", "{", "sql", ".", "push", "(", "sqlRet", ")", ";", "}", "}", "}", ",", "this", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "e", ";", "}", "return", "sql", ".", "join", "(", "\"\"", ")", ";", "}" ]
Prepares an SQL statement by calling all clause methods for the given statement type.
[ "Prepares", "an", "SQL", "statement", "by", "calling", "all", "clause", "methods", "for", "the", "given", "statement", "type", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L597-L614
25,131
C2FO/patio
lib/dataset/sql.js
function (sql) { var columns = this.__opts.columns, ret = ""; if (columns && columns.length) { ret = " (" + columns.map( function (c) { return c.toString(this); }, this).join(this._static.COMMA_SEPARATOR) + ")"; } return ret; }
javascript
function (sql) { var columns = this.__opts.columns, ret = ""; if (columns && columns.length) { ret = " (" + columns.map( function (c) { return c.toString(this); }, this).join(this._static.COMMA_SEPARATOR) + ")"; } return ret; }
[ "function", "(", "sql", ")", "{", "var", "columns", "=", "this", ".", "__opts", ".", "columns", ",", "ret", "=", "\"\"", ";", "if", "(", "columns", "&&", "columns", ".", "length", ")", "{", "ret", "=", "\" (\"", "+", "columns", ".", "map", "(", "function", "(", "c", ")", "{", "return", "c", ".", "toString", "(", "this", ")", ";", "}", ",", "this", ")", ".", "join", "(", "this", ".", "_static", ".", "COMMA_SEPARATOR", ")", "+", "\")\"", ";", "}", "return", "ret", ";", "}" ]
SQL fragment specifying the columns to insert into
[ "SQL", "fragment", "specifying", "the", "columns", "to", "insert", "into" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L623-L632
25,132
C2FO/patio
lib/dataset/sql.js
function () { var values = this.__opts.values, ret = []; if (isArray(values)) { ret.push(values.length === 0 ? " DEFAULT VALUES" : " VALUES " + this.literal(values)); } else if (isInstanceOf(values, Dataset)) { ret.push(" " + this._subselectSql(values)); } else if (isInstanceOf(values, LiteralString)) { ret.push(" " + values.toString(this)); } else { throw new QueryError("Unsupported INSERT values type, should be an array or dataset"); } return ret.join(""); }
javascript
function () { var values = this.__opts.values, ret = []; if (isArray(values)) { ret.push(values.length === 0 ? " DEFAULT VALUES" : " VALUES " + this.literal(values)); } else if (isInstanceOf(values, Dataset)) { ret.push(" " + this._subselectSql(values)); } else if (isInstanceOf(values, LiteralString)) { ret.push(" " + values.toString(this)); } else { throw new QueryError("Unsupported INSERT values type, should be an array or dataset"); } return ret.join(""); }
[ "function", "(", ")", "{", "var", "values", "=", "this", ".", "__opts", ".", "values", ",", "ret", "=", "[", "]", ";", "if", "(", "isArray", "(", "values", ")", ")", "{", "ret", ".", "push", "(", "values", ".", "length", "===", "0", "?", "\" DEFAULT VALUES\"", ":", "\" VALUES \"", "+", "this", ".", "literal", "(", "values", ")", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "values", ",", "Dataset", ")", ")", "{", "ret", ".", "push", "(", "\" \"", "+", "this", ".", "_subselectSql", "(", "values", ")", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "values", ",", "LiteralString", ")", ")", "{", "ret", ".", "push", "(", "\" \"", "+", "values", ".", "toString", "(", "this", ")", ")", ";", "}", "else", "{", "throw", "new", "QueryError", "(", "\"Unsupported INSERT values type, should be an array or dataset\"", ")", ";", "}", "return", "ret", ".", "join", "(", "\"\"", ")", ";", "}" ]
SQL fragment specifying the values to insert.
[ "SQL", "fragment", "specifying", "the", "values", "to", "insert", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L635-L647
25,133
C2FO/patio
lib/dataset/sql.js
function (source) { if (!Array.isArray(source)) { source = [source]; } if (!source || !source.length) { throw new QueryError("No source specified for the query"); } return " " + source.map( function (s) { return this.__tableRef(s); }, this).join(this._static.COMMA_SEPARATOR); }
javascript
function (source) { if (!Array.isArray(source)) { source = [source]; } if (!source || !source.length) { throw new QueryError("No source specified for the query"); } return " " + source.map( function (s) { return this.__tableRef(s); }, this).join(this._static.COMMA_SEPARATOR); }
[ "function", "(", "source", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "source", ")", ")", "{", "source", "=", "[", "source", "]", ";", "}", "if", "(", "!", "source", "||", "!", "source", ".", "length", ")", "{", "throw", "new", "QueryError", "(", "\"No source specified for the query\"", ")", ";", "}", "return", "\" \"", "+", "source", ".", "map", "(", "function", "(", "s", ")", "{", "return", "this", ".", "__tableRef", "(", "s", ")", ";", "}", ",", "this", ")", ".", "join", "(", "this", ".", "_static", ".", "COMMA_SEPARATOR", ")", ";", "}" ]
Converts an array of source names into into a comma separated list.
[ "Converts", "an", "array", "of", "source", "names", "into", "into", "a", "comma", "separated", "list", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/sql.js#L1503-L1514
25,134
C2FO/patio
example/readme-example/migration/1398228686331.createInitialTables.js
function (db) { //create a table called state; return db .createTable("state", function () { this.primaryKey("id"); this.name(String); this.population("integer"); this.founded(Date); this.climate(String); this.description("text"); }) .chain(function () { //create another table called capital return db.createTable("capital", function () { this.primaryKey("id"); this.population("integer"); this.name(String); this.founded(Date); this.foreignKey("stateId", "state", {key: "id", onDelete: "CASCADE"}); }); }); }
javascript
function (db) { //create a table called state; return db .createTable("state", function () { this.primaryKey("id"); this.name(String); this.population("integer"); this.founded(Date); this.climate(String); this.description("text"); }) .chain(function () { //create another table called capital return db.createTable("capital", function () { this.primaryKey("id"); this.population("integer"); this.name(String); this.founded(Date); this.foreignKey("stateId", "state", {key: "id", onDelete: "CASCADE"}); }); }); }
[ "function", "(", "db", ")", "{", "//create a table called state;", "return", "db", ".", "createTable", "(", "\"state\"", ",", "function", "(", ")", "{", "this", ".", "primaryKey", "(", "\"id\"", ")", ";", "this", ".", "name", "(", "String", ")", ";", "this", ".", "population", "(", "\"integer\"", ")", ";", "this", ".", "founded", "(", "Date", ")", ";", "this", ".", "climate", "(", "String", ")", ";", "this", ".", "description", "(", "\"text\"", ")", ";", "}", ")", ".", "chain", "(", "function", "(", ")", "{", "//create another table called capital", "return", "db", ".", "createTable", "(", "\"capital\"", ",", "function", "(", ")", "{", "this", ".", "primaryKey", "(", "\"id\"", ")", ";", "this", ".", "population", "(", "\"integer\"", ")", ";", "this", ".", "name", "(", "String", ")", ";", "this", ".", "founded", "(", "Date", ")", ";", "this", ".", "foreignKey", "(", "\"stateId\"", ",", "\"state\"", ",", "{", "key", ":", "\"id\"", ",", "onDelete", ":", "\"CASCADE\"", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
up is called when you migrate your database up
[ "up", "is", "called", "when", "you", "migrate", "your", "database", "up" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/example/readme-example/migration/1398228686331.createInitialTables.js#L3-L24
25,135
C2FO/patio
lib/migration.js
function (db, directory, opts) { this.db = db; this.directory = directory; opts = opts || {}; this.table = opts.table || this._static.DEFAULT_SCHEMA_TABLE; this.column = opts.column || this._static.DEFAULT_SCHEMA_COLUMN; this._opts = opts; }
javascript
function (db, directory, opts) { this.db = db; this.directory = directory; opts = opts || {}; this.table = opts.table || this._static.DEFAULT_SCHEMA_TABLE; this.column = opts.column || this._static.DEFAULT_SCHEMA_COLUMN; this._opts = opts; }
[ "function", "(", "db", ",", "directory", ",", "opts", ")", "{", "this", ".", "db", "=", "db", ";", "this", ".", "directory", "=", "directory", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "table", "=", "opts", ".", "table", "||", "this", ".", "_static", ".", "DEFAULT_SCHEMA_TABLE", ";", "this", ".", "column", "=", "opts", ".", "column", "||", "this", ".", "_static", ".", "DEFAULT_SCHEMA_COLUMN", ";", "this", ".", "_opts", "=", "opts", ";", "}" ]
Abstract Migrator class. This class should be be instantiated directly. @constructs @param {patio.Database} db the database to migrate @param {String} directory directory that the migration files reside in @param {Object} [opts={}] optional parameters. @param {String} [opts.column] the column in the table that version information should be stored. @param {String} [opts.table] the table that version information should be stored. @param {Number} [opts.target] the target migration(i.e the migration to migrate up/down to). @param {String} [opts.current] the version that the database is currently at if the current version
[ "Abstract", "Migrator", "class", ".", "This", "class", "should", "be", "be", "instantiated", "directly", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/migration.js#L43-L50
25,136
C2FO/patio
lib/migration.js
function () { if (!this.__schemaDataset) { var ds = this.db.from(this.table), self = this; return this.__createTable().chain(function () { return (self.__schemaDataset = ds); }); } else { return when(this.__schemaDataset); } }
javascript
function () { if (!this.__schemaDataset) { var ds = this.db.from(this.table), self = this; return this.__createTable().chain(function () { return (self.__schemaDataset = ds); }); } else { return when(this.__schemaDataset); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "__schemaDataset", ")", "{", "var", "ds", "=", "this", ".", "db", ".", "from", "(", "this", ".", "table", ")", ",", "self", "=", "this", ";", "return", "this", ".", "__createTable", "(", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "(", "self", ".", "__schemaDataset", "=", "ds", ")", ";", "}", ")", ";", "}", "else", "{", "return", "when", "(", "this", ".", "__schemaDataset", ")", ";", "}", "}" ]
Returns the dataset for the schema_migrations table. If no such table exists, it is automatically created.
[ "Returns", "the", "dataset", "for", "the", "schema_migrations", "table", ".", "If", "no", "such", "table", "exists", "it", "is", "automatically", "created", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/migration.js#L485-L494
25,137
C2FO/patio
lib/sql.js
function (obj) { return isHash(obj) || (isArray(obj) && obj.length && obj.every(function (i) { return isArray(i) && i.length === 2; })); }
javascript
function (obj) { return isHash(obj) || (isArray(obj) && obj.length && obj.every(function (i) { return isArray(i) && i.length === 2; })); }
[ "function", "(", "obj", ")", "{", "return", "isHash", "(", "obj", ")", "||", "(", "isArray", "(", "obj", ")", "&&", "obj", ".", "length", "&&", "obj", ".", "every", "(", "function", "(", "i", ")", "{", "return", "isArray", "(", "i", ")", "&&", "i", ".", "length", "===", "2", ";", "}", ")", ")", ";", "}" ]
Helper to determine if something is a condition specifier. Returns true if the object is a Hash or is an array of two element arrays. @example Expression.isConditionSpecifier({a : "b"}); //=> true Expression.isConditionSpecifier("a"); //=> false Expression.isConditionSpecifier([["a", "b"], ["c", "d"]]); //=> true Expression.isConditionSpecifier([["a", "b", "e"], ["c", "d"]]); //=> false @param {*} obj object to test if it is a condition specifier @return {Boolean} true if the object is a Hash or is an array of two element arrays.
[ "Helper", "to", "determine", "if", "something", "is", "a", "condition", "specifier", ".", "Returns", "true", "if", "the", "object", "is", "a", "Hash", "or", "is", "an", "array", "of", "two", "element", "arrays", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/sql.js#L1397-L1401
25,138
C2FO/patio
lib/sql.js
function (ds) { !Dataset && (Dataset = require("./dataset")); ds = ds || new Dataset(); return ds.castSql(this.expr, this.type); }
javascript
function (ds) { !Dataset && (Dataset = require("./dataset")); ds = ds || new Dataset(); return ds.castSql(this.expr, this.type); }
[ "function", "(", "ds", ")", "{", "!", "Dataset", "&&", "(", "Dataset", "=", "require", "(", "\"./dataset\"", ")", ")", ";", "ds", "=", "ds", "||", "new", "Dataset", "(", ")", ";", "return", "ds", ".", "castSql", "(", "this", ".", "expr", ",", "this", ".", "type", ")", ";", "}" ]
Converts the cast expression to a string @param {patio.Dataset} [ds] dataset used to created the SQL fragment, if the dataset is ommited then the default {@link patio.Dataset} implementation is used. @return String the SQL cast expression fragment.
[ "Converts", "the", "cast", "expression", "to", "a", "string" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/sql.js#L1549-L1553
25,139
C2FO/patio
lib/sql.js
function (ds) { !Dataset && (Dataset = require("./dataset")); ds = ds || new Dataset(); return ds.complexExpressionSql(this.op, this.args); }
javascript
function (ds) { !Dataset && (Dataset = require("./dataset")); ds = ds || new Dataset(); return ds.complexExpressionSql(this.op, this.args); }
[ "function", "(", "ds", ")", "{", "!", "Dataset", "&&", "(", "Dataset", "=", "require", "(", "\"./dataset\"", ")", ")", ";", "ds", "=", "ds", "||", "new", "Dataset", "(", ")", ";", "return", "ds", ".", "complexExpressionSql", "(", "this", ".", "op", ",", "this", ".", "args", ")", ";", "}" ]
Converts the ComplexExpression to a string. @param {patio.Dataset} [ds] dataset used to created the SQL fragment, if the dataset is ommited then the default {@link patio.Dataset} implementation is used. @return String the SQL version of the {@link patio.sql.ComplexExpression}.
[ "Converts", "the", "ComplexExpression", "to", "a", "string", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/sql.js#L1674-L1678
25,140
C2FO/patio
lib/dataset/query.js
function (args) { args = argsToArray(arguments); if (args.length && !this.supportsDistinctOn) { throw new QueryError("DISTICT ON is not supported"); } args = args.map(function (a) { return isString(a) ? new Identifier(a) : a; }); return this.mergeOptions({distinct: args}); }
javascript
function (args) { args = argsToArray(arguments); if (args.length && !this.supportsDistinctOn) { throw new QueryError("DISTICT ON is not supported"); } args = args.map(function (a) { return isString(a) ? new Identifier(a) : a; }); return this.mergeOptions({distinct: args}); }
[ "function", "(", "args", ")", "{", "args", "=", "argsToArray", "(", "arguments", ")", ";", "if", "(", "args", ".", "length", "&&", "!", "this", ".", "supportsDistinctOn", ")", "{", "throw", "new", "QueryError", "(", "\"DISTICT ON is not supported\"", ")", ";", "}", "args", "=", "args", ".", "map", "(", "function", "(", "a", ")", "{", "return", "isString", "(", "a", ")", "?", "new", "Identifier", "(", "a", ")", ":", "a", ";", "}", ")", ";", "return", "this", ".", "mergeOptions", "(", "{", "distinct", ":", "args", "}", ")", ";", "}" ]
Returns a copy of the dataset with the SQL DISTINCT clause. The DISTINCT clause is used to remove duplicate rows from the output. If arguments are provided, uses a DISTINCT ON clause, in which case it will only be distinct on those columns, instead of all returned columns. @example DB.from("items").distinct().sqll //=> SELECT DISTINCT * FROM items DB.from("items").order("id").distinct("id").sql; //=> SELECT DISTINCT ON (id) * FROM items ORDER BY id @throws {patio.QueryError} If arguments are given and DISTINCT ON is not supported. @param {...String|...patio.sql.Identifier} args variable number of arguments used to create the DISTINCT ON clause. @return {patio.Dataset} a cloned dataset with the DISTINCT/DISTINCT ON clause added.
[ "Returns", "a", "copy", "of", "the", "dataset", "with", "the", "SQL", "DISTINCT", "clause", ".", "The", "DISTINCT", "clause", "is", "used", "to", "remove", "duplicate", "rows", "from", "the", "output", ".", "If", "arguments", "are", "provided", "uses", "a", "DISTINCT", "ON", "clause", "in", "which", "case", "it", "will", "only", "be", "distinct", "on", "those", "columns", "instead", "of", "all", "returned", "columns", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L327-L336
25,141
C2FO/patio
lib/dataset/query.js
function(includeDatasets, fromModel) { var ds = this.mergeOptions({}), originalRowCb = ds.rowCb; if(!ds.__opts._eagerAssoc) { ds.__opts._eagerAssoc = includeDatasets; ds.rowCb = function (topLevelResults) { function toObject(thing) { if (!thing) { return comb.when(thing); } if (Array.isArray(thing)) { return comb.when(thing.map(function(item) { return toObject(item); })); } if ('toObject' in thing) { return comb.when(thing.toObject()); } return comb.when(thing); } var eagerResults = {}, whens = []; if (!originalRowCb) { // pass through for when topLevelResults is already resolved originalRowCb = function(r){return r;}; } return comb.when(originalRowCb(topLevelResults)).chain(function(maybeModel) { whens = Object.keys(ds.__opts._eagerAssoc).map(function(key) { return ds.__opts._eagerAssoc[key](maybeModel).chain(function(result) { return toObject(result).chain(function(res) { eagerResults[key] = res; return result; }); }); }); return comb.when(whens).chain(function () { return toObject(maybeModel).chain(function(json) { // merge associations on to main data return Object.assign(json, eagerResults); }); }); }); }; } return ds.mergeOptions({ _eagerAssoc: Object.assign(ds.__opts._eagerAssoc, includeDatasets) }); }
javascript
function(includeDatasets, fromModel) { var ds = this.mergeOptions({}), originalRowCb = ds.rowCb; if(!ds.__opts._eagerAssoc) { ds.__opts._eagerAssoc = includeDatasets; ds.rowCb = function (topLevelResults) { function toObject(thing) { if (!thing) { return comb.when(thing); } if (Array.isArray(thing)) { return comb.when(thing.map(function(item) { return toObject(item); })); } if ('toObject' in thing) { return comb.when(thing.toObject()); } return comb.when(thing); } var eagerResults = {}, whens = []; if (!originalRowCb) { // pass through for when topLevelResults is already resolved originalRowCb = function(r){return r;}; } return comb.when(originalRowCb(topLevelResults)).chain(function(maybeModel) { whens = Object.keys(ds.__opts._eagerAssoc).map(function(key) { return ds.__opts._eagerAssoc[key](maybeModel).chain(function(result) { return toObject(result).chain(function(res) { eagerResults[key] = res; return result; }); }); }); return comb.when(whens).chain(function () { return toObject(maybeModel).chain(function(json) { // merge associations on to main data return Object.assign(json, eagerResults); }); }); }); }; } return ds.mergeOptions({ _eagerAssoc: Object.assign(ds.__opts._eagerAssoc, includeDatasets) }); }
[ "function", "(", "includeDatasets", ",", "fromModel", ")", "{", "var", "ds", "=", "this", ".", "mergeOptions", "(", "{", "}", ")", ",", "originalRowCb", "=", "ds", ".", "rowCb", ";", "if", "(", "!", "ds", ".", "__opts", ".", "_eagerAssoc", ")", "{", "ds", ".", "__opts", ".", "_eagerAssoc", "=", "includeDatasets", ";", "ds", ".", "rowCb", "=", "function", "(", "topLevelResults", ")", "{", "function", "toObject", "(", "thing", ")", "{", "if", "(", "!", "thing", ")", "{", "return", "comb", ".", "when", "(", "thing", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "thing", ")", ")", "{", "return", "comb", ".", "when", "(", "thing", ".", "map", "(", "function", "(", "item", ")", "{", "return", "toObject", "(", "item", ")", ";", "}", ")", ")", ";", "}", "if", "(", "'toObject'", "in", "thing", ")", "{", "return", "comb", ".", "when", "(", "thing", ".", "toObject", "(", ")", ")", ";", "}", "return", "comb", ".", "when", "(", "thing", ")", ";", "}", "var", "eagerResults", "=", "{", "}", ",", "whens", "=", "[", "]", ";", "if", "(", "!", "originalRowCb", ")", "{", "// pass through for when topLevelResults is already resolved", "originalRowCb", "=", "function", "(", "r", ")", "{", "return", "r", ";", "}", ";", "}", "return", "comb", ".", "when", "(", "originalRowCb", "(", "topLevelResults", ")", ")", ".", "chain", "(", "function", "(", "maybeModel", ")", "{", "whens", "=", "Object", ".", "keys", "(", "ds", ".", "__opts", ".", "_eagerAssoc", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "ds", ".", "__opts", ".", "_eagerAssoc", "[", "key", "]", "(", "maybeModel", ")", ".", "chain", "(", "function", "(", "result", ")", "{", "return", "toObject", "(", "result", ")", ".", "chain", "(", "function", "(", "res", ")", "{", "eagerResults", "[", "key", "]", "=", "res", ";", "return", "result", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "comb", ".", "when", "(", "whens", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "toObject", "(", "maybeModel", ")", ".", "chain", "(", "function", "(", "json", ")", "{", "// merge associations on to main data", "return", "Object", ".", "assign", "(", "json", ",", "eagerResults", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}", "return", "ds", ".", "mergeOptions", "(", "{", "_eagerAssoc", ":", "Object", ".", "assign", "(", "ds", ".", "__opts", ".", "_eagerAssoc", ",", "includeDatasets", ")", "}", ")", ";", "}" ]
Allows the loading of another query and combining them in one patio command. Queries can be related or completely unrelated. All data comes back as JSON NOT Patio models. @example DB.from('company').filter({name: 'Amazon'}) .eager({ // company from parent query is passed in and usable in the eager query. leader: (company) => DB.from('leader').filter({id: company.leaderId}).one() }) // Load completely unrelated data. .eager({org: () => DB.from('organization').one() }) .one()}) { id: 1, name: 'Amazon.com', leader: { id: 1, name: 'Jeff' }, org: { id: 1, name: 'Google Inc.' } } Can do one to many loading for every item in the parent dataset. Be careful doing this because it can lead to lots of extra queries. DB.from('company').filter({state: 'IA'}) .eager({invoices: (company) => DB.from('invoices').filter({companyId: company.id}).one() }) .all()}) [ { id: 1, name: 'Principal', invoices: [ { id: 1, amount: 200}, { id: 2, amount: 300}, ] }, { id: 2, name: 'John Deere', invoices: [ { id: 3, amount: 200}, { id: 4, amount: 300}, ] } ]
[ "Allows", "the", "loading", "of", "another", "query", "and", "combining", "them", "in", "one", "patio", "command", ".", "Queries", "can", "be", "related", "or", "completely", "unrelated", ".", "All", "data", "comes", "back", "as", "JSON", "NOT", "Patio", "models", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L391-L446
25,142
C2FO/patio
lib/dataset/query.js
function (args, cb) { args = [this.__opts["having"] ? "having" : "where"].concat(argsToArray(arguments)); return this._filter.apply(this, args); }
javascript
function (args, cb) { args = [this.__opts["having"] ? "having" : "where"].concat(argsToArray(arguments)); return this._filter.apply(this, args); }
[ "function", "(", "args", ",", "cb", ")", "{", "args", "=", "[", "this", ".", "__opts", "[", "\"having\"", "]", "?", "\"having\"", ":", "\"where\"", "]", ".", "concat", "(", "argsToArray", "(", "arguments", ")", ")", ";", "return", "this", ".", "_filter", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
Returns a copy of the dataset with the given conditions applied to it. If the query already has a HAVING clause, then the conditions are applied to the HAVING clause otherwise they are applied to the WHERE clause. @example DB.from("items").filter({id : 3}).sql; //=> SELECT * FROM items WHERE (id = 3) DB.from("items").filter('price < ?', 100) //=> SELECT * FROM items WHERE price < 100 DB.from("items").filter({id, [1,2,3]}).filter({id : {between : [0, 10]}}).sql; //=> SELECT * FROM items WHERE ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10))) DB.from("items").filter('price < 100'); //=> SELECT * FROM items WHERE price < 100 DB.from("items").filter("active").sql; //=> SELECT * FROM items WHERE active DB.from("items").filter(function(){ return this.price.lt(100); }); //=> SELECT * FROM items WHERE (price < 100) //Multiple filter calls can be chained for scoping: DB.from("items").filter(:category => 'software').filter{price < 100} //=> SELECT * FROM items WHERE ((category = 'software') AND (price < 100)) @param {Object|Array|String|patio.sql.Identifier|patio.sql.BooleanExpression} args filters to apply to the WHERE/HAVING clause. Description of each: <ul> <li>Hash - list of equality/inclusion expressions</li> <li>Array - depends: <ul> <li>If first member is a string, assumes the rest of the arguments are parameters and interpolates them into the string.</li> <li>If all members are arrays of length two, treats the same way as a hash, except it allows for duplicate keys to be specified.</li> <li>Otherwise, treats each argument as a separate condition.</li> </ul> </li> <li>String - taken literally</li> <li>{@link patio.sql.Identifier} - taken as a boolean column argument (e.g. WHERE active)</li> <li>{@link patio.sql.BooleanExpression} - an existing condition expression, probably created using the patio.sql methods. </li> @param {Function} [cb] filter also takes a cb, which should return one of the above argument types, and is treated the same way. This block is called with an {@link patio.sql} object which can be used to dynaically create expression. For more details on the sql object see {@link patio.sql} <p> <b>NOTE:</b>If both a cb and regular arguments are provided, they get ANDed together. </p> @return {patio.Dataset} a cloned dataset with the filter arumgents applied to the WHERE/HAVING clause.
[ "Returns", "a", "copy", "of", "the", "dataset", "with", "the", "given", "conditions", "applied", "to", "it", ".", "If", "the", "query", "already", "has", "a", "HAVING", "clause", "then", "the", "conditions", "are", "applied", "to", "the", "HAVING", "clause", "otherwise", "they", "are", "applied", "to", "the", "WHERE", "clause", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L583-L586
25,143
C2FO/patio
lib/dataset/query.js
function (opts) { opts = isUndefined(opts) ? {} : opts; var fs = {}; var nonSqlOptions = this._static.NON_SQL_OPTIONS; Object.keys(this.__opts).forEach(function (k) { if (nonSqlOptions.indexOf(k) === -1) { fs[k] = null; } }); return this.mergeOptions(fs).from(opts["alias"] ? this.as(opts["alias"]) : this); }
javascript
function (opts) { opts = isUndefined(opts) ? {} : opts; var fs = {}; var nonSqlOptions = this._static.NON_SQL_OPTIONS; Object.keys(this.__opts).forEach(function (k) { if (nonSqlOptions.indexOf(k) === -1) { fs[k] = null; } }); return this.mergeOptions(fs).from(opts["alias"] ? this.as(opts["alias"]) : this); }
[ "function", "(", "opts", ")", "{", "opts", "=", "isUndefined", "(", "opts", ")", "?", "{", "}", ":", "opts", ";", "var", "fs", "=", "{", "}", ";", "var", "nonSqlOptions", "=", "this", ".", "_static", ".", "NON_SQL_OPTIONS", ";", "Object", ".", "keys", "(", "this", ".", "__opts", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "if", "(", "nonSqlOptions", ".", "indexOf", "(", "k", ")", "===", "-", "1", ")", "{", "fs", "[", "k", "]", "=", "null", ";", "}", "}", ")", ";", "return", "this", ".", "mergeOptions", "(", "fs", ")", ".", "from", "(", "opts", "[", "\"alias\"", "]", "?", "this", ".", "as", "(", "opts", "[", "\"alias\"", "]", ")", ":", "this", ")", ";", "}" ]
Returns a dataset selecting from the current dataset. Supplying the alias option controls the alias of the result. @example ds = DB.from("items").order("name").select("id", "name") //=> SELECT id,name FROM items ORDER BY name ds.fromSelf().sql; //=> SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS t1 ds.fromSelf({alias : "foo"}).sql; //=> SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS foo @param {Object} [opts] options @param {String|patio.sql.Identifier} [opts.alias] alias to use @return {patio.Dataset} a cloned dataset with the FROM clause set as the current dataset.
[ "Returns", "a", "dataset", "selecting", "from", "the", "current", "dataset", ".", "Supplying", "the", "alias", "option", "controls", "the", "alias", "of", "the", "result", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L677-L687
25,144
C2FO/patio
lib/dataset/query.js
function (columns) { columns = argsToArray(arguments); var group = this.group.apply(this, columns.map(function (c) { return this._unaliasedIdentifier(c); }, this)); return group.select.apply(group, columns.concat([this._static.COUNT_OF_ALL_AS_COUNT])); }
javascript
function (columns) { columns = argsToArray(arguments); var group = this.group.apply(this, columns.map(function (c) { return this._unaliasedIdentifier(c); }, this)); return group.select.apply(group, columns.concat([this._static.COUNT_OF_ALL_AS_COUNT])); }
[ "function", "(", "columns", ")", "{", "columns", "=", "argsToArray", "(", "arguments", ")", ";", "var", "group", "=", "this", ".", "group", ".", "apply", "(", "this", ",", "columns", ".", "map", "(", "function", "(", "c", ")", "{", "return", "this", ".", "_unaliasedIdentifier", "(", "c", ")", ";", "}", ",", "this", ")", ")", ";", "return", "group", ".", "select", ".", "apply", "(", "group", ",", "columns", ".", "concat", "(", "[", "this", ".", "_static", ".", "COUNT_OF_ALL_AS_COUNT", "]", ")", ")", ";", "}" ]
Returns a dataset grouped by the given column with count by group. Column aliases may be supplied, and will be included in the select clause. @example DB.from("items").groupAndCount("name").all() //=> SELECT name, count(*) AS count FROM items GROUP BY name //=> [{name : 'a', count : 1}, ...] DB.from("items").groupAndCount("first_name", "last_name").all() //SELECT first_name, last_name, count(*) AS count FROM items GROUP BY first_name, last_name //=> [{first_name : 'a', last_name : 'b', count : 1}, ...] DB.from("items").groupAndCount("first_name___name").all() //=> SELECT first_name AS name, count(*) AS count FROM items GROUP BY first_name //=> [{name : 'a', count:1}, ...] @param {String...|patio.sql.Identifier...} columns columns to croup and count on. @return {patio.Dataset} a cloned dataset with the GROUP clause and count added.
[ "Returns", "a", "dataset", "grouped", "by", "the", "given", "column", "with", "count", "by", "group", ".", "Column", "aliases", "may", "be", "supplied", "and", "will", "be", "included", "in", "the", "select", "clause", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L804-L811
25,145
C2FO/patio
lib/dataset/query.js
function (dataset, opts) { opts = isUndefined(opts) ? {} : opts; if (!isHash(opts)) { opts = {all: opts}; } if (!this.supportsIntersectExcept) { throw new QueryError("INTERSECT not supported"); } else if (opts.all && !this.supportsIntersectExceptAll) { throw new QueryError("INTERSECT ALL not supported"); } return this.compoundClone("intersect", dataset, opts); }
javascript
function (dataset, opts) { opts = isUndefined(opts) ? {} : opts; if (!isHash(opts)) { opts = {all: opts}; } if (!this.supportsIntersectExcept) { throw new QueryError("INTERSECT not supported"); } else if (opts.all && !this.supportsIntersectExceptAll) { throw new QueryError("INTERSECT ALL not supported"); } return this.compoundClone("intersect", dataset, opts); }
[ "function", "(", "dataset", ",", "opts", ")", "{", "opts", "=", "isUndefined", "(", "opts", ")", "?", "{", "}", ":", "opts", ";", "if", "(", "!", "isHash", "(", "opts", ")", ")", "{", "opts", "=", "{", "all", ":", "opts", "}", ";", "}", "if", "(", "!", "this", ".", "supportsIntersectExcept", ")", "{", "throw", "new", "QueryError", "(", "\"INTERSECT not supported\"", ")", ";", "}", "else", "if", "(", "opts", ".", "all", "&&", "!", "this", ".", "supportsIntersectExceptAll", ")", "{", "throw", "new", "QueryError", "(", "\"INTERSECT ALL not supported\"", ")", ";", "}", "return", "this", ".", "compoundClone", "(", "\"intersect\"", ",", "dataset", ",", "opts", ")", ";", "}" ]
Adds an INTERSECT clause using a second dataset object. An INTERSECT compound dataset returns all rows in both the current dataset and the given dataset. @example DB.from("items").intersect(DB.from("other_items")).sql; //=> SELECT * FROM (SELECT * FROM items INTERSECT SELECT * FROM other_items) AS t1 DB.from("items").intersect(DB.from("other_items"), {all : true, fromSelf : false}).sql; //=> SELECT * FROM items INTERSECT ALL SELECT * FROM other_items DB.from("items").intersect(DB.from("other_items"), {alias : "i"}).sql; //=> SELECT * FROM (SELECT * FROM items INTERSECT SELECT * FROM other_items) AS i @throws {patio.QueryError} if the operation is not supported. @param {patio.Dataset} dataset the dataset to intersect @param {Object} [opts] options @param {String|patio.sql.Identifier} [opts.alias] Use the given value as the {@link patio.Dataset#fromSelf} alias @param {Boolean} [opts.all] Set to true to use INTERSECT ALL instead of INTERSECT, so duplicate rows can occur @param {Boolean} [opts.fromSelf] Set to false to not wrap the returned dataset in a {@link patio.Dataset#fromSelf}. @return {patio.Dataset} a cloned dataset with the INTERSECT clause.
[ "Adds", "an", "INTERSECT", "clause", "using", "a", "second", "dataset", "object", ".", "An", "INTERSECT", "compound", "dataset", "returns", "all", "rows", "in", "both", "the", "current", "dataset", "and", "the", "given", "dataset", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L854-L865
25,146
C2FO/patio
lib/dataset/query.js
function () { var having = this.__opts.having, where = this.__opts.where; if (!(having || where)) { throw new QueryError("No current filter"); } var o = {}; if (having) { o.having = BooleanExpression.invert(having); } if (where) { o.where = BooleanExpression.invert(where); } return this.mergeOptions(o); }
javascript
function () { var having = this.__opts.having, where = this.__opts.where; if (!(having || where)) { throw new QueryError("No current filter"); } var o = {}; if (having) { o.having = BooleanExpression.invert(having); } if (where) { o.where = BooleanExpression.invert(where); } return this.mergeOptions(o); }
[ "function", "(", ")", "{", "var", "having", "=", "this", ".", "__opts", ".", "having", ",", "where", "=", "this", ".", "__opts", ".", "where", ";", "if", "(", "!", "(", "having", "||", "where", ")", ")", "{", "throw", "new", "QueryError", "(", "\"No current filter\"", ")", ";", "}", "var", "o", "=", "{", "}", ";", "if", "(", "having", ")", "{", "o", ".", "having", "=", "BooleanExpression", ".", "invert", "(", "having", ")", ";", "}", "if", "(", "where", ")", "{", "o", ".", "where", "=", "BooleanExpression", ".", "invert", "(", "where", ")", ";", "}", "return", "this", ".", "mergeOptions", "(", "o", ")", ";", "}" ]
Inverts the current filter. @example DB.from("items").filter({category : 'software'}).invert() //=> SELECT * FROM items WHERE (category != 'software') @example DB.from("items").filter({category : 'software', id : 3}).invert() //=> SELECT * FROM items WHERE ((category != 'software') OR (id != 3)) @return {patio.Dataset} a cloned dataset with the filter inverted.
[ "Inverts", "the", "current", "filter", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L880-L893
25,147
C2FO/patio
lib/dataset/query.js
function (limit, offset) { if (this.__opts.sql) { return this.fromSelf().limit(limit, offset); } if (Array.isArray(limit) && limit.length === 2) { offset = limit[0]; limit = limit[1] - limit[0] + 1; } if (isString(limit) || isInstanceOf(limit, LiteralString)) { limit = parseInt("" + limit, 10); } if (isNumber(limit) && limit < 1) { throw new QueryError("Limit must be >= 1"); } var opts = {limit: limit}; if (offset) { if (isString(offset) || isInstanceOf(offset, LiteralString)) { offset = parseInt("" + offset, 10); isNaN(offset) && (offset = 0); } if (isNumber(offset) && offset < 0) { throw new QueryError("Offset must be >= 0"); } opts.offset = offset; } return this.mergeOptions(opts); }
javascript
function (limit, offset) { if (this.__opts.sql) { return this.fromSelf().limit(limit, offset); } if (Array.isArray(limit) && limit.length === 2) { offset = limit[0]; limit = limit[1] - limit[0] + 1; } if (isString(limit) || isInstanceOf(limit, LiteralString)) { limit = parseInt("" + limit, 10); } if (isNumber(limit) && limit < 1) { throw new QueryError("Limit must be >= 1"); } var opts = {limit: limit}; if (offset) { if (isString(offset) || isInstanceOf(offset, LiteralString)) { offset = parseInt("" + offset, 10); isNaN(offset) && (offset = 0); } if (isNumber(offset) && offset < 0) { throw new QueryError("Offset must be >= 0"); } opts.offset = offset; } return this.mergeOptions(opts); }
[ "function", "(", "limit", ",", "offset", ")", "{", "if", "(", "this", ".", "__opts", ".", "sql", ")", "{", "return", "this", ".", "fromSelf", "(", ")", ".", "limit", "(", "limit", ",", "offset", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "limit", ")", "&&", "limit", ".", "length", "===", "2", ")", "{", "offset", "=", "limit", "[", "0", "]", ";", "limit", "=", "limit", "[", "1", "]", "-", "limit", "[", "0", "]", "+", "1", ";", "}", "if", "(", "isString", "(", "limit", ")", "||", "isInstanceOf", "(", "limit", ",", "LiteralString", ")", ")", "{", "limit", "=", "parseInt", "(", "\"\"", "+", "limit", ",", "10", ")", ";", "}", "if", "(", "isNumber", "(", "limit", ")", "&&", "limit", "<", "1", ")", "{", "throw", "new", "QueryError", "(", "\"Limit must be >= 1\"", ")", ";", "}", "var", "opts", "=", "{", "limit", ":", "limit", "}", ";", "if", "(", "offset", ")", "{", "if", "(", "isString", "(", "offset", ")", "||", "isInstanceOf", "(", "offset", ",", "LiteralString", ")", ")", "{", "offset", "=", "parseInt", "(", "\"\"", "+", "offset", ",", "10", ")", ";", "isNaN", "(", "offset", ")", "&&", "(", "offset", "=", "0", ")", ";", "}", "if", "(", "isNumber", "(", "offset", ")", "&&", "offset", "<", "0", ")", "{", "throw", "new", "QueryError", "(", "\"Offset must be >= 0\"", ")", ";", "}", "opts", ".", "offset", "=", "offset", ";", "}", "return", "this", ".", "mergeOptions", "(", "opts", ")", ";", "}" ]
If given an integer, the dataset will contain only the first l results. If a second argument is given, it is used as an offset. To use an offset without a limit, pass null as the first argument. @example DB.from("items").limit(10) //=> SELECT * FROM items LIMIT 10 DB.from("items").limit(10, 20) //=> SELECT * FROM items LIMIT 10 OFFSET 20 DB.from("items").limit([3, 7]).sql //=> SELECT * FROM items LIMIT 5 OFFSET 3'); DB.from("items").limit(null, 20) //=> SELECT * FROM items OFFSET 20 DB.from("items").limit('6', sql['a() - 1']).sql => 'SELECT * FROM items LIMIT 6 OFFSET a() - 1'); @param {Number|String|Number[]} limit the limit to apply @param {Number|String|patio.sql.LiteralString} offset the offset to apply @return {patio.Dataset} a cloned dataset witht the LIMIT and OFFSET applied.
[ "If", "given", "an", "integer", "the", "dataset", "will", "contain", "only", "the", "first", "l", "results", ".", "If", "a", "second", "argument", "is", "given", "it", "is", "used", "as", "an", "offset", ".", "To", "use", "an", "offset", "without", "a", "limit", "pass", "null", "as", "the", "first", "argument", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L1124-L1150
25,148
C2FO/patio
lib/dataset/query.js
function (table) { var o = this.__opts; if (o.sql) { return this.mergeOptions(); } var h = {}; array.intersect(Object.keys(o), this._static.QUALIFY_KEYS).forEach(function (k) { h[k] = this._qualifiedExpression(o[k], table); }, this); if (!o.select || isEmpty(o.select)) { h.select = [new ColumnAll(table)]; } return this.mergeOptions(h); }
javascript
function (table) { var o = this.__opts; if (o.sql) { return this.mergeOptions(); } var h = {}; array.intersect(Object.keys(o), this._static.QUALIFY_KEYS).forEach(function (k) { h[k] = this._qualifiedExpression(o[k], table); }, this); if (!o.select || isEmpty(o.select)) { h.select = [new ColumnAll(table)]; } return this.mergeOptions(h); }
[ "function", "(", "table", ")", "{", "var", "o", "=", "this", ".", "__opts", ";", "if", "(", "o", ".", "sql", ")", "{", "return", "this", ".", "mergeOptions", "(", ")", ";", "}", "var", "h", "=", "{", "}", ";", "array", ".", "intersect", "(", "Object", ".", "keys", "(", "o", ")", ",", "this", ".", "_static", ".", "QUALIFY_KEYS", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "h", "[", "k", "]", "=", "this", ".", "_qualifiedExpression", "(", "o", "[", "k", "]", ",", "table", ")", ";", "}", ",", "this", ")", ";", "if", "(", "!", "o", ".", "select", "||", "isEmpty", "(", "o", ".", "select", ")", ")", "{", "h", ".", "select", "=", "[", "new", "ColumnAll", "(", "table", ")", "]", ";", "}", "return", "this", ".", "mergeOptions", "(", "h", ")", ";", "}" ]
Return a copy of the dataset with unqualified identifiers in the SELECT, WHERE, GROUP, HAVING, and ORDER clauses qualified by the given table. If no columns are currently selected, select all columns of the given table. @example DB.from("items").filter({id : 1}).qualifyTo("i"); //=> SELECT i.* FROM items WHERE (i.id = 1) @param {String} table the name to qualify identifier to. @return {patio.Dataset} a cloned dataset with unqualified identifiers qualified.
[ "Return", "a", "copy", "of", "the", "dataset", "with", "unqualified", "identifiers", "in", "the", "SELECT", "WHERE", "GROUP", "HAVING", "and", "ORDER", "clauses", "qualified", "by", "the", "given", "table", ".", "If", "no", "columns", "are", "currently", "selected", "select", "all", "columns", "of", "the", "given", "table", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L1653-L1666
25,149
C2FO/patio
lib/dataset/query.js
function (args) { args = argsToArray(arguments); return this.order.apply(this, this._invertOrder(args.length ? args : this.__opts.order)); }
javascript
function (args) { args = argsToArray(arguments); return this.order.apply(this, this._invertOrder(args.length ? args : this.__opts.order)); }
[ "function", "(", "args", ")", "{", "args", "=", "argsToArray", "(", "arguments", ")", ";", "return", "this", ".", "order", ".", "apply", "(", "this", ",", "this", ".", "_invertOrder", "(", "args", ".", "length", "?", "args", ":", "this", ".", "__opts", ".", "order", ")", ")", ";", "}" ]
Returns a copy of the dataset with the order reversed. If no order is given, the existing order is inverted. @example DB.from("items").reverse("id"); //=> SELECT * FROM items ORDER BY id DESC DB.from("items").order("id").reverse(); //=> SELECT * FROM items ORDER BY id DESC DB.from("items").order("id").reverse(sql.identifier("name").asc); //=> SELECT * FROM items ORDER BY name ASC @param {String|patio.sql.Identifier|Function} args variable number of columns add to order before reversing. @return {patio.Dataset} a cloned dataset with the order reversed.
[ "Returns", "a", "copy", "of", "the", "dataset", "with", "the", "order", "reversed", ".", "If", "no", "order", "is", "given", "the", "existing", "order", "is", "inverted", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L1710-L1713
25,150
C2FO/patio
lib/dataset/query.js
function (cols) { var ret; if (!this.hasSelectSource) { ret = this.select.apply(this, arguments); } else { ret = this.mergeOptions(); } return ret; }
javascript
function (cols) { var ret; if (!this.hasSelectSource) { ret = this.select.apply(this, arguments); } else { ret = this.mergeOptions(); } return ret; }
[ "function", "(", "cols", ")", "{", "var", "ret", ";", "if", "(", "!", "this", ".", "hasSelectSource", ")", "{", "ret", "=", "this", ".", "select", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "else", "{", "ret", "=", "this", ".", "mergeOptions", "(", ")", ";", "}", "return", "ret", ";", "}" ]
Selects the columns if only if there is not already select sources. @example var ds = DB.from("items"); //SELECT * FROM items ds.select("a"); //SELECT a FROM items; ds.select("a").selectIfNoSource("a", "b"). //SELECT a FROM items; ds.selectIfNoSource("a", "b"). //SELECT a, b FROM items; @param cols columns to select if there is not already select sources. @return {patio.Dataset} a cloned dataset with the appropriate select sources.
[ "Selects", "the", "columns", "if", "only", "if", "there", "is", "not", "already", "select", "sources", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L1791-L1799
25,151
C2FO/patio
lib/dataset/query.js
function (cols) { cols = argsToArray(arguments); var currentSelect = this.__opts.select; return this.select.apply(this, (currentSelect || []).concat(cols)); }
javascript
function (cols) { cols = argsToArray(arguments); var currentSelect = this.__opts.select; return this.select.apply(this, (currentSelect || []).concat(cols)); }
[ "function", "(", "cols", ")", "{", "cols", "=", "argsToArray", "(", "arguments", ")", ";", "var", "currentSelect", "=", "this", ".", "__opts", ".", "select", ";", "return", "this", ".", "select", ".", "apply", "(", "this", ",", "(", "currentSelect", "||", "[", "]", ")", ".", "concat", "(", "cols", ")", ")", ";", "}" ]
Returns a copy of the dataset with the given columns added to the existing selected columns. If no columns are currently selected it will just select the columns given. @example DB.from("items").select("a").select("b").sql; //=> SELECT b FROM items DB.from("items").select("a").selectMore("b", "c", "d").sql //=> SELECT a, b, c, d FROM items DB.from("items").selectMore("b").sql //=> SELECT b FROM items @param [...] cols variable number of columns to add to the select statement @return {patio.Dataset} returns a cloned dataset with the new select columns appended.
[ "Returns", "a", "copy", "of", "the", "dataset", "with", "the", "given", "columns", "added", "to", "the", "existing", "selected", "columns", ".", "If", "no", "columns", "are", "currently", "selected", "it", "will", "just", "select", "the", "columns", "given", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L1848-L1852
25,152
C2FO/patio
lib/dataset/query.js
function (type, dataset, options) { var ds = this._compoundFromSelf().mergeOptions({compounds: (array.toArray(this.__opts.compounds || [])).concat([ [type, dataset._compoundFromSelf(), options.all] ])}); return options.fromSelf === false ? ds : ds.fromSelf(options); }
javascript
function (type, dataset, options) { var ds = this._compoundFromSelf().mergeOptions({compounds: (array.toArray(this.__opts.compounds || [])).concat([ [type, dataset._compoundFromSelf(), options.all] ])}); return options.fromSelf === false ? ds : ds.fromSelf(options); }
[ "function", "(", "type", ",", "dataset", ",", "options", ")", "{", "var", "ds", "=", "this", ".", "_compoundFromSelf", "(", ")", ".", "mergeOptions", "(", "{", "compounds", ":", "(", "array", ".", "toArray", "(", "this", ".", "__opts", ".", "compounds", "||", "[", "]", ")", ")", ".", "concat", "(", "[", "[", "type", ",", "dataset", ".", "_compoundFromSelf", "(", ")", ",", "options", ".", "all", "]", "]", ")", "}", ")", ";", "return", "options", ".", "fromSelf", "===", "false", "?", "ds", ":", "ds", ".", "fromSelf", "(", "options", ")", ";", "}" ]
Add the dataset to the list of compounds @param {String} type the type of compound (i.e. "union", "intersect") @param {patio.Dataset} dataset the dataset to add to @param [Object] [options={}] compound option to use (i.e {all : true}) @return {patio.Dataset} ds with the dataset added to the compounds.
[ "Add", "the", "dataset", "to", "the", "list", "of", "compounds" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L2097-L2102
25,153
C2FO/patio
lib/dataset/query.js
function (op, obj) { var pairs = []; if (Expression.isConditionSpecifier(obj)) { if (isHash(obj)) { obj = array.toArray(obj); } obj.forEach(function (pair) { pairs.push(new BooleanExpression(op, new Identifier(pair[0]), pair[1])); }); } return pairs.length === 1 ? pairs[0] : BooleanExpression.fromArgs(["AND"].concat(pairs)); }
javascript
function (op, obj) { var pairs = []; if (Expression.isConditionSpecifier(obj)) { if (isHash(obj)) { obj = array.toArray(obj); } obj.forEach(function (pair) { pairs.push(new BooleanExpression(op, new Identifier(pair[0]), pair[1])); }); } return pairs.length === 1 ? pairs[0] : BooleanExpression.fromArgs(["AND"].concat(pairs)); }
[ "function", "(", "op", ",", "obj", ")", "{", "var", "pairs", "=", "[", "]", ";", "if", "(", "Expression", ".", "isConditionSpecifier", "(", "obj", ")", ")", "{", "if", "(", "isHash", "(", "obj", ")", ")", "{", "obj", "=", "array", ".", "toArray", "(", "obj", ")", ";", "}", "obj", ".", "forEach", "(", "function", "(", "pair", ")", "{", "pairs", ".", "push", "(", "new", "BooleanExpression", "(", "op", ",", "new", "Identifier", "(", "pair", "[", "0", "]", ")", ",", "pair", "[", "1", "]", ")", ")", ";", "}", ")", ";", "}", "return", "pairs", ".", "length", "===", "1", "?", "pairs", "[", "0", "]", ":", "BooleanExpression", ".", "fromArgs", "(", "[", "\"AND\"", "]", ".", "concat", "(", "pairs", ")", ")", ";", "}" ]
Creates a boolean expression that each key is compared to its value using the provided operator. @example ds.__createBoolExpression("gt", {x : 1, y:2, z : 5}) //=> WHERE ((x > 1) AND (y > 2) AND (z > 5)) ds.__createBoolExpression("gt", [[x, 1], [y,2], [z, 5]) //=> WHERE ((x > 1) AND (y > 2) AND (z > 5)) ds.__createBoolExpression("lt", {x : 1, y:2, z : 5}) //=> WHERE ((x < 1) AND (y < 2) AND (z < 5)) ds.__createBoolExpression("lt", [[x, 1], [y,2], [z, 5]) //=> WHERE ((x < 1) AND (y < 2) AND (z < 5)) @param {String} op valid boolean expression operator to capare each K,V pair with @param {Object| Array } obj object or two dimensional array containing key value pairs @return {patio.sql.BooleanExpression} boolean expression joined by a AND of each key value pair compared by the op
[ "Creates", "a", "boolean", "expression", "that", "each", "key", "is", "compared", "to", "its", "value", "using", "the", "provided", "operator", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/query.js#L2262-L2273
25,154
C2FO/patio
lib/database/schemaGenerators.js
function (name, type, opts) { opts = opts || {}; this.columns.push(merge({name:name, type:type}, opts)); if (opts.index) { this.index(name); } }
javascript
function (name, type, opts) { opts = opts || {}; this.columns.push(merge({name:name, type:type}, opts)); if (opts.index) { this.index(name); } }
[ "function", "(", "name", ",", "type", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "columns", ".", "push", "(", "merge", "(", "{", "name", ":", "name", ",", "type", ":", "type", "}", ",", "opts", ")", ")", ";", "if", "(", "opts", ".", "index", ")", "{", "this", ".", "index", "(", "name", ")", ";", "}", "}" ]
Add a column with the given name, type, and opts to the DDL. <pre class="code"> DB.createTable("test", function(){ this.column("num", "integer"); //=> num INTEGER this.column("name", String, {allowNull : false, "default" : "a"); //=> name varchar(255) NOT NULL DEFAULT 'a' this.column("ip", "inet"); //=> ip inet }); </pre> You can also create columns via method missing, so the following are equivalent: <pre class="code"> DB.createTable("test", function(){ this.column("number", "integer"); this.number("integer"); }); </pre> @param {String|patio.sql.Identifier} name the name of the column @param type the datatype of the column. @param {Object} [opts] additional options @param [opts.default] The default value for the column. @param [opts.deferrable] This ensure Referential Integrity will work even if reference table will use for its foreign key a value that does not exists(yet) on referenced table. Basically it adds DEFERRABLE INITIALLY DEFERRED on key creation. @param {Boolean} [opts.index] Create an index on this column. @param {String|patio.sql.Identifier} [key] For foreign key columns, the column in the associated table that this column references. Unnecessary if this column references the primary key of the associated table. @param {Boolean} [opts.allowNull] Mark the column as allowing NULL values (if true), or not allowing NULL values (if false). If unspecified, will default to whatever the database default is. @param {String} [opts.onDelete] Specify the behavior of this column when being deleted ("restrict", "cascade", "setNull", "setDefault", "noAction"). @param {String} [opts.onUpdate] Specify the behavior of this column when being updated Valid options ("restrict", "cascade", "setNull", "setDefault", "noAction"). @param {Boolean} [opts.primaryKey] Make the column as a single primary key column. This should only be used if you have a single, non-autoincrementing primary key column. @param {Number} [opts.size] The size of the column, generally used with string columns to specify the maximum number of characters the column will hold. An array of two integers can be provided to set the size and the precision, respectively, of decimal columns. @param {String} [opts.unique] Mark the column as unique, generally has the same effect as creating a unique index on the column. @param {String} [opts.unsigned] Make the column type unsigned, only useful for integer columns. @param {Array} [opts.elements] Available items used for set and enum columns.
[ "Add", "a", "column", "with", "the", "given", "name", "type", "and", "opts", "to", "the", "DDL", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/database/schemaGenerators.js#L143-L149
25,155
C2FO/patio
lib/database/schemaGenerators.js
function (name) { if (Array.isArray(name)) { return this.__compositePrimaryKey.apply(this, arguments); } else { var args = argsToArray(arguments, 1), type; var opts = args.pop(); this.__primaryKey = merge({}, this.db.serialPrimaryKeyOptions, {name:name}, opts); if (isDefined((type = args.pop()))) { merge(opts, {type:type}); } merge(this.__primaryKey, opts); return this.__primaryKey; } }
javascript
function (name) { if (Array.isArray(name)) { return this.__compositePrimaryKey.apply(this, arguments); } else { var args = argsToArray(arguments, 1), type; var opts = args.pop(); this.__primaryKey = merge({}, this.db.serialPrimaryKeyOptions, {name:name}, opts); if (isDefined((type = args.pop()))) { merge(opts, {type:type}); } merge(this.__primaryKey, opts); return this.__primaryKey; } }
[ "function", "(", "name", ")", "{", "if", "(", "Array", ".", "isArray", "(", "name", ")", ")", "{", "return", "this", ".", "__compositePrimaryKey", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "else", "{", "var", "args", "=", "argsToArray", "(", "arguments", ",", "1", ")", ",", "type", ";", "var", "opts", "=", "args", ".", "pop", "(", ")", ";", "this", ".", "__primaryKey", "=", "merge", "(", "{", "}", ",", "this", ".", "db", ".", "serialPrimaryKeyOptions", ",", "{", "name", ":", "name", "}", ",", "opts", ")", ";", "if", "(", "isDefined", "(", "(", "type", "=", "args", ".", "pop", "(", ")", ")", ")", ")", "{", "merge", "(", "opts", ",", "{", "type", ":", "type", "}", ")", ";", "}", "merge", "(", "this", ".", "__primaryKey", ",", "opts", ")", ";", "return", "this", ".", "__primaryKey", ";", "}", "}" ]
Adds an auto-incrementing primary key column or a primary key constraint to the DDL. To create a constraint, the first argument should be an array of columns specifying the primary key columns. To create an auto-incrementing primary key column, a single column can be used. In both cases, an options hash can be used as the second argument. If you want to create a primary key column that is not auto-incrementing, you should not use this method. Instead, you should use the regular {@link patio.SchemaGenerator#column} method with a {primaryKey : true} option. @example db.createTable("airplane_type", function () { this.primaryKey("id"); //=> id integer NOT NULL PRIMARY KEY AUTOINCREMENT this.name(String, {allowNull:false}); this.max_seats(Number, {size:3, allowNull:false}); this.company(String, {allowNull:false}); });
[ "Adds", "an", "auto", "-", "incrementing", "primary", "key", "column", "or", "a", "primary", "key", "constraint", "to", "the", "DDL", ".", "To", "create", "a", "constraint", "the", "first", "argument", "should", "be", "an", "array", "of", "columns", "specifying", "the", "primary", "key", "columns", ".", "To", "create", "an", "auto", "-", "incrementing", "primary", "key", "column", "a", "single", "column", "can", "be", "used", ".", "In", "both", "cases", "an", "options", "hash", "can", "be", "used", "as", "the", "second", "argument", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/database/schemaGenerators.js#L263-L276
25,156
C2FO/patio
lib/database/schemaGenerators.js
function (name, newName, opts) { opts = opts || {}; this.operations.push(merge({op:"renameColumn", name:name, newName:newName}, opts)); }
javascript
function (name, newName, opts) { opts = opts || {}; this.operations.push(merge({op:"renameColumn", name:name, newName:newName}, opts)); }
[ "function", "(", "name", ",", "newName", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "operations", ".", "push", "(", "merge", "(", "{", "op", ":", "\"renameColumn\"", ",", "name", ":", "name", ",", "newName", ":", "newName", "}", ",", "opts", ")", ")", ";", "}" ]
Modify a column's name in the DDL for the table. @example DB.alterTable("artist", function(){ this.renameColumn("name", "artistName"); //=> RENAME COLUMN name TO artist_name });
[ "Modify", "a", "column", "s", "name", "in", "the", "DDL", "for", "the", "table", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/database/schemaGenerators.js#L600-L603
25,157
C2FO/patio
lib/database/schemaGenerators.js
function (name, type, opts) { opts = opts || {}; this.operations.push(merge({op:"setColumnType", name:name, type:type}, opts)); }
javascript
function (name, type, opts) { opts = opts || {}; this.operations.push(merge({op:"setColumnType", name:name, type:type}, opts)); }
[ "function", "(", "name", ",", "type", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "operations", ".", "push", "(", "merge", "(", "{", "op", ":", "\"setColumnType\"", ",", "name", ":", "name", ",", "type", ":", "type", "}", ",", "opts", ")", ")", ";", "}" ]
Modify a column's type in the DDL for the table. @example DB.alterTable("artist", function(){ this.setColumnType("artist_name", 'char(10)'); //=> ALTER COLUMN artist_name TYPE char(10) });
[ "Modify", "a", "column", "s", "type", "in", "the", "DDL", "for", "the", "table", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/database/schemaGenerators.js#L626-L629
25,158
C2FO/patio
lib/plugins/query.js
function () { if (!this.__isNew) { var self = this; return this.dataset.naked().filter(this._getPrimaryKeyQuery()).one().chain(function (values) { self.__setFromDb(values, true); return self; }); } else { return when(this); } }
javascript
function () { if (!this.__isNew) { var self = this; return this.dataset.naked().filter(this._getPrimaryKeyQuery()).one().chain(function (values) { self.__setFromDb(values, true); return self; }); } else { return when(this); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "__isNew", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "dataset", ".", "naked", "(", ")", ".", "filter", "(", "this", ".", "_getPrimaryKeyQuery", "(", ")", ")", ".", "one", "(", ")", ".", "chain", "(", "function", "(", "values", ")", "{", "self", ".", "__setFromDb", "(", "values", ",", "true", ")", ";", "return", "self", ";", "}", ")", ";", "}", "else", "{", "return", "when", "(", "this", ")", ";", "}", "}" ]
Forces the reload of the data for a particular model instance. The Promise returned is resolved with the model. @example myModel.reload().chain(function(model){ //model === myModel }); @return {comb.Promise} resolved with the model instance.
[ "Forces", "the", "reload", "of", "the", "data", "for", "a", "particular", "model", "instance", ".", "The", "Promise", "returned", "is", "resolved", "with", "the", "model", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/query.js#L75-L85
25,159
C2FO/patio
lib/plugins/query.js
function (vals, /*?object*/query, options) { options = options || {}; var dataset = this.dataset; return this._checkTransaction(options, function () { if (!isUndefined(query)) { dataset = dataset.filter(query); } return dataset.update(vals); }); }
javascript
function (vals, /*?object*/query, options) { options = options || {}; var dataset = this.dataset; return this._checkTransaction(options, function () { if (!isUndefined(query)) { dataset = dataset.filter(query); } return dataset.update(vals); }); }
[ "function", "(", "vals", ",", "/*?object*/", "query", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "dataset", "=", "this", ".", "dataset", ";", "return", "this", ".", "_checkTransaction", "(", "options", ",", "function", "(", ")", "{", "if", "(", "!", "isUndefined", "(", "query", ")", ")", "{", "dataset", "=", "dataset", ".", "filter", "(", "query", ")", ";", "}", "return", "dataset", ".", "update", "(", "vals", ")", ";", "}", ")", ";", "}" ]
Update multiple rows with a set of values. @example var User = patio.getModel("user"); //BEGIN //UPDATE `user` SET `password` = NULL WHERE (`last_accessed` <= '2011-01-27') //COMMIT User.update({password : null}, function(){ return this.lastAccessed.lte(comb.date.add(new Date(), "year", -1)); }); //same as User.update({password : null}, {lastAccess : {lte : comb.date.add(new Date(), "year", -1)}}); //UPDATE `user` SET `password` = NULL WHERE (`last_accessed` <= '2011-01-27') User.update({password : null}, function(){ return this.lastAccessed.lte(comb.date.add(new Date(), "year", -1)); }, {transaction : false}); @param {Object} vals a hash of values to update. See {@link patio.Dataset#update}. @param query a filter to apply to the UPDATE. See {@link patio.Dataset#filter}. @param {Object} [options] additional options. @param {Boolean} [options.transaction] boolean indicating if a transaction should be used when updating the models. @return {Promise} a promise that is resolved once the update statement has completed.
[ "Update", "multiple", "rows", "with", "a", "set", "of", "values", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/query.js#L513-L522
25,160
C2FO/patio
lib/plugins/query.js
function (id, options) { var self = this; return this._checkTransaction(options, function () { return self.findById(id).chain(function (model) { return model ? model.remove(options) : null; }); }); }
javascript
function (id, options) { var self = this; return this._checkTransaction(options, function () { return self.findById(id).chain(function (model) { return model ? model.remove(options) : null; }); }); }
[ "function", "(", "id", ",", "options", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "_checkTransaction", "(", "options", ",", "function", "(", ")", "{", "return", "self", ".", "findById", "(", "id", ")", ".", "chain", "(", "function", "(", "model", ")", "{", "return", "model", "?", "model", ".", "remove", "(", "options", ")", ":", "null", ";", "}", ")", ";", "}", ")", ";", "}" ]
Similar to remove but takes an id or an array for a composite key. @example User.removeById(1); @param id id or an array for a composite key, to find the model by @param {Object} [options] additional options. @param {Boolean} [options.transaction] boolean indicating if a transaction should be used when removing the model. @return {comb.Promise} called back when the removal completes.
[ "Similar", "to", "remove", "but", "takes", "an", "id", "or", "an", "array", "for", "a", "composite", "key", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/query.js#L579-L586
25,161
C2FO/patio
lib/plugins/query.js
function (items, options) { options = options || {}; var isArr = isArray(items), Self = this; return this._checkTransaction(options, function () { return asyncArray(items) .map(function (o) { if (!isInstanceOf(o, Self)) { o = new Self(o); } return o.save(null, options); }) .chain(function (res) { return isArr ? res : res[0]; }); }); }
javascript
function (items, options) { options = options || {}; var isArr = isArray(items), Self = this; return this._checkTransaction(options, function () { return asyncArray(items) .map(function (o) { if (!isInstanceOf(o, Self)) { o = new Self(o); } return o.save(null, options); }) .chain(function (res) { return isArr ? res : res[0]; }); }); }
[ "function", "(", "items", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "isArr", "=", "isArray", "(", "items", ")", ",", "Self", "=", "this", ";", "return", "this", ".", "_checkTransaction", "(", "options", ",", "function", "(", ")", "{", "return", "asyncArray", "(", "items", ")", ".", "map", "(", "function", "(", "o", ")", "{", "if", "(", "!", "isInstanceOf", "(", "o", ",", "Self", ")", ")", "{", "o", "=", "new", "Self", "(", "o", ")", ";", "}", "return", "o", ".", "save", "(", "null", ",", "options", ")", ";", "}", ")", ".", "chain", "(", "function", "(", "res", ")", "{", "return", "isArr", "?", "res", ":", "res", "[", "0", "]", ";", "}", ")", ";", "}", ")", ";", "}" ]
Save either a new model or list of models to the database. @example var Student = patio.getModel("student"); Student.save([ { firstName:"Bob", lastName:"Yukon", gpa:3.689, classYear:"Senior" }, { firstName:"Greg", lastName:"Horn", gpa:3.689, classYear:"Sohpmore" }, { firstName:"Sara", lastName:"Malloc", gpa:4.0, classYear:"Junior" }, { firstName:"John", lastName:"Favre", gpa:2.867, classYear:"Junior" }, { firstName:"Kim", lastName:"Bim", gpa:2.24, classYear:"Senior" }, { firstName:"Alex", lastName:"Young", gpa:1.9, classYear:"Freshman" } ]).chain(function(users){ //work with the users }); Save a single record MyModel.save(m1); @param {patio.Model|Object|patio.Model[]|Object[]} record the record/s to save. @param {Object} [options] additional options. @param {Boolean} [options.transaction] boolean indicating if a transaction should be used when saving the models. @return {comb.Promise} called back with the saved record/s.
[ "Save", "either", "a", "new", "model", "or", "list", "of", "models", "to", "the", "database", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/query.js#L644-L659
25,162
C2FO/patio
lib/time.js
function (dt, format) { var ret = ""; if (isInstanceOf(dt, SQL.Time)) { ret = this.timeToString(dt, format); } else if (isInstanceOf(dt, SQL.Year)) { ret = this.yearToString(dt, format); } else if (isInstanceOf(dt, SQL.DateTime)) { ret = this.dateTimeToString(dt, format); } else if (isInstanceOf(dt, SQL.TimeStamp)) { ret = this.timeStampToString(dt, format); } else if (isDate(dt)) { ret = dateFormat(dt, format || this.dateFormat); } return ret; }
javascript
function (dt, format) { var ret = ""; if (isInstanceOf(dt, SQL.Time)) { ret = this.timeToString(dt, format); } else if (isInstanceOf(dt, SQL.Year)) { ret = this.yearToString(dt, format); } else if (isInstanceOf(dt, SQL.DateTime)) { ret = this.dateTimeToString(dt, format); } else if (isInstanceOf(dt, SQL.TimeStamp)) { ret = this.timeStampToString(dt, format); } else if (isDate(dt)) { ret = dateFormat(dt, format || this.dateFormat); } return ret; }
[ "function", "(", "dt", ",", "format", ")", "{", "var", "ret", "=", "\"\"", ";", "if", "(", "isInstanceOf", "(", "dt", ",", "SQL", ".", "Time", ")", ")", "{", "ret", "=", "this", ".", "timeToString", "(", "dt", ",", "format", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "dt", ",", "SQL", ".", "Year", ")", ")", "{", "ret", "=", "this", ".", "yearToString", "(", "dt", ",", "format", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "dt", ",", "SQL", ".", "DateTime", ")", ")", "{", "ret", "=", "this", ".", "dateTimeToString", "(", "dt", ",", "format", ")", ";", "}", "else", "if", "(", "isInstanceOf", "(", "dt", ",", "SQL", ".", "TimeStamp", ")", ")", "{", "ret", "=", "this", ".", "timeStampToString", "(", "dt", ",", "format", ")", ";", "}", "else", "if", "(", "isDate", "(", "dt", ")", ")", "{", "ret", "=", "dateFormat", "(", "dt", ",", "format", "||", "this", ".", "dateFormat", ")", ";", "}", "return", "ret", ";", "}" ]
Converts a date to a string. @example var date = new Date(2004, 1, 1), timeStamp = new sql.TimeStamp(2004, 1, 1, 12, 12, 12), dateTime = new sql.DateTime(2004, 1, 1, 12, 12, 12), year = new sql.Year(2004), time = new sql.Time(12,12,12), //convert years patio.dateToString(year); //=> '2004' patio.yearFormat = "yy"; patio.dateToString(year); //=> '04' patio.yearFormat = patio.DEFAULT_YEAR_FORMAT; patio.dateToString(year); //=> '2004' //convert times patio.dateToString(time); //=> '12:12:12' //convert dates patio.dateToString(date); //=> '2004-02-01' patio.dateFormat = patio.TWO_YEAR_DATE_FORMAT; patio.dateToString(date); //=> '04-02-01' patio.dateFormat = patio.DEFAULT_DATE_FORMAT; patio.dateToString(date); //=> '2004-02-01' //convert dateTime patio.dateToString(dateTime); //=> '2004-02-01 12:12:12' patio.dateTimeFormat = patio.DATETIME_TWO_YEAR_FORMAT; patio.dateToString(dateTime); //=> '04-02-01 12:12:12' patio.dateTimeFormat = patio.DATETIME_FORMAT_TZ; patio.dateToString(dateTime); //=> '2004-02-01 12:12:12-0600' patio.dateTimeFormat = patio.ISO_8601; patio.dateToString(dateTime); //=> '2004-02-01T12:12:12-0600' patio.dateTimeFormat = patio.ISO_8601_TWO_YEAR; patio.dateToString(dateTime); //=> '04-02-01T12:12:12-0600' patio.dateTimeFormat = patio.DEFAULT_DATETIME_FORMAT; patio.dateToString(dateTime); //=> '2004-02-01 12:12:12' //convert timestamps patio.dateToString(timeStamp); //=> '2004-02-01 12:12:12' patio.timeStampFormat = patio.TIMESTAMP_TWO_YEAR_FORMAT; patio.dateToString(timeStamp); //=> '04-02-01 12:12:12' patio.timeStampFormat = patio.TIMESTAMP_FORMAT_TZ; patio.dateToString(timeStamp); //=> '2004-02-01 12:12:12-0600' patio.timeStampFormat = patio.ISO_8601; patio.dateToString(timeStamp); //=> '2004-02-01T12:12:12-0600' patio.timeStampFormat = patio.ISO_8601_TWO_YEAR; patio.dateToString(timeStamp); //=> '04-02-01T12:12:12-0600' patio.timeStampFormat = patio.DEFAULT_TIMESTAMP_FORMAT; patio.dateToString(timeStamp); //=> '2004-02-01 12:12:12' @param {Date\patio.sql.Time|patio.sql.Year|patio.sql.DateTime|patio.sql.TimeStamp} dt the date to covert to to a string. @returns {String} the date string.
[ "Converts", "a", "date", "to", "a", "string", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/time.js#L390-L404
25,163
C2FO/patio
lib/time.js
function (dt, format) { var ret; if (this.convertTwoDigitYears) { ret = date.parse(dt, this.TWO_YEAR_DATE_FORMAT); } if (!ret) { ret = date.parse(dt, format || this.dateFormat); } if (!ret) { throw new PatioError("Unable to convert date: " + dt); } return ret; }
javascript
function (dt, format) { var ret; if (this.convertTwoDigitYears) { ret = date.parse(dt, this.TWO_YEAR_DATE_FORMAT); } if (!ret) { ret = date.parse(dt, format || this.dateFormat); } if (!ret) { throw new PatioError("Unable to convert date: " + dt); } return ret; }
[ "function", "(", "dt", ",", "format", ")", "{", "var", "ret", ";", "if", "(", "this", ".", "convertTwoDigitYears", ")", "{", "ret", "=", "date", ".", "parse", "(", "dt", ",", "this", ".", "TWO_YEAR_DATE_FORMAT", ")", ";", "}", "if", "(", "!", "ret", ")", "{", "ret", "=", "date", ".", "parse", "(", "dt", ",", "format", "||", "this", ".", "dateFormat", ")", ";", "}", "if", "(", "!", "ret", ")", "{", "throw", "new", "PatioError", "(", "\"Unable to convert date: \"", "+", "dt", ")", ";", "}", "return", "ret", ";", "}" ]
Converts a date string to a Date @example var date = new Date(2004, 1,1,0,0,0); patio.stringToDate('2004-02-01'); //=> date patio.dateFormat = patio.TWO_YEAR_DATE_FORMAT; patio.stringToDate('04-02-01'); //=> date @param {String} dt the string to convert to a Date @param {String} [format=patio.Time#dateFormat] the format to use when converting the date. @throws {PatioError} thrown if the conversion fails. @return {Date} the {@link Date}
[ "Converts", "a", "date", "string", "to", "a", "Date" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/time.js#L469-L481
25,164
C2FO/patio
lib/adapters/mysql.js
function (args) { args = argsToArray(arguments); return !args.length ? this._super(arguments) : this.group.apply(this, args); }
javascript
function (args) { args = argsToArray(arguments); return !args.length ? this._super(arguments) : this.group.apply(this, args); }
[ "function", "(", "args", ")", "{", "args", "=", "argsToArray", "(", "arguments", ")", ";", "return", "!", "args", ".", "length", "?", "this", ".", "_super", "(", "arguments", ")", ":", "this", ".", "group", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
Use GROUP BY instead of DISTINCT ON if arguments are provided.
[ "Use", "GROUP", "BY", "instead", "of", "DISTINCT", "ON", "if", "arguments", "are", "provided", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L148-L151
25,165
C2FO/patio
lib/adapters/mysql.js
function (cols, terms, opts) { opts = opts || {}; cols = toArray(cols).map(this.stringToIdentifier, this); return this.filter(sql.literal(this.fullTextSql(cols, terms, opts))); }
javascript
function (cols, terms, opts) { opts = opts || {}; cols = toArray(cols).map(this.stringToIdentifier, this); return this.filter(sql.literal(this.fullTextSql(cols, terms, opts))); }
[ "function", "(", "cols", ",", "terms", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "cols", "=", "toArray", "(", "cols", ")", ".", "map", "(", "this", ".", "stringToIdentifier", ",", "this", ")", ";", "return", "this", ".", "filter", "(", "sql", ".", "literal", "(", "this", ".", "fullTextSql", "(", "cols", ",", "terms", ",", "opts", ")", ")", ")", ";", "}" ]
Adds full text filter
[ "Adds", "full", "text", "filter" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L159-L163
25,166
C2FO/patio
lib/adapters/mysql.js
function (cols, term, opts) { opts = opts || {}; return format("MATCH %s AGAINST (%s%s)", this.literal(toArray(cols)), this.literal(toArray(term).join(" ")), opts.boolean ? " IN BOOLEAN MODE" : ""); }
javascript
function (cols, term, opts) { opts = opts || {}; return format("MATCH %s AGAINST (%s%s)", this.literal(toArray(cols)), this.literal(toArray(term).join(" ")), opts.boolean ? " IN BOOLEAN MODE" : ""); }
[ "function", "(", "cols", ",", "term", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "return", "format", "(", "\"MATCH %s AGAINST (%s%s)\"", ",", "this", ".", "literal", "(", "toArray", "(", "cols", ")", ")", ",", "this", ".", "literal", "(", "toArray", "(", "term", ")", ".", "join", "(", "\" \"", ")", ")", ",", "opts", ".", "boolean", "?", "\" IN BOOLEAN MODE\"", ":", "\"\"", ")", ";", "}" ]
MySQL specific full text search syntax.
[ "MySQL", "specific", "full", "text", "search", "syntax", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L166-L170
25,167
C2FO/patio
lib/adapters/mysql.js
function (columns, values) { return [this.insertSql(columns, sql.literal('VALUES ' + values.map( function (r) { return this.literal(toArray(r)); }, this).join(this._static.COMMA_SEPARATOR)))]; }
javascript
function (columns, values) { return [this.insertSql(columns, sql.literal('VALUES ' + values.map( function (r) { return this.literal(toArray(r)); }, this).join(this._static.COMMA_SEPARATOR)))]; }
[ "function", "(", "columns", ",", "values", ")", "{", "return", "[", "this", ".", "insertSql", "(", "columns", ",", "sql", ".", "literal", "(", "'VALUES '", "+", "values", ".", "map", "(", "function", "(", "r", ")", "{", "return", "this", ".", "literal", "(", "toArray", "(", "r", ")", ")", ";", "}", ",", "this", ")", ".", "join", "(", "this", ".", "_static", ".", "COMMA_SEPARATOR", ")", ")", ")", "]", ";", "}" ]
MySQL specific syntax for inserting multiple values at once.
[ "MySQL", "specific", "syntax", "for", "inserting", "multiple", "values", "at", "once", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L216-L221
25,168
C2FO/patio
lib/adapters/mysql.js
function (sql) { if (this._joinedDataset) { return format(" %s FROM %s%s", this._sourceList(this.__opts.from[0]), this._sourceList(this.__opts.from), this._selectJoinSql()); } else { return this._super(arguments); } }
javascript
function (sql) { if (this._joinedDataset) { return format(" %s FROM %s%s", this._sourceList(this.__opts.from[0]), this._sourceList(this.__opts.from), this._selectJoinSql()); } else { return this._super(arguments); } }
[ "function", "(", "sql", ")", "{", "if", "(", "this", ".", "_joinedDataset", ")", "{", "return", "format", "(", "\" %s FROM %s%s\"", ",", "this", ".", "_sourceList", "(", "this", ".", "__opts", ".", "from", "[", "0", "]", ")", ",", "this", ".", "_sourceList", "(", "this", ".", "__opts", ".", "from", ")", ",", "this", ".", "_selectJoinSql", "(", ")", ")", ";", "}", "else", "{", "return", "this", ".", "_super", "(", "arguments", ")", ";", "}", "}" ]
Consider the first table in the joined dataset is the table to delete from, but include the others for the purposes of selecting rows.
[ "Consider", "the", "first", "table", "in", "the", "joined", "dataset", "is", "the", "table", "to", "delete", "from", "but", "include", "the", "others", "for", "the", "purposes", "of", "selecting", "rows", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L242-L248
25,169
C2FO/patio
lib/adapters/mysql.js
function (sql) { var values = this.__opts.values; if (isArray(values) && !values.length) { return " ()"; } else { return this._super(arguments); } }
javascript
function (sql) { var values = this.__opts.values; if (isArray(values) && !values.length) { return " ()"; } else { return this._super(arguments); } }
[ "function", "(", "sql", ")", "{", "var", "values", "=", "this", ".", "__opts", ".", "values", ";", "if", "(", "isArray", "(", "values", ")", "&&", "!", "values", ".", "length", ")", "{", "return", "\" ()\"", ";", "}", "else", "{", "return", "this", ".", "_super", "(", "arguments", ")", ";", "}", "}" ]
alias replace_clause_methods insert_clause_methods MySQL doesn't use the standard DEFAULT VALUES for empty values.
[ "alias", "replace_clause_methods", "insert_clause_methods", "MySQL", "doesn", "t", "use", "the", "standard", "DEFAULT", "VALUES", "for", "empty", "values", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L252-L259
25,170
C2FO/patio
lib/adapters/mysql.js
function () { var ret = ""; var updateCols = this.__opts.onDuplicateKeyUpdate; if (updateCols) { var updateVals = null, l, last; if ((l = updateCols.length) > 0 && isHash((last = updateCols[l - 1]))) { updateVals = last; updateCols = l === 2 ? [updateCols[0]] : updateCols.slice(0, l - 2); } var updating = updateCols.map(function (c) { var quoted = this.quoteIdentifier(c); return format("%s=VALUES(%s)", quoted, quoted); }, this); for (var i in updateVals) { if (i in updateVals) { updating.push(format("%s=%s", this.quoteIdentifier(i), this.literal(updateVals[i]))); } } if (updating || updateVals) { ret = format(" ON DUPLICATE KEY UPDATE %s", updating.join(this._static.COMMA_SEPARATOR)); } } return ret; }
javascript
function () { var ret = ""; var updateCols = this.__opts.onDuplicateKeyUpdate; if (updateCols) { var updateVals = null, l, last; if ((l = updateCols.length) > 0 && isHash((last = updateCols[l - 1]))) { updateVals = last; updateCols = l === 2 ? [updateCols[0]] : updateCols.slice(0, l - 2); } var updating = updateCols.map(function (c) { var quoted = this.quoteIdentifier(c); return format("%s=VALUES(%s)", quoted, quoted); }, this); for (var i in updateVals) { if (i in updateVals) { updating.push(format("%s=%s", this.quoteIdentifier(i), this.literal(updateVals[i]))); } } if (updating || updateVals) { ret = format(" ON DUPLICATE KEY UPDATE %s", updating.join(this._static.COMMA_SEPARATOR)); } } return ret; }
[ "function", "(", ")", "{", "var", "ret", "=", "\"\"", ";", "var", "updateCols", "=", "this", ".", "__opts", ".", "onDuplicateKeyUpdate", ";", "if", "(", "updateCols", ")", "{", "var", "updateVals", "=", "null", ",", "l", ",", "last", ";", "if", "(", "(", "l", "=", "updateCols", ".", "length", ")", ">", "0", "&&", "isHash", "(", "(", "last", "=", "updateCols", "[", "l", "-", "1", "]", ")", ")", ")", "{", "updateVals", "=", "last", ";", "updateCols", "=", "l", "===", "2", "?", "[", "updateCols", "[", "0", "]", "]", ":", "updateCols", ".", "slice", "(", "0", ",", "l", "-", "2", ")", ";", "}", "var", "updating", "=", "updateCols", ".", "map", "(", "function", "(", "c", ")", "{", "var", "quoted", "=", "this", ".", "quoteIdentifier", "(", "c", ")", ";", "return", "format", "(", "\"%s=VALUES(%s)\"", ",", "quoted", ",", "quoted", ")", ";", "}", ",", "this", ")", ";", "for", "(", "var", "i", "in", "updateVals", ")", "{", "if", "(", "i", "in", "updateVals", ")", "{", "updating", ".", "push", "(", "format", "(", "\"%s=%s\"", ",", "this", ".", "quoteIdentifier", "(", "i", ")", ",", "this", ".", "literal", "(", "updateVals", "[", "i", "]", ")", ")", ")", ";", "}", "}", "if", "(", "updating", "||", "updateVals", ")", "{", "ret", "=", "format", "(", "\" ON DUPLICATE KEY UPDATE %s\"", ",", "updating", ".", "join", "(", "this", ".", "_static", ".", "COMMA_SEPARATOR", ")", ")", ";", "}", "}", "return", "ret", ";", "}" ]
MySQL specific syntax for ON DUPLICATE KEY UPDATE
[ "MySQL", "specific", "syntax", "for", "ON", "DUPLICATE", "KEY", "UPDATE" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L296-L320
25,171
C2FO/patio
lib/adapters/mysql.js
function (type) { var ret = null, meth; if (isString(type)) { ret = this._static.CAST_TYPES[type] || this._super(arguments); } else if (type === String) { meth += "CHAR"; } else if (type === Number) { meth += "DECIMAL"; } else if (type === DateTime) { meth += "DATETIME"; } else if (type === Year) { meth += "Year"; } else if (type === Time) { meth += "DATETIME"; } else if (type === Double) { meth += "DECIMAL"; } else { ret = this._super(arguments); } return ret; }
javascript
function (type) { var ret = null, meth; if (isString(type)) { ret = this._static.CAST_TYPES[type] || this._super(arguments); } else if (type === String) { meth += "CHAR"; } else if (type === Number) { meth += "DECIMAL"; } else if (type === DateTime) { meth += "DATETIME"; } else if (type === Year) { meth += "Year"; } else if (type === Time) { meth += "DATETIME"; } else if (type === Double) { meth += "DECIMAL"; } else { ret = this._super(arguments); } return ret; }
[ "function", "(", "type", ")", "{", "var", "ret", "=", "null", ",", "meth", ";", "if", "(", "isString", "(", "type", ")", ")", "{", "ret", "=", "this", ".", "_static", ".", "CAST_TYPES", "[", "type", "]", "||", "this", ".", "_super", "(", "arguments", ")", ";", "}", "else", "if", "(", "type", "===", "String", ")", "{", "meth", "+=", "\"CHAR\"", ";", "}", "else", "if", "(", "type", "===", "Number", ")", "{", "meth", "+=", "\"DECIMAL\"", ";", "}", "else", "if", "(", "type", "===", "DateTime", ")", "{", "meth", "+=", "\"DATETIME\"", ";", "}", "else", "if", "(", "type", "===", "Year", ")", "{", "meth", "+=", "\"Year\"", ";", "}", "else", "if", "(", "type", "===", "Time", ")", "{", "meth", "+=", "\"DATETIME\"", ";", "}", "else", "if", "(", "type", "===", "Double", ")", "{", "meth", "+=", "\"DECIMAL\"", ";", "}", "else", "{", "ret", "=", "this", ".", "_super", "(", "arguments", ")", ";", "}", "return", "ret", ";", "}" ]
MySQL's cast rules are restrictive in that you can't just cast to any possible database type.
[ "MySQL", "s", "cast", "rules", "are", "restrictive", "in", "that", "you", "can", "t", "just", "cast", "to", "any", "possible", "database", "type", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L477-L497
25,172
C2FO/patio
lib/adapters/mysql.js
function (table, opts) { var indexes = {}; var removeIndexes = []; var m = this.outputIdentifierFunc; var im = this.inputIdentifierFunc; return this.metadataDataset.withSql("SHOW INDEX FROM ?", isInstanceOf(table, sql.Identifier) ? table : sql.identifier(im(table))) .forEach(function (r) { var name = r[m("Key_name")]; if (name !== "PRIMARY") { name = m(name); if (r[m("Sub_part")]) { removeIndexes.push(name); } var i = indexes[name] || (indexes[name] = {columns: [], unique: r[m("Non_unique")] !== 1}); i.columns.push(m(r[m("Column_name")])); } }).chain(function () { var r = {}; for (var i in indexes) { if (removeIndexes.indexOf(i) === -1) { r[i] = indexes[i]; } } return r; }); }
javascript
function (table, opts) { var indexes = {}; var removeIndexes = []; var m = this.outputIdentifierFunc; var im = this.inputIdentifierFunc; return this.metadataDataset.withSql("SHOW INDEX FROM ?", isInstanceOf(table, sql.Identifier) ? table : sql.identifier(im(table))) .forEach(function (r) { var name = r[m("Key_name")]; if (name !== "PRIMARY") { name = m(name); if (r[m("Sub_part")]) { removeIndexes.push(name); } var i = indexes[name] || (indexes[name] = {columns: [], unique: r[m("Non_unique")] !== 1}); i.columns.push(m(r[m("Column_name")])); } }).chain(function () { var r = {}; for (var i in indexes) { if (removeIndexes.indexOf(i) === -1) { r[i] = indexes[i]; } } return r; }); }
[ "function", "(", "table", ",", "opts", ")", "{", "var", "indexes", "=", "{", "}", ";", "var", "removeIndexes", "=", "[", "]", ";", "var", "m", "=", "this", ".", "outputIdentifierFunc", ";", "var", "im", "=", "this", ".", "inputIdentifierFunc", ";", "return", "this", ".", "metadataDataset", ".", "withSql", "(", "\"SHOW INDEX FROM ?\"", ",", "isInstanceOf", "(", "table", ",", "sql", ".", "Identifier", ")", "?", "table", ":", "sql", ".", "identifier", "(", "im", "(", "table", ")", ")", ")", ".", "forEach", "(", "function", "(", "r", ")", "{", "var", "name", "=", "r", "[", "m", "(", "\"Key_name\"", ")", "]", ";", "if", "(", "name", "!==", "\"PRIMARY\"", ")", "{", "name", "=", "m", "(", "name", ")", ";", "if", "(", "r", "[", "m", "(", "\"Sub_part\"", ")", "]", ")", "{", "removeIndexes", ".", "push", "(", "name", ")", ";", "}", "var", "i", "=", "indexes", "[", "name", "]", "||", "(", "indexes", "[", "name", "]", "=", "{", "columns", ":", "[", "]", ",", "unique", ":", "r", "[", "m", "(", "\"Non_unique\"", ")", "]", "!==", "1", "}", ")", ";", "i", ".", "columns", ".", "push", "(", "m", "(", "r", "[", "m", "(", "\"Column_name\"", ")", "]", ")", ")", ";", "}", "}", ")", ".", "chain", "(", "function", "(", ")", "{", "var", "r", "=", "{", "}", ";", "for", "(", "var", "i", "in", "indexes", ")", "{", "if", "(", "removeIndexes", ".", "indexOf", "(", "i", ")", "===", "-", "1", ")", "{", "r", "[", "i", "]", "=", "indexes", "[", "i", "]", ";", "}", "}", "return", "r", ";", "}", ")", ";", "}" ]
Use SHOW INDEX FROM to get the index information for the table.
[ "Use", "SHOW", "INDEX", "FROM", "to", "get", "the", "index", "information", "for", "the", "table", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L500-L526
25,173
C2FO/patio
lib/adapters/mysql.js
function () { var ret; if (!this.__serverVersion) { var self = this; ret = this.get(sql.version().sqlFunction).chain(function (version) { var m = version.match(/(\d+)\.(\d+)\.(\d+)/); return (self._serverVersion = (parseInt(m[1], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[3], 10)); }); } else { ret = new Promise().callback(this._serverVersion); } return ret.promise(); }
javascript
function () { var ret; if (!this.__serverVersion) { var self = this; ret = this.get(sql.version().sqlFunction).chain(function (version) { var m = version.match(/(\d+)\.(\d+)\.(\d+)/); return (self._serverVersion = (parseInt(m[1], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[3], 10)); }); } else { ret = new Promise().callback(this._serverVersion); } return ret.promise(); }
[ "function", "(", ")", "{", "var", "ret", ";", "if", "(", "!", "this", ".", "__serverVersion", ")", "{", "var", "self", "=", "this", ";", "ret", "=", "this", ".", "get", "(", "sql", ".", "version", "(", ")", ".", "sqlFunction", ")", ".", "chain", "(", "function", "(", "version", ")", "{", "var", "m", "=", "version", ".", "match", "(", "/", "(\\d+)\\.(\\d+)\\.(\\d+)", "/", ")", ";", "return", "(", "self", ".", "_serverVersion", "=", "(", "parseInt", "(", "m", "[", "1", "]", ",", "10", ")", "*", "10000", ")", "+", "(", "parseInt", "(", "m", "[", "2", "]", ",", "10", ")", "*", "100", ")", "+", "parseInt", "(", "m", "[", "3", "]", ",", "10", ")", ")", ";", "}", ")", ";", "}", "else", "{", "ret", "=", "new", "Promise", "(", ")", ".", "callback", "(", "this", ".", "_serverVersion", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Get version of MySQL server, used for determined capabilities.
[ "Get", "version", "of", "MySQL", "server", "used", "for", "determined", "capabilities", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L529-L541
25,174
C2FO/patio
lib/adapters/mysql.js
function (opts) { var m = this.outputIdentifierFunc; return this.metadataDataset.withSql('SHOW TABLES').map(function (r) { return m(r[Object.keys(r)[0]]); }); }
javascript
function (opts) { var m = this.outputIdentifierFunc; return this.metadataDataset.withSql('SHOW TABLES').map(function (r) { return m(r[Object.keys(r)[0]]); }); }
[ "function", "(", "opts", ")", "{", "var", "m", "=", "this", ".", "outputIdentifierFunc", ";", "return", "this", ".", "metadataDataset", ".", "withSql", "(", "'SHOW TABLES'", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "m", "(", "r", "[", "Object", ".", "keys", "(", "r", ")", "[", "0", "]", "]", ")", ";", "}", ")", ";", "}" ]
Return an array of strings specifying table names in the current database.
[ "Return", "an", "array", "of", "strings", "specifying", "table", "names", "in", "the", "current", "database", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L544-L549
25,175
C2FO/patio
lib/adapters/mysql.js
function (table, op) { var ret = new Promise(), self = this; if (op.op === "addColumn") { var related = op.table; if (related) { delete op.table; ret = this._super(arguments).chain(function (sql) { op.table = related; return [sql, format("ALTER TABLE %s ADD FOREIGN KEY (%s)%s", self.__quoteSchemaTable(table), self.__quoteIdentifier(op.name), self.__columnReferencesSql(op))]; }); } else { ret = this._super(arguments); } } else if (['renameColumn', "setColumnType", "setColumnNull", "setColumnDefault"].indexOf(op.op) !== -1) { ret = this.schema(table).chain(function (schema) { var name = op.name; var opts = schema[Object.keys(schema).filter(function (i) { return i === name; })[0]]; opts = merge({}, opts || {}); opts.name = op.newName || name; opts.type = op.type || opts.dbType; opts.allowNull = isUndefined(op["null"]) ? opts.allowNull : op["null"]; opts["default"] = op["default"] || opts.jsDefault; if (isUndefinedOrNull(opts["default"])) { delete opts["default"]; } return format("ALTER TABLE %s CHANGE COLUMN %s %s", self.__quoteSchemaTable(table), self.__quoteIdentifier(op.name), self.__columnDefinitionSql(merge(op, opts))); }); } else if (op.op === "dropIndex") { ret = when(format("%s ON %s", this.__dropIndexSql(table, op), this.__quoteSchemaTable(table))); } else { ret = this._super(arguments); } return ret.promise(); }
javascript
function (table, op) { var ret = new Promise(), self = this; if (op.op === "addColumn") { var related = op.table; if (related) { delete op.table; ret = this._super(arguments).chain(function (sql) { op.table = related; return [sql, format("ALTER TABLE %s ADD FOREIGN KEY (%s)%s", self.__quoteSchemaTable(table), self.__quoteIdentifier(op.name), self.__columnReferencesSql(op))]; }); } else { ret = this._super(arguments); } } else if (['renameColumn', "setColumnType", "setColumnNull", "setColumnDefault"].indexOf(op.op) !== -1) { ret = this.schema(table).chain(function (schema) { var name = op.name; var opts = schema[Object.keys(schema).filter(function (i) { return i === name; })[0]]; opts = merge({}, opts || {}); opts.name = op.newName || name; opts.type = op.type || opts.dbType; opts.allowNull = isUndefined(op["null"]) ? opts.allowNull : op["null"]; opts["default"] = op["default"] || opts.jsDefault; if (isUndefinedOrNull(opts["default"])) { delete opts["default"]; } return format("ALTER TABLE %s CHANGE COLUMN %s %s", self.__quoteSchemaTable(table), self.__quoteIdentifier(op.name), self.__columnDefinitionSql(merge(op, opts))); }); } else if (op.op === "dropIndex") { ret = when(format("%s ON %s", this.__dropIndexSql(table, op), this.__quoteSchemaTable(table))); } else { ret = this._super(arguments); } return ret.promise(); }
[ "function", "(", "table", ",", "op", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ",", "self", "=", "this", ";", "if", "(", "op", ".", "op", "===", "\"addColumn\"", ")", "{", "var", "related", "=", "op", ".", "table", ";", "if", "(", "related", ")", "{", "delete", "op", ".", "table", ";", "ret", "=", "this", ".", "_super", "(", "arguments", ")", ".", "chain", "(", "function", "(", "sql", ")", "{", "op", ".", "table", "=", "related", ";", "return", "[", "sql", ",", "format", "(", "\"ALTER TABLE %s ADD FOREIGN KEY (%s)%s\"", ",", "self", ".", "__quoteSchemaTable", "(", "table", ")", ",", "self", ".", "__quoteIdentifier", "(", "op", ".", "name", ")", ",", "self", ".", "__columnReferencesSql", "(", "op", ")", ")", "]", ";", "}", ")", ";", "}", "else", "{", "ret", "=", "this", ".", "_super", "(", "arguments", ")", ";", "}", "}", "else", "if", "(", "[", "'renameColumn'", ",", "\"setColumnType\"", ",", "\"setColumnNull\"", ",", "\"setColumnDefault\"", "]", ".", "indexOf", "(", "op", ".", "op", ")", "!==", "-", "1", ")", "{", "ret", "=", "this", ".", "schema", "(", "table", ")", ".", "chain", "(", "function", "(", "schema", ")", "{", "var", "name", "=", "op", ".", "name", ";", "var", "opts", "=", "schema", "[", "Object", ".", "keys", "(", "schema", ")", ".", "filter", "(", "function", "(", "i", ")", "{", "return", "i", "===", "name", ";", "}", ")", "[", "0", "]", "]", ";", "opts", "=", "merge", "(", "{", "}", ",", "opts", "||", "{", "}", ")", ";", "opts", ".", "name", "=", "op", ".", "newName", "||", "name", ";", "opts", ".", "type", "=", "op", ".", "type", "||", "opts", ".", "dbType", ";", "opts", ".", "allowNull", "=", "isUndefined", "(", "op", "[", "\"null\"", "]", ")", "?", "opts", ".", "allowNull", ":", "op", "[", "\"null\"", "]", ";", "opts", "[", "\"default\"", "]", "=", "op", "[", "\"default\"", "]", "||", "opts", ".", "jsDefault", ";", "if", "(", "isUndefinedOrNull", "(", "opts", "[", "\"default\"", "]", ")", ")", "{", "delete", "opts", "[", "\"default\"", "]", ";", "}", "return", "format", "(", "\"ALTER TABLE %s CHANGE COLUMN %s %s\"", ",", "self", ".", "__quoteSchemaTable", "(", "table", ")", ",", "self", ".", "__quoteIdentifier", "(", "op", ".", "name", ")", ",", "self", ".", "__columnDefinitionSql", "(", "merge", "(", "op", ",", "opts", ")", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "op", ".", "op", "===", "\"dropIndex\"", ")", "{", "ret", "=", "when", "(", "format", "(", "\"%s ON %s\"", ",", "this", ".", "__dropIndexSql", "(", "table", ",", "op", ")", ",", "this", ".", "__quoteSchemaTable", "(", "table", ")", ")", ")", ";", "}", "else", "{", "ret", "=", "this", ".", "_super", "(", "arguments", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Use MySQL specific syntax for rename column, set column type, and drop index cases.
[ "Use", "MySQL", "specific", "syntax", "for", "rename", "column", "set", "column", "type", "and", "drop", "index", "cases", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L565-L603
25,176
C2FO/patio
lib/adapters/mysql.js
function (conn, opts) { var self = this; return this.__setTransactionIsolation(conn, opts).chain(function () { return self.__logConnectionExecute(conn, self.beginTransactionSql); }); }
javascript
function (conn, opts) { var self = this; return this.__setTransactionIsolation(conn, opts).chain(function () { return self.__logConnectionExecute(conn, self.beginTransactionSql); }); }
[ "function", "(", "conn", ",", "opts", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "__setTransactionIsolation", "(", "conn", ",", "opts", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "self", ".", "__logConnectionExecute", "(", "conn", ",", "self", ".", "beginTransactionSql", ")", ";", "}", ")", ";", "}" ]
MySQL needs to set transaction isolation before beginning a transaction
[ "MySQL", "needs", "to", "set", "transaction", "isolation", "before", "beginning", "a", "transaction" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L606-L611
25,177
C2FO/patio
lib/adapters/mysql.js
function (column) { if (isString(column.type) && column.type.match(/string/i) && column.text) { delete column["default"]; } return this._super(arguments, [column]); }
javascript
function (column) { if (isString(column.type) && column.type.match(/string/i) && column.text) { delete column["default"]; } return this._super(arguments, [column]); }
[ "function", "(", "column", ")", "{", "if", "(", "isString", "(", "column", ".", "type", ")", "&&", "column", ".", "type", ".", "match", "(", "/", "string", "/", "i", ")", "&&", "column", ".", "text", ")", "{", "delete", "column", "[", "\"default\"", "]", ";", "}", "return", "this", ".", "_super", "(", "arguments", ",", "[", "column", "]", ")", ";", "}" ]
MySQL doesn't allow default values on text columns, so ignore if it the generic text type is used
[ "MySQL", "doesn", "t", "allow", "default", "values", "on", "text", "columns", "so", "ignore", "if", "it", "the", "generic", "text", "type", "is", "used" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L627-L632
25,178
C2FO/patio
lib/adapters/mysql.js
function (conn, opts) { opts = opts || {}; var s = opts.prepare, self = this; if (s) { return this.__logConnectionExecute(conn, comb("XA END %s").format(this.literal(s))).chain(function () { return self.__logConnectionExecute(comb("XA PREPARE %s").format(self.literal(s))); }); } else { return this._super(arguments); } }
javascript
function (conn, opts) { opts = opts || {}; var s = opts.prepare, self = this; if (s) { return this.__logConnectionExecute(conn, comb("XA END %s").format(this.literal(s))).chain(function () { return self.__logConnectionExecute(comb("XA PREPARE %s").format(self.literal(s))); }); } else { return this._super(arguments); } }
[ "function", "(", "conn", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "s", "=", "opts", ".", "prepare", ",", "self", "=", "this", ";", "if", "(", "s", ")", "{", "return", "this", ".", "__logConnectionExecute", "(", "conn", ",", "comb", "(", "\"XA END %s\"", ")", ".", "format", "(", "this", ".", "literal", "(", "s", ")", ")", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "self", ".", "__logConnectionExecute", "(", "comb", "(", "\"XA PREPARE %s\"", ")", ".", "format", "(", "self", ".", "literal", "(", "s", ")", ")", ")", ";", "}", ")", ";", "}", "else", "{", "return", "this", ".", "_super", "(", "arguments", ")", ";", "}", "}" ]
Prepare the XA transaction for a two-phase commit if the prepare option is given.
[ "Prepare", "the", "XA", "transaction", "for", "a", "two", "-", "phase", "commit", "if", "the", "prepare", "option", "is", "given", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L636-L646
25,179
C2FO/patio
lib/adapters/mysql.js
function (name, generator, options) { options = options || {}; var engine = options.engine, charset = options.charset, collate = options.collate; if (isUndefined(engine)) { engine = this._static.defaultEngine; } if (isUndefined(charset)) { charset = this._static.defaultCharset; } if (isUndefined(collate)) { collate = this._static.defaultCollate; } generator.columns.forEach(function (c) { var t = c.table; if (t) { delete c.table; generator.foreignKey([c.name], t, merge({}, c, {name: null, type: "foreignKey"})); } }); return format(" %s%s%s%s", this._super(arguments), engine ? " ENGINE=" + engine : "", charset ? " DEFAULT CHARSET=" + charset : "", collate ? " DEFAULT COLLATE=" + collate : ""); }
javascript
function (name, generator, options) { options = options || {}; var engine = options.engine, charset = options.charset, collate = options.collate; if (isUndefined(engine)) { engine = this._static.defaultEngine; } if (isUndefined(charset)) { charset = this._static.defaultCharset; } if (isUndefined(collate)) { collate = this._static.defaultCollate; } generator.columns.forEach(function (c) { var t = c.table; if (t) { delete c.table; generator.foreignKey([c.name], t, merge({}, c, {name: null, type: "foreignKey"})); } }); return format(" %s%s%s%s", this._super(arguments), engine ? " ENGINE=" + engine : "", charset ? " DEFAULT CHARSET=" + charset : "", collate ? " DEFAULT COLLATE=" + collate : ""); }
[ "function", "(", "name", ",", "generator", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "engine", "=", "options", ".", "engine", ",", "charset", "=", "options", ".", "charset", ",", "collate", "=", "options", ".", "collate", ";", "if", "(", "isUndefined", "(", "engine", ")", ")", "{", "engine", "=", "this", ".", "_static", ".", "defaultEngine", ";", "}", "if", "(", "isUndefined", "(", "charset", ")", ")", "{", "charset", "=", "this", ".", "_static", ".", "defaultCharset", ";", "}", "if", "(", "isUndefined", "(", "collate", ")", ")", "{", "collate", "=", "this", ".", "_static", ".", "defaultCollate", ";", "}", "generator", ".", "columns", ".", "forEach", "(", "function", "(", "c", ")", "{", "var", "t", "=", "c", ".", "table", ";", "if", "(", "t", ")", "{", "delete", "c", ".", "table", ";", "generator", ".", "foreignKey", "(", "[", "c", ".", "name", "]", ",", "t", ",", "merge", "(", "{", "}", ",", "c", ",", "{", "name", ":", "null", ",", "type", ":", "\"foreignKey\"", "}", ")", ")", ";", "}", "}", ")", ";", "return", "format", "(", "\" %s%s%s%s\"", ",", "this", ".", "_super", "(", "arguments", ")", ",", "engine", "?", "\" ENGINE=\"", "+", "engine", ":", "\"\"", ",", "charset", "?", "\" DEFAULT CHARSET=\"", "+", "charset", ":", "\"\"", ",", "collate", "?", "\" DEFAULT COLLATE=\"", "+", "collate", ":", "\"\"", ")", ";", "}" ]
Use MySQL specific syntax for engine type and character encoding
[ "Use", "MySQL", "specific", "syntax", "for", "engine", "type", "and", "character", "encoding" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L649-L670
25,180
C2FO/patio
lib/adapters/mysql.js
function (tableName, index) { var indexName = this.__quoteIdentifier(index.name || this.__defaultIndexName(tableName, index.columns)), t = index.type, using = ""; var indexType = ""; if (t === "fullText") { indexType = "FULLTEXT "; } else if (t === "spatial") { indexType = "SPATIAL "; } else { indexType = index.unique ? "UNIQUE " : ""; using = t ? " USING " + t : ""; } return format("CREATE %sINDEX %s%s ON %s %s", indexType, indexName, using, this.__quoteSchemaTable(tableName), this.literal(index.columns.map(function (c) { return isString(c) ? sql.identifier(c) : c; }))); }
javascript
function (tableName, index) { var indexName = this.__quoteIdentifier(index.name || this.__defaultIndexName(tableName, index.columns)), t = index.type, using = ""; var indexType = ""; if (t === "fullText") { indexType = "FULLTEXT "; } else if (t === "spatial") { indexType = "SPATIAL "; } else { indexType = index.unique ? "UNIQUE " : ""; using = t ? " USING " + t : ""; } return format("CREATE %sINDEX %s%s ON %s %s", indexType, indexName, using, this.__quoteSchemaTable(tableName), this.literal(index.columns.map(function (c) { return isString(c) ? sql.identifier(c) : c; }))); }
[ "function", "(", "tableName", ",", "index", ")", "{", "var", "indexName", "=", "this", ".", "__quoteIdentifier", "(", "index", ".", "name", "||", "this", ".", "__defaultIndexName", "(", "tableName", ",", "index", ".", "columns", ")", ")", ",", "t", "=", "index", ".", "type", ",", "using", "=", "\"\"", ";", "var", "indexType", "=", "\"\"", ";", "if", "(", "t", "===", "\"fullText\"", ")", "{", "indexType", "=", "\"FULLTEXT \"", ";", "}", "else", "if", "(", "t", "===", "\"spatial\"", ")", "{", "indexType", "=", "\"SPATIAL \"", ";", "}", "else", "{", "indexType", "=", "index", ".", "unique", "?", "\"UNIQUE \"", ":", "\"\"", ";", "using", "=", "t", "?", "\" USING \"", "+", "t", ":", "\"\"", ";", "}", "return", "format", "(", "\"CREATE %sINDEX %s%s ON %s %s\"", ",", "indexType", ",", "indexName", ",", "using", ",", "this", ".", "__quoteSchemaTable", "(", "tableName", ")", ",", "this", ".", "literal", "(", "index", ".", "columns", ".", "map", "(", "function", "(", "c", ")", "{", "return", "isString", "(", "c", ")", "?", "sql", ".", "identifier", "(", "c", ")", ":", "c", ";", "}", ")", ")", ")", ";", "}" ]
Handle MySQL specific index SQL syntax
[ "Handle", "MySQL", "specific", "index", "SQL", "syntax" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L673-L689
25,181
C2FO/patio
lib/adapters/mysql.js
function (conn, opts) { opts = opts || {}; var s = opts.prepare; var logConnectionExecute = comb("__logConnectionExecute"); if (s) { s = this.literal(s); var self = this; return this.__logConnectionExecute(conn, "XA END " + s) .chain(function () { return self.__logConnectionExecute(conn, "XA PREPARE " + s); }) .chain(function () { return self.__logConnectionExecute(conn, "XA ROLLBACK " + s); }); } else { return this._super(arguments); } }
javascript
function (conn, opts) { opts = opts || {}; var s = opts.prepare; var logConnectionExecute = comb("__logConnectionExecute"); if (s) { s = this.literal(s); var self = this; return this.__logConnectionExecute(conn, "XA END " + s) .chain(function () { return self.__logConnectionExecute(conn, "XA PREPARE " + s); }) .chain(function () { return self.__logConnectionExecute(conn, "XA ROLLBACK " + s); }); } else { return this._super(arguments); } }
[ "function", "(", "conn", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "s", "=", "opts", ".", "prepare", ";", "var", "logConnectionExecute", "=", "comb", "(", "\"__logConnectionExecute\"", ")", ";", "if", "(", "s", ")", "{", "s", "=", "this", ".", "literal", "(", "s", ")", ";", "var", "self", "=", "this", ";", "return", "this", ".", "__logConnectionExecute", "(", "conn", ",", "\"XA END \"", "+", "s", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "self", ".", "__logConnectionExecute", "(", "conn", ",", "\"XA PREPARE \"", "+", "s", ")", ";", "}", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "self", ".", "__logConnectionExecute", "(", "conn", ",", "\"XA ROLLBACK \"", "+", "s", ")", ";", "}", ")", ";", "}", "else", "{", "return", "this", ".", "_super", "(", "arguments", ")", ";", "}", "}" ]
Rollback the currently open XA transaction
[ "Rollback", "the", "currently", "open", "XA", "transaction" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L692-L709
25,182
C2FO/patio
lib/adapters/mysql.js
function (tableName, opts) { var m = this.outputIdentifierFunc, im = this.inputIdentifierFunc, self = this; return this.metadataDataset.withSql("DESCRIBE ?", sql.identifier(im(tableName))).map(function (row) { var ret = {}; var e = row[m("Extra")]; var allowNull = row[m("Null")]; var key = row[m("Key")]; ret.autoIncrement = e.match(/auto_increment/i) !== null; ret.allowNull = allowNull.match(/Yes/i) !== null; ret.primaryKey = key.match(/PRI/i) !== null; var defaultValue = row[m("Default")]; ret["default"] = Buffer.isBuffer(defaultValue) ? defaultValue.toString() : defaultValue; if (isEmpty(row["default"])) { row["default"] = null; } ret.dbType = row[m("Type")]; if (Buffer.isBuffer(ret.dbType)) { //handle case for field type being returned at 252 (i.e. BLOB) ret.dbType = ret.dbType.toString(); } ret.type = self.schemaColumnType(ret.dbType.toString("utf8")); var fieldName = m(row[m("Field")]); return [fieldName, ret]; }); }
javascript
function (tableName, opts) { var m = this.outputIdentifierFunc, im = this.inputIdentifierFunc, self = this; return this.metadataDataset.withSql("DESCRIBE ?", sql.identifier(im(tableName))).map(function (row) { var ret = {}; var e = row[m("Extra")]; var allowNull = row[m("Null")]; var key = row[m("Key")]; ret.autoIncrement = e.match(/auto_increment/i) !== null; ret.allowNull = allowNull.match(/Yes/i) !== null; ret.primaryKey = key.match(/PRI/i) !== null; var defaultValue = row[m("Default")]; ret["default"] = Buffer.isBuffer(defaultValue) ? defaultValue.toString() : defaultValue; if (isEmpty(row["default"])) { row["default"] = null; } ret.dbType = row[m("Type")]; if (Buffer.isBuffer(ret.dbType)) { //handle case for field type being returned at 252 (i.e. BLOB) ret.dbType = ret.dbType.toString(); } ret.type = self.schemaColumnType(ret.dbType.toString("utf8")); var fieldName = m(row[m("Field")]); return [fieldName, ret]; }); }
[ "function", "(", "tableName", ",", "opts", ")", "{", "var", "m", "=", "this", ".", "outputIdentifierFunc", ",", "im", "=", "this", ".", "inputIdentifierFunc", ",", "self", "=", "this", ";", "return", "this", ".", "metadataDataset", ".", "withSql", "(", "\"DESCRIBE ?\"", ",", "sql", ".", "identifier", "(", "im", "(", "tableName", ")", ")", ")", ".", "map", "(", "function", "(", "row", ")", "{", "var", "ret", "=", "{", "}", ";", "var", "e", "=", "row", "[", "m", "(", "\"Extra\"", ")", "]", ";", "var", "allowNull", "=", "row", "[", "m", "(", "\"Null\"", ")", "]", ";", "var", "key", "=", "row", "[", "m", "(", "\"Key\"", ")", "]", ";", "ret", ".", "autoIncrement", "=", "e", ".", "match", "(", "/", "auto_increment", "/", "i", ")", "!==", "null", ";", "ret", ".", "allowNull", "=", "allowNull", ".", "match", "(", "/", "Yes", "/", "i", ")", "!==", "null", ";", "ret", ".", "primaryKey", "=", "key", ".", "match", "(", "/", "PRI", "/", "i", ")", "!==", "null", ";", "var", "defaultValue", "=", "row", "[", "m", "(", "\"Default\"", ")", "]", ";", "ret", "[", "\"default\"", "]", "=", "Buffer", ".", "isBuffer", "(", "defaultValue", ")", "?", "defaultValue", ".", "toString", "(", ")", ":", "defaultValue", ";", "if", "(", "isEmpty", "(", "row", "[", "\"default\"", "]", ")", ")", "{", "row", "[", "\"default\"", "]", "=", "null", ";", "}", "ret", ".", "dbType", "=", "row", "[", "m", "(", "\"Type\"", ")", "]", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "ret", ".", "dbType", ")", ")", "{", "//handle case for field type being returned at 252 (i.e. BLOB)", "ret", ".", "dbType", "=", "ret", ".", "dbType", ".", "toString", "(", ")", ";", "}", "ret", ".", "type", "=", "self", ".", "schemaColumnType", "(", "ret", ".", "dbType", ".", "toString", "(", "\"utf8\"", ")", ")", ";", "var", "fieldName", "=", "m", "(", "row", "[", "m", "(", "\"Field\"", ")", "]", ")", ";", "return", "[", "fieldName", ",", "ret", "]", ";", "}", ")", ";", "}" ]
Use the MySQL specific DESCRIBE syntax to get a table description.
[ "Use", "the", "MySQL", "specific", "DESCRIBE", "syntax", "to", "get", "a", "table", "description", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/adapters/mysql.js#L717-L741
25,183
C2FO/patio
lib/dataset/actions.js
function (block, cb) { var self = this; var ret = asyncArray(this.forEach().chain(function (records) { return self.postLoad(records); })); if (block) { ret = ret.forEach(block); } return ret.classic(cb).promise(); }
javascript
function (block, cb) { var self = this; var ret = asyncArray(this.forEach().chain(function (records) { return self.postLoad(records); })); if (block) { ret = ret.forEach(block); } return ret.classic(cb).promise(); }
[ "function", "(", "block", ",", "cb", ")", "{", "var", "self", "=", "this", ";", "var", "ret", "=", "asyncArray", "(", "this", ".", "forEach", "(", ")", ".", "chain", "(", "function", "(", "records", ")", "{", "return", "self", ".", "postLoad", "(", "records", ")", ";", "}", ")", ")", ";", "if", "(", "block", ")", "{", "ret", "=", "ret", ".", "forEach", "(", "block", ")", ";", "}", "return", "ret", ".", "classic", "(", "cb", ")", ".", "promise", "(", ")", ";", "}" ]
Returns a Promise that is resolved with an array with all records in the dataset. If a block is given, the array is iterated over after all items have been loaded. @example // SELECT * FROM table DB.from("table").all().chain(function(res){ //res === [{id : 1, ...}, {id : 2, ...}, ...]; }); // Iterate over all rows in the table var myArr = []; var rowPromise = DB.from("table").all(function(row){ myArr.push(row);}); rowPromise.chain(function(rows){ //=> rows == myArr; }); @param {Function} block a block to be called with each item. The return value of the block is ignored. @param {Function} [cb] a block to invoke when the action is done @return {comb.Promise} a promise that is resolved with an array of rows.
[ "Returns", "a", "Promise", "that", "is", "resolved", "with", "an", "array", "with", "all", "records", "in", "the", "dataset", ".", "If", "a", "block", "is", "given", "the", "array", "is", "iterated", "over", "after", "all", "items", "have", "been", "loaded", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L121-L130
25,184
C2FO/patio
lib/dataset/actions.js
function (cb) { return this.__aggregateDataset().get(sql.COUNT(sql.literal("*")).as("count")).chain(function (res) { return parseInt(res, 10); }).classic(cb); }
javascript
function (cb) { return this.__aggregateDataset().get(sql.COUNT(sql.literal("*")).as("count")).chain(function (res) { return parseInt(res, 10); }).classic(cb); }
[ "function", "(", "cb", ")", "{", "return", "this", ".", "__aggregateDataset", "(", ")", ".", "get", "(", "sql", ".", "COUNT", "(", "sql", ".", "literal", "(", "\"*\"", ")", ")", ".", "as", "(", "\"count\"", ")", ")", ".", "chain", "(", "function", "(", "res", ")", "{", "return", "parseInt", "(", "res", ",", "10", ")", ";", "}", ")", ".", "classic", "(", "cb", ")", ";", "}" ]
Returns a promise that is resolved with the number of records in the dataset. @example // SELECT COUNT(*) AS count FROM table LIMIT 1 DB.from("table").count().chain(function(count){ //count === 3; }); @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is resolved with the the number of records in the dataset.
[ "Returns", "a", "promise", "that", "is", "resolved", "with", "the", "number", "of", "records", "in", "the", "dataset", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L166-L170
25,185
C2FO/patio
lib/dataset/actions.js
function (block, cb) { var rowCb, ret; if (this.__opts.graph) { ret = this.graphEach(block); } else { ret = this.fetchRows(this.selectSql); if ((rowCb = this.rowCb)) { ret = ret.map(function (r) { return rowCb(r); }); } if (block) { ret = ret.forEach(block); } } return ret.classic(cb); }
javascript
function (block, cb) { var rowCb, ret; if (this.__opts.graph) { ret = this.graphEach(block); } else { ret = this.fetchRows(this.selectSql); if ((rowCb = this.rowCb)) { ret = ret.map(function (r) { return rowCb(r); }); } if (block) { ret = ret.forEach(block); } } return ret.classic(cb); }
[ "function", "(", "block", ",", "cb", ")", "{", "var", "rowCb", ",", "ret", ";", "if", "(", "this", ".", "__opts", ".", "graph", ")", "{", "ret", "=", "this", ".", "graphEach", "(", "block", ")", ";", "}", "else", "{", "ret", "=", "this", ".", "fetchRows", "(", "this", ".", "selectSql", ")", ";", "if", "(", "(", "rowCb", "=", "this", ".", "rowCb", ")", ")", "{", "ret", "=", "ret", ".", "map", "(", "function", "(", "r", ")", "{", "return", "rowCb", "(", "r", ")", ";", "}", ")", ";", "}", "if", "(", "block", ")", "{", "ret", "=", "ret", ".", "forEach", "(", "block", ")", ";", "}", "}", "return", "ret", ".", "classic", "(", "cb", ")", ";", "}" ]
Iterates over the records in the dataset as they are returned from the database adapter. @example // SELECT * FROM table DB.from("table").forEach(function(row){ //....do something }); @param {Function} [block] the block to invoke for each row. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is resolved when the action has completed.
[ "Iterates", "over", "the", "records", "in", "the", "dataset", "as", "they", "are", "returned", "from", "the", "database", "adapter", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L214-L230
25,186
C2FO/patio
lib/dataset/actions.js
function (args) { args = comb(arguments).toArray(); var cb, block = isFunction(args[args.length - 1]) ? args.pop() : null; if (block && block.length > 0) { cb = block; block = isFunction(args[args.length - 1]) ? args.pop() : null; } var ds = block ? this.filter(block) : this; if (!args.length) { return ds.singleRecord(cb); } else { args = (args.length === 1) ? args[0] : args; if (isNumber(args)) { return ds.limit(args).all(null, cb); } else { return ds.filter(args).singleRecord(cb); } } }
javascript
function (args) { args = comb(arguments).toArray(); var cb, block = isFunction(args[args.length - 1]) ? args.pop() : null; if (block && block.length > 0) { cb = block; block = isFunction(args[args.length - 1]) ? args.pop() : null; } var ds = block ? this.filter(block) : this; if (!args.length) { return ds.singleRecord(cb); } else { args = (args.length === 1) ? args[0] : args; if (isNumber(args)) { return ds.limit(args).all(null, cb); } else { return ds.filter(args).singleRecord(cb); } } }
[ "function", "(", "args", ")", "{", "args", "=", "comb", "(", "arguments", ")", ".", "toArray", "(", ")", ";", "var", "cb", ",", "block", "=", "isFunction", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "args", ".", "pop", "(", ")", ":", "null", ";", "if", "(", "block", "&&", "block", ".", "length", ">", "0", ")", "{", "cb", "=", "block", ";", "block", "=", "isFunction", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "args", ".", "pop", "(", ")", ":", "null", ";", "}", "var", "ds", "=", "block", "?", "this", ".", "filter", "(", "block", ")", ":", "this", ";", "if", "(", "!", "args", ".", "length", ")", "{", "return", "ds", ".", "singleRecord", "(", "cb", ")", ";", "}", "else", "{", "args", "=", "(", "args", ".", "length", "===", "1", ")", "?", "args", "[", "0", "]", ":", "args", ";", "if", "(", "isNumber", "(", "args", ")", ")", "{", "return", "ds", ".", "limit", "(", "args", ")", ".", "all", "(", "null", ",", "cb", ")", ";", "}", "else", "{", "return", "ds", ".", "filter", "(", "args", ")", ".", "singleRecord", "(", "cb", ")", ";", "}", "}", "}" ]
If a integer argument is given, it is interpreted as a limit, and then returns all matching records up to that limit. If no arguments are passed, it returns the first matching record. If a function taking no arguments is passed in as the last parameter then it is assumed to be a filter block. If the a funciton is passed in that takes arguments then it is assumed to be a callback. You may also pass in both the second to last argument being a filter function, and the last being a callback. If any other type of argument(s) is passed, it is given to {@link patio.Dataset#filter} and the first matching record is returned. Examples: @example comb.executeInOrder(DB.from("table"), function(ds){ // SELECT * FROM table LIMIT 1 ds.first(); // => {id : 7} // SELECT * FROM table LIMIT 2 ds.first(2); // => [{id : 6}, {id : 4}] // SELECT * FROM table WHERE (id = 2) LIMIT 1 ds.first({id : 2}) // => {id : 2} // SELECT * FROM table WHERE (id = 3) LIMIT 1 ds.first("id = 3"); // => {id : 3} // SELECT * FROM table WHERE (id = 4) LIMIT 1 ds.first("id = ?", 4); // => {id : 4} // SELECT * FROM table WHERE (id > 2) LIMIT 1 ds.first(function(){return this.id.gt(2);}); // => {id : 5} // SELECT * FROM table WHERE ((id > 4) AND (id < 6)) LIMIT 1 ds.first("id > ?", 4, function(){ return this.id.lt(6); }); // => {id : 5} // SELECT * FROM table WHERE (id < 2) LIMIT 2 ds.first(2, function(){ return this.id.lt(2) }); // => [{id:1}] }); @param {*} args varargs to be used to limit/filter the result set. @return {comb.Promise} a promise that is resolved with the either the first matching record. Or an array of items if a limit was provided as the first argument.
[ "If", "a", "integer", "argument", "is", "given", "it", "is", "interpreted", "as", "a", "limit", "and", "then", "returns", "all", "matching", "records", "up", "to", "that", "limit", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L367-L387
25,187
C2FO/patio
lib/dataset/actions.js
function (columns, values, opts, cb) { if (isFunction(opts)) { cb = opts; opts = null; } opts = opts || {}; var ret, self = this; if (isInstanceOf(values, Dataset)) { ret = this.db.transaction(function () { return self.insert(columns, values); }); } else { if (!values.length) { ret = new Promise().callback(); } else if (!columns.length) { throw new QueryError("Invalid columns in import"); } var sliceSize = opts.commitEvery || opts.slice, result = []; if (sliceSize) { ret = asyncArray(partition(values, sliceSize)).forEach(function (entries, offset) { offset = (offset * sliceSize); return self.db.transaction(opts, function () { return when(self.multiInsertSql(columns, entries).map(function (st, index) { return self.executeDui(st).chain(function (res) { result[offset + index] = res; }); })); }); }, 1); } else { var statements = this.multiInsertSql(columns, values); ret = this.db.transaction(function () { return when(statements.map(function (st, index) { return self.executeDui(st).chain(function (res) { result[index] = res; }); })); }); } } return ret.chain(function () { return flatten(result); }).classic(cb).promise(); }
javascript
function (columns, values, opts, cb) { if (isFunction(opts)) { cb = opts; opts = null; } opts = opts || {}; var ret, self = this; if (isInstanceOf(values, Dataset)) { ret = this.db.transaction(function () { return self.insert(columns, values); }); } else { if (!values.length) { ret = new Promise().callback(); } else if (!columns.length) { throw new QueryError("Invalid columns in import"); } var sliceSize = opts.commitEvery || opts.slice, result = []; if (sliceSize) { ret = asyncArray(partition(values, sliceSize)).forEach(function (entries, offset) { offset = (offset * sliceSize); return self.db.transaction(opts, function () { return when(self.multiInsertSql(columns, entries).map(function (st, index) { return self.executeDui(st).chain(function (res) { result[offset + index] = res; }); })); }); }, 1); } else { var statements = this.multiInsertSql(columns, values); ret = this.db.transaction(function () { return when(statements.map(function (st, index) { return self.executeDui(st).chain(function (res) { result[index] = res; }); })); }); } } return ret.chain(function () { return flatten(result); }).classic(cb).promise(); }
[ "function", "(", "columns", ",", "values", ",", "opts", ",", "cb", ")", "{", "if", "(", "isFunction", "(", "opts", ")", ")", "{", "cb", "=", "opts", ";", "opts", "=", "null", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "var", "ret", ",", "self", "=", "this", ";", "if", "(", "isInstanceOf", "(", "values", ",", "Dataset", ")", ")", "{", "ret", "=", "this", ".", "db", ".", "transaction", "(", "function", "(", ")", "{", "return", "self", ".", "insert", "(", "columns", ",", "values", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "!", "values", ".", "length", ")", "{", "ret", "=", "new", "Promise", "(", ")", ".", "callback", "(", ")", ";", "}", "else", "if", "(", "!", "columns", ".", "length", ")", "{", "throw", "new", "QueryError", "(", "\"Invalid columns in import\"", ")", ";", "}", "var", "sliceSize", "=", "opts", ".", "commitEvery", "||", "opts", ".", "slice", ",", "result", "=", "[", "]", ";", "if", "(", "sliceSize", ")", "{", "ret", "=", "asyncArray", "(", "partition", "(", "values", ",", "sliceSize", ")", ")", ".", "forEach", "(", "function", "(", "entries", ",", "offset", ")", "{", "offset", "=", "(", "offset", "*", "sliceSize", ")", ";", "return", "self", ".", "db", ".", "transaction", "(", "opts", ",", "function", "(", ")", "{", "return", "when", "(", "self", ".", "multiInsertSql", "(", "columns", ",", "entries", ")", ".", "map", "(", "function", "(", "st", ",", "index", ")", "{", "return", "self", ".", "executeDui", "(", "st", ")", ".", "chain", "(", "function", "(", "res", ")", "{", "result", "[", "offset", "+", "index", "]", "=", "res", ";", "}", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}", ",", "1", ")", ";", "}", "else", "{", "var", "statements", "=", "this", ".", "multiInsertSql", "(", "columns", ",", "values", ")", ";", "ret", "=", "this", ".", "db", ".", "transaction", "(", "function", "(", ")", "{", "return", "when", "(", "statements", ".", "map", "(", "function", "(", "st", ",", "index", ")", "{", "return", "self", ".", "executeDui", "(", "st", ")", ".", "chain", "(", "function", "(", "res", ")", "{", "result", "[", "index", "]", "=", "res", ";", "}", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}", "}", "return", "ret", ".", "chain", "(", "function", "(", ")", "{", "return", "flatten", "(", "result", ")", ";", "}", ")", ".", "classic", "(", "cb", ")", ".", "promise", "(", ")", ";", "}" ]
Inserts multiple records into the associated table. This method can be used to efficiently insert a large number of records into a table in a single query if the database supports it. Inserts are automatically wrapped in a transaction. This method is called with a columns array and an array of value arrays: <pre class="code"> // INSERT INTO table (x, y) VALUES (1, 2) // INSERT INTO table (x, y) VALUES (3, 4) DB.from("table").import(["x", "y"], [[1, 2], [3, 4]]). </pre> This method also accepts a dataset instead of an array of value arrays: <pre class="code"> // INSERT INTO table (x, y) SELECT a, b FROM table2 DB.from("table").import(["x", "y"], DB.from("table2").select("a", "b")); </pre> The method also accepts a commitEvery option that specifies the number of records to insert per transaction. This is useful especially when inserting a large number of records, e.g.: <pre class="code"> // this will commit every 50 records DB.from("table").import(["x", "y"], [[1, 2], [3, 4], ...], {commitEvery : 50}); </pre> @param {Array} columns The columns to insert values for. This array will be used as the base for each values item in the values array. @param {Array[Array]} values Array of arrays of values to insert into the columns. @param {Object} [opts] options @param {Number} [opts.commitEvery] the number of records to insert per transaction. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is resolved once all records have been inserted.
[ "Inserts", "multiple", "records", "into", "the", "associated", "table", ".", "This", "method", "can", "be", "used", "to", "efficiently", "insert", "a", "large", "number", "of", "records", "into", "a", "table", "in", "a", "single", "query", "if", "the", "database", "supports", "it", ".", "Inserts", "are", "automatically", "wrapped", "in", "a", "transaction", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L459-L504
25,188
C2FO/patio
lib/dataset/actions.js
function () { var args = argsToArray(arguments); var cb = isFunction(args[args.length - 1]) ? args.pop() : null; return this.executeInsert(this.insertSql.apply(this, args)).classic(cb); }
javascript
function () { var args = argsToArray(arguments); var cb = isFunction(args[args.length - 1]) ? args.pop() : null; return this.executeInsert(this.insertSql.apply(this, args)).classic(cb); }
[ "function", "(", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ")", ";", "var", "cb", "=", "isFunction", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "args", ".", "pop", "(", ")", ":", "null", ";", "return", "this", ".", "executeInsert", "(", "this", ".", "insertSql", ".", "apply", "(", "this", ",", "args", ")", ")", ".", "classic", "(", "cb", ")", ";", "}" ]
Inserts values into the associated table. The returned value is generally the value of the primary key for the inserted row, but that is adapter dependent. @example // INSERT INTO items DEFAULT VALUES DB.from("items").insert() // INSERT INTO items DEFAULT VALUES DB.from("items").insert({}); // INSERT INTO items VALUES (1, 2, 3) DB.from("items").insert([1,2,3]); // INSERT INTO items (a, b) VALUES (1, 2) DB.from("items").insert(["a", "b"], [1,2]); // INSERT INTO items (a, b) VALUES (1, 2) DB.from("items").insert({a : 1, b : 2}); // INSERT INTO items SELECT * FROM old_items DB.from("items").insert(DB.from("old_items")); // INSERT INTO items (a, b) SELECT * FROM old_items DB.from("items").insert(["a", "b"], DB.from("old_items")); @param {patio.Dataset|patio.sql.LiteralString|Array|Object|patio.sql.BooleanExpression|...} values values to insert into the database. The INSERT statement generated depends on the type. <ul> <li>Empty object| Or no arugments: then DEFAULT VALUES is used.</li> <li>Object: the keys will be used as the columns, and values will be the values inserted.</li> <li>Single {@link patio.Dataset} : an insert with subselect will be performed.</li> <li>Array with {@link patio.Dataset} : The array will be used for columns and a subselect will performed with the dataset for the values.</li> <li>{@link patio.sql.LiteralString} : the literal value will be used.</li> <li>Single Array : the values in the array will be used as the VALUES clause.</li> <li>Two Arrays: the first array is the columns the second array is the values.</li> <li>{@link patio.sql.BooleanExpression} : the expression will be used as the values. <li>An arbitrary number of arguments : the {@link patio.Dataset#literal} version of the values will be used</li> </ul> @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is typically resolved with the ID of the inserted row.
[ "Inserts", "values", "into", "the", "associated", "table", ".", "The", "returned", "value", "is", "generally", "the", "value", "of", "the", "primary", "key", "for", "the", "inserted", "row", "but", "that", "is", "adapter", "dependent", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L604-L608
25,189
C2FO/patio
lib/dataset/actions.js
function (column, cb) { return this.__aggregateDataset().get(sql.max(column).minus(sql.min(column)), cb); }
javascript
function (column, cb) { return this.__aggregateDataset().get(sql.max(column).minus(sql.min(column)), cb); }
[ "function", "(", "column", ",", "cb", ")", "{", "return", "this", ".", "__aggregateDataset", "(", ")", ".", "get", "(", "sql", ".", "max", "(", "column", ")", ".", "minus", "(", "sql", ".", "min", "(", "column", ")", ")", ",", "cb", ")", ";", "}" ]
Returns a promise that is resolved with the interval between minimum and maximum values for the given column. @example // SELECT (max(id) - min(id)) FROM table LIMIT 1 DB.from("table").interval("id").chain(function(interval){ //(e.g) interval === 6 }); @param {String|patio.sql.Identifier} column to find the interval of. @param {Function} [cb] a function to be called when the aciton is complete @return {comb.Promise} a promise that will be resolved with the interval between the min and max values of the column.
[ "Returns", "a", "promise", "that", "is", "resolved", "with", "the", "interval", "between", "minimum", "and", "maximum", "values", "for", "the", "given", "column", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L680-L682
25,190
C2FO/patio
lib/dataset/actions.js
function (args) { if (!this.__opts.order) { throw new QueryError("No order specified"); } var ds = this.reverse(); return ds.first.apply(ds, arguments); }
javascript
function (args) { if (!this.__opts.order) { throw new QueryError("No order specified"); } var ds = this.reverse(); return ds.first.apply(ds, arguments); }
[ "function", "(", "args", ")", "{", "if", "(", "!", "this", ".", "__opts", ".", "order", ")", "{", "throw", "new", "QueryError", "(", "\"No order specified\"", ")", ";", "}", "var", "ds", "=", "this", ".", "reverse", "(", ")", ";", "return", "ds", ".", "first", ".", "apply", "(", "ds", ",", "arguments", ")", ";", "}" ]
Reverses the order and then runs first. Note that this will not necessarily give you the last record in the dataset, unless you have an unambiguous order. @example // SELECT * FROM table ORDER BY id DESC LIMIT 1 DB.from("table").order("id").last().chain(function(lastItem){ //...(e.g lastItem === {id : 10}) }); // SELECT * FROM table ORDER BY id ASC LIMIT 2 DB.from("table").order(sql.id.desc()).last(2).chain(function(lastItems){ //...(e.g lastItems === [{id : 1}, {id : 2}); }); @throws {patio.error.QueryError} If there is not currently an order for this dataset. @param {*} args See {@link patio.Dataset#first} for argument types. @return {comb.Promise} a promise that will be resolved with a single object or array depending on the arguments provided.
[ "Reverses", "the", "order", "and", "then", "runs", "first", ".", "Note", "that", "this", "will", "not", "necessarily", "give", "you", "the", "last", "record", "in", "the", "dataset", "unless", "you", "have", "an", "unambiguous", "order", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L708-L714
25,191
C2FO/patio
lib/dataset/actions.js
function (column, cb) { var ret = new Promise(); this.__aggregateDataset() .select(sql.min(this.stringToIdentifier(column)).as("v1"), sql.max(this.stringToIdentifier(column)).as("v2")) .first() .chain(function (r) { ret.callback(r.v1, r.v2); }, ret.errback); return ret.classic(cb).promise(); }
javascript
function (column, cb) { var ret = new Promise(); this.__aggregateDataset() .select(sql.min(this.stringToIdentifier(column)).as("v1"), sql.max(this.stringToIdentifier(column)).as("v2")) .first() .chain(function (r) { ret.callback(r.v1, r.v2); }, ret.errback); return ret.classic(cb).promise(); }
[ "function", "(", "column", ",", "cb", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ";", "this", ".", "__aggregateDataset", "(", ")", ".", "select", "(", "sql", ".", "min", "(", "this", ".", "stringToIdentifier", "(", "column", ")", ")", ".", "as", "(", "\"v1\"", ")", ",", "sql", ".", "max", "(", "this", ".", "stringToIdentifier", "(", "column", ")", ")", ".", "as", "(", "\"v2\"", ")", ")", ".", "first", "(", ")", ".", "chain", "(", "function", "(", "r", ")", "{", "ret", ".", "callback", "(", "r", ".", "v1", ",", "r", ".", "v2", ")", ";", "}", ",", "ret", ".", "errback", ")", ";", "return", "ret", ".", "classic", "(", "cb", ")", ".", "promise", "(", ")", ";", "}" ]
Returns a promise resolved with a range from the minimum and maximum values for the given column. @example // SELECT max(id) AS v1, min(id) AS v2 FROM table LIMIT 1 DB.from("table").range("id").chain(function(min, max){ //e.g min === 1 AND max === 10 }); @param {String|patio.sql.Identifier} column the column to find the min and max value for. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is resolved with the min and max value, as the first and second args respectively.
[ "Returns", "a", "promise", "resolved", "with", "a", "range", "from", "the", "minimum", "and", "maximum", "values", "for", "the", "given", "column", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L804-L813
25,192
C2FO/patio
lib/dataset/actions.js
function (includeColumnTitles, cb) { var n = this.naked(); if (isFunction(includeColumnTitles)) { cb = includeColumnTitles; includeColumnTitles = true; } includeColumnTitles = isBoolean(includeColumnTitles) ? includeColumnTitles : true; return n.columns.chain(function (cols) { var vals = []; if (includeColumnTitles) { vals.push(cols.join(", ")); } return n.forEach(function (r) { vals.push(cols.map(function (c) { return r[c] || ""; }).join(", ")); }).chain(function () { return vals.join("\r\n") + "\r\n"; }); }.bind(this)).classic(cb).promise(); }
javascript
function (includeColumnTitles, cb) { var n = this.naked(); if (isFunction(includeColumnTitles)) { cb = includeColumnTitles; includeColumnTitles = true; } includeColumnTitles = isBoolean(includeColumnTitles) ? includeColumnTitles : true; return n.columns.chain(function (cols) { var vals = []; if (includeColumnTitles) { vals.push(cols.join(", ")); } return n.forEach(function (r) { vals.push(cols.map(function (c) { return r[c] || ""; }).join(", ")); }).chain(function () { return vals.join("\r\n") + "\r\n"; }); }.bind(this)).classic(cb).promise(); }
[ "function", "(", "includeColumnTitles", ",", "cb", ")", "{", "var", "n", "=", "this", ".", "naked", "(", ")", ";", "if", "(", "isFunction", "(", "includeColumnTitles", ")", ")", "{", "cb", "=", "includeColumnTitles", ";", "includeColumnTitles", "=", "true", ";", "}", "includeColumnTitles", "=", "isBoolean", "(", "includeColumnTitles", ")", "?", "includeColumnTitles", ":", "true", ";", "return", "n", ".", "columns", ".", "chain", "(", "function", "(", "cols", ")", "{", "var", "vals", "=", "[", "]", ";", "if", "(", "includeColumnTitles", ")", "{", "vals", ".", "push", "(", "cols", ".", "join", "(", "\", \"", ")", ")", ";", "}", "return", "n", ".", "forEach", "(", "function", "(", "r", ")", "{", "vals", ".", "push", "(", "cols", ".", "map", "(", "function", "(", "c", ")", "{", "return", "r", "[", "c", "]", "||", "\"\"", ";", "}", ")", ".", "join", "(", "\", \"", ")", ")", ";", "}", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "vals", ".", "join", "(", "\"\\r\\n\"", ")", "+", "\"\\r\\n\"", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ".", "classic", "(", "cb", ")", ".", "promise", "(", ")", ";", "}" ]
Returns a promise resolved with a string in CSV format containing the dataset records. By default the CSV representation includes the column titles in the first line. You can turn that off by passing false as the includeColumnTitles argument. <p> <b>NOTE:</b> This does not use a CSV library or handle quoting of values in any way. If any values in any of the rows could include commas or line endings, you shouldn't use this. </p> @example // SELECT * FROM table DB.from("table").toCsv().chain(function(csv){ console.log(csv); //outputs id,name 1,Jim 2,Bob }); // SELECT * FROM table DB.from("table").toCsv(false).chain(function(csv){ console.log(csv); //outputs 1,Jim 2,Bob }); @param {Boolean} [includeColumnTitles=true] Set to false to prevent the printing of the column titles as the first line. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that will be resolved with the CSV string of the results of the query.
[ "Returns", "a", "promise", "resolved", "with", "a", "string", "in", "CSV", "format", "containing", "the", "dataset", "records", ".", "By", "default", "the", "CSV", "representation", "includes", "the", "column", "titles", "in", "the", "first", "line", ".", "You", "can", "turn", "that", "off", "by", "passing", "false", "as", "the", "includeColumnTitles", "argument", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L1007-L1027
25,193
C2FO/patio
lib/ConnectionPool.js
function () { var fc = this.freeCount, def, defQueue = this.__deferredQueue; while (fc-- >= 0 && defQueue.count) { def = defQueue.dequeue(); var conn = this.getObject(); if (conn) { def.callback(conn); } else { throw new Error("UNEXPECTED ERROR"); } fc--; } }
javascript
function () { var fc = this.freeCount, def, defQueue = this.__deferredQueue; while (fc-- >= 0 && defQueue.count) { def = defQueue.dequeue(); var conn = this.getObject(); if (conn) { def.callback(conn); } else { throw new Error("UNEXPECTED ERROR"); } fc--; } }
[ "function", "(", ")", "{", "var", "fc", "=", "this", ".", "freeCount", ",", "def", ",", "defQueue", "=", "this", ".", "__deferredQueue", ";", "while", "(", "fc", "--", ">=", "0", "&&", "defQueue", ".", "count", ")", "{", "def", "=", "defQueue", ".", "dequeue", "(", ")", ";", "var", "conn", "=", "this", ".", "getObject", "(", ")", ";", "if", "(", "conn", ")", "{", "def", ".", "callback", "(", "conn", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"UNEXPECTED ERROR\"", ")", ";", "}", "fc", "--", ";", "}", "}" ]
Checks all deferred connection requests.
[ "Checks", "all", "deferred", "connection", "requests", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L41-L53
25,194
C2FO/patio
lib/ConnectionPool.js
function () { var ret = new Promise(), conn; if (this.count > this.__maxObjects) { this.__deferredQueue.enqueue(ret); } else { //todo override getObject to make async so creating a connetion can execute setup sql conn = this.getObject(); if (!conn) { //we need to deffer it this.__deferredQueue.enqueue(ret); } else { ret.callback(conn); } } if (this.count > this.__maxObjects && !conn) { ret.errback(new Error("Unexpected ConnectionPool error")); } return ret.promise(); }
javascript
function () { var ret = new Promise(), conn; if (this.count > this.__maxObjects) { this.__deferredQueue.enqueue(ret); } else { //todo override getObject to make async so creating a connetion can execute setup sql conn = this.getObject(); if (!conn) { //we need to deffer it this.__deferredQueue.enqueue(ret); } else { ret.callback(conn); } } if (this.count > this.__maxObjects && !conn) { ret.errback(new Error("Unexpected ConnectionPool error")); } return ret.promise(); }
[ "function", "(", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ",", "conn", ";", "if", "(", "this", ".", "count", ">", "this", ".", "__maxObjects", ")", "{", "this", ".", "__deferredQueue", ".", "enqueue", "(", "ret", ")", ";", "}", "else", "{", "//todo override getObject to make async so creating a connetion can execute setup sql", "conn", "=", "this", ".", "getObject", "(", ")", ";", "if", "(", "!", "conn", ")", "{", "//we need to deffer it", "this", ".", "__deferredQueue", ".", "enqueue", "(", "ret", ")", ";", "}", "else", "{", "ret", ".", "callback", "(", "conn", ")", ";", "}", "}", "if", "(", "this", ".", "count", ">", "this", ".", "__maxObjects", "&&", "!", "conn", ")", "{", "ret", ".", "errback", "(", "new", "Error", "(", "\"Unexpected ConnectionPool error\"", ")", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Performs a query on one of the connection in this Pool. @return {comb.Promise} A promise to called back with a connection.
[ "Performs", "a", "query", "on", "one", "of", "the", "connection", "in", "this", "Pool", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L60-L78
25,195
C2FO/patio
lib/ConnectionPool.js
function (obj) { var self = this; this.validate(obj).chain(function (valid) { var index; if (self.count <= self.__maxObjects && valid && (index = self.__inUseObjects.indexOf(obj)) > -1) { self.__inUseObjects.splice(index, 1); self.__freeObjects.enqueue(obj); self.__checkQueries(); } else { self.removeObject(obj); } }); }
javascript
function (obj) { var self = this; this.validate(obj).chain(function (valid) { var index; if (self.count <= self.__maxObjects && valid && (index = self.__inUseObjects.indexOf(obj)) > -1) { self.__inUseObjects.splice(index, 1); self.__freeObjects.enqueue(obj); self.__checkQueries(); } else { self.removeObject(obj); } }); }
[ "function", "(", "obj", ")", "{", "var", "self", "=", "this", ";", "this", ".", "validate", "(", "obj", ")", ".", "chain", "(", "function", "(", "valid", ")", "{", "var", "index", ";", "if", "(", "self", ".", "count", "<=", "self", ".", "__maxObjects", "&&", "valid", "&&", "(", "index", "=", "self", ".", "__inUseObjects", ".", "indexOf", "(", "obj", ")", ")", ">", "-", "1", ")", "{", "self", ".", "__inUseObjects", ".", "splice", "(", "index", ",", "1", ")", ";", "self", ".", "__freeObjects", ".", "enqueue", "(", "obj", ")", ";", "self", ".", "__checkQueries", "(", ")", ";", "}", "else", "{", "self", ".", "removeObject", "(", "obj", ")", ";", "}", "}", ")", ";", "}" ]
Override comb.collections.Pool to allow async validation to allow pools to do any calls to reset a connection if it needs to be done. @param {*} connection the connection to return.
[ "Override", "comb", ".", "collections", ".", "Pool", "to", "allow", "async", "validation", "to", "allow", "pools", "to", "do", "any", "calls", "to", "reset", "a", "connection", "if", "it", "needs", "to", "be", "done", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L87-L99
25,196
C2FO/patio
lib/ConnectionPool.js
function () { this.__ending = true; var conn, fQueue = this.__freeObjects, count = this.count, ps = []; while ((conn = this.__freeObjects.dequeue()) !== undefined) { ps.push(this.closeConnection(conn)); } var inUse = this.__inUseObjects; for (var i = inUse.length - 1; i >= 0; i--) { ps.push(this.closeConnection(inUse[i])); } this.__inUseObjects.length = 0; return new PromiseList(ps).promise(); }
javascript
function () { this.__ending = true; var conn, fQueue = this.__freeObjects, count = this.count, ps = []; while ((conn = this.__freeObjects.dequeue()) !== undefined) { ps.push(this.closeConnection(conn)); } var inUse = this.__inUseObjects; for (var i = inUse.length - 1; i >= 0; i--) { ps.push(this.closeConnection(inUse[i])); } this.__inUseObjects.length = 0; return new PromiseList(ps).promise(); }
[ "function", "(", ")", "{", "this", ".", "__ending", "=", "true", ";", "var", "conn", ",", "fQueue", "=", "this", ".", "__freeObjects", ",", "count", "=", "this", ".", "count", ",", "ps", "=", "[", "]", ";", "while", "(", "(", "conn", "=", "this", ".", "__freeObjects", ".", "dequeue", "(", ")", ")", "!==", "undefined", ")", "{", "ps", ".", "push", "(", "this", ".", "closeConnection", "(", "conn", ")", ")", ";", "}", "var", "inUse", "=", "this", ".", "__inUseObjects", ";", "for", "(", "var", "i", "=", "inUse", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "ps", ".", "push", "(", "this", ".", "closeConnection", "(", "inUse", "[", "i", "]", ")", ")", ";", "}", "this", ".", "__inUseObjects", ".", "length", "=", "0", ";", "return", "new", "PromiseList", "(", "ps", ")", ".", "promise", "(", ")", ";", "}" ]
Override to implement the closing of all connections. @return {comb.Promise} called when all connections are closed.
[ "Override", "to", "implement", "the", "closing", "of", "all", "connections", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L130-L142
25,197
C2FO/patio
lib/ConnectionPool.js
function (conn) { if (!this.__validateConnectionCB) { var ret = new Promise(); ret.callback(true); return ret; } else { return this.__validateConnectionCB(conn); } }
javascript
function (conn) { if (!this.__validateConnectionCB) { var ret = new Promise(); ret.callback(true); return ret; } else { return this.__validateConnectionCB(conn); } }
[ "function", "(", "conn", ")", "{", "if", "(", "!", "this", ".", "__validateConnectionCB", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ";", "ret", ".", "callback", "(", "true", ")", ";", "return", "ret", ";", "}", "else", "{", "return", "this", ".", "__validateConnectionCB", "(", "conn", ")", ";", "}", "}" ]
Override to provide any additional validation. By default the promise is called back with true. @param {*} connection the conneciton to validate. @return {comb.Promise} called back with a valid or invalid state.
[ "Override", "to", "provide", "any", "additional", "validation", ".", "By", "default", "the", "promise", "is", "called", "back", "with", "true", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L152-L160
25,198
C2FO/patio
lib/dataset/index.js
function (s) { var ret, m; if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) { ret = m.slice(1); } else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) { ret = [null, m[1], m[2]]; } else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) { ret = [m[1], m[2], null]; } else { ret = [null, s, null]; } return ret; }
javascript
function (s) { var ret, m; if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) { ret = m.slice(1); } else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) { ret = [null, m[1], m[2]]; } else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) { ret = [m[1], m[2], null]; } else { ret = [null, s, null]; } return ret; }
[ "function", "(", "s", ")", "{", "var", "ret", ",", "m", ";", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE1", ")", ")", "!==", "null", ")", "{", "ret", "=", "m", ".", "slice", "(", "1", ")", ";", "}", "else", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE2", ")", ")", "!==", "null", ")", "{", "ret", "=", "[", "null", ",", "m", "[", "1", "]", ",", "m", "[", "2", "]", "]", ";", "}", "else", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE3", ")", ")", "!==", "null", ")", "{", "ret", "=", "[", "m", "[", "1", "]", ",", "m", "[", "2", "]", ",", "null", "]", ";", "}", "else", "{", "ret", "=", "[", "null", ",", "s", ",", "null", "]", ";", "}", "return", "ret", ";", "}" ]
Can either be a string or null. @example //columns table__column___alias //=> table.column as alias table__column //=> table.column //tables schema__table___alias //=> schema.table as alias schema__table //=> schema.table //name and alias columnOrTable___alias //=> columnOrTable as alias @return {String[]} an array with the elements being: <ul> <li>For columns :[table, column, alias].</li> <li>For tables : [schema, table, alias].</li> </ul>
[ "Can", "either", "be", "a", "string", "or", "null", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/index.js#L348-L363
25,199
C2FO/patio
lib/associations/oneToMany.js
function () { var model; try { model = this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db)); } catch (e) { model = this["__model__"] = this.patio.getModel(this.name, this.parent.db); } return model; }
javascript
function () { var model; try { model = this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db)); } catch (e) { model = this["__model__"] = this.patio.getModel(this.name, this.parent.db); } return model; }
[ "function", "(", ")", "{", "var", "model", ";", "try", "{", "model", "=", "this", "[", "\"__model__\"", "]", "||", "(", "this", "[", "\"__model__\"", "]", "=", "this", ".", "patio", ".", "getModel", "(", "this", ".", "_model", ",", "this", ".", "parent", ".", "db", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "model", "=", "this", "[", "\"__model__\"", "]", "=", "this", ".", "patio", ".", "getModel", "(", "this", ".", "name", ",", "this", ".", "parent", ".", "db", ")", ";", "}", "return", "model", ";", "}" ]
Returns our model
[ "Returns", "our", "model" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/oneToMany.js#L355-L363