Creates a connection if not already connected.

@private
@returns {mysql.Connection}
772770
function (connectionName, callback) {
        var self = this,
            _db = Transaction.databases[connectionName],
            transactionId;

        // validate db setup prior to every connection. this ensures nothing goes forward post teardown
        if (!_db) {
            callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP));
        }

        // validate connection name
        if (!connectionName) {
            callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED));
        }

        // if this transaction is already connected, then continue
        if (self.connection()) {
            // @todo implement error check when multi-db conn is attempted
            // // callback with error if connection name and current connection mismatch
            // if (connectionName !== self.connection().identity) {
            //     callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
            // }
            callback(undefined, self.connection());
            return;
        }

        // at this point, it seems like the connection has not been setup yet, so we setup one and then move forward
        transactionId = self.id(); // this will return and cache a new transaction ID if not already present

        // set the actual connection name
        self._connectionName = connectionName;

        _db.getConnection(function (error, conn) {
            if (!error) {
                self._connection = conn; // save reference
                Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc
            }

            callback(error, self._connection);
        });
    }
59047
function Connection(options) {
	
	if (!(this instanceof Connection)){
		return new Connection(options);
	}
	
	
	this.prefixCounter = 0;
	this.serverMessages = {};
	this._options = {
		username: options.username || options.user || '',
		password: options.password || '',
		host: options.host || 'localhost',
		port: options.port || 143,
		secure: options.secure === true ? { // secure = true means default behavior
			rejectUnauthorized: false // Force pre-node-0.9.2 behavior
		} : (options.secure || false),
		timeout: options.timeout || 10000, // connection timeout in msecs
		xoauth: options.xoauth,
		xoauth2: options.xoauth2
	};
	
	this._messages = {};
	this._messages = {};
	
	if (options.debug===true){
		this.debug = function(msg){
			console.log(msg);
		}
	}
	
		
	if (options.chainDebug===true){
		this.chainDebug = function(msg){
			console.log(msg);
		}
	}
	
	this.socket = null;
	
	this._messages_prefix_key={};
	this._messages_key_prefix={};
	this._messages={};
	
	
	this._msg_buffer = '';
	this._resetChainCommands();
}
1200621
async function getConnection(url, opts = {}) {
    try {
        const dbName = opts.databaseName;
        if (!dbName || dbName === '')
            throw boom.badImplementation('jollof-data-arangodb: databaseName config is required', { url, opts })

        const key = url + dbName;

        //Get connection
        let connection;
        if (connPool[key]) {
            connection = connPool[key];
        } else {
            connection = new Database(opts)
            connection.useBasicAuth(opts.username, opts.password)
            connPool[key] = connection;
        }

        //Now ensure database exists
        const dbNames = await connection.listDatabases();
        if (dbNames.indexOf(dbName) > -1) {
            //our db exists. use it.
            connection.useDatabase(dbName)
        } else {
            //our db does not exist. Attempting to create it
            await connection.createDatabase(dbName)
            connection.useDatabase(dbName)
        }

        return connection;
    } catch (e) {
        console.error(`There was an issue creating/ensuring connection to DB: ${url} with opts: ${util.inspect(opts)}`)
        throw new Error(e);
    }
}
414657
function () {
            var ret = new Promise(), conn;
            if (this.count > this.__maxObjects) {
                this.__deferredQueue.enqueue(ret);
            } else {
                //todo override getObject to make async so creating a connetion can execute setup sql
                conn = this.getObject();
                if (!conn) {
                    //we need to deffer it
                    this.__deferredQueue.enqueue(ret);
                } else {
                    ret.callback(conn);
                }
            }
            if (this.count > this.__maxObjects && !conn) {
                ret.errback(new Error("Unexpected ConnectionPool error"));
            }
            return ret.promise();
        }
429863
function(connection, collection, query, options, cb) {
      return connections[connection].query(query, options, cb);
    }
143627
public function connection()
    {
        if (!$this->connection) {
            $config = $this->app['config']['plastic'];

            $this->connection = new Connection($config);
        }

        return $this->connection;
    }
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;
    
        };
    
    }
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);
}
352610
public function connection()
    {
        if (!is_object($this->db)) {
            $this->db = new \MysqliDb();
            $this->db->addConnection($this->dbName, $this->database);
        }

        return $this;
    }
