Convienience method to create a cached query instance
556706
public function cache($query, array $params = null, $timeout = null)
    {
        $options = array_merge($this->cacheOptions, [
            "sql"     =>  $this,
            "query"   =>  $query,
            "params"  =>  $params,
        ]);

        if ($timeout) {
            $options["timeout"] = $timeout;
        }

        return new Cache($options);
    }
367238
def cached(func, instance, args, kwargs):
    """"""
    cache = getattr(instance, "__cache", None)
    if cache is None:
        instance.__cache = cache = {}
    try:
        return cache[func]
    except KeyError:
        cache[func] = result = func(*args, **kwargs)
        return result
919025
def get(cls, id=None, condition=None, fields=None, cache=False, engine_name=None, **kwargs):
        
        
        if id is None and condition is None:
            return None
        
        can_cacheable = (cache or getattr(cls, '__cacheable__', None)) and \
            isinstance(id, (int, long, str, unicode))
        if can_cacheable:
            #send 'get_object' topic to get cached object
            obj = dispatch.get(cls, 'get_object', id)
            if obj:
                return obj

        if condition is not None:
            _cond = condition
        else:
            if is_condition(id):
                _cond = id
            else:
                _cond = cls.c[cls._primary_field] == id
            #todo
            # if isinstance(id, (int, long)):
            #     _cond = cls.c.id==id
            # elif isinstance(id, (str, unicode)) and id.isdigit():
            #     _cond = cls.c.id==int(id)
            # else:
            #     _cond = id

        #if there is no cached object, then just fetch from database
        obj = cls.filter(_cond, **kwargs).fields(*(fields or [])).one()
        
        if obj and cache or getattr(cls, '__cacheable__', None):
            dispatch.call(cls, 'set_object', instance=obj)

        return obj
703355
private void updateCache(int index, QueryParameters params) {
        if (generatedCacheMap.containsKey(index) == true) {
            this.generatedCacheMap.put(index, params);
        } else {
            this.resultSetCacheMap.put(index, params);
        }
    }
262969
function ExecutionCache() {
  var cache = {};

  function getKey(query) {
    return query.queryKey + '(' + JSON.stringify(query.queryParams) + ')'
  }

  function get(query) {
    return cache[getKey(query)]
  }

  this.execute = function (query) {
    var query = _.cloneDeep(query);
    var execution = get(query);
    if (execution) {
      var requestedKeys = _.keys(query.shape);
      if (_.intersection(_.keys(execution.shape), requestedKeys).length != requestedKeys.length) {
        // TODO we probably should also merge the nested shape
        var newShape = _.assign(execution.shape, query.shape);
        query.shape = newShape;
        execution = {
          shape: newShape,
          promise: getHandler(query.name, query.queryKey)(query.shape, query.queryParams, query.type)
        }
      }
    } else {
      execution = {
        shape: query.shape,
        promise: getHandler(query.name, query.queryKey)(query.shape, query.queryParams, query.type)
      };
    }
    cache[getKey(query)] = execution;
    return execution;
  };

  this.get = get;
  this.getKey = getKey;
  return this;
}
464655
def __cache( self, method_name, *args, **kwargs ):
        
        trace_string           = util.get_stack(method_name)
        call_hash              = self.__get_hash(args, trace_string, kwargs)
        cd                     = call_descriptor.fetch( call_hash )
        if not cd:
            c  = self.__store__['callables'][method_name]
            if hasattr( c, '__class__' ) and c.__class__ == LazyBones:
                c = c.init()
            returnval = c(*args, **kwargs)
            cd = call_descriptor.CallDescriptor( hash      = call_hash,
                                                 stack     = trace_string,
                                                 method    = method_name,
                                                 returnval = returnval,
                                                 args      = args,
                                                 kwargs    = kwargs )
            cd.save()
            if not call_hash:
                raise Exception("CALL HASH IS NONE")

            util.last_hash = call_hash
            self.last_cached = call_hash
        else:
            returnval = cd.returnval

        if inspect.isclass(returnval):
            returnval = LazyBones( c, args, kwargs )

        return returnval
