Override to provide any additional validation. By default the promise is called back with true.

@param {*} connection the conneciton to validate.

@return {comb.Promise} called back with a valid or invalid state.
964872
function (conn) {
            if (!this.__validateConnectionCB) {
                var ret = new Promise();
                ret.callback(true);
                return ret;
            } else {
                return this.__validateConnectionCB(conn);
            }
        }
149408
function responsePromise(response) {
				response.status = response.status || 200;
				return $q(function(resolve, reject) {
					(response.status >= 200 && response.status <= 299 ? resolve : reject)(response);
				});
			}
370031
function () {
        "use strict";
    
        var events = new Events({'bind': this});
    
        /**
         * Triggers the connect:before event that can be extended by binding
         * to beyond.sockets.bind('connect:before', query, host)
         *
         * @param host {string} The host where the connection is going to be stablished
         * @returns {object} The connection query
         */
        this.getConnectionParams = function (host) {
    
            var query = {};
            events.trigger('connect:before', query, host);
            return query;
    
        };
    
    }
1318524
function _check(asyncClient, route) {
    return new Promise((resolve, reject) => {
        // 有问题时直接执行真实的fetch方法
        if (!asyncClient) {
            return reject(RESULT.NO_ASYNC_CLIENT);
        }

        // 如果远程服务未启动也需要放弃async
        if (!route) {
            return reject(RESULT.NO_ROUTE);
        }

        let i = 0;
        let checkT;

        function checkConnect() {
            if (asyncClient.isConnected()) {
                // 如果已经连接成功，则清除定时器，并返回
                if (checkT) {
                    clearTimeout(checkT);
                }

                resolve();
            } else if (i > 9) {
                // 如果重试次数大于了10次，也终止，清除定时器，并返回
                if (checkT) {
                    clearTimeout(checkT);
                }

                alert(`mockstar async 服务未启动！请检查 ${asyncClient.getURI()} 是否已启动`);
                reject(RESULT.NOT_CONNECTED);
            } else {
                i++;
                // 使之异步，避免 websocket 还未连接成功
                checkT = setTimeout(() => {
                    checkConnect();
                }, 10);
            }
        }

        checkConnect();
    });
}
574274
protected void setSICoreConnection(SICoreConnection connection)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setSICoreConnection", connection);

      //Retrieve Client Conversation State if necessary
      validateConversationState();
      cConState.setSICoreConnection(connection);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setSICoreConnection");
   }
824323
function (event) {

	// check if connection object exists
	if (typeof event.conn === 'undefined') {
		LOG.error('no connection records, cannot respond to request', l_name);
		return false;
	}

	// if no mechanism to store (such as from a bot), just ignore
	// TODO: cleaner approach?
	if (event.conn.type !== 'socket' ||
    	event.conn.connector.queuedEvents === undefined) {
		return true;
	}

	var socket = event.conn.connector;

	// check if id exist
	if (socket.queuedEvents.hasOwnProperty(event.id) === false) {
		LOG.error('event not found. id = ' + event.id, l_name);
		LOG.stack();
		return false;
	}

	// remove current event from the socket's event queues
	delete socket.queuedEvents[event.id];

	return true;
}
549847
function getConnection(options) {
  debug('getConnection','start',options);

  let key = null;
  let promise = null;
  try {
    //clone options
    options = clone(options);

    //serialize the options as a key for pools
    key = stringify(options || {});

    //if there's already a promise for the given connection, return it
    if (promises[key]) return promises[key];

    //create a new promise for the given connection options
    promise = promises[key] = createConnectionPromise(key, options);

    debug('getConnection','success')
    return promise;
  } catch(err) {
    debug('getConnection','error',err);
    return Promise.reject(err);
  }
}
1162999
function(command, callback) {
    var self = this;
    return new Promise(function(resolve, reject) {
        var prCB = function(err, data) {
          if (err) {
            log.error(err.message);
            log.debug(command);
          }
          return (err ? reject('err') : resolve(data));
        };
        self.connection.execute(command, function(err, result) {
          prCB(err, result)
        });
    });
  }
