Class that is used for querying/retrieving datasets from a database.

Dynamically generated methods include

Features:

Features that a particular patio.Dataset supports are shown in the example below. If you wish to implement an adapter please override these values depending on the database that you are developing the adapter for.

         var ds = DB.from("test");

         //The default values returned

         //Whether this dataset quotes identifiers.
         //Whether this dataset quotes identifiers.
         ds.quoteIdentifiers //=>true

         //Whether this dataset will provide accurate number of rows matched for
         //delete and update statements.  Accurate in this case is the number of
         //rows matched by the dataset's filter.
         ds.providesAccurateRowsMatched; //=>true

         //Times Whether the dataset requires SQL standard datetimes (false by default,
         // as most allow strings with ISO 8601 format).
         ds.requiresSqlStandardDate; //=>false

         //Whether the dataset supports common table expressions (the WITH clause).
         ds.supportsCte; //=>true

         //Whether the dataset supports the DISTINCT ON clause, false by default.
         ds.supportsDistinctOn; //=>false

         //Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default.
         ds.supportsIntersectExcept; //=>true

         //Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default
         ds.supportsIntersectExceptAll; //=>true

         //Whether the dataset supports the IS TRUE syntax.
         ds.supportsIsTrue; //=>true

         //Whether the dataset supports the JOIN table USING (column1, ...) syntax.
         ds.supportsJoinUsing; //=>true

         //Whether modifying joined datasets is supported.
         ds.supportsModifyingJoin; //=>false

         //Whether the IN/NOT IN operators support multiple columns when an
         ds.supportsMultipleColumnIn; //=>true

         //Whether the dataset supports timezones in literal timestamps
         ds.supportsTimestampTimezone; //=>false

         //Whether the dataset supports fractional seconds in literal timestamps
         ds.supportsTimestampUsecs; //=>true

         //Whether the dataset supports window functions.
         ds.supportsWindowFunctions; //=>false
      

Actions

