Expects the connection to behave like an instance of +Mysql+
 If you need something else, replace +acquire_lock+ with your own code.
 Or define your own lock_function while configuring a new Revenant task.
356445
def acquire_lock(lock_name)
      begin
        acquired = false
        sql = lock_query(lock_name)
        connection.query(sql) do |result|
          acquired = result.fetch_row.first == "1"
        end
        acquired
      rescue ::Exception
        false
      end
    end
865946
def acquire(self, lock_transactions=None):
        

        if not self.personal_lock.acquire(timeout=self.lock_timeout):
            raise LockTimeoutError(self)

        self.with_count += 1

        if lock_transactions is None:
            lock_transactions = self.lock_transactions

        if lock_transactions and self.db_state.active_connection is not self:
            if not self.db_state.transaction_lock.acquire(timeout=self.lock_timeout):
                self.personal_lock.release()
                raise LockTimeoutError(self)

            self.db_state.active_connection = self

        if not self.db_state.lock.acquire(timeout=self.lock_timeout):
            self.personal_lock.release()

            if lock_transactions:
                self.db_state.active_connection = None
                self.db_state.transaction_lock.release()

            raise LockTimeoutError(self)

        try:
            # If the connection is closed, an exception is thrown
            in_transaction = self.in_transaction
        except sqlite3.ProgrammingError:
            in_transaction = False

        self.was_in_transaction = in_transaction
480337
function(sql, attrs, callback) {
    var promise = this.definition.store.connection.raw(sql, attrs)

    if (typeof callback === 'function') {
      promise.then(callback)
    }

    return promise
  }