430898
function (connection, sessionRead) {
        connection = OT.Connection.fromHash(connection);
        if (sessionRead || session.connection && connection.id !== session.connection.id) {
          session.connections.add( connection );
          delayedSessionEvents.triggerConnectionCreated(connection);
        }

        OT.$.forEach(OT.$.keys(unconnectedStreams), function(streamId) {
          var stream = unconnectedStreams[streamId];
          if (stream && connection.id === stream.connection.id) {
            // dispatch streamCreated event now that the connectionCreated has been dispatched
            parseAndAddStreamToSession(stream, session);
            delete unconnectedStreams[stream.id];
            
            var payload = {
              debug: sessionRead ? 'connection came in session#read' :
                'connection came in connection#created',
              streamId : stream.id,
              connectionId : connection.id
            };
            session.logEvent('streamCreated', 'warning', payload);
          }
        });
        
        return connection;
      }
1294928
function handleConnectionCallback(err, resolve, reject, key, connection) {
  debug('handleConnectionCallback','start');

  //error, remove cached entry, reject the promise
  if (err) {
    debug('handleConnectionCallback','error',err);
    delete promises[key];
    return reject(err);
  }

  //patch close method for caching
  shadowClose(connection);

  //create a reference to the original connection for cleanup
  connection._mssqlngKey = key;

  //add connection to the pool
  connections[connection._mssqlngKey] = connection;

  //resolve the promise
  debug('handleConnectionCallback','success');
  return resolve(connection);
}
429863
function(connection, collection, query, options, cb) {
      return connections[connection].query(query, options, cb);
    }