Each dataset does not actually send any query to the database until an action method has been called upon it(with the exception of patio.Dataset#graph because columns from the other table might need retrived in order to set up the graph). Each action returns a comb.Promise that will be resolved with the result or errback, it is important that you account for errors otherwise it can be difficult to track down issues. The list of action methods is:

Static Properties
PropertyTypeDefault ValueDescription
ACTION_METHODSString[] ['all', 'one', 'avg', 'count', 'columns', 'remove', 'forEach', 'isEmpty', 'first', 'get', 'import', 'insert', 'save', 'insertMultiple', 'saveMultiple', 'interval', 'last', 'map', 'max', 'min', 'multiInsert', 'range', 'selectHash', 'selectMap', 'selectOrderMap', 'set', 'singleRecord', 'singleValue', 'sum', 'toCsv', 'toHash', 'truncate', 'update', 'stream']

List of action methods avaiable on the dataset.

AND_SEPARATORproperty" AND "

Default SQL AND separator.

BOOL_FALSEproperty"'f'"

Default SQL boolean false operator.

BOOL_TRUEproperty"'t'"

Default SQL boolean true operator.

COLUMN_CHANGE_OPTSproperty["select", "sql", "from", "join"]

The dataset options that require the removal of cached columns if changed.

COMMA_SEPARATORproperty'

Default SQL comma sperator.

CONDITIONED_JOIN_TYPESproperty["inner", "fullOuter", "rightOuter", "leftOuter", "full", "right", "left"]

These strings have {name}Join methods created (e.g. patio.Dataset#innerJoin) that call patio.Dataset#joinTable with the string, passing along the arguments and block from the method call.

COUNT_FROM_SELF_OPTSString[] ["distinct", "group", "sql", "limit", "compounds"]

List of options that can interfere with the aggregation of a patio.Dataset

COUNT_OF_ALL_AS_COUNTpropertysql.count(sql.literal('*')).as("count")

Default COUNT expression.

DATASET_ALIAS_BASE_NAMEproperty't'

Default alias for datasets.

DELETE_CLAUSE_METHODSpropertyclauseMethods("delete"

Default SQL DELETE clause methods. This may be overrode by adapters.

FEATURESproperty ["quoteIdentifiers","providesAccurateRowsMatched","requiresSqlStandardDateTimes","supportsCte", "supportsDistinctOn","supportsIntersectExcept","supportsIntersectExceptAll","supportsIsTrue","supportsJoinUsing", "supportsModifyingJoins","supportsMultipleColumnIn","supportsTimestampTimezones","supportsTimestampUsecs", "supportsWindowFunctions"] Array of features.
FOR_UPDATEproperty' FOR UPDATE'

Default FOR UPDATE SQL fragment.

FROMproperty"FROM"

Default FROM clause

INSERT_CLAUSE_METHODSpropertyclauseMethods("insert"

Default SQL INSERT clause. This may be overrode by adapters.

IS_LITERALSproperty{NULL: 'NULL', true: 'TRUE', false: 'FALSE'}

Hash of IS literals

IS_OPERATORSpropertyComplexExpression.IS_OPERATORS

Defaults IS OPERATORS. See patio.sql.ComplexExpression.IS_OPERATORS.

JOIN_METHODSproperty["join", "joinTable"]

All methods that return modified datasets with a joined table added.

NON_SQL_OPTIONSproperty["server", "defaults", "overrides", "graph", "eagerGraph", "graphAliases"]

Which options don't affect the SQL generation. Used by patio.Dataset#simpleSelectAll to determine if this is a simple SELECT * FROM table.

NULLproperty"NULL"

Defaults SQL NULL.

N_ARITY_OPERATORSpropertyComplexExpression.N_ARITY_OPERATORS

Defaults N(Multi arity) OPERATORS. See patio.sql.ComplexExpression.N_ARITY_OPERATORS.

QUALIFY_KEYSproperty["select", "where", "having", "order", "group"]

Default SQL clauses that need qualifying. This may be overrode by adapters.

QUERY_METHODSproperty['addGraphAliases', "and", "distinct", "eager", "except", "exclude", "filter", "find", "is", "isNot", "eq", "neq", "lt", "lte", "gt", "gte", "forUpdate", "from", "fromSelf", "graph", "grep", "group", "groupAndCount", "groupBy", "having", "intersect", "invert", "limit", "lockStyle", "naked", "or", "order", "orderAppend", "orderBy", "orderMore", "orderPrepend", "qualify", "reverse", "reverseOrder", "select", "selectAll", "selectAppend", "selectMore", "setDefaults", "setGraphAliases", "setOverrides", "unfiltered", "ungraphed", "ungrouped", "union", "unlimited", "unordered", "where", "with", "withRecursive", "withSql"]

Methods that return modified datasets

QUESTION_MARKproperty/\?/g

Regexp used to replace '?' in patio.sql.PlaceHolderLiteralString

RETURNINGproperty" RETURNING "

Default SQL 'RETURNING' literal string

SELECT_CLAUSE_METHODSpropertyclauseMethods("select"

Default SQL SELECT clause. This may be overrode by adapters.

SPACEproperty" "

Default space to use when building SQL queries

SQL_WITHproperty"WITH"

Default SQL WITH base. This may be overrode by adapters.

TWO_ARITY_OPERATORSpropertyComplexExpression.TWO_ARITY_OPERATORS

Defaults TWO OPERATORS. See patio.sql.ComplexExpression.TWO_ARITY_OPERATORS.

UNCONDITIONED_JOIN_TYPESproperty["natural", "naturalLeft", "naturalRight", "naturalFull", "cross"]

These strings have {name}Join methods created (e.g. naturalJoin) that call patio.Dataset#joinTable. They only accept a single table argument which is passed to patio.Dataset#joinTable, and they throw an error if called with a block.

UPDATE_CLAUSE_METHODSpropertyclauseMethods("update"

Default SQL UPDATE clause. This may be overrode by adapters.

WILDCARDpropertynew LiteralString('*')

Default SQL '*' literal string.

Instance Properties
PropertyTypeDefault ValueDescription
columns{comb.Promise} Returns a promise that is resolved with the columns in the result set in order as an array of strings. If the columns are currently cached, then the promise is immediately resolved with the cached value. Otherwise, a SELECT query is performed to retrieve a single row in order to get the columns. If you are looking for all columns for a single table and maybe some information about each column (e.g. database type), see {@link patio.Database#schema}.
 DB.from("table").columns.chain(function(columns){
       // => ["id", "name"]
  });
function (){ if (this.__columns) { return asyncArray(this.__columns); } else { var ds = this.unfiltered().unordered().mergeOptions({distinct: null, limit: 1}); return asyncArray(ds.forEach().chain(function () { var columns = this.__columns = ds.__columns || []; return columns; }.bind(this))); } }
firstSourceAliasString

The first source (primary table) for this dataset. If the table is aliased, returns the aliased name. throws a {patio.DatasetError} tf the dataset doesn't have a table.

   DB.from("table").firstSourceAlias;   //=> "table"    DB.from("table___t").firstSourceAlias;   //=> "t" 

firstSourceTableString

The first source (primary table) for this dataset. If the dataset doesn't have a table, raises a patio.erros.DatasetError.

   DB.from("table").firstSourceTable;         //=> "table"   DB.from("table___t").firstSourceTable;         //=> "t" 

hasSelectSourceBoolean

true if this dataset already has a select sources.

identifierInputMethodString

this is the method that will be called on each identifier returned from the database. This value will be defaulted to whatever the identifierInputMethod is on the database used in initialization.

identifierOutputMethodString

this is the method that will be called on each identifier sent to the database. This value will be defaulted to whatever the identifierOutputMethod is on the database used in initialization.

isSimpleSelectAllBoolean

Returns true if this dataset is a simple SELECT * FROM {table}, otherwise false.

     DB.from("items").isSimpleSelectAll; //=> true     DB.from("items").filter({a : 1}).isSimpleSelectAll; //=> false 

joinSourceListpatio.sql.Identifier[][]

a list of join sources

providesAccurateRowsMatchedbooleantrue

Whether this dataset will provide accurate number of rows matched for delete and update statements. Accurate in this case is the number of rows matched by the dataset's filter.

quoteIdentifiersbooleantrue

Whether this dataset quotes identifiers.

requiresSqlStandardDatebooleanfalse

Whether the dataset requires SQL standard datetimes (false by default, as most allow strings with ISO 8601 format).

rowCbFunction

callback to be invoked for each row returned from the database. the return value will be used as the result of query. The rowCb can also return a promise, The resolved value of the promise will be used as result.

sourceListpatio.sql.Identifier[][]

a list of sources for this dataset.

supportsCtebooleantrue

Whether the dataset supports common table expressions (the WITH clause).

supportsDistinctOnbooleanfalse

Whether the dataset supports the DISTINCT ON clause, false by default.

supportsIntersectExceptbooleantrue

Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default.

supportsIntersectExceptAllbooleantrue

Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default.

supportsIsTruebooleantrue

Whether the dataset supports the IS TRUE syntax.

supportsJoinUsingbooleantrue

Whether the dataset supports the JOIN table USING (column1, ...) syntax.

supportsModifyingJoinbooleanfalse

Whether modifying joined datasets is supported.

supportsMultipleColumnInbooleantrue

Whether the IN/NOT IN operators support multiple columns when an

supportsTimestampTimezonebooleanfalse

Whether the dataset supports timezones in literal timestamps

supportsTimestampUsecsbooleantrue

Whether the dataset supports fractional seconds in literal timestamps

supportsWindowFunctionsbooleanfalse

Whether the dataset supports window functions.

Constructor

Defined dataset/index.js Source
  1. function (db,opts){
  2. this._super(arguments);
  3. this.db = db;
  4. this.__opts = {};
  5. this.__rowCb = null;
  6. if (db) {
  7. this.__quoteIdentifiers = db.quoteIdentifiers;
  8. this.__identifierInputMethod = db.identifierInputMethod;
  9. this.__identifierOutputMethod = db.identifierOutputMethod;
  10. }
  11. }

__aggregateDataset Function Private


Defined dataset/actions.js

Source
  1. function (){
  2. return this._optionsOverlap(this._static.COUNT_FROM_SELF_OPTS) ? this.fromSelf() : this.unordered();
  3. }

__argumentList Function Private


Defined dataset/sql.js

Do a simple join of the arguments (which should be strings) separated by commas

Arguments Source
  1. function (args){
  2. return args.join(this._static.COMMA_SEPARATOR);
  3. }

__arrayToConditionSpecifier Function Private


Defined dataset/query.js

Arguments Returns Source
  1. function (arr,defaultOp){
  2. var ret = [];
  3. arr.forEach(function (a) {
  4. if (isString(a)) {
  5. a = this.stringToIdentifier(a);
  6. }
  7. if (isInstanceOf(a, Identifier)) {
  8. ret.push([a, defaultOp]);
  9. } else if (isHash(a)) {
  10. ret = ret.concat(array.toArray(a));
  11. } else {
  12. throw new QueryError("Invalid condition specifier " + a);
  13. }
  14. }, this);
  15. return ret;
  16. }

__asSql Function Private


Defined dataset/sql.js

SQL fragment for specifying an alias. expression should already be literalized.

Arguments Source
  1. function (expression,alias){
  2. return string.format("%s AS %s", expression, this.quoteIdentifier(alias));
  3. }

__columnList Function Private


Defined dataset/sql.js

Converts an array of column names into a comma seperated string of column names. If the array is empty, a wildcard (*) is returned.

Arguments Source
  1. function (columns){
  2. return (!columns || columns.length === 0) ? this._static.WILDCARD : this.__expressionList(columns);
  3. }

__createBetweenExpression Function Private


Defined dataset/query.js

Example
  1. ds.__createBetweenExpression({x : [1,2]}) => //=> WHERE ((x >= 1) AND (x <= 10))
  2. ds.__createBetweenExpression({x : [1,2]}, true) => //=> WHERE ((x < 1) OR (x > 10))
Arguments Returns Source
  1. function (obj,invert){
  2. var pairs = [];
  3. for (var i in obj) {
  4. var v = obj[i];
  5. if (isArray(v) && v.length) {
  6. var ident = this.stringToIdentifier(i);
  7. pairs.push(new BooleanExpression("AND", new BooleanExpression("gte", ident, v[0]), new BooleanExpression("lte", ident, v[1])));
  8. } else {
  9. throw new QueryError("Between requires an array for the value");
  10. }
  11. }
  12. var ret = pairs.length === 1 ? pairs[0] : BooleanExpression.fromArgs(["AND"].concat(pairs));
  13. return invert ? BooleanExpression.invert(ret) : ret;
  14. }

__createBoolExpression Function Private


Defined dataset/query.js

Creates a boolean expression that each key is compared to its value using the provided operator.

Example
  1. ds.__createBoolExpression("gt", {x : 1, y:2, z : 5}) //=> WHERE ((x > 1) AND (y > 2) AND (z > 5))
  2. ds.__createBoolExpression("gt", [[x, 1], [y,2], [z, 5]) //=> WHERE ((x > 1) AND (y > 2) AND (z > 5))
  3. ds.__createBoolExpression("lt", {x : 1, y:2, z : 5}) //=> WHERE ((x < 1) AND (y < 2) AND (z < 5))
  4. ds.__createBoolExpression("lt", [[x, 1], [y,2], [z, 5]) //=> WHERE ((x < 1) AND (y < 2) AND (z < 5))
Arguments Returns Source
  1. function (op,obj){
  2. var pairs = [];
  3. if (Expression.isConditionSpecifier(obj)) {
  4. if (isHash(obj)) {
  5. obj = array.toArray(obj);
  6. }
  7. obj.forEach(function (pair) {
  8. pairs.push(new BooleanExpression(op, new Identifier(pair[0]), pair[1]));
  9. });
  10. }
  11. return pairs.length === 1 ? pairs[0] : BooleanExpression.fromArgs(["AND"].concat(pairs));
  12. }

__defaultServerOpts Function Private


Defined dataset/actions.js

Arguments Source
  1. function (opts){
  2. return merge({server: this.__opts.server || "default"}, opts || {});
  3. }

__expressionList Function Private


Defined dataset/sql.js

Converts an array of expressions into a comma separated string of expressions.

Arguments Source
  1. function (columns){
  2. return columns.map(this.literal, this).join(this._static.COMMA_SEPARATOR);
  3. }

__hashIdentifierToName Function Private


Defined dataset/actions.js

Arguments Returns Source
  1. function (identifier){
  2. return isString(identifier) ? this.__hashIdentifierToName(this.stringToIdentifier(identifier)) :
  3. isInstanceOf(identifier, Identifier) ? identifier.value :
  4. isInstanceOf(identifier, QualifiedIdentifier) ? identifier.column :
  5. isInstanceOf(identifier, AliasedExpression) ? identifier.alias : identifier;
  6. }

__tableRef Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (t){
  2. return isString(t) ? this._quotedIdentifier(t) : this.literal(t);
  3. }

_addGroupedCondition Function Private


Defined dataset/query.js

Example
  1. DB.from("items").filter({id, [1,2,3]})._addGroupedCondition("AND", "OR", [{price: {lt : 0}}, {price: {gt: 10}]).sql;
  2. //=> SELECT
  3. *
  4. FROM
  5. items
  6. WHERE
  7. ((id IN (1, 2, 3)) AND ((price < 0) OR (price > 10)))
  8.  
  9. DB.from("items")._addGroupedCondition("AND", "OR", [{price: {lt : 0}}, {price: {gt: 10}]).sql;
  10. //=> SELECT
  11. *
  12. FROM
  13. items
  14. WHERE
  15. ((price < 0) OR (price > 10))
Arguments Returns Source
  1. function (addedByBool,groupedByBool){
  2. groupedByBool = isUndefined(groupedByBool) ? "AND" : groupedByBool;
  3. var tOpts = this.__opts,
  4. clause = (tOpts.having ? "having" : "where"),
  5. clauseObj = tOpts[clause];
  6. var args = argsToArray(arguments, 2);
  7. args = args.length === 1 ? args[0] : args;
  8. var opts = {};
  9. if (clauseObj) {
  10. addedByBool = isUndefined(addedByBool) ? "AND" : addedByBool;
  11. opts[clause] = new BooleanExpression(addedByBool, clauseObj, this._filterExpr(args, null, groupedByBool));
  12. } else {
  13. opts[clause] = this._filterExpr(args, null, groupedByBool);
  14. }
  15. return this.mergeOptions(opts);
  16. }

_compoundFromSelf Function Private


Defined dataset/sql.js

Return a [@link patio.sql._Query#fromSelf} dataset if an order or limit is specified, so it works as expected with UNION, EXCEPT, and INTERSECT clauses.

Source
  1. function (){
  2. var opts = this.__opts;
  3. return (opts["limit"] || opts["order"]) ? this.fromSelf() : this;
  4. }

_datasetAlias Function Private


Defined dataset/sql.js

The alias to use for datasets, takes a number to make sure the name is unique.

Arguments Source
  1. function (number){
  2. return this._static.DATASET_ALIAS_BASE_NAME + number;
  3. }

_deleteFromSql Function Private


Defined dataset/sql.js

Source
  1. function (){
  2. return this._selectFromSql();
  3. }

_deleteOrderSql Function Private


Defined dataset/sql.js

Source
  1. function (){
  2. return this._selectOrderSql();
  3. }

_deleteWhereSql Function Private


Defined dataset/sql.js

Source
  1. function (){
  2. return this._selectWhereSql();
  3. }

_filter Function Private


Defined dataset/query.js

Arguments Source
  1. function (clause){
  2. var cond = argsToArray(arguments).slice(1), cb;
  3. if (cond.length && isFunction(cond[cond.length - 1])) {
  4. cb = cond.pop();
  5. }
  6. cond = cond.length === 1 ? cond[0] : cond;
  7. if ((cond == null || cond === undefined || cond === "") || (isArray(cond) && cond.length === 0 && !cb) || (isObject(cond) && isEmpty(cond) && !cb)) {
  8. return this.mergeOptions();
  9. } else {
  10. cond = this._filterExpr(cond, cb);
  11. var cl = this.__opts[clause];
  12. cl && (cond = new BooleanExpression("AND", cl, cond));
  13. var opts = {};
  14. opts[clause] = cond;
  15. return this.mergeOptions(opts);
  16. }
  17. }

_filterExpr Function Private


Defined dataset/query.js

Arguments Source
  1. function (expr,cb,joinCond){
  2. expr = (isUndefined(expr) || isNull(expr) || (isArray(expr) && !expr.length)) ? null : expr;
  3. if (expr && cb) {
  4. return new BooleanExpression(joinCond || "AND", this._filterExpr(expr, null, joinCond), this._filterExpr(cb, null, joinCond));
  5. } else if (cb) {
  6. expr = cb;
  7. }
  8. if (isInstanceOf(expr, Expression)) {
  9. if (isInstanceOf(expr, NumericExpression, StringExpression)) {
  10. throw new QueryError("Invalid SQL Expression type : " + expr);
  11. }
  12. return expr;
  13. } else if (isArray(expr)) {
  14. if (expr.length) {
  15. var first = expr[0];
  16. if (isString(first)) {
  17. return new PlaceHolderLiteralString(first, expr.slice(1), true);
  18. } else if (Expression.isConditionSpecifier(expr)) {
  19. return BooleanExpression.fromValuePairs(expr, joinCond);
  20. } else {
  21. return BooleanExpression.fromArgs([joinCond || "AND"].concat(expr.map(function (e) {
  22. return this._filterExpr(e, null, "AND");
  23. }, this)));
  24. }
  25. }
  26. } else if (isFunction(expr)) {
  27. return this._filterExpr(expr.call(sql, sql), null, joinCond);
  28. } else if (isBoolean(expr)) {
  29. return new BooleanExpression("NOOP", expr);
  30. } else if (isString(expr)) {
  31. return this.stringToIdentifier(expr);
  32. } else if (isInstanceOf(expr, LiteralString)) {
  33. return new LiteralString("(" + expr + ")");
  34. } else if (isHash(expr)) {
  35. return BooleanExpression.fromValuePairs(expr, joinCond);
  36. } else {
  37. throw new QueryError("Invalid filter argument");
  38. }
  39. }

_invertOrder Function Private


Defined dataset/query.js

Arguments Source
  1. function (order){
  2. var ret = order;
  3. if (order) {
  4. ret = order.map(function (o) {
  5. if (isInstanceOf(o, OrderedExpression)) {
  6. return o.invert();
  7. } else {
  8. return new OrderedExpression(isString(o) ? new Identifier(o) : o);
  9. }
  10. }, this);
  11. }
  12. return ret;
  13. }

_joinTypeSql Function Private


Defined dataset/sql.js

SQL fragment specifying a JOIN type, splits a camelCased join type and converts to uppercase/

Arguments Source
  1. function (joinType){
  2. return (joinType || "").replace(/([a-z]+)|([A-Z][a-z]+)/g, function (m) {
  3. return m.toUpperCase() + " ";
  4. }).trimRight() + " JOIN";
  5. }

_literalArray Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return Expression.isConditionSpecifier(v) ? this._literalExpression(BooleanExpression.fromValuePairs(v)) : this._arraySql(v);
  3. }

_literalBoolean Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (b){
  2. return b ? this._static.BOOL_TRUE : this._static.BOOL_FALSE;
  3. }

_literalBuffer Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (b){
  2. return "X'" + b.toString("hex") + "'";
  3. }

_literalDataset Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (dataset){
  2. return string.format("(%s)", this._subselectSql(dataset));
  3. }

_literalDate Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (date){
  2. return (this.requiresSqlStandardDateTimes ? "DATE '" : "'") + patio.dateToString(date) + "'";
  3. }

_literalExpression Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return v.toString(this);
  3. }

_literalHash Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return this._literalExpression(BooleanExpression.fromValuePairs(v));
  3. }

_literalJson Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. throw new QueryError("Json not supported.");
  3. }

_literalNull Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. return this._static.NULL;
  3. }

_literalNumber Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (num){
  2. var ret = "" + num;
  3. if (isNaN(num) || num === Infinity) {
  4. ret = string.format("'%s'", ret);
  5. }
  6. return ret;
  7. }

_literalObject Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return this._literalExpression(BooleanExpression.fromValuePairs(v));
  3. }

_literalOther Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. if (isFunction(v.sqlLiteral)) {
  3. return v.sqlLiteral(this);
  4. } else {
  5. throw new QueryError(string.format("can't express %j as a SQL literal", [v]));
  6. }
  7. }

_literalString Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. var parts = this._splitString(v);
  3. var table = parts[0], column = parts[1], alias = parts[2], ret;
  4. if (!alias) {
  5. if (column && table) {
  6. ret = this._literalExpression(QualifiedIdentifier.fromArgs([table, column]));
  7. } else {
  8. ret = "'" + v.replace(/\\/g, "\\\\").replace(/'/g, "''") + "'";
  9. }
  10. } else {
  11. if (column && table) {
  12. ret = new AliasedExpression(QualifiedIdentifier.fromArgs([table, column]), alias);
  13. } else {
  14. ret = new AliasedExpression(new Identifier(column), alias);
  15. }
  16. ret = this.literal(ret);
  17. }
  18. return ret;
  19. }

_literalTime Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return this.formatTimestamp(v, this._static.TIME_FORMAT);
  3. }

_literalTimestamp Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (v){
  2. return this.formatTimestamp(v, this._static.TIMESTAMP_FORMAT);
  3. }

_literalYear Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (o){
  2. return patio.dateToString(o, this._static.YEAR_FORMAT);
  3. }

_optionsOverlap Function Private


Defined dataset/sql.js

Return true if the dataset has a non-null value for any key in opts.

Arguments Returns Source
  1. function (opts){
  2. var o = [];
  3. for (var i in this.__opts) {
  4. if (!isUndefinedOrNull(this.__opts[i])) {
  5. o.push(i);
  6. }
  7. }
  8. return intersect(compact(o), opts).length !== 0;
  9. }

_qualifiedExpression Function Private


Defined dataset/sql.js

Qualify the given expression to the given table.

Arguments Source
  1. function (e,table){
  2. var h, i, args;
  3. if (isString(e)) {
  4. //this should not be hit but here just for completeness
  5. return this.stringToIdentifier(e);
  6. } else if (isArray(e)) {
  7. return e.map(function (exp) {
  8. return this._qualifiedExpression(exp, table);
  9. }, this);
  10. } else if (isInstanceOf(e, Identifier)) {
  11. return new QualifiedIdentifier(table, e);
  12. } else if (isInstanceOf(e, OrderedExpression)) {
  13. return new OrderedExpression(this._qualifiedExpression(e.expression, table), e.descending,
  14. {nulls: e.nulls});
  15. } else if (isInstanceOf(e, AliasedExpression)) {
  16. return new AliasedExpression(this._qualifiedExpression(e.expression, table), e.alias);
  17. } else if (isInstanceOf(e, CaseExpression)) {
  18. args = [this._qualifiedExpression(e.conditions, table), this._qualifiedExpression(e.def, table)];
  19. if (e.hasExpression) {
  20. args.push(this._qualifiedExpression(e.expression, table));
  21. }
  22. return CaseExpression.fromArgs(args);
  23. } else if (isInstanceOf(e, Cast)) {
  24. return new Cast(this._qualifiedExpression(e.expr, table), e.type);
  25. } else if (isInstanceOf(e, SQLFunction)) {
  26. return SQLFunction.fromArgs([e.f].concat(this._qualifiedExpression(e.args, table)));
  27. } else if (isInstanceOf(e, ComplexExpression)) {
  28. return ComplexExpression.fromArgs([e.op].concat(this._qualifiedExpression(e.args, table)));
  29. } else if (isInstanceOf(e, SubScript)) {
  30. return new SubScript(this._qualifiedExpression(e.f, table), this._qualifiedExpression(e.sub, table));
  31. } else if (isInstanceOf(e, PlaceHolderLiteralString)) {
  32. args = [];
  33. var eArgs = e.args;
  34. if (isHash(eArgs)) {
  35. h = {};
  36. for (i in eArgs) {
  37. h[i] = this._qualifiedExpression(eArgs[i], table);
  38. }
  39. args = h;
  40. } else {
  41. args = this._qualifiedExpression(eArgs, table);
  42. }
  43. return new PlaceHolderLiteralString(e.str, args, e.parens);
  44. } else if (isHash(e)) {
  45. h = {};
  46. for (i in e) {
  47. h[this._qualifiedExpression(i, table) + ""] = this._qualifiedExpression(e[i], table);
  48. }
  49. return h;
  50. } else {
  51. return e;
  52. }
  53. }

_selectColumnsSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. return " " + this.__columnList(this.__opts.select);
  3. }

_selectCompoundsSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var opts = this.__opts, compounds = opts.compounds, ret = [];
  3. if (compounds) {
  4. compounds.forEach(function (c) {
  5. var type = c[0], dataset = c[1], all = c[2];
  6. ret.push(string.format(" %s%s %s", type.toUpperCase(), all ? " ALL" : "", this._subselectSql(dataset)));
  7. }, this);
  8. }
  9. return ret.join("");
  10. }

_selectDistinctSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var distinct = this.__opts.distinct, ret = [];
  3. if (distinct) {
  4. ret.push(" DISTINCT");
  5. if (distinct.length) {
  6. ret.push(format(" ON (%s)", this.__expressionList(distinct)));
  7. }
  8. }
  9. return ret.join("");
  10. }

_selectFromSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var from = this.__opts.from;
  3. return from ? string.format(" %s%s", this._static.FROM, this._sourceList(from)) : "";
  4. }

_selectGroupSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var group = this.__opts.group;
  3. return group ? string.format(" GROUP BY %s", this.__expressionList(group)) : "";
  4. }

_selectHavingSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var having = this.__opts.having;
  3. return having ? string.format(" HAVING %s", this.literal(having)) : "";
  4. }

_selectJoinSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var join = this.__opts.join, ret = [];
  3. if (join) {
  4. join.forEach(function (j) {
  5. ret.push(this.literal(j));
  6. }, this);
  7. }
  8. return ret.join("");
  9. }

_selectLimitSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var ret = [], limit = this.__opts.limit, offset = this.__opts.offset;
  3. !isUndefined(limit) && !isNull(limit) && (ret.push(format(" LIMIT %s", this.literal(limit))));
  4. !isUndefined(offset) && !isNull(offset) && (ret.push(format(" OFFSET %s", this.literal(offset))));
  5. return ret.join("");
  6. }

_selectLockSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var lock = this.__opts.lock, ret = [];
  3. if (lock) {
  4. if (lock === "update") {
  5. ret.push(this._static.FOR_UPDATE);
  6. } else {
  7. ret.push(" ", lock);
  8. }
  9. }
  10. return ret.join("");
  11. }

_selectOrderSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var order = this.__opts.order;
  3. return order ? string.format(" ORDER BY %s", this.__expressionList(order)) : "";
  4. }

_selectWhereSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var where = this.__opts.where;
  3. return where ? string.format(" WHERE %s", this.literal(where)) : "";
  4. }

_selectWithSql Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (sql){
  2. var wit = this.__opts["with"];
  3. if (wit && wit.length) {
  4. //sql.length = 0;
  5. var base = sql.join("");
  6. sql.length = 0;
  7. sql.push([this._selectWithSqlBase(), wit.map(function (w) {
  8. return [
  9. this.quoteIdentifier(w.name),
  10. (w.args ? ("(" + this.__argumentList(w.args) + ")") : ""),
  11. " AS ",
  12. this._literalDataset(w.dataset)
  13. ].join("");
  14. }, this).join(this._static.COMMA_SEPARATOR), base].join(" "));
  15. }
  16. }

_selectWithSqlBase Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. return this._static.SQL_WITH;
  3. }

_sourceList Function Private


Defined dataset/sql.js

Converts an array of source names into into a comma separated list.

Arguments Source
  1. function (source){
  2. if (!Array.isArray(source)) {
  3. source = [source];
  4. }
  5. if (!source || !source.length) {
  6. throw new QueryError("No source specified for the query");
  7. }
  8. return " " + source.map(
  9. function (s) {
  10. return this.__tableRef(s);
  11. }, this).join(this._static.COMMA_SEPARATOR);
  12. }

