Get a cursor for the specified transaction connection
        or acquire from the pool.
771352
async def cursor(self, conn=None, *args, **kwargs):
        
        in_transaction = conn is not None
        if not conn:
            conn = await self.acquire()
        cursor = await conn.cursor(*args, **kwargs)
        cursor.release = functools.partial(
            self.release_cursor, cursor,
            in_transaction=in_transaction)
        return cursor
140597
def _get_tough_method(self, name):
        """"""
        def tough_method(*args, **kwargs):
            execute = name.startswith('execute')
            con = self._con
            transaction = con._transaction
            if not transaction:
                con._ping_check(4)
            try:
                if con._maxusage:
                    if con._usage >= con._maxusage:
                        # the connection was used too often
                        raise con._failure
                if execute:
                    self._setsizes()
                method = getattr(self._cursor, name)
                result = method(*args, **kwargs)  # try to execute
                if execute:
                    self._clearsizes()
            except con._failures as error:  # execution error
                if not transaction:
                    try:
                        cursor2 = con._cursor(
                            *self._args, **self._kwargs)  # open new cursor
                    except Exception:
                        pass
                    else:
                        try:  # and try one more time to execute
                            if execute:
                                self._setsizes(cursor2)
                            method = getattr(cursor2, name)
                            result = method(*args, **kwargs)
                            if execute:
                                self._clearsizes()
                        except Exception:
                            pass
                        else:
                            self.close()
                            self._cursor = cursor2
                            con._usage += 1
                            return result
                        try:
                            cursor2.close()
                        except Exception:
                            pass
                try:  # try to reopen the connection
                    con2 = con._create()
                except Exception:
                    pass
                else:
                    try:
                        cursor2 = con2.cursor(
                            *self._args, **self._kwargs)  # open new cursor
                    except Exception:
                        pass
                    else:
                        if transaction:
                            self.close()
                            con._close()
                            con._store(con2)
                            self._cursor = cursor2
                            raise error  # raise the original error again
                        error2 = None
                        try:  # try one more time to execute
                            if execute:
                                self._setsizes(cursor2)
                            method2 = getattr(cursor2, name)
                            result = method2(*args, **kwargs)
                            if execute:
                                self._clearsizes()
                        except error.__class__:  # same execution error
                            use2 = False
                            error2 = error
                        except Exception as error:  # other execution errors
                            use2 = True
                            error2 = error
                        else:
                            use2 = True
                        if use2:
                            self.close()
                            con._close()
                            con._store(con2)
                            self._cursor = cursor2
                            con._usage += 1
                            if error2:
                                raise error2  # raise the other error
                            return result
                        try:
                            cursor2.close()
                        except Exception:
                            pass
                    try:
                        con2.close()
                    except Exception:
                        pass
                if transaction:
                    self._transaction = False
                raise error  # re-raise the original error again
            else:
                con._usage += 1
                return result
        return tough_method
1103580
public <C> DbxDeltaC<C> getDeltaC(Collector<DbxDeltaC.Entry<DbxEntry>, C> collector, /*@Nullable*/String cursor)
        throws DbxException
    {
        return getDeltaC(collector, cursor, false);
    }
367588
def _cursor(self):
        '''
        
        '''
        from django.db.backends.postgresql.version import get_version

        new_connection = False
        set_tz = False
        settings_dict = self.settings_dict

        if self.connection is None or connection_pools[self.alias]['settings'] != settings_dict:
            new_connection = True
            set_tz = settings_dict.get('TIME_ZONE')

            # Is this the initial use of the global connection_pools dictionary for 
            # this python interpreter? Build a ThreadedConnectionPool instance and 
            # add it to the dictionary if so.
            if self.alias not in connection_pools or connection_pools[self.alias]['settings'] != settings_dict:
                if settings_dict['NAME'] == '':
                    from django.core.exceptions import ImproperlyConfigured
                    raise ImproperlyConfigured("You need to specify NAME in your Django settings file.")
                conn_params = {
                    'database': settings_dict['NAME'],
                }
                conn_params.update(settings_dict['OPTIONS'])
                for extra in ['autocommit'] + pool_config_defaults.keys():
                    if extra in conn_params:
                        del conn_params[extra]
                if settings_dict['USER']:
                    conn_params['user'] = settings_dict['USER']
                if settings_dict['PASSWORD']:
                    conn_params['password'] = settings_dict['PASSWORD']
                if settings_dict['HOST']:
                    conn_params['host'] = settings_dict['HOST']
                if settings_dict['PORT']:
                    conn_params['port'] = settings_dict['PORT']

                self.create_connection_pool(conn_params)

            self.connection = PooledConnection(connection_pools[self.alias]['pool'], 
                                               test_query=self._test_on_borrow_query)
            self.connection.set_client_encoding('UTF8')
            self.connection.set_isolation_level(self.isolation_level)
            # We'll continue to emulate the old signal frequency in case any code depends upon it
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        cursor.tzinfo_factory = None
        if new_connection:
            if set_tz:
                cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']])
            if not hasattr(self, '_version'):
                self.__class__._version = get_version(cursor)
            if self._version[0:2] < (8, 0):
                # No savepoint support for earlier version of PostgreSQL.
                self.features.uses_savepoints = False
            if self.features.uses_autocommit:
                if self._version[0:2] < (8, 2):
                    # FIXME: Needs extra code to do reliable model insert
                    # handling, so we forbid it for now.
                    from django.core.exceptions import ImproperlyConfigured
                    raise ImproperlyConfigured("You cannot use autocommit=True with PostgreSQL prior to 8.2 at the moment.")
                else:
                    # FIXME: Eventually we're enable this by default for
                    # versions that support it, but, right now, that's hard to
                    # do without breaking other things (#10509).
                    self.features.can_return_id_from_insert = True
        return CursorWrapper(cursor)
