/*
Closure used to handle both cases of when the sql.js library
has already been loaded, or when it has not yet been.
341345
function () {

                    _this.db = new window.SQL.Database();
                    $.each(SQLite_driver.prototype.splitStatement.call(this,args["ddl"],args["statement_separator"]), function (i, statement) {
                        _this.db.exec(statement);
                    });

                    args["success"]();
                }
365451
function outputQuery(compiled, isParameter) {
    var sql = compiled.sql || '';
    if (sql) {
      if (compiled.method === 'select' && (isParameter || compiled.as)) {
        sql = '(' + sql + ')';
        if (compiled.as) {
          return this.alias(sql, this.wrap(compiled.as));
        }
      }
    }
    return sql;
  }
218922
function _callHandler(handler) {
        try {
            // TODO (issue 1034): We *could* use a $.Deferred for this, except deferred objects enter a broken
            // state if any resolution callback throws an exception. Since third parties (e.g. extensions) may
            // add callbacks to this, we need to be robust to exceptions
            handler();
        } catch (e) {
            console.error("Exception when calling a 'brackets done loading' handler: " + e);
            console.log(e.stack);
        }
    }
969019
function(libraries) {
            var deferred       = null,
                promiseWrapper = null,
                $              = null;

            promiseWrapper = new this.Deferred();

            if (mixitup.features.has.promises) {
                // ES6 native promise or polyfill

                promiseWrapper.promise = new Promise(function(resolve, reject) {
                    promiseWrapper.resolve = resolve;
                    promiseWrapper.reject  = reject;
                });
            } else if (($ = (window.jQuery || libraries.$)) && typeof $.Deferred === 'function') {
                // jQuery

                deferred = $.Deferred();

                promiseWrapper.promise = deferred.promise();
                promiseWrapper.resolve = deferred.resolve;
                promiseWrapper.reject  = deferred.reject;
            } else if (window.console) {
                // No implementation

                console.warn(mixitup.messages.warningNoPromiseImplementation());
            }

            return promiseWrapper;
        }
1228937
function(fn, context){
      var cursor = this;
      while (cursor = cursor.handler)
        if (cursor.fn === fn && cursor.context === context)
          console.warn('duplicate fn & context pair');

      this.handler = {
        fn: fn,
        context: context,
        handler: this.handler
      };
    }
962740
function initialize() {
        var self = this;

        // NOTE: triggered before `creating`/`updating`
        this.on('saving', function onSaving(newObj, attrs, options) {
            if (options.method === 'insert') {
                // id = 0 is still a valid value for external usage
                if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) {
                    newObj.setId();
                }
            }
        });

        [
            'fetching',
            'fetching:collection',
            'fetched',
            'fetched:collection',
            'creating',
            'created',
            'updating',
            'updated',
            'destroying',
            'destroyed',
            'saving',
            'saved'
        ].forEach(function (eventName) {
            var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1);

            if (functionName.indexOf(':') !== -1) {
                functionName = functionName.slice(0, functionName.indexOf(':'))
                    + functionName[functionName.indexOf(':') + 1].toUpperCase()
                    + functionName.slice(functionName.indexOf(':') + 2);
                functionName = functionName.replace(':', '');
            }

            if (!self[functionName]) {
                return;
            }

            self.on(eventName, self[functionName]);
        });

        // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work.
        proto.initialize.call(this);
    }
381999
function updateQueryForNextPage(pulledRecords) {
        return Platform.async(function(callback) {
            callback();
        })().then(function() {

            if (!pulledRecords) {
                throw new Error('Something is wrong. pulledRecords cannot be null at this point');
            }

            var lastRecord = pulledRecords[ pulledRecords.length - 1];

            if (!lastRecord) {
                throw new Error('Something is wrong. Possibly invalid response from the server. lastRecord cannot be null!');
            }

            var lastRecordTime = lastRecord[tableConstants.sysProps.updatedAtColumnName];

            if (!_.isDate(lastRecordTime)) {
                throw new Error('Property ' + tableConstants.sysProps.updatedAtColumnName + ' of the last record should be a valid date');
            }

            if (lastRecordTime.getTime() === lastKnownUpdatedAt.getTime()) {
                pagePullQuery.skip(pagePullQuery.getComponents().skip + pulledRecords.length);
            } else {
                buildQueryFromLastKnownUpdateAt(lastRecordTime);
            }
        });
    }
137600
function() {
        if (!this._disconnected) {
            console.log(
                `LocalIndexedDBStoreBackend.connect: already connected or connecting`,
            );
            return Promise.resolve();
        }

        this._disconnected = false;

        console.log(
            `LocalIndexedDBStoreBackend.connect: connecting...`,
        );
        const req = this.indexedDB.open(this._dbName, VERSION);
        req.onupgradeneeded = (ev) => {
            const db = ev.target.result;
            const oldVersion = ev.oldVersion;
            console.log(
                `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`,
            );
            if (oldVersion < 1) { // The database did not previously exist.
                this._isNewlyCreated = true;
                createDatabase(db);
            }
            if (oldVersion < 2) {
                upgradeSchemaV2(db);
            }
            if (oldVersion < 3) {
                upgradeSchemaV3(db);
            }
            // Expand as needed.
        };

        req.onblocked = () => {
            console.log(
                `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`,
            );
        };

        console.log(
            `LocalIndexedDBStoreBackend.connect: awaiting connection...`,
        );
        return reqAsEventPromise(req).then((ev) => {
            console.log(
                `LocalIndexedDBStoreBackend.connect: connected`,
            );
            this.db = ev.target.result;

            // add a poorly-named listener for when deleteDatabase is called
            // so we can close our db connections.
            this.db.onversionchange = () => {
                this.db.close();
            };

            return this._init();
        });
    }
118421
@Cmd
	public void onError(final Closure<Void> closure) {
		int errorCount = errors.size();
		if (errorCount > 0) {
			log.info(errorCount + " error" + (errorCount == 1 ? "" : "s") + " in list --> executing block");
			closure.call();
			log.info("Finished OnError block");
		} else {
			log.info("No errors in list --> skipping block");
		}
	}
26060
function (connectionName, callback) {
        var self = this,
            conn = self.connection();

        // if not yet connected, spawn new connection and initiate transaction
        if (!conn) {
            self.connect(connectionName, function (error, conn) {
                if (error) {
                    callback(error, conn);
                    return;
                }
                // now that we have the connection, we initiate transaction. note that this sql_start is part of the new
                // connection branch. it is always highly likely that this would be the program flow. in a very unlikely
                // case the alternate flow will kick in, which is the `conn.query` right after this if-block.
                conn.beginTransaction(function (error) {
                    callback(error, self);
                });
            });

            return; // do not proceed with sql_start if connection wasn't initially present.
        }

        // if transaction is attempted across multiple connections, return an error
        if (connectionName !== self._connectionName) {
            return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
        }

        conn.beginTransaction(function (error) {
            // if callback mode is used, then execute it and send self as a parameter to match the new Constructor API.
            callback(error, self);
        });
    }
368056
function reload(req, res) {
  var log = this.log;
  if(Persistence.loading) {
    return res.send(new Error('database load in progress'));
  }
  Persistence.load(this.state.store, this.state.conf,
    function onLoad(err, time, diff, version) {
      if(err) return log.warning('db reload error: %s', err.message);
      log.notice(
        'db reloaded by DEBUG RELOAD: %s seconds (v%s)', time, version);
    }
  );
  res.send(null, Constants.OK);
}
1284779
function handleResults(results) {
      // check if uniqueDisplayProperty is set
      // then filter the result to uniqueness
      if (self.uniqueDisplayProperty)
        results = handleUniqueResult(results);
      self.itemList = results;
      self.hidden = shouldHide();

      // If loading is in progress, then we'll end the progress. This is needed for example,
      // when the `clear` button was clicked, because there we always show the loading process, to prevent flashing.
      if (self.loading) setLoading(false);
    }
1258260
public void processConnectionClosedEvent(WSJdbcConnection handle) 
    throws ResourceException {
        //A connection handle was closed - must notify the connection manager
        // of the close on the handle.  JDBC connection handles
        // which are closed are not allowed to be reused because there is no
        // guarantee that the user will not try to reuse an already closed JDBC handle.

        // Only send the event if the application is requesting the close. 
        if (cleaningUpHandles)
            return;

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        // Fill in the ConnectionEvent only if needed. 
        connEvent.recycle(ConnectionEvent.CONNECTION_CLOSED, null, handle);

        if (isTraceOn && tc.isEventEnabled())
            Tr.event(this, tc, "Firing CONNECTION CLOSED", handle);

        try {
            removeHandle(handle); 

            // - Remove resetting autocommit in connection close time
        } catch (NullPointerException nullX) {
            // No FFDC code needed.  ManagedConnection is already closed.

            // A ConnectionError situation may
            // trigger a ManagedConnection close before the handle sends the ConnectionClosed
            // event.  When the event is sent the ManagedConnection is already closed.  If so,
            // just do a no-op here.
            if (handlesInUse == null) {
                if (isTraceOn && tc.isEventEnabled())
                    Tr.event(this, tc, "ManagedConnection already closed"); 
                return;
            } else
                throw nullX;
        }

        if (numHandlesInUse == 0) 
        {
            if (haveVendorConnectionPropertiesChanged) {
                try {

                    helper.doConnectionVendorPropertyReset(this.sqlConn, CONNECTION_VENDOR_DEFAULT_PROPERTIES);
                } catch (SQLException sqle) {
                    FFDCFilter.processException(sqle, getClass().getName(), "1905", this);
                    throw new DataStoreAdapterException("DSA_ERROR", sqle, getClass());
                }

                haveVendorConnectionPropertiesChanged = false;
            }
        } 

        // loop through the listeners
        // Not synchronized because of contract that listeners will only be changed on
        // ManagedConnection create/destroy. 

        for (int i = 0; i < numListeners; i++) {
            // send Connection Closed event to the current listener
            ivEventListeners[i].connectionClosed(connEvent); 
        }

        // Replace ConnectionEvent caching with a single reusable instance per
        // ManagedConnection. 
    }
115988
function extend(ctx, obj) {

        /**
         * @method Database#none
         * @description
         * Executes a query that expects no data to be returned. If the query returns any kind of data,
         * the method rejects.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise<null>}
         * A promise object that represents the query result:
         * - When no records are returned, it resolves with `null`.
         * - When any data is returned, it rejects with {@link errors.QueryResultError QueryResultError}:
         *   - `.message` = `No return data was expected.`
         *   - `.code` = {@link errors.queryResultErrorCode.notEmpty queryResultErrorCode.notEmpty}
         */
        obj.none = function (query, values) {
            return obj.query.call(this, query, values, npm.result.none);
        };

        /**
         * @method Database#one
         * @description
         * Executes a query that expects exactly one row of data. When 0 or more than 1 rows are returned,
         * the method rejects.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @param {function} [cb]
         * Value transformation callback, to allow in-line value change.
         * When specified, the return value replaces the original resolved value.
         *
         * The function takes only one parameter - value resolved from the query.
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the transformation callback.
         *
         * @returns {external:Promise}
         * A promise object that represents the query result:
         * - When 1 row is returned, it resolves with that row as a single object.
         * - When no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
         *   - `.message` = `No data returned from the query.`
         *   - `.code` = {@link errors.queryResultErrorCode.noData queryResultErrorCode.noData}
         * - When multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
         *   - `.message` = `Multiple rows were not expected.`
         *   - `.code` = {@link errors.queryResultErrorCode.multiple queryResultErrorCode.multiple}
         * - Resolves with the new value, if transformation callback `cb` was specified.
         *
         * @see
         * {@link Database#oneOrNone oneOrNone}
         *
         * @example
         *
         * // a query with in-line value transformation:
         * db.one('INSERT INTO Events VALUES($1) RETURNING id', [123], event => event.id)
         *     .then(data => {
         *         // data = a new event id, rather than an object with it
         *     });
         *
         * @example
         *
         * // a query with in-line value transformation + conversion:
         * db.one('SELECT count(*) FROM Users', [], c => +c.count)
         *     .then(count => {
         *         // count = a proper integer value, rather than an object with a string
         *     });
         *
         */
        obj.one = function (query, values, cb, thisArg) {
            const v = obj.query.call(this, query, values, npm.result.one);
            return transform(v, cb, thisArg);
        };

        /**
         * @method Database#many
         * @description
         * Executes a query that expects one or more rows. When the query returns no rows, the method rejects.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise}
         * A promise object that represents the query result:
         * - When 1 or more rows are returned, it resolves with the array of rows.
         * - When no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
         *   - `.message` = `No data returned from the query.`
         *   - `.code` = {@link errors.queryResultErrorCode.noData queryResultErrorCode.noData}
         */
        obj.many = function (query, values) {
            return obj.query.call(this, query, values, npm.result.many);
        };

        /**
         * @method Database#oneOrNone
         * @description
         * Executes a query that expects 0 or 1 rows, to resolve with the row-object when 1 row is returned,
         * and with `null` when nothing is returned. When the query returns more than 1 row, the method rejects.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @param {function} [cb]
         * Value transformation callback, to allow in-line value change.
         * When specified, the return value replaces the original resolved value.
         *
         * The function takes only one parameter - value resolved from the query.
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the transformation callback.
         *
         * @returns {external:Promise}
         * A promise object that represents the query result:
         * - When no rows are returned, it resolves with `null`.
         * - When 1 row is returned, it resolves with that row as a single object.
         * - When multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
         *   - `.message` = `Multiple rows were not expected.`
         *   - `.code` = {@link errors.queryResultErrorCode.multiple queryResultErrorCode.multiple}
         * - Resolves with the new value, if transformation callback `cb` was specified.
         *
         * @see
         * {@link Database#one one},
         * {@link Database#none none},
         * {@link Database#manyOrNone manyOrNone}
         *
         * @example
         *
         * // a query with in-line value transformation:
         * db.oneOrNone('SELECT id FROM Events WHERE type = $1', ['entry'], e => e && e.id)
         *     .then(data => {
         *         // data = the event id or null (rather than object or null)
         *     });
         *
         */
        obj.oneOrNone = function (query, values, cb, thisArg) {
            const v = obj.query.call(this, query, values, npm.result.one | npm.result.none);
            return transform(v, cb, thisArg);
        };

        /**
         * @method Database#manyOrNone
         * @description
         * Executes a query that expects any number of rows.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise<Array>}
         * A promise object that represents the query result:
         * - When no rows are returned, it resolves with an empty array.
         * - When 1 or more rows are returned, it resolves with the array of rows.
         *
         * @see
         * {@link Database#any any},
         * {@link Database#many many},
         * {@link Database#none none}
         *
         */
        obj.manyOrNone = function (query, values) {
            return obj.query.call(this, query, values, npm.result.many | npm.result.none);
        };

        /**
         * @method Database#any
         * @description
         * Executes a query that expects any number of rows.
         * This is simply a shorter alias for method {@link Database#manyOrNone manyOrNone}.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise<Array>}
         * A promise object that represents the query result:
         * - When no rows are returned, it resolves with an empty array.
         * - When 1 or more rows are returned, it resolves with the array of rows.
         *
         * @see
         * {@link Database#manyOrNone manyOrNone},
         * {@link Database#map map},
         * {@link Database#each each}
         *
         */
        obj.any = function (query, values) {
            return obj.query.call(this, query, values, npm.result.any);
        };

        /**
         * @method Database#result
         * @description
         * Executes a query without any expectation for the return data, to resolve with the
         * original $[Result] object when successful.
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @param {function} [cb]
         * Value transformation callback, to allow in-line value change.
         * When specified, the return value replaces the original resolved value.
         *
         * The function takes only one parameter - value resolved from the query.
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the transformation callback.
         *
         * @returns {external:Promise}
         * A promise object that represents the query result:
         * - resolves with the original $[Result] object (by default);
         * - resolves with the new value, if transformation callback `cb` was specified.
         *
         * @example
         *
         * // use of value transformation:
         * // deleting rows and returning the number of rows deleted
         * db.result('DELETE FROM Events WHERE id = $1', [123], r => r.rowCount)
         *     .then(data => {
         *         // data = number of rows that were deleted
         *     });
         *
         * @example
         *
         * // use of value transformation:
         * // getting only column details from a table
         * db.result('SELECT * FROM Users LIMIT 0', null, r => r.fields)
         *     .then(data => {
         *         // data = array of column descriptors
         *     });
         *
         */
        obj.result = function (query, values, cb, thisArg) {
            const v = obj.query.call(this, query, values, npm.special.cache.resultQuery);
            return transform(v, cb, thisArg);
        };

        /**
         * @method Database#multiResult
         * @description
         * Executes a multi-query string, without any expectation for the return data, to resolve with an array
         * of the original $[Result] objects when successful.
         *
         * The operation is atomic, i.e. all queries are executed in a single transaction, unless there are explicit
         * `BEGIN/COMMIT` commands included in the query string to divide it into multiple transactions.
         *
         * @param {string|function|object} query
         * Multi-query string to be executed, which can be any of the following types:
         * - A non-empty string that can contain any number of queries
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise<external:Result[]>}
         *
         * @see {@link Database#multi multi}
         *
         */
        obj.multiResult = function (query, values) {
            return obj.query.call(this, query, values, npm.special.cache.multiResultQuery);
        };

        /**
         * @method Database#multi
         * @description
         * Executes a multi-query string without any expectation for the return data, to resolve with an array
         * of arrays of rows when successful.
         *
         * The operation is atomic, i.e. all queries are executed in a single transaction, unless there are explicit
         * `BEGIN/COMMIT` commands included in the query string to divide it into multiple transactions.
         *
         * @param {string|function|object} query
         * Multi-query string to be executed, which can be any of the following types:
         * - A non-empty string that can contain any number of queries
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @returns {external:Promise<Array<Array>>}
         *
         * @see {@link Database#multiResult multiResult}
         *
         * @example
         *
         * db.multi('SELECT * FROM users;SELECT * FROM products')
         *    .then(([users, products]) => {
         *        // we get data from all queries at once
         *    })
         *    .catch(error => {
         *        // error
         *    });
         */
        obj.multi = function (query, values) {
            return obj.query.call(this, query, values, npm.special.cache.multiResultQuery)
                .then(data => data.map(a => a.rows));
        };

        /**
         * @method Database#stream
         * @description
         * Custom data streaming, with the help of $[pg-query-stream].
         *
         * This method doesn't work with the $[Native Bindings], and if option `pgNative`
         * is set, it will reject with `Streaming doesn't work with Native Bindings.`
         *
         * @param {QueryStream} qs
         * Stream object of type $[QueryStream].
         *
         * @param {Database.streamInitCB} initCB
         * Stream initialization callback.
         *
         * It is invoked with the same `this` context as the calling method.
         *
         * @returns {external:Promise}
         * Result of the streaming operation.
         *
         * Once the streaming has finished successfully, the method resolves with
         * `{processed, duration}`:
         * - `processed` - total number of rows processed;
         * - `duration` - streaming duration, in milliseconds.
         *
         * Possible rejections messages:
         * - `Invalid or missing stream object.`
         * - `Invalid stream state.`
         * - `Invalid or missing stream initialization callback.`
         */
        obj.stream = function (qs, init) {
            return obj.query.call(this, qs, init, npm.special.cache.streamQuery);
        };

        /**
         * @method Database#func
         * @description
         * Executes a query against a database function by its name: `SELECT * FROM funcName(values)`.
         *
         * @param {string} funcName
         * Name of the function to be executed.
         *
         * @param {array|value} [values]
         * Parameters for the function - one value or an array of values.
         *
         * @param {queryResult} [qrm=queryResult.any] - {@link queryResult Query Result Mask}.
         *
         * @returns {external:Promise}
         *
         * A promise object as returned from method {@link Database#query query}, according to parameter `qrm`.
         *
         * @see
         * {@link Database#query query},
         * {@link Database#proc proc}
         */
        obj.func = function (funcName, values, qrm) {
            return obj.query.call(this, {funcName}, values, qrm);
        };

        /**
         * @method Database#proc
         * @description
         * Executes a query against a stored procedure via its name: `SELECT * FROM procName(values)`,
         * expecting back 0 or 1 rows. It resolves either with the resulting row-object, or with
         * `null` when none returned.
         *
         * The method simply forwards into {@link Database#func func}`(procName, values, queryResult.one|queryResult.none)`.
         *
         * @param {string} procName
         * Name of the stored procedure to be executed.
         *
         * @param {array|value} [values]
         * Parameters for the procedure - one value or an array of values.
         *
         * @param {function} [cb]
         * Value transformation callback, to allow in-line value change.
         * When specified, the return value replaces the original resolved value.
         *
         * The function takes only one parameter - value resolved from the query.
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the transformation callback.
         *
         * @returns {external:Promise}
         *
         * It calls {@link Database#func func}(`procName`, `values`, `queryResult.one|queryResult.none`),
         * and then returns the same result as method {@link Database#oneOrNone oneOrNone}.
         *
         * And if transformation callback `cb` was specified, it resolves with the new value.
         *
         * @see
         * {@link Database#oneOrNone oneOrNone},
         * {@link Database#func func}
         */
        obj.proc = function (procName, values, cb, thisArg) {
            const v = obj.func.call(this, procName, values, npm.result.one | npm.result.none);
            return transform(v, cb, thisArg);
        };

        /**
         * @method Database#map
         * @description
         * Creates a new array with the results of calling a provided function on every element in the array of rows
         * resolved by method {@link Database#any any}.
         *
         * It is a convenience method to reduce the following code:
         *
         * ```js
         * db.any(query, values)
         *     .then(data => {
         *         return data.map((row, index, data) => {
         *              // return a new element
         *         });
         *     });
         * ```
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} values
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @param {function} cb
         * Function that produces an element of the new array, taking three arguments:
         * - `row` - the current row object being processed in the array
         * - `index` - the index of the current row being processed in the array
         * - `data` - the original array of rows resolved by method {@link Database#any any}
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the callback.
         *
         * @returns {external:Promise<Array>}
         * Resolves with the new array of values returned from the callback.
         *
         * @see
         * {@link Database#any any},
         * {@link Database#each each},
         * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.map}
         *
         * @example
         *
         * db.map('SELECT id FROM Users WHERE status = $1', ['active'], row => row.id)
         *     .then(data => {
         *         // data = array of active user id-s
         *     })
         *     .catch(error => {
         *        // error
         *     });
         *
         * @example
         *
         * db.tx(t => {
         *     return t.map('SELECT id FROM Users WHERE status = $1', ['active'], row => {
         *        return t.none('UPDATE Events SET checked = $1 WHERE userId = $2', [true, row.id]);
         *     }).then(t.batch);
         * })
         *     .then(data => {
         *         // success
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         * @example
         *
         * // Build a list of active users, each with the list of user events:
         * db.task(t => {
         *     return t.map('SELECT id FROM Users WHERE status = $1', ['active'], user => {
         *         return t.any('SELECT * FROM Events WHERE userId = $1', user.id)
         *             .then(events=> {
         *                 user.events = events;
         *                 return user;
         *             });
         *     }).then(t.batch);
         * })
         *     .then(data => {
         *         // success
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         */
        obj.map = function (query, values, cb, thisArg) {
            return obj.any.call(this, query, values)
                .then(data => data.map(cb, thisArg));
        };

        /**
         * @method Database#each
         * @description
         * Executes a provided function once per array element, for an array of rows resolved by method {@link Database#any any}.
         *
         * It is a convenience method to reduce the following code:
         *
         * ```js
         * db.any(query, values)
         *     .then(data => {
         *         data.forEach((row, index, data) => {
         *              // process the row
         *         });
         *         return data;
         *     });
         * ```
         *
         * When receiving a multi-query result, only the last result is processed, ignoring the rest.
         *
         * @param {string|function|object} query
         * Query to be executed, which can be any of the following types:
         * - A non-empty query string
         * - A function that returns a query string or another function, i.e. recursive resolution
         *   is supported, passing in `values` as `this`, and as the first parameter.
         * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
         * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
         * - {@link QueryFile} object
         *
         * @param {array|value} [values]
         * Query formatting parameters.
         *
         * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
         * - a single value - to replace all `$1` occurrences
         * - an array of values - to replace all `$1`, `$2`, ... variables
         * - an object - to apply $[Named Parameters] formatting
         *
         * When `query` is a Prepared Statement or a Parameterized Query (or their class types),
         * and `values` is not `null` or `undefined`, it is automatically set within such object,
         * as an override for its internal `values`.
         *
         * @param {function} cb
         * Function to execute for each row, taking three arguments:
         * - `row` - the current row object being processed in the array
         * - `index` - the index of the current row being processed in the array
         * - `data` - the array of rows resolved by method {@link Database#any any}
         *
         * @param {*} [thisArg]
         * Value to use as `this` when executing the callback.
         *
         * @returns {external:Promise<Array<Object>>}
         * Resolves with the original array of rows.
         *
         * @see
         * {@link Database#any any},
         * {@link Database#map map},
         * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach Array.forEach}
         *
         * @example
         *
         * db.each('SELECT id, code, name FROM Events', [], row => {
         *     row.code = parseInt(row.code);
         * })
         *     .then(data => {
         *         // data = array of events, with 'code' converted into integer
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         */
        obj.each = function (query, values, cb, thisArg) {
            return obj.any.call(this, query, values)
                .then(data => {
                    data.forEach(cb, thisArg);
                    return data;
                });
        };

        /**
         * @method Database#task
         * @description
         * Executes a callback function with automatically managed connection.
         *
         * When invoked on the root {@link Database} object, the method allocates the connection from the pool,
         * executes the callback, and once finished - releases the connection back to the pool.
         * However, when invoked inside another task or transaction, the method reuses the parent connection.
         *
         * This method should be used whenever executing more than one query at once, so the allocated connection
         * is reused between all queries, and released only after the task has finished (see $[Chaining Queries]).
         *
         * The callback function is called with one parameter - database protocol (same as `this`), extended with methods
         * {@link Task#batch batch}, {@link Task#page page}, {@link Task#sequence sequence}, plus property {@link Task#ctx ctx} -
         * the task context object. See class {@link Task} for more details.
         *
         * @param {string|number|Object} [options]
         * This parameter is optional, and presumed skipped when the first parameter is a function (`cb` parameter).
         *
         * When it is of type `string` or `number`, it is assumed to be option `tag` passed in directly. Otherwise,
         * it is expected to be an object with options as listed below.
         *
         * @param {} [options.tag]
         * Traceable context for the task (see $[tags]).
         *
         * @param {function|generator} cb
         * Task callback function, to return the result that will determine either success or failure for the operation.
         *
         * The function can be either the first of the second parameter passed into the method.
         *
         * It also can be an $[ES6 generator] or an ES7 `async` function.
         *
         * @returns {external:Promise}
         * A promise object with the result from the callback function.
         *
         * @see
         * {@link Task},
         * {@link Database#taskIf taskIf},
         * {@link Database#tx tx},
         * $[tags],
         * $[Chaining Queries]
         *
         * @example
         *
         * db.task('my-task', t => {
         *         // t.ctx = task context object
         *
         *         return t.one('SELECT id FROM Users WHERE name = $1', 'John')
         *             .then(user => {
         *                 return t.any('SELECT * FROM Events WHERE userId = $1', user.id);
         *             });
         *     })
         *     .then(data => {
         *         // success
         *         // data = as returned from the task's callback
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         * @example
         *
         * // using an ES6 generator for the callback:
         * db.task('my-task', function * (t) {
         *         // t.ctx = task context object
         *
         *         const user = yield t.one('SELECT id FROM Users WHERE name = $1', 'John');
         *         return yield t.any('SELECT * FROM Events WHERE userId = $1', user.id);
         *     })
         *     .then(data => {
         *         // success
         *         // data = as returned from the task's callback
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         */
        obj.task = function () {
            const args = npm.pubUtils.taskArgs(arguments);
            npm.assertOptions(args.options, ['tag']);
            return taskProcessor.call(this, args, false);
        };

        /**
         * @method Database#taskIf
         * @description
         * Executes a conditional task that results in an actual new {@link Database#task task}, if either condition is met or
         * when it is necessary (on the top level), or else it reuses the current connection context.
         *
         * The default condition is `not in task or transaction`, to start a task only if currently not inside another task or transaction,
         * which is the same as calling the following:
         *
         * ```js
         * db.taskIf({cnd: t => !t.ctx}, cb => {})
         * ```
         *
         * It can be useful, if you want to simplify/reduce the task + log events footprint, by creating new tasks only when necessary.
         *
         * @param {string|number|Object} [options]
         * This parameter is optional, and presumed skipped when the first parameter is a function (`cb` parameter).
         *
         * When it is of type `string` or `number`, it is assumed to be option `tag` passed in directly. Otherwise,
         * it is expected to be an object with options as listed below.
         *
         * @param {} [options.tag]
         * Traceable context for the task/transaction (see $[tags]).
         *
         * @param {boolean|function} [options.cnd]
         * Condition for creating a ({@link Database#task task}), if it is met.
         * It can be either a simple boolean, or a callback function that takes the task context as `this` and as the first parameter.
         *
         * Default condition (when it is not specified):
         *
         * ```js
         * {cnd: t => !t.ctx}
         * ```
         *
         * @param {function|generator} cb
         * Task callback function, to return the result that will determine either success or failure for the operation.
         *
         * The function can be either the first or the second parameter passed into the method.
         *
         * It also can be an $[ES6 generator] or an ES7 `async` function.
         *
         * @returns {external:Promise}
         * A promise object with the result from the callback function.
         *
         * @see
         * {@link Task},
         * {@link Database#task Database.task},
         * {@link Database#tx Database.tx},
         * {@link Database#txIf Database.txIf},
         * {@link TaskContext}
         *
         */
        obj.taskIf = function () {
            const args = npm.pubUtils.taskArgs(arguments);
            npm.assertOptions(args.options, ['tag', 'cnd']);
            try {
                let cnd = args.options.cnd;
                if ('cnd' in args.options) {
                    cnd = typeof cnd === 'function' ? cnd.call(obj, obj) : !!cnd;
                } else {
                    cnd = !obj.ctx; // create task, if it is the top level
                }
                // reusable only if condition fails, and not top-level:
                args.options.reusable = !cnd && !!obj.ctx;
            } catch (e) {
                return $p.reject(e);
            }
            return taskProcessor.call(this, args, false);
        };

        /**
         * @method Database#tx
         * @description
         * Executes a callback function as a transaction, with automatically managed connection.
         *
         * When invoked on the root {@link Database} object, the method allocates the connection from the pool,
         * executes the callback, and once finished - releases the connection back to the pool.
         * However, when invoked inside another task or transaction, the method reuses the parent connection.
         *
         * A transaction wraps a regular {@link Database#task task} into additional queries:
         * - it executes `BEGIN` just before invoking the callback function
         * - it executes `COMMIT`, if the callback didn't throw any error or return a rejected promise
         * - it executes `ROLLBACK`, if the callback did throw an error or return a rejected promise
         * - it executes corresponding `SAVEPOINT` commands when the method is called recursively.
         *
         * The callback function is called with one parameter - database protocol (same as `this`), extended with methods
         * {@link Task#batch batch}, {@link Task#page page}, {@link Task#sequence sequence}, plus property {@link Task#ctx ctx} -
         * the transaction context object. See class {@link Task} for more details.
         *
         * Note that transactions should be chosen over tasks only where necessary, because unlike regular tasks,
         * transactions are blocking operations, and must be used with caution.
         *
         * @param {string|number|Object} [options]
         * This parameter is optional, and presumed skipped when the first parameter is a function (`cb` parameter).
         *
         * When it is of type `string` or `number`, it is assumed to be option `tag` passed in directly. Otherwise,
         * it is expected to be an object with options as listed below.
         *
         * @param {} [options.tag]
         * Traceable context for the transaction (see $[tags]).
         *
         * @param {txMode.TransactionMode} [options.mode]
         * Transaction Configuration Mode - extends the transaction-opening command with additional configuration.
         *
         * @param {function|generator} cb
         * Transaction callback function, to return the result that will determine either success or failure for the operation.
         *
         * The function can be either the first of the second parameter passed into the method.
         *
         * It also can be an $[ES6 generator] or an ES7 `async` function.
         *
         * @returns {external:Promise}
         * A promise object with the result from the callback function.
         *
         * @see
         * {@link Task},
         * {@link Database#task Database.task},
         * {@link Database#taskIf Database.taskIf},
         * {@link TaskContext},
         * $[tags],
         * $[Chaining Queries]
         *
         * @example
         *
         * db.tx('my-transaction', t => {
         *         // t.ctx = transaction context object
         *
         *         return t.one('INSERT INTO Users(name, age) VALUES($1, $2) RETURNING id', ['Mike', 25])
         *             .then(user => {
         *                 return t.batch([
         *                     t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'created']),
         *                     t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'login'])
         *                 ]);
         *             });
         *     })
         *     .then(data => {
         *         // success
         *         // data = as returned from the transaction's callback
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         * @example
         *
         * // using an ES6 generator for the callback:
         * db.tx('my-transaction', function * (t) {
         *         // t.ctx = transaction context object
         *
         *         const user = yield t.one('INSERT INTO Users(name, age) VALUES($1, $2) RETURNING id', ['Mike', 25]);
         *         return yield t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'created']);
         *     })
         *     .then(data => {
         *         // success
         *         // data = as returned from the transaction's callback
         *     })
         *     .catch(error => {
         *         // error
         *     });
         *
         */
        obj.tx = function () {
            const args = npm.pubUtils.taskArgs(arguments);
            npm.assertOptions(args.options, ['tag', 'mode']);
            return taskProcessor.call(this, args, true);
        };

        /**
         * @method Database#txIf
         * @description
         * Executes a conditional transaction that results in an actual transaction ({@link Database#tx tx}), if the condition is met,
         * or else it executes a regular {@link Database#task task}.
         *
         * The default condition is `not in transaction`, to start a transaction only if currently not in transaction,
         * or else start a task, which is the same as calling the following:
         *
         * ```js
         * db.txIf({cnd: t => !t.ctx || !t.ctx.inTransaction}, cb => {})
         * ```
         *
         * It is useful when you want to avoid $[Nested Transactions] - savepoints.
         *
         * @param {string|number|Object} [options]
         * This parameter is optional, and presumed skipped when the first parameter is a function (`cb` parameter).
         *
         * When it is of type `string` or `number`, it is assumed to be option `tag` passed in directly. Otherwise,
         * it is expected to be an object with options as listed below.
         *
         * @param {} [options.tag]
         * Traceable context for the task/transaction (see $[tags]).
         *
         * @param {txMode.TransactionMode} [options.mode]
         * Transaction Configuration Mode - extends the transaction-opening command with additional configuration.
         *
         * @param {boolean|function} [options.cnd]
         * Condition for opening a transaction ({@link Database#tx tx}), if it is met, or a {@link Database#task task} when the condition is not met.
         * It can be either a simple boolean, or a callback function that takes the task/tx context as `this` and as the first parameter.
         *
         * Default condition (when it is not specified):
         *
         * ```js
         * {cnd: t => !t.ctx || !t.ctx.inTransaction}
         * ```
         *
         * @param {boolean|function} [options.reusable=false]
         * When `cnd` is/returns false, reuse context of the current task/transaction, if one exists.
         * It can be either a simple boolean, or a callback function that takes the task/tx context as `this`
         * and as the first parameter.
         *
         * By default, when `cnd` is/returns false, the method creates a new task. This option tells
         * the method to reuse the current task/transaction context, and not create a new task.
         *
         * This option is ignored when executing against the top level of the protocol, because on
         * that level, if no transaction is suddenly needed, a new task becomes necessary.
         *
         * @param {function|generator} cb
         * Transaction/task callback function, to return the result that will determine either
         * success or failure for the operation.
         *
         * The function can be either the first or the second parameter passed into the method.
         *
         * It also can be an $[ES6 generator] or an ES7 `async` function.
         *
         * @returns {external:Promise}
         * A promise object with the result from the callback function.
         *
         * @see
         * {@link Task},
         * {@link Database#task Database.task},
         * {@link Database#taskIf Database.taskIf},
         * {@link Database#tx Database.tx},
         * {@link TaskContext}
         *
         */
        obj.txIf = function () {
            const args = npm.pubUtils.taskArgs(arguments);
            npm.assertOptions(args.options, ['tag', 'mode', 'cnd', 'reusable']);
            try {
                let cnd;
                if ('cnd' in args.options) {
                    cnd = args.options.cnd;
                    cnd = typeof cnd === 'function' ? cnd.call(obj, obj) : !!cnd;
                } else {
                    cnd = !obj.ctx || !obj.ctx.inTransaction;
                }
                args.options.cnd = cnd;
                const reusable = args.options.reusable;
                args.options.reusable = !cnd && obj.ctx && typeof reusable === 'function' ? reusable.call(obj, obj) : !!reusable;
            } catch (e) {
                return $p.reject(e);
            }
            return taskProcessor.call(this, args, args.options.cnd);
        };

        // Task method;
        // Resolves with result from the callback function;
        function taskProcessor(params, isTX) {

            if (typeof params.cb !== 'function') {
                return $p.reject(new TypeError('Callback function is required.'));
            }

            if (params.options.reusable) {
                return config.$npm.task.callback(obj.ctx, obj, params.cb, config);
            }

            const taskCtx = ctx.clone(); // task context object;
            if (isTX) {
                taskCtx.txLevel = taskCtx.txLevel >= 0 ? (taskCtx.txLevel + 1) : 0;
            }
            taskCtx.inTransaction = taskCtx.txLevel >= 0;
            taskCtx.level = taskCtx.level >= 0 ? (taskCtx.level + 1) : 0;
            taskCtx.cb = params.cb; // callback function;
            taskCtx.mode = params.options.mode; // transaction mode;
            if (this !== obj) {
                taskCtx.context = this; // calling context object;
            }

            const tsk = new config.$npm.task.Task(taskCtx, params.options.tag, isTX, config);
            taskCtx.taskCtx = tsk.ctx;
            extend(taskCtx, tsk);

            if (taskCtx.db) {
                // reuse existing connection;
                npm.utils.addReadProp(tsk.ctx, 'useCount', taskCtx.db.useCount);
                return config.$npm.task.execute(taskCtx, tsk, isTX, config);
            }

            // connection required;
            return config.$npm.connect.pool(taskCtx, dbThis)
                .then(db => {
                    taskCtx.connect(db);
                    npm.utils.addReadProp(tsk.ctx, 'useCount', db.useCount);
                    return config.$npm.task.execute(taskCtx, tsk, isTX, config);
                })
                .then(data => {
                    taskCtx.disconnect();
                    return data;
                })
                .catch(error => {
                    taskCtx.disconnect();
                    return $p.reject(error);
                });
        }

        // lock all default properties to read-only,
        // to prevent override by the client.
        npm.utils.lock(obj, false, ctx.options);

        // extend the protocol;
        npm.events.extend(ctx.options, obj, ctx.dc);

        // freeze the protocol permanently;
        npm.utils.lock(obj, true, ctx.options);
    }