_splitAlias Function Private


Defined dataset/query.js

Splits a possible implicit alias, handling both patio.sql.AliasedExpressions and strings. Returns an array of two elements, with the first being the main expression, and the second being the alias. Alias may be null if it is a string that does not contain an alias {table}_{alias}.

Arguments Source
  1. function (c){
  2. var ret;
  3. if (isInstanceOf(c, AliasedExpression)) {
  4. ret = [c.expression, c.alias];
  5. } else if (isString(c)) {
  6. var parts = this._splitString(c), cTable = parts[0], column = parts[1], alias = parts[2];
  7. if (alias) {
  8. ret = [cTable ? new QualifiedIdentifier(cTable, column) : column, alias];
  9. } else {
  10. ret = [c, null];
  11. }
  12. } else {
  13. ret = [c, null];
  14. }
  15. return ret;
  16. }

_splitString Function Private


Defined dataset/index.js

Can either be a string or null.

Example
  1. //columns
  2. table__column___alias //=> table.column as alias
  3. table__column //=> table.column
  4. //tables
  5. schema__table___alias //=> schema.table as alias
  6. schema__table //=> schema.table
  7.  
  8. //name and alias
  9. columnOrTable___alias //=> columnOrTable as alias
Arguments Returns Source
  1. function (s){
  2. var ret, m;
  3. if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) {
  4. ret = m.slice(1);
  5. }
  6. else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) {
  7. ret = [null, m[1], m[2]];
  8. }
  9. else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) {
  10. ret = [m[1], m[2], null];
  11. }
  12. else {
  13. ret = [null, s, null];
  14. }
  15. return ret;
  16. }

_staticSql Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (sql){
  2. return isString(sql) ? sql : this.literal(sql);
  3. }

_subselectSql Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (ds){
  2. return ds.sql;
  3. }

_toTableName Function Private


Defined dataset/sql.js

Returns a string that is the name of the table.

Arguments Returns Throws Source
  1. function (name){
  2. var ret;
  3. if (isString(name)) {
  4. var parts = this._splitString(name);
  5. var schema = parts[0], table = parts[1], alias = parts[2];
  6. ret = (schema || alias) ? alias || table : table;
  7. } else if (isInstanceOf(name, Identifier)) {
  8. ret = name.value;
  9. } else if (isInstanceOf(name, QualifiedIdentifier)) {
  10. ret = this._toTableName(name.column);
  11. } else if (isInstanceOf(name, AliasedExpression)) {
  12. ret = this.__toAliasedTableName(name.alias);
  13. } else {
  14. throw new QueryError("Invalid object to retrieve the table name from");
  15. }
  16. return ret;
  17. }

_unaliasedIdentifier Function Private


Defined dataset/sql.js

Return the unaliased part of the identifier. Handles both implicit aliases in strings, as well as patio.sql.AliasedExpressions. Other objects are returned as is.

Arguments Returns Source
  1. function (c){
  2. if (isString(c)) {
  3. var parts = this._splitString(c);
  4. var table = parts[0], column = parts[1];
  5. if (table) {
  6. return new QualifiedIdentifier(table, column);
  7. }
  8. return column;
  9. } else if (isInstanceOf(c, AliasedExpression)) {
  10. return c.expression;
  11. } else {
  12. return c;
  13. }
  14. }

_updateOrderSql Function Private


Defined dataset/sql.js

Source
  1. function (){
  2. return this._selectOrderSql();
  3. }

_updateSetSql Function Private


Defined dataset/sql.js

Returns Source
  1. function (){
  2. var values = this.__opts.values, defs = this.__opts.defaults, overrides = this.__opts.overrides;
  3. var st = [" SET "];
  4. if (isArray(values)) {
  5. var v = [], mergedDefsAndOverrides = false, length = values.length, ident, val;
  6. for (var i = 0; i &lt; length; i++) {
  7. val = values[i];
  8. if (isHash(val)) {
  9. mergedDefsAndOverrides = true;
  10. val = merge({}, defs || {}, val);
  11. val = merge({}, val, overrides || {});
  12. for (var j in val) {
  13. ident = this.stringToIdentifier(j);
  14. v.push(this.quoteIdentifier(ident) + " = " + this.literal(val[j]));
  15. }
  16. } else if (isInstanceOf(val, Expression)) {
  17. v.push(this._literalExpression(val).replace(/^\(|\)$/g, ""));
  18. } else {
  19. v.push(val);
  20. }
  21. }
  22. if (!mergedDefsAndOverrides) {
  23. val = merge({}, defs || {});
  24. val = merge({}, val, overrides || {});
  25. for (i in val) {
  26. ident = this.stringToIdentifier(i);
  27. v.push(this.quoteIdentifier(ident) + " = " + this.literal(val[i]));
  28. }
  29. }
  30. st.push(v.join(this._static.COMMA_SEPARATOR));
  31. } else {
  32. st.push(values);
  33. }
  34. return st.join("");
  35. }