518730
function Connection(context)
{
  // validate input
  Errors.assertInternal(Util.isObject(context));

  var services = context.getServices();
  var connectionConfig = context.getConnectionConfig();

  // generate an id for the connection
  var id = uuidv4();

  /**
   * Returns true if the connection is active otherwise false
   *
   * @returns {boolean}
   */
  this.isUp = function()
  {
    return services.sf.isConnected();
  };

  this.getServiceName = function()
  {
    return services.sf.getServiceName();
  };

  this.getClientSessionKeepAlive = function()
  {
    return services.sf.getClientSessionKeepAlive();
  };

  this.getClientSessionKeepAliveHeartbeatFrequency = function()
  {
    return services.sf.getClientSessionKeepAliveHeartbeatFrequency();
  };

  /**
   * Returns the connection id.
   *
   * @returns {String}
   */
  this.getId = function()
  {
    return id;
  };

  this.heartbeat = function(self)
  {
    self.execute({
      sqlText: 'select /* nodejs:heartbeat */ 1;',
      complete: function () {},
      internal: true,
    });
  };

  /**
   * Establishes a connection if we aren't in a fatal state.
   *
   * @param {Function} callback
   *
   * @returns {Object} the connection object.
   */
  this.connect = function(callback)
  {
    // invalid callback
    Errors.checkArgumentValid(
        !Util.exists(callback) || Util.isFunction(callback),
        ErrorCodes.ERR_CONN_CONNECT_INVALID_CALLBACK);

    // connect to the snowflake service and provide our own callback so that
    // the connection can be passed in when invoking the connection.connect()
    // callback
    var self = this;

    services.sf.connect(
    {
      callback: function(err)
      {
        if (Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE))
        {
          self.keepalive = setInterval(self.heartbeat, Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY) * 1000, self);
        }

        if (Util.isFunction(callback))
        {
          callback(Errors.externalize(err), self);
        }
      }
    });

    // return the connection to facilitate chaining
    return this;
  };

  /**
   * Executes a statement.
   *
   * @param {Object} options
   *
   * @returns {Object}
   */
  this.execute = function(options)
  {
    return Statement.createRowStatementPreExec(
        options, services, connectionConfig);
  };

  /**
   * Fetches the result of a previously issued statement.
   *
   * @param {Object} options
   *
   * @returns {Object}
   */
  this.fetchResult = function(options)
  {
    return Statement.createRowStatementPostExec(
        options, services, connectionConfig);
  };

  /**
   * Immediately terminates the connection without waiting for currently
   * executing statements to complete.
   *
   * @param {Function} callback
   *
   * @returns {Object} the connection object.
   */
  this.destroy = function(callback)
  {
    // invalid callback
    Errors.checkArgumentValid(
        !Util.exists(callback) || Util.isFunction(callback),
        ErrorCodes.ERR_CONN_DESTROY_INVALID_CALLBACK);

    // log out of the snowflake service and provide our own callback so that
    // the connection can be passed in when invoking the connection.destroy()
    // callback
    var self = this;
    services.sf.destroy(
    {
      callback: function(err)
      {
        if (Util.exists(self.keepalive))
        {
          clearInterval(self.keepalive);
        }

        if (Util.isFunction(callback))
        {
          callback(Errors.externalize(err), self);
        }
      }
    });

    // return the connection to facilitate chaining
    return this;
  };

  /**
   * Returns a serialized version of this connection.
   *
   * @returns {String}
   */
  this.serialize = function()
  {
    return JSON.stringify(context.getConfig());
  };

  EventEmitter.call(this);
}
906455
async function createSftpConnection(client) {
  return new Promise((resolve, reject) => {
    client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp)));
  });
}
209461
function createConnectionPromise(key, options) {
  
  debug('createConnectionPromise','start');

  //create promise that resolves to a connection
  var promise = new Promise((resolve,reject)=>{
    //create a new mssql connection
    let connection = new mssql.Connection(options,(err)=>handleConnectionCallback(err, resolve, reject, key, connection));
    connection.close = ()=>promise.then((conn)=>conn.close()).catch(()=>{ delete promises[key]; delete connections[key] });
    connection.query = (templateParts, ...params)=>promise.then((conn)=>query(conn,{},templateParts,params));
    connection.queryStream = (templateParts, ...params)=>promise.then((conn)=>query(conn,{stream:true},templateParts,params));
    connection.output = require('../parameters/output');
    connection.input = require('../parameters/input');

    debug('createConnectionPromise','success');
  });

  //add mssql types to promise - convenience access
  assign(promise, mssql.TYPES); //add mssql types to promise being returned
  promise.MAX = mssql.MAX;
  
  //back reference to cache
  promise._mssqlngKey = key;

  //extended methods
  promise.close = ()=>promise.then((conn)=>conn.close()).catch(()=>{ delete promises[key]; delete connections[key] });
  promise.query = (templateParts, ...params)=>promise.then((conn)=>query(conn,{},templateParts,params));
  promise.queryStream = (templateParts, ...params)=>promise.then((conn)=>query(conn,{stream:true},templateParts,params));
  promise.output = require('../parameters/output');
  promise.input = require('../parameters/input');

  debug('createConnectionPromise','success');
  return promise;
}
651596
function Connection(conn) {
	if(!(this instanceof Connection)) {
		return new Connection(conn);
	}
	var self = this;
	if(!conn) { throw new TypeError("no connection set"); }
	self._connection = conn;
	self._connect    = Q.nfbind(self._connection.connect.bind(self._connection));
	self._query      = Q.nfbind(self._connection.query.bind(self._connection));

	// These do not have callbacks when PoolConnection is used
	//self._end        = Q.nfbind(self._connection.end.bind(self._connection));
	//self._release        = Q.nfbind(self._connection.release.bind(self._connection));

	self._changeUser = Q.nfbind(self._connection.changeUser.bind(self._connection));
	db.Connection.call(self, conn);
}
1297904
function runQuery(query, connection) {
  const config = {
    user: connection.username,
    password: connection.password,
    connection_string: connection.connection_string
  };
  // TODO use connection pool
  // TODO handle connection.maxRows

  let cn = config.connection_string;

  // Not all drivers require auth
  if (config.user) {
    cn = cn + ';Uid=' + config.user;
  }
  if (config.password) {
    cn = cn + ';Pwd=' + config.password;
  }

  return openConnection(cn)
    .then(() => executeQuery(query))
    .then(queryResult => {
      odbc.close(); // TODO consider putting into finally()?
      return Promise.resolve({ rows: queryResult, incomplete: false });
    })
    .catch(function(e) {
      console.error(e, e.stack);
    });
}
386297
function (connection) {
            var headerStr = connection.getAllResponseHeaders(), headers = {};

            if (headerStr) {
                var headerLines = headerStr.split("\n");
                for (var i = 0; i < headerLines.length; i++) {
                    var delimitPos = headerLines[i].indexOf(":");
                    if (delimitPos != -1) {
                        // Trime headers
                        headers[headerLines[i].substring(0, delimitPos)] = headerLines[i].substring(delimitPos + 2).replace(/^\s+|\s+$/g, "");
                    }
                }
            }

            var response = {
                statusText : (connection.status == 1223) ? "No Content" : connection.statusText,
                getResponseHeader : headers,
                getAllResponseHeaders : headerLines,
                responseText : connection.responseText,
                responseXML : connection.responseXML
            };

            return response;
        }