998999
def get(self, *args, **kwargs):
        
        if self.query.where:
            # If there is any other ``where`` filter on this QuerySet just call
            # super. There will be a where clause if this QuerySet has already
            # been filtered/cloned.
            return super(CachingQuerySet, self).get(*args, **kwargs)
 
        # Punt on anything more complicated than get by pk/id only...
        if len(kwargs) == 1:
            k = kwargs.keys()[0]
            if k in ('pk', 'pk__exact', '%s' % self.model._meta.pk.attname, 
                     '%s__exact' % self.model._meta.pk.attname):
                obj = cache.get(self.model._cache_key(pk=kwargs.values()[0]))
                if obj is not None:
                    obj.from_cache = True
                    return obj
 
        # Calls self.iterator to fetch objects, storing object in cache.
        return super(CachingQuerySet, self).get(*args, **kwargs)
255205
function createUriQueryMapper (query) {
  var parameters = extractQueryParameters(query);
  return (queryValues, args) => {
    queryValues = queryValues || Object.create(null);

    Object.keys(queryValues)
      .forEach(queryKey => {
        var parameter = parameters[queryKey];

        if (!parameter) {
          return;
        }

        var value = util.isArray(queryValues[queryKey]) ?
          queryValues[queryKey]
            .map(parameter.map)
            .filter(value => value !== null) :
          parameter.map(queryValues[queryKey]);

        if (value === null) {
          return;
        }

        args[parameter.name] = value;
      });
  };
}
731006
private Cache<QueryCacheKey, Object> getCache() {
      final Cache<QueryCacheKey, Object> cache = lazyCache;

      //Most likely branch first:
      if (cache != null) {
         return cache;
      }
      synchronized (this) {
         if (lazyCache == null) {
            // define the query cache configuration if it does not already exist (from a previous call or manually defined by the user)
            internalCacheRegistry.registerInternalCache(QUERY_CACHE_NAME, getQueryCacheConfig().build(), EnumSet.noneOf(InternalCacheRegistry.Flag.class));
            lazyCache = cacheManager.getCache(QUERY_CACHE_NAME);
         }
         return lazyCache;
      }
   }
501618
function _buildQuery(){

            var url         = data.url;
            var cache       = typeof data.cache !== 'undefined' ? !!data.cache : true;
            var queryString = data.queryString || '';
            var _data       = data.data;

            //add a cache buster
            if(cache === false){
                queryString += '&ajabuster=' + new Date().getTime();
            }

            url = appendQueryString(url, queryString);

            if(_data && !_dataInBody()){
                url =  appendQueryString(url, _data);
            }
            return url;
        }
814840
function loadUncachedSome () {
    // debug
    debug('id:loadUncachedSome')
    // create new select for only uncached ids
    var select = sql.select(this.query.model, {
        all: true,
        where: {id: this.uncachedIds},
    })
    // replace original select in query
    this.query.select = select
    // execute modified query
    return this.query.executeQuery()
    // cache result
    .then(results => {
        // cache results if there are any
        if (results.length > 0) {
            this.cacheResults(results)
        }
        // resolve with cached + loaded results
        return this.cached.concat(results)
    })
}
582601
public GenericRawResults<String[]> queryRaw(ConnectionSource connectionSource, String query, String[] arguments,
			ObjectCache objectCache) throws SQLException {
		logger.debug("executing raw query for: {}", query);
		if (arguments.length > 0) {
			// need to do the (Object) cast to force args to be a single object
			logger.trace("query arguments: {}", (Object) arguments);
		}
		DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
		CompiledStatement compiledStatement = null;
		try {
			compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
					DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
			assignStatementArguments(compiledStatement, arguments);
			GenericRawResults<String[]> rawResults = new RawResultsImpl<String[]>(connectionSource, connection, query,
					String[].class, compiledStatement, this, objectCache);
			compiledStatement = null;
			connection = null;
			return rawResults;
		} finally {
			IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
			if (connection != null) {
				connectionSource.releaseConnection(connection);
			}
		}
	}