1098255
def cursor(self):
        
        self._assert_open()
        if self.mars_enabled:
            in_tran = self._conn.tds72_transaction
            if in_tran and self._dirty:
                try:
                    return _MarsCursor(self,
                                       self._conn.create_session(self._tzinfo_factory),
                                       self._tzinfo_factory)
                except (socket.error, OSError) as e:
                    self._conn.close()
                    raise
            else:
                try:
                    return _MarsCursor(self,
                                       self._conn.create_session(self._tzinfo_factory),
                                       self._tzinfo_factory)
                except (socket.error, OSError) as e:
                    if e.errno not in (errno.EPIPE, errno.ECONNRESET):
                        raise
                    self._conn.close()
                except ClosedConnectionError:
                    pass
                self._assert_open()
                return _MarsCursor(self,
                                   self._conn.create_session(self._tzinfo_factory),
                                   self._tzinfo_factory)
        else:
            return Cursor(self,
                          self._conn.main_session,
                          self._tzinfo_factory)
1333873
public final Cursor<T> queryByLikeExample (Connection conn, T obj,
                                               FieldMask mask)
    {
        return new Cursor<T>(this, conn, obj, mask, true);
    }
1320267
@Nullable
    public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {
        return this.first.get(txn, first);
    }
565607
async def release_cursor(self, cursor, in_transaction=False):
        
        conn = cursor.connection
        await cursor.close()
        if not in_transaction:
            self.release(conn)
382825
protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException {
		boolean tryAgain = false;
		Connection result = null;
		Connection oldRawConnection = connectionHandle.getInternalConnection();
		String url = this.getConfig().getJdbcUrl();
		
		int acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();
		long acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();
		AcquireFailConfig acquireConfig = new AcquireFailConfig();
		acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));
		acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);
		acquireConfig.setLogMessage("Failed to acquire connection to "+url);
		ConnectionHook connectionHook = this.getConfig().getConnectionHook();
		do{ 
			result = null;
			try { 
				// keep track of this hook.
				result = this.obtainRawInternalConnection();
				tryAgain = false;

				if (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){
					logger.info("Successfully re-established connection to "+url);
				}
				
				this.getDbIsDown().set(false);
				
				connectionHandle.setInternalConnection(result);
				
				// call the hook, if available.
				if (connectionHook != null){
					connectionHook.onAcquire(connectionHandle);
				}

				
				ConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL());
			} catch (SQLException e) {
				// call the hook, if available.
				if (connectionHook != null){
					tryAgain = connectionHook.onAcquireFail(e, acquireConfig);
				} else {
					logger.error(String.format("Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d", url, acquireRetryDelayInMs, acquireRetryAttempts), e);

					try {
						if (acquireRetryAttempts > 0){
							Thread.sleep(acquireRetryDelayInMs);
	 					}
						tryAgain = (acquireRetryAttempts--) > 0;
					} catch (InterruptedException e1) {
						tryAgain=false;
					}
				}
				if (!tryAgain){
					if (oldRawConnection != null) {
						oldRawConnection.close();
					}
					if (result != null) {
						result.close();
					}
					connectionHandle.setInternalConnection(oldRawConnection);
					throw e;
				}
			}
		} while (tryAgain);

		return result;

	}
1020378
public TransactionWrapper getTransactionWrapper(Transaction t) {
    	if (t == null) {
    		return null;
    	}
    	final TransactionWrapperAppData twad = (TransactionWrapperAppData) t.getApplicationData();
    	return twad != null ? twad.getTransactionWrapper(t, this) : null;
	}
965028
@Override
  public <T> Cursor<T> selectCursor(String statement) {
    return session.selectCursor(statement);
  }
376405
def pkey_get(clas,pool_or_cursor,*vals):
    ""
    pkey = clas.PKEY.split(',')
    if len(vals)!=len(pkey): raise ValueError("%i args != %i-len primary key for %s"%(len(vals),len(pkey),clas.TABLE))
    rows = list(clas.select(pool_or_cursor,**dict(zip(pkey,vals))))
    if not rows: raise Missing
    return set_options(pool_or_cursor,clas(*rows[0]))
474421
function (conn, opts) {
            var self = this;
            return this.__setTransactionIsolation(conn, opts).chain(function () {
                return self.__logConnectionExecute(conn, self.beginTransactionSql);
            });
        }
1007138
def cursor(self, as_dict=False):
        """"""
        self.ensure_connect()
        ctype = self.real_ctype(as_dict)
        return self._connect.cursor(ctype)
640269
def _cursor(self):
        """"""
        if self._conn is None:
            self._conn = sqlite3.connect(self.filename,
                                         check_same_thread=False)
        return self._conn.cursor()
409484
def get_cursor(cls):
        """"""
        db = SqliteConnection.get()
        db.row_factory = sqlite3.Row
        return db.cursor()
310624
def _get_query(self, callback, schema, query=None, *args, **kwargs):
        """"""
        if not query: query = Query()

        ret = None
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                if connection.in_transaction():
                    # we wrap SELECT queries in a transaction if we are in a transaction because
                    # it could cause data loss if it failed by causing the db to discard
                    # anything in the current transaction if the query isn't wrapped,
                    # go ahead, ask me how I know this
                    with self.transaction(**kwargs):
                        ret = callback(schema, query, *args, **kwargs)

                else:
                    ret = callback(schema, query, *args, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    ret = callback(schema, query, *args, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return ret