self
 Returns a no_sql_connection which is bound to a mongodb adapter
 or builds a new no_sql_connection if block is given
331239
def mongodb_connection(options={}, &block)
      return @mongodb_conncetion if @mongodb_connection and !block_given?
      options.stringify_keys!
      options['adapter'] ||= 'mongodb'
      @mongodb_connection = no_sql_connection(options, &block)
    end
1277736
function (connectionName, collectionName, relations, cb) {

      var connectionObject = connections[connectionName];
      if (!connectionObject) return cb(Errors.InvalidConnection);

      async.series(
        [
          // drop the main table
          function(cb) {

            var collection = connectionObject.collections[collectionName];
            if (!collection) return cb(Errors.CollectionNotRegistered);

            collection.dropTable(function(err) {
              // ignore "table does not exist" error
              if (err && err.code === 8704) return cb();
              if (err) return cb(err);
              cb();
            });
          },

          // drop relations
          function(cb) {
            // do it in parallel
            async.eachSeries(relations,
              function(item, cb) {

                var collection = connectionObject.collections[item];
                if (!collection) return cb(Errors.CollectionNotRegistered);

                collection.dropTable(function(err) {
                  // ignore "table does not exist" error
                  if (err && err.code === 8704) return cb();
                  if (err) return cb(err);
                  cb();
                });
              },
              function(err, results) {
                if (err) return cb(err);
                cb();
              }
            );
          }
        ],
        function(err, results) {
          if (err) return cb(err);
          cb();
        }
      );
    }
563508
def fetch(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch()
1160347
def pandasSQL_builder(con, schema=None, meta=None,
                      is_cursor=False):
    
    # When support for DBAPI connections is removed,
    # is_cursor should not be necessary.
    con = _engine_builder(con)
    if _is_sqlalchemy_connectable(con):
        return SQLDatabase(con, schema=schema, meta=meta)
    elif isinstance(con, str):
        raise ImportError("Using URI string without sqlalchemy installed.")
    else:
        return SQLiteDatabase(con, is_cursor=is_cursor)
429863
function(connection, collection, query, options, cb) {
      return connections[connection].query(query, options, cb);
    }
8856
def fetch(db=None, sql=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(sql)
    rows = cur.fetchall()
    return rows
309572
async def get_object_or_none(cls, db, **kwargs):
        
        async for obj in cls.filter_by(db, limit=1, **kwargs):
            return obj
        return None
1008133
@FFDCIgnore(InvocationTargetException.class)
    Object getDB(String databaseName) throws Exception {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        lock.readLock().lock();
        try {
            if (mongoClient == null) {
                // Switch to write lock for lazy initialization
                lock.readLock().unlock();
                lock.writeLock().lock();
                try {
                    if (mongoClient == null)
                        init();
                } finally {
                    // Downgrade to read lock for rest of method
                    lock.readLock().lock();
                    lock.writeLock().unlock();
                }
            }

            Object db = MongoClient_getDB.invoke(mongoClient, databaseName);

            // authentication
            String user = (String) props.get(USER);
            if (user != null) {
                if ((Boolean) DB_isAuthenticated.invoke(db)) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "already authenticated");
                } else {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "authenticate as: " + user);
                    SerializableProtectedString password = (SerializableProtectedString) props.get(PASSWORD);
                    String pwdStr = password == null ? null : String.valueOf(password.getChars());
                    pwdStr = PasswordUtil.getCryptoAlgorithm(pwdStr) == null ? pwdStr : PasswordUtil.decode(pwdStr);
                    char[] pwdChars = pwdStr == null ? null : pwdStr.toCharArray();
                    try {
                        if (!(Boolean) DB_authenticate.invoke(db, user, pwdChars))
                            if ((Boolean) DB_isAuthenticated.invoke(db)) {
                                if (trace && tc.isDebugEnabled())
                                    Tr.debug(this, tc, "another thread must have authenticated first");
                            } else
                                throw new IllegalArgumentException(Tr.formatMessage(tc, "CWKKD0012.authentication.error", MONGO, id, databaseName));
                    } catch (InvocationTargetException x) {
                        // If already authenticated, Mongo raises:
                        // IllegalStateException: can't authenticate twice on the same database
                        // Maybe another thread did the authentication right after we checked, so check again.
                        Throwable cause = x.getCause();
                        if (cause instanceof IllegalStateException && (Boolean) DB_isAuthenticated.invoke(db)) {
                            if (trace && tc.isDebugEnabled())
                                Tr.debug(this, tc, "another thread must have authenticated first", cause);
                        } else
                            throw cause;
                    }
                }
            } else if (useCertAuth) {
                // If we specified a certificate we will already have used the client constructor that
                // specified the credential so if we have got to here we are already authenticated and
                // JIT should remove this so it will not be an overhead.
            }
            return db;
        } catch (Throwable x) {
            // rethrowing the exception allows it to be captured in FFDC and traced automatically
            x = x instanceof InvocationTargetException ? x.getCause() : x;
            if (x instanceof Exception)
                throw (Exception) x;
            else if (x instanceof Error)
                throw (Error) x;
            else
                throw new RuntimeException(x);
        } finally {
            lock.readLock().unlock();
        }
    }