402896
function run_search(query) {
      	 var cache_key = query + computeURL();
          //var cached_results = cache.get(cache_key);
          /*if (cached_results) {
              if ($.isFunction($(input).data("settings").onCachedResult)) {
                cached_results = $(input).data("settings").onCachedResult.call(hidden_input, cached_results);
              }
              populate_dropdown(query, cached_results);
          } else {*/
              // Are we doing an ajax search or local data search?
              if($(input).data("settings").url) {
                  var url = computeURL();
                  // Extract existing get params
                  var ajax_params = {};
                  ajax_params.data = {};
                  if(url.indexOf("?") > -1) {
                      var parts = url.split("?");
                      ajax_params.url = parts[0];

                      var param_array = parts[1].split("&");
                      $.each(param_array, function (index, value) {
                          var kv = value.split("=");
                          ajax_params.data[kv[0]] = kv[1];
                      });
                  } else {
                      ajax_params.url = url;
                  }

                  // Prepare the request
                  ajax_params.data[$(input).data("settings").queryParam] = query;
                  ajax_params.type = $(input).data("settings").method;
                  ajax_params.dataType = $(input).data("settings").contentType;
                  if ($(input).data("settings").crossDomain) {
                      ajax_params.dataType = "jsonp";
                  }

                  // exclude current tokens?
                  // send exclude list to the server, so it can also exclude existing tokens
                  if ($(input).data("settings").excludeCurrent) {
                      var currentTokens = $(input).data("tokenInputObject").getTokens();
                      var tokenList = $.map(currentTokens, function (el) {
                          if(typeof $(input).data("settings").tokenValue == 'function')
                              return $(input).data("settings").tokenValue.call(this, el);

                          return el[$(input).data("settings").tokenValue];
                      });

                      ajax_params.data[$(input).data("settings").excludeCurrentParameter] = tokenList.join($(input).data("settings").tokenDelimiter);
                  }

                  // Attach the success callback
                  ajax_params.success = function(results) {
                    cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
                    if($.isFunction($(input).data("settings").onResult)) {
                        results = $(input).data("settings").onResult.call(hidden_input, results);
                    }

                    // only populate the dropdown if the results are associated with the active search query
                    if(input_box.val() === query) {
                        populate_dropdown(query, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
                    }
                  };

                  // Provide a beforeSend callback
                  if (settings.onSend) {
                    settings.onSend(ajax_params);
                  }

                  // Make the request
                  $.ajax(ajax_params);
              } else if($(input).data("settings").local_data) {
                  // Do the search through local data
                 var results = $.grep($(input).data("settings").local_data, function (row) {
                      return row[$(input).data("settings").propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
                  });

                  cache.add(cache_key, results);
                  if($.isFunction($(input).data("settings").onResult)) {
                      results = $(input).data("settings").onResult.call(hidden_input, results);
                  }
                  populate_dropdown(query, results);
              }
          //}
      }
1170234
function createFetchInstance(defaultConfig) {
    const context = fetchFactory(defaultConfig);
    const instance = bind(context.request, context);

    // Copy properties from context
    extend(instance, context, context);

    return instance;
}
758523
def cachedmethod(cache, key=keys.hashkey, lock=None):
    
    def decorator(method):
        if lock is None:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        else:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    with lock(self):
                        return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    with lock(self):
                        c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        return _update_wrapper(wrapper, method)
    return decorator
1125010
function CacheEntry(table, key, id) {
  if(!(this instanceof entry)) {
    return new entry(table, key, id);
  }
  this.table = table;   // This is the table that we're going to search to in the db
  this.key = key;       // This is the primary key we'll use for SELECT WHERE key=
  this.id = id;       // This is the id value of the entry.
  this.data = null;     // The data field is populated right after it was read from the db.
  this.where = {};
  this._filter = null;
  this._fields = null;
  this.where[key] = id;
}
374995
def factory(opts, **kwargs):
    '''
    
    '''
    if opts.get('memcache_expire_seconds', 0):
        cls = MemCache
    else:
        cls = Cache
    return cls(opts, **kwargs)