301922
public function createConnection()
    {
        $uri                = $this->pool->getConnectionAddress();
        $options            = $this->parseUri($uri);
        $options['timeout'] = $this->pool->getTimeout();

        /** @var DbPoolProperties $config */
        $config     = $this->pool->getPoolConfig();
        $strictType = $config->isStrictType();
        $fetchMode  = $config->isFetchMode();

        $serverConfig = [
            'host'        => $options['host'],
            'port'        => $options['port'],
            'user'        => $options['user'],
            'password'    => $options['password'],
            'database'    => $options['database'],
            'timeout'     => $options['timeout'],
            'charset'     => $options['charset'],
            'strict_type' => $strictType,
        ];

        if (version_compare(swoole_version(), '4.0', '>=')) {
            $serverConfig['fetch_mode'] = $fetchMode;
        }

        // init
        $mysql = new MySQL();
        $mysql->connect($serverConfig);

        // error
        if ($mysql->connected === false) {
            throw new MysqlException('Database connection error，error=' . $mysql->connect_error);
        }

        $this->originDb   = $options['database'];
        $this->connection = $mysql;
    }
550114
function initConnectionPool() {

  const setting = {
    host            : process.env.LIGHTMYSQL_HOST,
    port            : process.env.LIGHTMYSQL_PORT,
    user            : process.env.LIGHTMYSQL_USER,
    password        : process.env.LIGHTMYSQL_PASS,
    database        : process.env.APPNAME,
    connectionLimit : 10
  };

  console.log('MySQL name: ' + setting.database);
  console.log('MySQL host: ' + setting.host);
  console.log('MySQL port: ' + setting.port);
  console.log('MySQL user: ' + setting.user);
  console.log('MySQL pool: ' + setting.connectionLimit);

  return mysql.createPool(setting);
}
1194563
function connection() {
  return {
    ssl: JSON.parse(JSON.stringify(process.env.DATABASE_SSL || "")),
    host: process.env.DATABASE_HOST || "localhost",
    user: process.env.DATABASE_USER || "",
    charset: process.env.DATABASE_CHARSET || "utf8",
    password: process.env.DATABASE_PASS || "",
    database: process.env.DATABASE_NAME || ""
  };
}
507870
def sql_connection(options={}, &block)
      @sql_connection ||= Mongify::Database::SqlConnection.new(options)
      @sql_connection.instance_exec(&block) if block_given?
      @sql_connection
    end
373033
async function createMysqlConnection (connectionParams) {
    // set required defaults 
    connectionParams = _.merge(connectionParams, {
        bigNumberStrings: true,
        dateStrings: true,
        namedPlaceholders: true,
        rowsAsArray: false,
        supportBigNumbers: true,
    })

    return defined(connectionParams.connectionLimit)
        ? MySQL2.createPool(connectionParams)
        : MySQL2.createConnection(connectionParams)
}
597437
function connectionDelay() {
      var delay = self.connectionWait;
      if (delay === 0) {
        if (self.connectedAt) {
          var t = 1000;
          var connectedFor = new Date().getTime() - self.connectedAt;
          if (connectedFor < t) {
            delay = t - connectedFor;
          }
        }
      }
      return delay;
    }
369218
def connection(self):
        
        
        self._condition.acquire()
        try:
            if (self._maxconnections and self._connections >= self._maxconnections):
                raise TooManyConnections("%d connections are already equal to the max: %d" % (self._connections, self._maxconnections))
            # connection limit not reached, get a dedicated connection
            try: # first try to get it from the idle cache
                con = self._idle_cache.pop(0)
            except IndexError: # else get a fresh connection
                con = self.new_connection()
            self._connections += 1
        finally:
            self._condition.release()
        return con
829096
public static function conn()
    {
        // Auto connect using Jasny's Config class
        if (!isset(self::$connection)) {
            if (!class_exists('Jasny\Config') || !isset(\Jasny\Config::i()->db)) throw new DB_Exception("Unable to create DB connection: not configured");
            new static(\Jasny\Config::i()->db);
        }

        return self::$connection;
    }