1371121
async function getConnection(url, opts = {}) {

    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(url)
        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, [{ username: opts.username, passw: opts.password }])
        connection.useDatabase(dbName)
    }

    return connection;
}
205633
def _get_conn(ret):
    '''
    
    '''
    _options = _get_options(ret)

    host = _options.get('host')
    port = _options.get('port')
    db_ = _options.get('db')
    user = _options.get('user')
    password = _options.get('password')
    indexes = _options.get('indexes', False)

    # at some point we should remove support for
    # pymongo versions < 2.3 until then there are
    # a bunch of these sections that need to be supported

    if PYMONGO_VERSION > _LooseVersion('2.3'):
        conn = pymongo.MongoClient(host, port)
    else:
        conn = pymongo.Connection(host, port)
    mdb = conn[db_]

    if user and password:
        mdb.authenticate(user, password)

    if indexes:
        if PYMONGO_VERSION > _LooseVersion('2.3'):
            mdb.saltReturns.create_index('minion')
            mdb.saltReturns.create_index('jid')

            mdb.jobs.create_index('jid')
        else:
            mdb.saltReturns.ensure_index('minion')
            mdb.saltReturns.ensure_index('jid')

            mdb.jobs.ensure_index('jid')

    return conn, mdb
363929
def get_bind(self, mapper=None, clause=None):
        
        # mapper is None if someone tries to just get a connection
        if mapper is not None:
            try:
                # SA >= 1.3
                persist_selectable = mapper.persist_selectable
            except AttributeError:
                # SA < 1.3
                persist_selectable = mapper.mapped_table

            info = getattr(persist_selectable, 'info', {})
            bind_key = info.get('bind_key')
            if bind_key is not None:
                state = get_state(self.app)
                return state.db.get_engine(self.app, bind=bind_key)
        return SessionBase.get_bind(self, mapper, clause)
1226538
def get_default_query_from_module(module):
  
  if isinstance(module, types.ModuleType):
    return module.__dict__.get(_SQL_MODULE_LAST, None)
  return None
1365943
def try_mongodb_opts(self, host="localhost", database_name='INGInious'):
        
        try:
            mongo_client = MongoClient(host=host)
        except Exception as e:
            self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e)))
            return None

        try:
            database = mongo_client[database_name]
        except Exception as e:
            self._display_warning("Cannot access database %s: %s" % (database_name, str(e)))
            return None

        try:
            GridFS(database)
        except Exception as e:
            self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e)))
            return None

        return database
720090
public void unbind(String name) throws ObjectNameNotFoundException
    {
        /**
         * Is DB open? ODMG 3.0 says it has to be to call unbind.
         */
        if (!this.isOpen())
        {
            throw new DatabaseClosedException("Database is not open. Must have an open DB to call unbind");
        }
        TransactionImpl tx = getTransaction();
        if (tx == null || !tx.isOpen())
        {
            throw new TransactionNotInProgressException("Tx is not open. Must have an open TX to call lookup.");
        }

        tx.getNamedRootsMap().unbind(name);
    }
875963
def set_read_only_connection_for_block(action)
      read_pool_method = nil
      if session
        read_pool_method = session[:next_request_db_connection]
        session.delete(:next_request_db_connection) if session[:next_request_db_connection]
      end

      read_pool_method ||= seamless_database_pool_options[action.to_sym] || seamless_database_pool_options[:all]
      if read_pool_method
        SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do
          yield
        end
      else
        yield
      end
    end
756692
function mongoConnectionStringOS2(cb) {
  debug('Running in OpenShift 2, constructing db connection string from additional env vars');
  var connectionString,
    host = process.env.OPENSHIFT_MONGODB_DB_HOST,
    user = process.env.OPENSHIFT_MONGODB_DB_USERNAME,
    pass = process.env.OPENSHIFT_MONGODB_DB_PASSWORD,
    port = process.env.OPENSHIFT_MONGODB_DB_PORT,
    dbname = process.env.OPENSHIFT_APP_NAME;
  connectionString = mongodbUri.format({
    username: user,
    password: pass,
    hosts: [
      {
        host: host,
        port: port
      }
    ],
    database: dbname
  });
  process.env.FH_MONGODB_CONN_URL = connectionString;
  return cb(undefined, process.env.FH_MONGODB_CONN_URL);

}
414610
def db_conn(self):
        """"""
        if self._db_conn is None:
            try:
                self._db_conn = sqlite3.connect(':memory:')
            except sqlite3.Error as e:
                self.handle_error(e)
        return self._db_conn