_updateTableSql Function Private


Defined dataset/sql.js

Arguments Returns Source
  1. function (sql){
  2. var ret = [this._sourceList(this.__opts.from)];
  3. if (this.supportsModifyingJoins) {
  4. ret.push(this._selectJoinSql());
  5. }
  6. return ret.join("");
  7. }

_updateWhereSql Function Private


Defined dataset/sql.js

Source
  1. function (){
  2. return this._selectWhereSql();
  3. }

addGraphAliases Function Public


Defined dataset/graph.js

Adds the given graph aliases to the list of graph aliases to use, unlike patio.Dataset#setGraphAliases, which replaces the list (the equivalent of patio.Dataset#selectMore when graphing). See patio.Dataset#setGraphAliases.

Example
  1. var DB = patio.defaultDatabase;
  2. // SELECT ..., table.column AS someAlias
  3. DB.from("table").addGraphAliases({someAlias : ["table", "column"]);
  4. //returns from graphing
  5. // => {table : {column : someAlias_value, ...}, ...}
Arguments Returns Source
  1. function (graphAliases){
  2. var ds = this.selectMore.apply(this, this.__graphAliasColumns(graphAliases));
  3. ds.__opts.graphAliases = merge((ds.__opts.graphAliases || (ds.__opts.graph ? ds.__opts.graph.columnAliases : {}) || {}), graphAliases);
  4. return ds;
  5. }

aliasedExpressionSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (ae){
  2. return this.__asSql(this.literal(ae.expression), ae.alias);
  3. }

all Function Public


Defined dataset/actions.js

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
  1. // SELECT * FROM table
  2. DB.from("table").all().chain(function(res){
  3. //res === [{id : 1, ...}, {id : 2, ...}, ...];
  4. });
  5. // Iterate over all rows in the table
  6. var myArr = [];
  7. var rowPromise = DB.from("table").all(function(row){ myArr.push(row);});
  8. rowPromise.chain(function(rows){
  9. //=> rows == myArr;
  10. });
Arguments Returns Source
  1. function (block,cb){
  2. var self = this;
  3. var ret = asyncArray(this.forEach().chain(function (records) {
  4. return self.postLoad(records);
  5. }));
  6. if (block) {
  7. ret = ret.forEach(block);
  8. }
  9. return ret.classic(cb).promise();
  10. }

alwaysQualify Function Public


Defined dataset/query.js

Same as patio.Dataset@qualifyTo except that it forces qualification on methods called after it has been called.

Example
  1. //qualfyTo would generate
  2. DB.from("items").qualifyTo("i").filter({id : 1});
  3. //=> SELECT i.* FROM items WHERE (id = 1)
  4.  
  5. //alwaysQualify qualifies filter also.
  6. DB.from("items").alwaysQualify("i").filter({id : 1});
  7. //=> SELECT i.* FROM items WHERE (i.id = 1)
Arguments Returns Source
  1. function (table){
  2. return this.mergeOptions({alwaysQualify: table || this.firstSourceAlias});
  3. }

and Function Public


Defined dataset/query.js

Adds a further filter to an existing filter using AND. This method is identical to patio.Dataset#filter except it expects an existing filter.

For parameter types see patio.Dataset#filter.

Example
  1. DB.from("table").filter("a").and("b").sql;
  2. //=>SELECT * FROM table WHERE a AND b
Returns Throws Source
  1. function (){
  2. var tOpts = this.__opts, clauseObj = tOpts[tOpts.having ? "having" : "where"];
  3. if (clauseObj) {
  4. return this.filter.apply(this, arguments);
  5. } else {
  6. throw new QueryError("No existing filter found");
  7. }
  8. }

andGroupedAnd Function Public


Defined dataset/query.js

Adds a group of ANDed conditions wrapped in parens to an existing where/having clause by an AND. If there isn't yet a clause, a where clause is created with the ANDed conditions

For parameter types see patio.Dataset#filter.

Example
  1. DB.from("items").filter({id, [1,2,3]}).andGroupedAnd([{price: {gt : 0}}, {price: {lt: 10}]).sql;
  2. //=> SELECT
  3. *
  4. FROM
  5. items
  6. WHERE
  7. ((id IN (1, 2, 3)) AND ((price > 0) AND (price < 10)))
  8.  
  9. DB.from("items").andGroupedAnd([{price: {gt : 0}}, {price: {lt: 10}]).sql;
  10. //=> SELECT
  11. *
  12. FROM
  13. items
  14. WHERE
  15. ((price > 0) AND (price < 10))
Arguments Returns Source
  1. function (filterExp){
  2. return this._addGroupedCondition("AND", "AND", filterExp);
  3. }

andGroupedOr Function Public


Defined dataset/query.js

Adds a group of ORed conditions wrapped in parens, connected to an existing where/having clause by an AND. If the where/having clause doesn't yet exist, a where clause is created with the ORed group.

For parameter types see patio.Dataset#filter.

Example
  1. DB.from("items").filter({id, [1,2,3]}).andGroupedOr([{price: {lt : 0}}, {price: {gt: 10}]).sql;
  2. //=> SELECT
  3. *
  4. FROM
  5. items
  6. WHERE
  7. ((id IN (1, 2, 3)) AND ((price < 0) OR (price > 10)))
  8.  
  9. DB.from("items").andGroupedOr([{price: {lt : 0}}, {price: {gt: 10}]).sql;
  10. //=> SELECT
  11. *
  12. FROM
  13. items
  14. WHERE
  15. ((price < 0) OR (price > 10))
  16.  
  17. DB.from("items").filter({x:1}).andGroupedOr([{a:1, b:2}, {c:3, d:4}]).sql;
  18. //=> SELECT
  19. *
  20. FROM
  21. items
  22. WHERE
  23. ((x = 1) AND (((a = 1) AND (b = 2)) OR ((c = 3) AND (d = 4)))
Arguments Returns Source
  1. function (filterExp){
  2. return this._addGroupedCondition("AND", "OR", filterExp);
  3. }

avg Function Public


Defined dataset/actions.js

Returns a promise that is resolved with the average value for the given column.

Example
  1. // SELECT avg(number) FROM table LIMIT 1
  2. DB.from("table").avg("number").chain(function(avg){
  3. // avg === 3
  4. });
Arguments Returns Source
  1. function (column,cb){
  2. return this.__aggregateDataset().get(sql.avg(this.stringToIdentifier(column)), cb);
  3. }

between Function Public


Defined dataset/query.js

Returns a cloned dataset with a between clause added to the where clause.

Example
  1. ds.notBetween({x:[1, 2]}).sql;
  2. //=> SELECT * FROM test WHERE ((x >= 1) OR (x <= 2))
  3.  
  4. ds.find({x:{notBetween:[1, 2]}}).sql;
  5. //=> SELECT * FROM test WHERE ((x >= 1) OR (x <= 2))
Arguments Returns Source
  1. function (obj){
  2. return this.filter(this.__createBetweenExpression(obj));
  3. }

booleanConstantSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (constant){
  2. return this.literal(constant);
  3. }

caseExpressionSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (ce){
  2. var sql = ['(CASE '];
  3. if (ce.expression) {
  4. sql.push(this.literal(ce.expression), " ");
  5. }
  6. var conds = ce.conditions;
  7. if (isArray(conds)) {
  8. conds.forEach(function (cond) {
  9. sql.push(format("WHEN %s THEN %s", this.literal(cond[0]), this.literal(cond[1])));
  10. }, this);
  11. } else if (isHash(conds)) {
  12. for (var i in conds) {
  13. sql.push(format("WHEN %s THEN %s", this.literal(i), this.literal(conds[i])));
  14. }
  15. }
  16. return format("%s ELSE %s END)", sql.join(""), this.literal(ce.def));
  17. }

castSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (expr,type){
  2. return string.format("CAST(%s AS %s)", this.literal(expr), this.db.castTypeLiteral(type));
  3. }

columnAllSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (ca){
  2. return string.format("%s.*", this.quoteSchemaTable(ca.table));
  3. }

complexExpressionSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (op,args){
  2. var newOp;
  3. var isOperators = this._static.IS_OPERATORS, isLiterals = this._static.IS_LITERALS, l;
  4. if ((newOp = isOperators[op]) != null) {
  5. var r = args[1], v = isNull(r) ? isLiterals.NULL : isLiterals[r];
  6. if (r == null || this.supportsIsTrue) {
  7. if (isUndefined(v)) {
  8. throw new QueryError(string.format("Invalid argument('%s') used for IS operator", r));
  9. }
  10. l = args[0];
  11. return string.format("(%s %s %s)", isString(l) ? l : this.literal(l), newOp, v);
  12. } else if (op === "IS") {
  13. return this.complexExpressionSql("EQ", args);
  14. } else {
  15. return this.complexExpressionSql("OR",
  16. [BooleanExpression.fromArgs(["NEQ"].concat(args)), new BooleanExpression("IS", args[0],
  17. null)]);
  18. }
  19. } else if (["IN", "NOTIN"].indexOf(op) !== -1) {
  20. var cols = args[0], vals = args[1], colArray = isArray(cols), valArray = false, emptyValArray = false;
  21. if (isArray(vals)) {
  22. valArray = true;
  23. emptyValArray = vals.length === 0;
  24. }
  25. if (colArray) {
  26. if (emptyValArray) {
  27. if (op === "IN") {
  28. return this.literal(BooleanExpression.fromValuePairs(cols.map(function (x) {
  29. return [x, x];
  30. }), "AND", true));
  31. } else {
  32. return this.literal({1: 1});
  33. }
  34. } else if (!this.supportsMultipleColumnIn) {
  35. if (valArray) {
  36. var expr = BooleanExpression.fromArgs(["OR"].concat(vals.map(function (vs) {
  37. return BooleanExpression.fromValuePairs(array.zip(cols, vs));
  38. })));
  39. return this.literal(op === "IN" ? expr : expr.invert());
  40. }
  41. } else {
  42. //If the columns and values are both arrays, use _arraySql instead of
  43. //literal so that if values is an array of two element arrays, it
  44. //will be treated as a value list instead of a condition specifier.
  45. return format("(%s %s %s)", isString(cols) ? cols : this.literal(cols),
  46. ComplexExpression.IN_OPERATORS[op],
  47. valArray ? this._arraySql(vals) : this.literal(vals));
  48. }
  49. }
  50. else {
  51. if (emptyValArray) {
  52. if (op === "IN") {
  53. return this.literal(BooleanExpression.fromValuePairs([
  54. [cols, cols]
  55. ], "AND", true));
  56. } else {
  57. return this.literal({1: 1});
  58. }
  59. } else {
  60. return format("(%s %s %s)", isString(cols) ? cols : this.literal(cols),
  61. ComplexExpression.IN_OPERATORS[op], this.literal(vals));
  62. }
  63. }
  64. } else if ((newOp = this._static.TWO_ARITY_OPERATORS[op]) != null) {
  65. l = args[0];
  66. return format("(%s %s %s)", isString(l) ? l : this.literal(l), newOp,
  67. this.literal(args[1]));
  68. } else if ((newOp = this._static.N_ARITY_OPERATORS[op]) != null) {
  69. return string.format("(%s)", args.map(this.literal, this).join(" " + newOp + " "));
  70. } else if (op === "NOT") {
  71. return string.format("NOT %s", this.literal(args[0]));
  72. } else if (op === "NOOP") {
  73. return this.literal(args[0]);
  74. } else {
  75. throw new QueryError("Invalid operator " + op);
  76. }
  77. }

compoundClone Function Public


Defined dataset/query.js

Add the dataset to the list of compounds

Arguments Returns Source
  1. function (type,dataset,options){
  2. var ds = this._compoundFromSelf().mergeOptions({compounds: (array.toArray(this.__opts.compounds || [])).concat([
  3. [type, dataset._compoundFromSelf(), options.all]
  4. ])});
  5. return options.fromSelf === false ? ds : ds.fromSelf(options);
  6. }

constantSql Function Private


Defined dataset/sql.js

Arguments Source
  1. function (constant){
  2. return "" + constant;
  3. }

count Function Public


Defined dataset/actions.js

Returns a promise that is resolved with the number of records in the dataset.

Example
  1. // SELECT COUNT(*) AS count FROM table LIMIT 1
  2. DB.from("table").count().chain(function(count){
  3. //count === 3;
  4. });
Arguments Returns Source
  1. function (cb){
  2. return this.__aggregateDataset().get(sql.COUNT(sql.literal("*")).as("count")).chain(function (res) {
  3. return parseInt(res, 10);
  4. }).classic(cb);
  5. }

distinct Function Public


Defined dataset/query.js

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
  1. DB.from("items").distinct().sqll
  2. //=> SELECT DISTINCT * FROM items
  3. DB.from("items").order("id").distinct("id").sql;
  4. //=> SELECT DISTINCT ON (id) * FROM items ORDER BY id
Arguments Returns Throws Source
  1. function (args){
  2. args = argsToArray(arguments);
  3. if (args.length && !this.supportsDistinctOn) {
  4. throw new QueryError("DISTICT ON is not supported");
  5. }
  6. args = args.map(function (a) {
  7. return isString(a) ? new Identifier(a) : a;
  8. });
  9. return this.mergeOptions({distinct: args});
  10. }

eager Function Public


Defined dataset/query.js

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
  1. DB.from('company').filter({name: 'Amazon'})
  2. .eager({
  3. // company from parent query is passed in and usable in the eager query.
  4. leader: (company) => DB.from('leader').filter({id: company.leaderId}).one()
  5. })
  6. // Load completely unrelated data.
  7. .eager({org: () => DB.from('organization').one() })
  8. .one()})
  9.  
  10. { id: 1,
  11. name: 'Amazon.com',
  12. leader: {
  13. id: 1,
  14. name: 'Jeff'
  15. },
  16. org: {
  17. id: 1,
  18. name: 'Google Inc.'
  19. }
  20. }
  21.  
  22. Can do one to many loading for every item in the parent dataset.
  23. Be careful doing this because it can lead to lots of extra queries.
  24.  
  25. DB.from('company').filter({state: 'IA'})
  26. .eager({invoices: (company) => DB.from('invoices').filter({companyId: company.id}).one() })
  27. .all()})
  28.  
  29. [
  30. { id: 1,
  31. name: 'Principal',
  32. invoices: [
  33. { id: 1, amount: 200},
  34. { id: 2, amount: 300},
  35. ]
  36. },
  37. { id: 2,
  38. name: 'John Deere',
  39. invoices: [
  40. { id: 3, amount: 200},
  41. { id: 4, amount: 300},
  42. ]
  43. }
  44. ]
Arguments Source
  1. function (includeDatasets,fromModel){
  2. var ds = this.mergeOptions({}),
  3. originalRowCb = ds.rowCb;
  4. if(!ds.__opts._eagerAssoc) {
  5. ds.__opts._eagerAssoc = includeDatasets;
  6. ds.rowCb = function (topLevelResults) {
  7. function toObject(thing) {
  8. if (!thing) {
  9. return comb.when(thing);
  10. }
  11. if (Array.isArray(thing)) {
  12. return comb.when(thing.map(function(item) {
  13. return toObject(item);
  14. }));
  15. }
  16. if ('toObject' in thing) {
  17. return comb.when(thing.toObject());
  18. }
  19. return comb.when(thing);
  20. }
  21. var eagerResults = {},
  22. whens = [];
  23. if (!originalRowCb) {
  24. // pass through for when topLevelResults is already resolved
  25. originalRowCb = function(r){return r;};
  26. }
  27. return comb.when(originalRowCb(topLevelResults)).chain(function(maybeModel) {
  28. whens = Object.keys(ds.__opts._eagerAssoc).map(function(key) {
  29. return ds.__opts._eagerAssoc[key](maybeModel).chain(function(result) {
  30. return toObject(result).chain(function(res) {
  31. eagerResults[key] = res;
  32. return result;
  33. });
  34. });
  35. });
  36. return comb.when(whens).chain(function () {
  37. return toObject(maybeModel).chain(function(json) {
  38. // merge associations on to main data
  39. return Object.assign(json, eagerResults);
  40. });
  41. });
  42. });
  43. };
  44. }
  45. return ds.mergeOptions({
  46. _eagerAssoc: Object.assign(ds.__opts._eagerAssoc, includeDatasets)
  47. });
  48. }

eq Function Public


Defined dataset/query.js

Returns a cloned dataset with an equal expression added to the WHERE clause.

Example
  1. DB.from("test").eq({x : 1});
  2. //=> SELECT * FROM test WHERE (x = 1)
  3. DB.from("test").eq({x : 1, y : 10});
  4. //=> SELECT * FROM test WHERE ((x = 1) AND (y = 10))
Arguments Returns Source
  1. function (obj){
  2. return this.filter(this.__createBoolExpression("eq", obj));
  3. }

except Function Public


Defined dataset/query.js

Adds an EXCEPT clause using a second dataset object. An EXCEPT compound dataset returns all rows in the current dataset that are not in the given dataset.

Example
  1. DB.from("items").except(DB.from("other_items")).sql;
  2. //=> SELECT * FROM items EXCEPT SELECT * FROM other_items
  3.  
  4. DB.from("items").except(DB.from("other_items"),
  5. {all : true, fromSelf : false}).sql;
  6. //=> SELECT * FROM items EXCEPT ALL SELECT * FROM other_items
  7.  
  8. DB.from("items").except(DB.from("other_items"),
  9. {alias : "i"}).sql;
  10. //=>SELECT * FROM (SELECT * FROM items EXCEPT SELECT * FROM other_items) AS i
Arguments Returns Throws Source
  1. function (dataset,opts){
  2. opts = isUndefined(opts) ? {} : opts;
  3. if (!isHash(opts)) {
  4. opts = {all: true};
  5. }
  6. if (!this.supportsIntersectExcept) {
  7. throw new QueryError("EXCEPT not supoorted");
  8. } else if (opts.hasOwnProperty("all") && !this.supportsIntersectExceptAll) {
  9. throw new QueryError("EXCEPT ALL not supported");
  10. }
  11. return this.compoundClone("except", dataset, opts);
  12. }

exclude Function Public


Defined dataset/query.js

Performs the inverse of patio.Dataset#filter. Note that if you have multiple filter conditions, this is not the same as a negation of all conditions. For argument types see patio.Dataset#filter

Example
  1. DB.from("items").exclude({category : "software").sql;
  2. //=> SELECT * FROM items WHERE (category != 'software')
  3.  
  4. DB.from("items").exclude({category : 'software', id : 3}).sql;
  5. //=> SELECT * FROM items WHERE ((category != 'software') OR (id != 3))
Returns Source
  1. function (){
  2. var cond = argsToArray(arguments), tOpts = this.__opts;
  3. var clause = (tOpts["having"] ? "having" : "where"), clauseObj = tOpts[clause];
  4. cond = cond.length > 1 ? cond : cond[0];
  5. cond = this._filterExpr.call(this, cond);
  6. cond = BooleanExpression.invert(cond);
  7. if (clauseObj) {
  8. cond = new BooleanExpression("AND", clauseObj, cond);
  9. }
  10. var opts = {};
  11. opts[clause] = cond;
  12. return this.mergeOptions(opts);
  13. }

execute Function Private


Defined dataset/actions.js

Arguments Source
  1. function (sql,opts){
  2. return this.db.execute(sql, merge({server: this.__opts.server || "readOnly"}, opts || {}));
  3. }

executeDdl Function Private


Defined dataset/actions.js

Arguments Source
  1. function (sql,opts){
  2. return this.db.executeDdl(sql, this.__defaultServerOpts(opts || {}));
  3. }

executeDui Function Private


Defined dataset/actions.js

Arguments Source
  1. function (sql,opts){
  2. return this.db.executeDui(sql, this.__defaultServerOpts(opts || {}));
  3. }

executeInsert Function Private


Defined dataset/actions.js

Arguments Source
  1. function (sql,opts){
  2. return this.db.executeInsert(sql, this.__defaultServerOpts(opts || {}));
  3. }

fetchRows Function Private


Defined dataset/actions.js

Arguments Source
  1. function (sql,opts){
  2. opts = opts || {};
  3. var ret;
  4. if (opts.stream) {
  5. ret = this.fetchStreamedRows(sql, opts);
  6. } else {
  7. ret = this.fetchPromisedRows(sql, opts);
  8. }
  9. return ret;
  10. }

filter Function Public


Defined dataset/query.js

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
  1. DB.from("items").filter({id : 3}).sql;
  2. //=> SELECT * FROM items WHERE (id = 3)
  3.  
  4. DB.from("items").filter('price < ?', 100)
  5. //=> SELECT * FROM items WHERE price < 100
  6.  
  7. DB.from("items").filter({id, [1,2,3]}).filter({id : {between : [0, 10]}}).sql;
  8. //=> SELECT
  9. *
  10. FROM
  11. items
  12. WHERE
  13. ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10)))
  14.  
  15. DB.from("items").filter('price < 100');
  16. //=> SELECT * FROM items WHERE price < 100
  17.  
  18. DB.from("items").filter("active").sql;
  19. //=> SELECT * FROM items WHERE active
  20.  
  21. DB.from("items").filter(function(){
  22. return this.price.lt(100);
  23. });
  24. //=> SELECT * FROM items WHERE (price < 100)
  25.  
  26. //Multiple filter calls can be chained for scoping:
  27. DB.from("items").filter(:category => 'software').filter{price < 100}
  28. //=> SELECT * FROM items WHERE ((category = 'software') AND (price < 100))
Arguments