942742
function (database, callback) {
        var s = this,
            querier = s._querier;
        querier.connect();
        async.waterfall([
            function (callback) {
                querier.showTables(database, function (err, tables) {
                    callback(err, tables);
                });
            },
            function (tables, callback) {
                var tableNames = s._parseTableNames(tables);
                async.map(tableNames, function (table, callback) {
                    querier.descTable(database, table, function (err, data1) {
                        querier.selectKeyColumnUsage(database, table, function (err, data2) {
                            callback(err, {
                                name: table,
                                columns: s._parseTableData(data1),
                                relations: s._getRelations(data2, table)
                            });
                        });
                    });
                }, callback);
            },
            function (data, callback) {
                var database = {};
                data.forEach(function (data) {
                    database[data.name] = data;
                });
                callback(null, database);
            }
        ], function (err, result) {
            querier.disconnect();
            callback(err, result);
        });
        return s;
    }
54374
function _tryReconnect(dbInfo) {
    _deferReadiness(dbInfo);

    var dbContext = dbContexts[dbInfo.name];
    var forages = dbContext.forages;

    for (var i = 0; i < forages.length; i++) {
        var forage = forages[i];
        if (forage._dbInfo.db) {
            forage._dbInfo.db.close();
            forage._dbInfo.db = null;
        }
    }
    dbInfo.db = null;

    return _getOriginalConnection(dbInfo).then(function (db) {
        dbInfo.db = db;
        if (_isUpgradeNeeded(dbInfo)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
        }
        return db;
    }).then(function (db) {
        // store the latest db reference
        // in case the db was upgraded
        dbInfo.db = dbContext.db = db;
        for (var i = 0; i < forages.length; i++) {
            forages[i]._dbInfo.db = db;
        }
    })["catch"](function (err) {
        _rejectReadiness(dbInfo, err);
        throw err;
    });
}
325956
function toSQL(method) {
    method = method || this.method;
    var val = this[method]();
    var defaults = {
      method: method,
      options: assign({}, this.options),
      bindings: this.formatter.bindings
    };
    if (typeof val === 'string') {
      val = { sql: val };
    }

    if (method === 'select' && this.single.as) {
      defaults.as = this.single.as;
    }
    var out = assign(defaults, val);
    debug(out);
    return out;
  }