desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor. Args: query: the query request proto dsquery: a datastore_query.Query over query. orders: the orders of query as returned by _GuessOrders. index_list: A list of indexes used by the query. results: iterator over entity_pb.EntityProto'
def __init__(self, query, dsquery, orders, index_list, results):
super(IteratorCursor, self).__init__(query, dsquery, orders, index_list) self.__last_result = None self.__next_result = None self.__results = results self.__distincts = set() self.__done = False if query.has_end_compiled_cursor(): if query.end_compiled_cursor().position_list(): ...
'Advance to next result (handles end cursor, ignores limit).'
def _Advance(self):
if self.__done: raise StopIteration try: while True: self.__next_result = self.__results.next() if (not self.group_by): break next_group = _GetGroupByKey(self.__next_result, self.group_by) if (next_group not in self.__distincts): ...
'Ensures next result is fetched.'
def _GetNext(self):
if ((self.__limit is not None) and (self.__offset >= self.__limit)): self._Done() if (self.__next_result is None): self._Advance()
'Returns and consumes next result.'
def _Next(self):
self._GetNext() self.__last_result = self.__next_result self.__next_result = None self.__offset += 1 return self.__last_result
'Populates a QueryResult with this cursor and the given number of results. Args: result: datastore_pb.QueryResult count: integer of how many results to return offset: integer of how many results to skip compile: boolean, whether we are compiling this query first_result: whether the query result is the first for this qu...
def PopulateQueryResult(self, result, count, offset, compile=False, first_result=False):
Check((offset >= 0), 'Offset must be >= 0') skipped = 0 try: limited_offset = min(offset, _MAX_QUERY_OFFSET) while (skipped < limited_offset): self._Next() skipped += 1 if (skipped == offset): if (count > _MAXIMUM_RESULTS): ...
'Constructor. Args: query: the query request proto dsquery: a datastore_query.Query over query. orders: the orders of query as returned by _GuessOrders. index_list: the list of indexes used by the query. results: list of entity_pb.EntityProto'
def __init__(self, query, dsquery, orders, index_list, results):
super(ListCursor, self).__init__(query, dsquery, orders, index_list) if self.group_by: distincts = set() new_results = [] for result in results: key_value = _GetGroupByKey(result, self.group_by) if (key_value not in distincts): distincts.add(key_va...
'Converts a cursor into a offset into the result set even if the cursor\'s entity no longer exists. Args: results: the query\'s results (sequence of entity_pb.EntityProto) cursor: a compiled cursor as returned by _DecodeCompiledCursor Returns: the integer offset'
def _GetCursorOffset(self, results, cursor):
lo = 0 hi = len(results) while (lo < hi): mid = ((lo + hi) // 2) if self._IsBeforeCursor(results[mid], cursor): lo = (mid + 1) else: hi = mid return lo
'Populates a QueryResult with this cursor and the given number of results. Args: result: datastore_pb.QueryResult count: integer of how many results to return offset: integer of how many results to skip compile: boolean, whether we are compiling this query first_result: whether the query result is the first for this qu...
def PopulateQueryResult(self, result, count, offset, compile=False, first_result=False):
Check((offset >= 0), 'Offset must be >= 0') offset = min(offset, (self.__count - self.__offset)) limited_offset = min(offset, _MAX_QUERY_OFFSET) if limited_offset: self.__offset += limited_offset result.set_skipped_results(limited_offset) if ((offset == limited_offset) an...
'Gets the entity group tracker for reference. If this is the first time reference\'s entity group is seen, creates a new tracker, checking that the transaction doesn\'t exceed the entity group limit.'
def _GetTracker(self, reference):
entity_group = _GetEntityGroup(reference) key = datastore_types.ReferenceToKeyValue(entity_group) tracker = self._entity_groups.get(key, None) if (tracker is None): Check((self._app == reference.app()), ('Transactions cannot span applications (expected %s, got %s)' % (self._...
'Get the trackers for the transaction\'s entity groups. If no entity group has been discovered returns a \'global\' entity group tracker. This is possible if the txn only contains transactional tasks. Returns: The tracker list for the entity groups used in this txn.'
def _GetAllTrackers(self):
if (not self._entity_groups): self._GetTracker(datastore_types.Key.from_path('__global__', 1, _app=self._app)._ToPb()) return self._entity_groups.values()
'Gets snapshot for this reference, creating it if necessary. If no snapshot has been set for reference\'s entity group, a snapshot is taken and stored for future reads (this also sets the read position), and a CONCURRENT_TRANSACTION exception is thrown if we no longer have a consistent snapshot. Args: reference: A enti...
def _GrabSnapshot(self, reference):
tracker = self._GetTracker(reference) check_contention = (tracker._snapshot is None) snapshot = tracker._GrabSnapshot(self._txn_manager) if check_contention: candidates = [other for other in self._entity_groups.values() if ((other._snapshot is not None) and (other != tracker))] meta_data...
'Returns the entity associated with the given entity_pb.Reference or None. Does not see any modifications in the current txn. Args: reference: The entity_pb.Reference of the entity to look up. Returns: The associated entity_pb.EntityProto or None if no such entity exists.'
@_SynchronizeTxn def Get(self, reference):
snapshot = self._GrabSnapshot(reference) entity = snapshot.get(datastore_types.ReferenceToKeyValue(reference)) return LoadEntity(entity)
'Runs the given datastore_pb.Query and returns a QueryCursor for it. Does not see any modifications in the current txn. Args: query: The datastore_pb.Query to run. filters: A list of filters that override the ones found on query. orders: A list of orders that override the ones found on query. index_list: A list of inde...
@_SynchronizeTxn def GetQueryCursor(self, query, filters, orders, index_list):
Check(query.has_ancestor(), 'Query must have an ancestor when performed in a transaction.') snapshot = self._GrabSnapshot(query.ancestor()) return _ExecuteQuery(snapshot.values(), query, filters, orders, index_list)
'Puts the given entity. Args: entity: The entity_pb.EntityProto to put. insert: A boolean that indicates if we should fail if the entity already exists. indexes: The composite indexes that apply to the entity.'
@_SynchronizeTxn def Put(self, entity, insert, indexes):
tracker = self._GetTracker(entity.key()) key = datastore_types.ReferenceToKeyValue(entity.key()) tracker._delete.pop(key, None) tracker._put[key] = (entity, insert) self._kind_to_indexes[_GetKeyKind(entity.key())] = indexes
'Deletes the entity associated with the given reference. Args: reference: The entity_pb.Reference of the entity to delete. indexes: The composite indexes that apply to the entity.'
@_SynchronizeTxn def Delete(self, reference, indexes):
tracker = self._GetTracker(reference) key = datastore_types.ReferenceToKeyValue(reference) tracker._put.pop(key, None) tracker._delete[key] = reference self._kind_to_indexes[_GetKeyKind(reference)] = indexes
'Adds the given actions to the current txn. Args: actions: A list of pbs to send to taskqueue.Add when the txn is applied. max_actions: A number that indicates the maximum number of actions to allow on this txn.'
@_SynchronizeTxn def AddActions(self, actions, max_actions=None):
Check(((not max_actions) or ((len(self._actions) + len(actions)) <= max_actions)), ('Too many messages, maximum allowed %s' % max_actions)) self._actions.extend(actions)
'Rollback the current txn.'
def Rollback(self):
self._lock.acquire() try: Check(((self._state is self.ACTIVE) or (self._state is self.FAILED)), 'transaction closed') self._state = self.ROLLEDBACK finally: self._txn_manager._RemoveTxn(self) self._lock.release()
'Commits the current txn. This function hands off the responsibility of calling _Apply to the owning TransactionManager. Returns: The cost of the transaction.'
@_SynchronizeTxn def Commit(self):
try: trackers = self._GetAllTrackers() empty = True for tracker in trackers: snapshot = tracker._GrabSnapshot(self._txn_manager) empty = (empty and (not tracker._put) and (not tracker._delete)) for (entity, insert) in tracker._put.itervalues(): ...
'Adds the cost of writing the new_entity to the _cost member. We assume that old_entity represents the current state of the Datastore. Args: old_entity: Entity representing the current state in the Datstore. new_entity: Entity representing the desired state in the Datstore.'
def _AddWriteOps(self, old_entity, new_entity):
composite_indexes = self._kind_to_indexes[_GetKeyKind(new_entity.key())] (entity_writes, index_writes) = _CalculateWriteOps(composite_indexes, old_entity, new_entity) _UpdateCost(self._cost, entity_writes, index_writes)
'Applies the current txn on the given entity group. This function blindly performs the operations contained in the current txn. The calling function must acquire the entity group write lock and ensure transactions are applied in order.'
def _Apply(self, meta_data):
self._apply_lock.acquire() try: assert (self._state == self.COMMITED) for tracker in self._entity_groups.values(): if (tracker._meta_data is meta_data): break else: assert False assert (tracker._read_pos != tracker.APPLIED) for (ent...
'Snapshot this entity group, remembering the read position.'
def _GrabSnapshot(self, txn_manager):
if (self._snapshot is None): (self._meta_data, self._read_pos, self._snapshot) = txn_manager._GrabSnapshot(self._entity_group) return self._snapshot
'Applies all outstanding txns.'
def CatchUp(self):
assert (self._write_lock.acquire(False) is False) while self._apply_queue: self._apply_queue[0]._Apply(self)
'Add a pending transaction to this entity group. Requires that the caller hold the meta data lock. This also increments the current log position and clears the snapshot cache.'
def Log(self, txn):
assert (self._write_lock.acquire(False) is False) self._apply_queue.append(txn) self._log_pos += 1 self._snapshot = None
'Remove the first pending transaction from the apply queue. Requires that the caller hold the meta data lock. This checks that the first pending transaction is indeed txn.'
def Unlog(self, txn):
assert (self._write_lock.acquire(False) is False) Check((self._apply_queue and (self._apply_queue[0] is txn)), 'Transaction is not appliable', datastore_pb.Error.INTERNAL_ERROR) self._apply_queue.pop(0)
'Called after a LiveTxn has been commited. This function can decide whether to apply the txn right away. Args: txn: A LiveTxn that has been commited'
def _OnCommit(self, txn):
raise NotImplementedError
'Called once for every global query. This function must aqcuire the write lock for any meta data before applying any outstanding txns. Args: meta_data_list: A list of EntityGroupMetaData objects.'
def _OnGroom(self, meta_data_list):
raise NotImplementedError
'Determins if the given transaction should be applied.'
def _ShouldApply(self, txn, meta_data):
raise NotImplementedError
'Set the probability a txn will be applied after a given amount of time. Args: classification_map: A list of tuples containing (float between 0 and 1, number of miliseconds) that define the probability of a transaction applying after a given amount of time.'
def SetClassificationMap(self, classification_map):
for (prob, delay) in classification_map: if ((prob < 0) or (prob > 1) or (delay <= 0)): raise TypeError(('classification_map must be a list of (probability, delay) tuples, found %r' % (classification_map,))) self._classification_map = sorted(classification_map)
'Constructor. Args: probability: A number between 0 and 1 that is the likelihood of a transaction applying before a global query is executed. seed: A hashable object to use as a seed. Use None to use the current timestamp.'
def __init__(self, probability=0.5, seed=0):
self.SetProbability(probability) self.SetSeed(seed)
'Change the probability of a transaction applying. Args: probability: A number between 0 and 1 that determins the probability of a transaction applying before a global query is run.'
def SetProbability(self, probability):
if ((probability < 0) or (probability > 1)): raise TypeError(('probability must be a number between 0 and 1, found %r' % probability)) self._probability = probability
'Reset the seed.'
def SetSeed(self, seed):
self._random = random.Random(seed)
'Set the consistency to use. Causes all data to be flushed. Args: policy: A obj inheriting from BaseConsistencyPolicy.'
def SetConsistencyPolicy(self, policy):
if (not isinstance(policy, BaseConsistencyPolicy)): raise TypeError(('policy should be of type datastore_stub_util.BaseConsistencyPolicy found %r.' % (policy,))) self.Flush() self._consistency_policy = policy
'Discards any pending transactions and resets the meta data.'
def Clear(self):
self._meta_data = {} self._txn_map = {}
'Start a transaction on the given app. Args: app: A string representing the app for which to start the transaction. allow_multiple_eg: True if transactions can span multiple entity groups. Returns: A datastore_pb.Transaction for the created transaction'
def BeginTransaction(self, app, allow_multiple_eg):
Check((not (allow_multiple_eg and isinstance(self._consistency_policy, MasterSlaveConsistencyPolicy))), 'transactions on multiple entity groups only allowed with the High Replication datastore') txn = self._BeginTransaction(app, allow_multiple_eg) self._txn_map[id(txn)] = tx...
'Gets the LiveTxn object associated with the given transaction. Args: transaction: The datastore_pb.Transaction to look up. request_trusted: A boolean indicating If the requesting app is trusted. request_app: A string representing the app making the request. Returns: The associated LiveTxn object.'
def GetTxn(self, transaction, request_trusted, request_app):
request_app = datastore_types.ResolveAppId(request_app) CheckTransaction(request_trusted, request_app, transaction) txn = self._txn_map.get(transaction.handle()) Check((txn and (txn._app == transaction.app())), ('Transaction(<%s>) not found' % str(transaction).replace('\n', ', '))) return t...
'Attempts to apply any outstanding transactions. The consistency policy determins if a transaction should be applied.'
def Groom(self):
self._meta_data_lock.acquire() try: self._consistency_policy._OnGroom(self._meta_data.itervalues()) finally: self._meta_data_lock.release()
'Applies all outstanding transactions.'
def Flush(self):
self._meta_data_lock.acquire() try: for meta_data in self._meta_data.itervalues(): if (not meta_data._apply_queue): continue meta_data._write_lock.acquire() try: meta_data.CatchUp() finally: meta_data._write_...
'Safely gets the EntityGroupMetaData object for the given entity_group.'
def _GetMetaData(self, entity_group):
self._meta_data_lock.acquire() try: key = datastore_types.ReferenceToKeyValue(entity_group) meta_data = self._meta_data.get(key, None) if (not meta_data): meta_data = EntityGroupMetaData(entity_group) self._meta_data[key] = meta_data return meta_data f...
'Starts a transaction without storing it in the txn_map.'
def _BeginTransaction(self, app, allow_multiple_eg):
return LiveTxn(self, app, allow_multiple_eg)
'Grabs a consistent snapshot of the given entity group. Args: entity_group: A entity_pb.Reference of the entity group of which the snapshot should be taken. Returns: A tuple of (meta_data, log_pos, snapshot) where log_pos is the current log position and snapshot is a map of reference key value to entity_pb.EntityProto....
def _GrabSnapshot(self, entity_group):
meta_data = self._GetMetaData(entity_group) meta_data._write_lock.acquire() try: if (not meta_data._snapshot): meta_data.CatchUp() meta_data._snapshot = self._GetEntitiesInEntityGroup(entity_group) return (meta_data, meta_data._log_pos, meta_data._snapshot) finall...
'Acquire the write locks for the given entity group meta data. These locks must be released with _ReleaseWriteLock before returning to the user. Args: meta_data_list: list of EntityGroupMetaData objects.'
def _AcquireWriteLocks(self, meta_data_list):
for meta_data in sorted(meta_data_list): meta_data._write_lock.acquire()
'Release the write locks of the given entity group meta data. Args: meta_data_list: list of EntityGroupMetaData objects.'
def _ReleaseWriteLocks(self, meta_data_list):
for meta_data in sorted(meta_data_list): meta_data._write_lock.release()
'Removes a LiveTxn from the txn_map (if present).'
def _RemoveTxn(self, txn):
self._txn_map.pop(id(txn), None)
'Put the given entity. This must be implemented by a sub-class. The sub-class can assume that any need consistency is enforced at a higher level (and can just put blindly). Args: entity: The entity_pb.EntityProto to put. insert: A boolean that indicates if we should fail if the entity already exists.'
def _Put(self, entity, insert):
raise NotImplementedError
'Delete the entity associated with the specified reference. This must be implemented by a sub-class. The sub-class can assume that any need consistency is enforced at a higher level (and can just delete blindly). Args: reference: The entity_pb.Reference of the entity to delete.'
def _Delete(self, reference):
raise NotImplementedError
'Gets the contents of a specific entity group. This must be implemented by a sub-class. The sub-class can assume that any need consistency is enforced at a higher level (and can just blindly read). Other entity groups may be modified concurrently. Args: entity_group: A entity_pb.Reference of the entity group to get. Re...
def _GetEntitiesInEntityGroup(self, entity_group):
raise NotImplementedError
'Finds an existing index by definition. Args: index: entity_pb.CompositeIndex Returns: entity_pb.CompositeIndex, if it exists; otherwise None'
def __FindIndex(self, index):
app = index.app_id() if (app in self.__indexes): for stored_index in self.__indexes[app]: if (index.definition() == stored_index.definition()): return stored_index return None
'Get the CompositeIndex objects for the given app.'
def GetIndexes(self, app, trusted=False, calling_app=None):
calling_app = datastore_types.ResolveAppId(calling_app) CheckAppId(trusted, calling_app, app) return self.__indexes[app]
'Clears out all stored values.'
def Clear(self):
BaseTransactionManager.Clear(self)
'Registers a pseudo kind to be used to satisfy a meta data query.'
def _RegisterPseudoKind(self, kind):
self._pseudo_kinds[kind.name] = kind kind._stub = weakref.proxy(self)
'Execute a query. Args: raw_query: The non-validated datastore_pb.Query to run. trusted: If the calling app is trusted. calling_app: The app requesting the results or None to pull the app from the environment. Returns: A BaseCursor that can be used to retrieve results.'
def GetQueryCursor(self, raw_query, trusted=False, calling_app=None):
calling_app = datastore_types.ResolveAppId(calling_app) CheckAppId(trusted, calling_app, raw_query.app()) (filters, orders) = datastore_index.Normalize(raw_query.filter_list(), raw_query.order_list(), raw_query.property_name_list()) CheckQuery(raw_query, filters, orders, self._MAX_QUERY_COMPONENTS) ...
'Get the single composite index pb used by the query, if any, as a list. Args: query: the datastore_pb.Query to compute the index list for Returns: A singleton list of the composite index pb used by the query,'
def __IndexListForQuery(self, query):
(required, kind, ancestor, props) = datastore_index.CompositeIndexForQuery(query) if (not required): return [] composite_index_pb = entity_pb.CompositeIndex() composite_index_pb.set_app_id(query.app()) composite_index_pb.set_id(0) composite_index_pb.set_state(entity_pb.CompositeIndex.REA...
'Get the entities for the given keys. Args: raw_keys: A list of unverified entity_pb.Reference objects. transaction: The datastore_pb.Transaction to use or None. eventual_consistency: If we should allow stale, potentially inconsistent results. trusted: If the calling app is trusted. calling_app: The app requesting the ...
def Get(self, raw_keys, transaction=None, eventual_consistency=False, trusted=False, calling_app=None):
if (not raw_keys): return [] calling_app = datastore_types.ResolveAppId(calling_app) if ((not transaction) and eventual_consistency): result = [] for key in raw_keys: CheckReference(calling_app, trusted, key) result.append(self._GetWithPseudoKinds(None, key)) ...
'Fetch entity key in txn, taking account of pseudo-kinds.'
def _GetWithPseudoKinds(self, txn, key):
pseudo_kind = self._pseudo_kinds.get(_GetKeyKind(key), None) if pseudo_kind: return pseudo_kind.Get(txn, key) elif txn: return txn.Get(key) else: return self._Get(key)
'Writes the given given entities. Updates an entity\'s key and entity_group in place if needed Args: raw_entities: A list of unverified entity_pb.EntityProto objects. cost: Out param. The cost of putting the provided entities. transaction: The datastore_pb.Transaction to use or None. trusted: If the calling app is trus...
def Put(self, raw_entities, cost, transaction=None, trusted=False, calling_app=None):
if (not raw_entities): return [] calling_app = datastore_types.ResolveAppId(calling_app) result = ([None] * len(raw_entities)) grouped_entities = collections.defaultdict(list) for (i, raw_entity) in enumerate(raw_entities): CheckEntity(trusted, calling_app, raw_entity) entity...
'Deletes the entities associated with the given keys. Args: raw_keys: A list of unverified entity_pb.Reference objects. cost: Out param. The cost of putting the provided entities. transaction: The datastore_pb.Transaction to use or None. trusted: If the calling app is trusted. calling_app: The app requesting the result...
def Delete(self, raw_keys, cost, transaction=None, trusted=False, calling_app=None):
if (not raw_keys): return calling_app = datastore_types.ResolveAppId(calling_app) grouped_keys = collections.defaultdict(list) for key in raw_keys: CheckReference(trusted, calling_app, key) entity_group = _GetEntityGroup(key) entity_group_key = datastore_types.ReferenceTo...
'Applies all outstanding writes.'
def Touch(self, raw_keys, trusted=False, calling_app=None):
calling_app = datastore_types.ResolveAppId(calling_app) grouped_keys = collections.defaultdict(list) for key in raw_keys: CheckReference(trusted, calling_app, key) entity_group = _GetEntityGroup(key) entity_group_key = datastore_types.ReferenceToKeyValue(entity_group) grouped...
'Runs the given values in a separate Txn. Retries up to _RETRIES times on CONCURRENT_TRANSACTION errors. Args: values: A list of arguments to op. app: The app to create the Txn on. op: A function to run on each value in the Txn. Returns: The cost of the txn.'
def _RunInTxn(self, values, app, op):
retries = 0 backoff = (_INITIAL_RETRY_DELAY_MS / 1000.0) while True: try: txn = self._BeginTransaction(app, False) for value in values: op(txn, value) return txn.Commit() except apiproxy_errors.ApplicationError as e: if (e.appli...
'Checks if the query can be satisfied given the existing indexes. Args: query: the datastore_pb.Query to check trusted: True if the calling app is trusted (like dev_admin_console) calling_app: app_id of the current running application'
def _CheckHasIndex(self, query, trusted=False, calling_app=None):
if ((query.kind() in self._pseudo_kinds) or (not self._require_indexes)): return minimal_index = datastore_index.MinimalCompositeIndexForQuery(query, (datastore_index.ProtoToIndexDefinition(index) for index in self.GetIndexes(query.app(), trusted, calling_app) if (index.state() == entity_pb.CompositeInd...
'Set value of _auto_id_policy flag (default SEQUENTIAL). SEQUENTIAL auto ID assignment behavior will eventually be deprecated and the default will be SCATTERED. Args: auto_id_policy: string constant. Raises: TypeError: if auto_id_policy is not one of SEQUENTIAL or SCATTERED.'
def SetAutoIdPolicy(self, auto_id_policy):
valid_policies = (SEQUENTIAL, SCATTERED) if (auto_id_policy not in valid_policies): raise TypeError('auto_id_policy must be in %s, found %s instead', valid_policies, auto_id_policy) self._auto_id_policy = auto_id_policy
'Writes the datastore to disk.'
def Write(self):
self.Flush()
'Runs the given datastore_pb.Query and returns a QueryCursor for it. This must be implemented by a sub-class. The sub-class does not need to enforced any consistency guarantees (and can just blindly read). Args: query: The datastore_pb.Query to run. filters: A list of filters that override the ones found on query. orde...
def _GetQueryCursor(self, query, filters, orders, index_list):
raise NotImplementedError
'Get the entity for the given reference or None. This must be implemented by a sub-class. The sub-class does not need to enforced any consistency guarantees (and can just blindly read). Args: reference: A entity_pb.Reference to loop up. Returns: The entity_pb.EntityProto associated with the given reference or None.'
def _Get(self, reference):
raise NotImplementedError
'Allocate ids for given reference. Args: reference: A entity_pb.Reference to allocate an id for. size: The size of the range to allocate max_id: The upper bound of the range to allocate Returns: A tuple containing (min, max) of the allocated range.'
def _AllocateIds(self, reference, size=1, max_id=None):
raise NotImplementedError
'Fetch key of this pseudo-kind within txn. Args: txn: transaction within which Get occurs, may be None if this is an eventually consistent Get. key: key of pseudo-entity to Get. Returns: An entity for key, or None if it doesn\'t exist.'
def Get(self, txn, key):
if (not txn): txn = self._stub._BeginTransaction(key.app(), False) try: return self.Get(txn, key) finally: txn.Rollback() if isinstance(txn._txn_manager._consistency_policy, MasterSlaveConsistencyPolicy): return None path = key.path() if ((path.ele...
'Perform a query on this pseudo-kind. Args: query: the original datastore_pb.Query. filters: the filters from query. orders: the orders from query. Returns: always raises an error'
def Query(self, query, filters, orders):
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, ('queries not supported on ' + self.name))
'Clears out all stored values.'
def Clear(self):
self._query_cursors = {} self.__query_history = {} self.__query_ci_history = set()
'Returns a dict that maps Query PBs to times they\'ve been run.'
def QueryHistory(self):
return dict(((pb, times) for (pb, times) in self.__query_history.items() if (pb.app() == self._app_id)))
'Returns the length of the CompositeIndex set for query history.'
def _QueryCompositeIndexHistoryLength(self):
return len(self.__query_ci_history)
'Set/clear the trusted bit in the stub. This bit indicates that the app calling the stub is trusted. A trusted app can write to datastores of other apps. Args: trusted: boolean.'
def SetTrusted(self, trusted):
self._trusted = trusted
'Associates the creation of one or more tasks with a transaction. Args: request: A taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks that should be created when the transaction is committed.'
def _Dynamic_AddActions(self, request, _):
if (not request.add_request_list()): return transaction = request.add_request_list()[0].transaction() txn = self._datastore.GetTxn(transaction, self._trusted, self._app_id) new_actions = [] for add_request in request.add_request_list(): Check((add_request.transaction() == transaction...
'Ensure that the set of existing composite indexes matches index.yaml. Note: this is similar to the algorithm used by the admin console for the same purpose.'
def _SetupIndexes(self, _open=open):
if (not self._root_path): return index_yaml_file = os.path.join(self._root_path, 'index.yaml') if ((self._cached_yaml[0] == index_yaml_file) and os.path.exists(index_yaml_file) and (os.path.getmtime(index_yaml_file) == self._cached_yaml[1])): requested_indexes = self._cached_yaml[2] else...
'Returns a set of property names used by the filter.'
def _get_prop_names(self):
raise NotImplementedError
'Applies the filter predicate to the given entity. Args: entity: the datastore_pb.EntityProto to test. Returns: True if the given entity matches the filter, False otherwise.'
def __call__(self, entity):
return self._apply(_make_key_value_map(entity, self._get_prop_names()))
'Apply the given component to the comparable value map. A filter matches a list of values if at least one value in the list matches the filter, for example: \'prop: [1, 2]\' matches both \'prop = 1\' and \'prop = 2\' but not \'prop = 3\' Note: the values are actually represented as tuples whose first item encodes the t...
def _apply(self, key_value_map):
raise NotImplementedError
'Removes values from the given map that do not match the filter. When doing a scan in the datastore, only index values that match the filters are seen. When multiple values that point to the same entity are seen, the entity only appears where the first value is found. This function removes all values that don\'t match ...
def _prune(self, key_value_map):
raise NotImplementedError
'Internal only function to generate a pb.'
def _to_pb(self):
raise NotImplementedError(('This filter only supports in memory operations (%r)' % self))
'Internal only function to generate a list of pbs.'
def _to_pbs(self):
return [self._to_pb()]
'Returns the name of the property being filtered.'
def _get_prop_name(self):
raise NotImplementedError
'Apply the filter to the given value. Args: value: The comparable value to check. Returns: A boolean indicating if the given value matches the filter.'
def _apply_to_value(self, value):
raise NotImplementedError
'Constructor. Args: op: A string representing the operator to use. value: A entity_pb.Property, the property and value to compare against. Raises: datastore_errors.BadArgumentError if op has an unsupported value or value is not an entity_pb.Property.'
def __init__(self, op, value):
if (op not in self._OPERATORS): raise datastore_errors.BadArgumentError(('unknown operator: %r' % (op,))) if (not isinstance(value, entity_pb.Property)): raise datastore_errors.BadArgumentError(('value argument should be entity_pb.Property (%r)' % (value,))) super(Proper...
'Returns True if the filter predicate contains inequalities filters.'
def _has_inequality(self):
return (self._filter.op() in self._INEQUALITY_OPERATORS_ENUM)
'Returns the internal only pb representation.'
def _to_pb(self):
return self._filter
'Constructs a range filter using start and end properties. Args: start: A entity_pb.Property to use as a lower bound or None to indicate no lower bound. start_incl: A boolean that indicates if the lower bound is inclusive. end: A entity_pb.Property to use as an upper bound or None to indicate no upper bound. end_incl: ...
@datastore_rpc._positional(1) def __init__(self, start=None, start_incl=True, end=None, end_incl=True):
if ((start is not None) and (not isinstance(start, entity_pb.Property))): raise datastore_errors.BadArgumentError(('start argument should be entity_pb.Property (%r)' % (start,))) if ((end is not None) and (not isinstance(end, entity_pb.Property))): raise datastore_errors.BadArgume...
'Returns a filter representing the intersection of self and other.'
def intersect(self, other):
if isinstance(other, PropertyFilter): other = self.from_property_filter(other) elif (not isinstance(other, _PropertyRangeFilter)): raise datastore_errors.BadArgumentError(('other argument should be a _PropertyRangeFilter (%r)' % (other,))) if (other._get_prop_name() != self...
'Apply the filter to the given value. Args: value: The comparable value to check. Returns: A boolean indicating if the given value matches the filter.'
def _apply_to_value(self, value):
if self._start: result = cmp(self._get_start_key_value(), value) if ((result > 0) or ((result == 0) and (not self._start_incl))): return False if self._end: result = cmp(self._get_end_key_value(), value) if ((result < 0) or ((result == 0) and (not self._end_incl))): ...
'Constructor. Args: subfilter: A FilterPredicate to apply to the correlated values'
def __init__(self, subfilter):
self._subfilter = subfilter
'Applies sub-filter to the correlated value maps. The default implementation matches when any value_map in value_maps matches the sub-filter. Args: value_maps: A list of correlated value_maps. Returns: True if any the entity matches the correlation filter.'
def _apply_correlated(self, value_maps):
for map in value_maps: if self._subfilter._apply(map): return True return False
'A function that groups the given values. Override this function to introduce custom grouping logic. The default implementation assumes each value belongs in its own group. Args: prop: The name of the property who\'s values are being grouped. values: A list of opaque values. Returns: A list of lists of grouped values.'...
def _group_values(self, prop, values):
return [[value] for value in values]
'Constructor. Args: op: The operator to use to combine the given filters filters: A list of one or more filters to combine Raises: datastore_errors.BadArgumentError if op is not in CompsiteFilter.OPERATORS or filters is not a non-empty list containing only FilterPredicates.'
def __init__(self, op, filters):
if (not (op in self._OPERATORS)): raise datastore_errors.BadArgumentError(('unknown operator (%s)' % (op,))) if ((not filters) or (not isinstance(filters, (list, tuple)))): raise datastore_errors.BadArgumentError(('filters argument should be a non-empty list (%r)' % (f...
'Returns the internal only pb representation.'
def _to_pbs(self):
pbs = [] for f in self._filters: pbs.extend(f._to_pbs()) return pbs
'Constructs an order representing the reverse of the current order. This function takes into account the effects of orders on properties not in the group_by clause of a query. For example, consider: SELECT A, First(B) ... GROUP BY A ORDER BY A, B Changing the order of B would effect which value is listed in the \'First...
@datastore_rpc._positional(1) def reversed(self, group_by=None):
raise NotImplementedError
'Creates a key for the given value map.'
def _key(self, lhs_value_map):
raise NotImplementedError
'Compares the given value maps.'
def _cmp(self, lhs_value_map, rhs_value_map):
raise NotImplementedError
'Internal only function to generate a filter pb.'
def _to_pb(self):
raise NotImplementedError
'Constructs a "key" value for the given entity based on the current order. This function can be used as the key argument for list.sort() and sorted(). Args: entity: The entity_pb.EntityProto to convert filter_predicate: A FilterPredicate used to prune values before comparing entities or None. Returns: A key value that ...
def key(self, entity, filter_predicate=None):
names = self._get_prop_names() names.add(datastore_types.KEY_SPECIAL_PROPERTY) if (filter_predicate is not None): names |= filter_predicate._get_prop_names() value_map = _make_key_value_map(entity, names) if (filter_predicate is not None): filter_predicate._prune(value_map) retur...
'Compares the given values taking into account any filters. This function can be used as the cmp argument for list.sort() and sorted(). This function is slightly more efficient that Order.key when comparing two entities, however it is much less efficient when sorting a list of entities. Args: lhs: An entity_pb.EntityPr...
def cmp(self, lhs, rhs, filter_predicate=None):
names = self._get_prop_names() if (filter_predicate is not None): names |= filter_predicate._get_prop_names() lhs_value_map = _make_key_value_map(lhs, names) rhs_value_map = _make_key_value_map(rhs, names) if (filter_predicate is not None): filter_predicate._prune(lhs_value_map) ...
'Constructor for _ReverseOrder. Args: obj: Any comparable and hashable object.'
def __init__(self, obj):
super(_ReverseOrder, self).__init__() self._obj = obj
'Constructor. Args: prop: the name of the prop by which to sort. direction: the direction in which to sort the given prop. Raises: datastore_errors.BadArgumentError if the prop name or direction is invalid.'
def __init__(self, prop, direction=ASCENDING):
datastore_types.ValidateString(prop, 'prop', datastore_errors.BadArgumentError) if (not (direction in self._DIRECTIONS)): raise datastore_errors.BadArgumentError(('unknown direction: %r' % (direction,))) super(PropertyOrder, self).__init__() self.__order = datastore_pb.Query_Order() se...
'Returns the internal only pb representation.'
def _to_pb(self):
return self.__order