1201780
function (backend) {

    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(backend.opts);
    backend.count ++;
      
    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);
        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
             backend.Debug (4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
             
        } else { 
            throw err;  // server variable configures this)
        };
    });
    
    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
             backend.Debug (4, "MySQL connection fail [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
            
        } else {
            backend.Debug (5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
}
972407
def execute_sql(self, *args, **kwargs):
        
        assert self._allow_sync, (
            "Error, sync query is not allowed! Call the `.set_allow_sync()` "
            "or use the `.allow_sync()` context manager.")
        if self._allow_sync in (logging.ERROR, logging.WARNING):
            logging.log(self._allow_sync,
                        "Error, sync query is not allowed: %s %s" %
                        (str(args), str(kwargs)))
        return super().execute_sql(*args, **kwargs)
1164216
def _init_client():
    
    if client is not None:
        return

    global _mysql_kwargs, _table_name
    _mysql_kwargs = {
        'host': __opts__.get('mysql.host', '127.0.0.1'),
        'user': __opts__.get('mysql.user', None),
        'passwd': __opts__.get('mysql.password', None),
        'db': __opts__.get('mysql.database', _DEFAULT_DATABASE_NAME),
        'port': __opts__.get('mysql.port', 3306),
        'unix_socket': __opts__.get('mysql.unix_socket', None),
        'connect_timeout': __opts__.get('mysql.connect_timeout', None),
        'autocommit': True,
    }
    _table_name = __opts__.get('mysql.table_name', _table_name)
    # TODO: handle SSL connection parameters

    for k, v in _mysql_kwargs.items():
        if v is None:
            _mysql_kwargs.pop(k)
    kwargs_copy = _mysql_kwargs.copy()
    kwargs_copy['passwd'] = "<hidden>"
    log.info("mysql_cache: Setting up client with params: %r", kwargs_copy)
    # The MySQL client is created later on by run_query
    _create_table()
1173894
def __execute_text(self, query, **replacements):
        

        # We've had persistent and long-term issues where we can't access tables 
        # from another client because they're locked, as well as getting the 
        # "gone away" error quite frequenctly. Per the documentation, apparently 
        # it is common to -not- reuse the same session from request to request,
        # and we believe this to be the problem. Hopefully it's fixed, now.
        #
        # REF: http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it
        session = self.__get_session()
        
        try:
            records = session.execute(query, replacements)
        except:
            _LOGGER.exception("Query failure:\n%s", query)

            raise

        # Verifying that we have a realized list of results before we commit 
        # the transaction.

        try:
            records = list(records)
        finally:
            session.commit()

        for record in records:
            yield dict(record)
563508
def fetch(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch()
832900
def connection(state = nil, &block)
      opts = merge_options(options, state || {})
      validate_options(opts)
      conn_opts = connection_options(opts)

      if @connection && @connection_options == conn_opts
        reuse_connection(&block)
      else
        create_new_connection(conn_opts, &block)
      end
    end
1017966
def _connect(**kwargs):
    '''
    
    '''
    connargs = dict()

    # Shamelessy ripped from the mysql module
    def __connarg(name, key=None, default=None):
        '''
        Add key to connargs, only if name exists in our kwargs or as
        netscaler.<name> in __opts__ or __pillar__ Evaluate in said order - kwargs,
        opts then pillar. To avoid collision with other functions, kwargs-based
        connection arguments are prefixed with 'netscaler_' (i.e.
        'netscaler_host', 'netscaler_user', etc.).
        '''
        if key is None:
            key = name
        if name in kwargs:
            connargs[key] = kwargs[name]
        else:
            prefix = 'netscaler_'
            if name.startswith(prefix):
                try:
                    name = name[len(prefix):]
                except IndexError:
                    return
            val = __salt__['config.option']('netscaler.{0}'.format(name), None)
            if val is not None:
                connargs[key] = val
            elif default is not None:
                connargs[key] = default

    __connarg('netscaler_host', 'host')
    __connarg('netscaler_user', 'user')
    __connarg('netscaler_pass', 'pass')
    __connarg('netscaler_useSSL', 'useSSL', True)

    nitro = NSNitro(connargs['host'], connargs['user'], connargs['pass'], connargs['useSSL'])
    try:
        nitro.login()
    except NSNitroError as error:
        log.debug('netscaler module error - NSNitro.login() failed: %s', error)
        return None
    return nitro
1073656
def set_up(self, u, engine):
        """"""
        # add the reconnecting PoolListener that will detect a
        # disconnected connection and automatically start a new
        # one.  This provides a measure of additional safety over
        # the pool_recycle parameter, and is useful when e.g., the
        # mysql server goes away
        def checkout_listener(dbapi_con, con_record, con_proxy):
            try:
                cursor = dbapi_con.cursor()
                cursor.execute("SELECT 1")
            except dbapi_con.OperationalError as ex:
                if self.is_disconnect(ex.args):
                    # sqlalchemy will re-create the connection
                    log.msg('connection will be removed')
                    raise sa.exc.DisconnectionError()
                log.msg('exception happened {}'.format(ex))
                raise

        # older versions of sqlalchemy require the listener to be specified
        # in the kwargs, in a class instance
        if sautils.sa_version() < (0, 7, 0):
            class ReconnectingListener:
                pass
            rcl = ReconnectingListener()
            rcl.checkout = checkout_listener
            engine.pool.add_listener(rcl)
        else:
            sa.event.listen(engine.pool, 'checkout', checkout_listener)
1345062
def _MakeConnection(self, database=""):
    """"""
    first_attempt_time = time.time()
    wait_time = config.CONFIG["Mysql.max_connect_wait"]
    while wait_time == 0 or time.time() - first_attempt_time < wait_time:
      try:
        connection_args = dict(
            user=config.CONFIG["Mysql.database_username"],
            db=database,
            charset="utf8",
            passwd=config.CONFIG["Mysql.database_password"],
            autocommit=True,
            cursorclass=cursors.DictCursor,
            host=config.CONFIG["Mysql.host"],
            port=config.CONFIG["Mysql.port"])

        key_path = config.CONFIG["Mysql.client_key_path"]
        if key_path:
          cert_path = config.CONFIG["Mysql.client_cert_path"]
          ca_cert_path = config.CONFIG["Mysql.ca_cert_path"]
          logging.debug("Client key file configured, trying to use SSL.")

          connection_args["ssl"] = {
              "key": key_path,
              "cert": cert_path,
              "ca": ca_cert_path,
          }

        return MySQLdb.connect(**connection_args)

      except MySQLdb.OperationalError as e:
        # This is a fatal error, we just raise the top level exception here.
        if "Access denied" in str(e):
          raise Error(str(e))

        if "Can't connect" in str(e):
          logging.warning("Datastore connection retrying after failed with %s.",
                          str(e))
          time.sleep(.5)
          continue
        raise

    raise IOError("Unable to connect to Mysql database.")
417657
def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
		""""""
		i = 0
		errcode = 0
		caughte = None
		while i < self.numTries:
			i += 1
			try:	
				cursor = self.connection.cursor(cursorClass)
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				if InnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				self.lastrowid = int(cursor.lastrowid)
				cursor.close()
				return results
			except MySQLdb.OperationalError, e:
				errcode = e[0]
				# errcodes of 2006 or 2013 usually indicate a dropped connection  
				# errcode 1100 is an error with table locking
				print(e)
				self.connection.ping(True)
				caughte = e
				continue
			except:				
				traceback.print_exc()
				break
		
		sys.stderr.write("\nSQL execution error in query at %s:" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
		sys.stderr.write("\n %s." % sql)
		sys.stderr.flush()
		sys.stderr.write("\nErrorcode: '%s'.\n" % (str(caughte)))
		sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
155055
function MysqlVault(name, logger) {
	var that = this;

	// required exposed properties

	this.name = name;                  // the unique vault name
	this.archive = new Archive(this);  // archivist bindings

	// internals

	this.mysql = null;                 // node-mysql library
	this.config = null;                   // the URI that connections will be established to
	this.pool = null;                  // node-mysql connection pool
	this.logger = logger;

	/* jshint camelcase:false */
	// connection is here for backward compat, please use pool from now on
	this.__defineGetter__('connection', function () {
		logger.debug('Accessing the "connection" property on the mysql vault is deprecated, please' +
			' use the "pool" property');
		return that.pool;
	});
}
1153833
function( collectionID, key, data) {
            collectionID = collectionID.toLowerCase();
            var deferred = q.defer();

            // acquire a connection from the pool
            db.getClient().then( function(dbClient) {
                if ( !dbClient ) {
                    throw Error("Failed to acquire sqlite client");
                }

                // do any necessary dynamic schema syncs, if its supported
                schemaSyncer.prepCollection(collectionID).then( function() {
                    if ( typeof data !== "object" ) {
                        // the data is a primitive
                        // therefore its a table with a single column, whose value is that primitive
                    } else if ( data && !data['_id'] ) {
                        // the data is an object
                        data._id = key;
                    }
                })
                .then( function() {
                    return expandIfNecessary(collectionID, schemaSyncer.getTableSchema(collectionID), key, data);
                })

                // start a transaction using the acquired db connection
                .then( function() {
                    return startTx(dbClient);
                })

                // first try an update
                .then( function() {
                    var sql = sqlAdaptor.createUpdateSQL(collectionID, data, key);
                    return query(dbClient, sql).then(
                        // success
                        function(dbResult) {
                            var r = dbResult.results();
                            return q.resolve(r.rowCount >= 1);
                        },

                        // error
                        function(e) {
                            return rollbackTx(dbClient, e).finally( function() {
                                deferred.reject(e);
                            });
                        }
                    );
                })

                // if the update fails (because this requires an insert), try to insert the data
                .then( function(updated) {
                    if (updated ) {
                        // we're done
                        return q.resolve(data);
                    } else {
                        // otherwise do insert
                        var sql = sqlAdaptor.createInsertSQL(collectionID, data, key);
                        return query(dbClient, sql).then(
                            // success
                            function(dbResult) {
                                var r = dbResult.results();
                                if (r.rowCount < 1 ) {
                                    dbClient.release();
                                    throwError("failed to insert");
                                }
                                return q.resolve(data);
                            },

                            // error
                            function(e) {
                                return rollbackTx(dbClient, e).finally( function() {
                                    deferred.reject(e);
                                });
                            }
                        );
                    }
                })

                // commit the transaction if no problems are encountered, this should also close the acquired db client
                // and return it to the connection pool
                .then( function(r) {
                    return commitTx(dbClient).then( function() {
                        deferred.resolve(r);
                    });
                })

                // ultimately rollback if there is any upstream thrown exception caught
                .catch(function(e) {
                    return rollbackTx(dbClient, e).finally( function() {
                        deferred.reject(e);
                    });
                })

                // always try to release the client, if it exists
                .finally(function() {
                    if ( dbClient ) {
                        dbClient.release();
                    }
                });
            })
            // failed to acquire the client
            .fail( function(e) {
                deferred.reject(e);
            });

            return deferred.promise;
        }
503891
def _add_process_guards(self, engine):
        

        @sqlalchemy.event.listens_for(engine, "connect")
        def connect(dbapi_connection, connection_record):
            connection_record.info['pid'] = os.getpid()

        @sqlalchemy.event.listens_for(engine, "checkout")
        def checkout(dbapi_connection, connection_record, connection_proxy):
            pid = os.getpid()
            if connection_record.info['pid'] != pid:
                self.logger.debug(
                    "Parent process %(orig)s forked (%(newproc)s) with an open database connection, "
                    "which is being discarded and recreated." % {"newproc": pid, "orig": connection_record.info['pid']})
                connection_record.connection = connection_proxy.connection = None
                raise exc.DisconnectionError(
                    "Connection record belongs to pid %s, attempting to check out in pid %s" % (
                        connection_record.info['pid'], pid)
                )
125632
def check_db_connection():
    '''
    
    '''
    # mysql is lazily connected to in django.
    # connection.connection is None means
    # you have not connected to mysql before
    if connection.connection and not connection.is_usable():
        # destroy the default mysql connection
        # after this line, when you use ORM methods
        # django will reconnect to the default mysql
        logger.debug('deleted default connection')
        del connections._connections.default