desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'True if configuration obj handles all options of this class.
Use this method rather than isinstance(obj, cls) to test if a
configuration object handles the options of cls (is_configuration
is handled specially for results of merge which may handle the options
of unrelated configuration classes).
Args:
obj: the object ... | @classmethod
def is_configuration(cls, obj):
| return (isinstance(obj, BaseConfiguration) and obj._is_configuration(cls))
|
'Merge two configurations.
The configuration given as an argument (if any) takes priority;
defaults are filled in from the current configuration.
Args:
config: Configuration providing overrides, or None (but cannot
be omitted).
Returns:
Either a new configuration object or (if it would be equivalent)
self or the config... | def merge(self, config):
| if ((config is None) or (config is self)):
return self
if (not (isinstance(config, _MergedConfiguration) or isinstance(self, _MergedConfiguration))):
if isinstance(config, self.__class__):
for key in self._values:
if (key not in config._values):
br... |
'The deadline for any RPC issued.
If unset the system default will be used which is typically 5 seconds.
Raises:
BadArgumentError if value is not a number or is less than zero.'
| @ConfigOption
def deadline(value):
| if (not isinstance(value, (int, long, float))):
raise datastore_errors.BadArgumentError(('deadline argument should be int/long/float (%r)' % (value,)))
if (value <= 0):
raise datastore_errors.BadArgumentError(('deadline argument should be > 0 (%r)' % (value,)))
... |
'A callback that is invoked when any RPC completes.
If specified, it will be called with a UserRPC object as argument when an
RPC completes.
NOTE: There is a subtle but important difference between
UserRPC.callback and Configuration.on_completion: on_completion is
called with the RPC object as its first argument, where... | @ConfigOption
def on_completion(value):
| return value
|
'The read policy to use for any relevent RPC.
if unset STRONG_CONSISTENCY will be used.
Raises:
BadArgumentError if value is not a known read policy.'
| @ConfigOption
def read_policy(value):
| if (value not in Configuration.ALL_READ_POLICIES):
raise datastore_errors.BadArgumentError(('read_policy argument invalid (%r)' % (value,)))
return value
|
'If a write request should succeed even if the app is read-only.
This only applies to user controlled read-only periods.'
| @ConfigOption
def force_writes(value):
| if (not isinstance(value, bool)):
raise datastore_errors.BadArgumentError(('force_writes argument invalid (%r)' % (value,)))
return value
|
'The maximum number of entity groups that can be represented in one rpc.
For a non-transactional operation that involves more entity groups than the
maximum, the operation will be performed by executing multiple, asynchronous
rpcs to the datastore, each of which has no more entity groups represented
than the maximum. ... | @ConfigOption
def max_entity_groups_per_rpc(value):
| if (not (isinstance(value, (int, long)) and (value > 0))):
raise datastore_errors.BadArgumentError('max_entity_groups_per_rpc should be a positive integer')
return value
|
'The maximum serialized size of a Get/Put/Delete without batching.'
| @ConfigOption
def max_rpc_bytes(value):
| if (not (isinstance(value, (int, long)) and (value > 0))):
raise datastore_errors.BadArgumentError('max_rpc_bytes should be a positive integer')
return value
|
'The maximum number of keys in a Get without batching.'
| @ConfigOption
def max_get_keys(value):
| if (not (isinstance(value, (int, long)) and (value > 0))):
raise datastore_errors.BadArgumentError('max_get_keys should be a positive integer')
return value
|
'The maximum number of entities in a Put without batching.'
| @ConfigOption
def max_put_entities(value):
| if (not (isinstance(value, (int, long)) and (value > 0))):
raise datastore_errors.BadArgumentError('max_put_entities should be a positive integer')
return value
|
'The maximum number of keys in a Delete without batching.'
| @ConfigOption
def max_delete_keys(value):
| if (not (isinstance(value, (int, long)) and (value > 0))):
raise datastore_errors.BadArgumentError('max_delete_keys should be a positive integer')
return value
|
'Constructor.
Args:
rpcs: A list of UserRPC and MultiRpc objects; it is flattened
before being stored.
extra_hook: Optional function to be applied to the final result
or list of results.'
| def __init__(self, rpcs, extra_hook=None):
| self.__rpcs = self.flatten(rpcs)
self.__extra_hook = extra_hook
|
'Get a flattened list containing the RPCs wrapped.
This returns a copy to prevent users from modifying the state.'
| @property
def rpcs(self):
| return list(self.__rpcs)
|
'Get the combined state of the wrapped RPCs.
This mimics the UserRPC.state property. If all wrapped RPCs have
the same state, that state is returned; otherwise, RUNNING is
returned (which here really means \'neither fish nor flesh\').'
| @property
def state(self):
| lo = apiproxy_rpc.RPC.FINISHING
hi = apiproxy_rpc.RPC.IDLE
for rpc in self.__rpcs:
lo = min(lo, rpc.state)
hi = max(hi, rpc.state)
if (lo == hi):
return lo
return apiproxy_rpc.RPC.RUNNING
|
'Wait for all wrapped RPCs to finish.
This mimics the UserRPC.wait() method.'
| def wait(self):
| apiproxy_stub_map.UserRPC.wait_all(self.__rpcs)
|
'Check success of all wrapped RPCs, failing if any of the failed.
This mimics the UserRPC.check_success() method.
NOTE: This first waits for all wrapped RPCs to finish before
checking the success of any of them. This makes debugging easier.'
| def check_success(self):
| self.wait()
for rpc in self.__rpcs:
rpc.check_success()
|
'Return the combined results of all wrapped RPCs.
This mimics the UserRPC.get_results() method. Multiple results
are combined using the following rules:
1. If there are no wrapped RPCs, an empty list is returned.
2. If exactly one RPC is wrapped, its result is returned.
3. If more than one RPC is wrapped, the result i... | def get_result(self):
| if (len(self.__rpcs) == 1):
results = self.__rpcs[0].get_result()
else:
results = []
for rpc in self.__rpcs:
result = rpc.get_result()
if isinstance(result, list):
results.extend(result)
elif (result is not None):
result... |
'Return a list of UserRPCs, expanding MultiRpcs in the argument list.
For example: given 4 UserRPCs rpc1 through rpc4,
flatten(rpc1, MultiRpc([rpc2, rpc3], rpc4)
returns [rpc1, rpc2, rpc3, rpc4].
Args:
rpcs: A list of UserRPC and MultiRpc objects.
Returns:
A list of UserRPC objects.'
| @classmethod
def flatten(cls, rpcs):
| flat = []
for rpc in rpcs:
if isinstance(rpc, MultiRpc):
flat.extend(rpc.__rpcs)
else:
if (not isinstance(rpc, apiproxy_stub_map.UserRPC)):
raise datastore_errors.BadArgumentError(('Expected a list of UserRPC object (%r)' % (rpc,)))
... |
'Wait until one of the RPCs passed in is finished.
This mimics UserRPC.wait_any().
Args:
rpcs: A list of UserRPC and MultiRpc objects.
Returns:
A UserRPC object or None.'
| @classmethod
def wait_any(cls, rpcs):
| return apiproxy_stub_map.UserRPC.wait_any(cls.flatten(rpcs))
|
'Wait until all RPCs passed in are finished.
This mimics UserRPC.wait_all().
Args:
rpcs: A list of UserRPC and MultiRpc objects.'
| @classmethod
def wait_all(cls, rpcs):
| apiproxy_stub_map.UserRPC.wait_all(cls.flatten(rpcs))
|
'Constructor.
All arguments should be specified as keyword arguments.
Args:
adapter: Optional AbstractAdapter subclass instance;
default IdentityAdapter.
config: Optional Configuration object.'
| @_positional(1)
def __init__(self, adapter=None, config=None):
| if (adapter is None):
adapter = IdentityAdapter()
if (not isinstance(adapter, AbstractAdapter)):
raise datastore_errors.BadArgumentError(('invalid adapter argument (%r)' % (adapter,)))
self.__adapter = adapter
if (config is None):
config = Configuration()
elif (not C... |
'The adapter used by this connection.'
| @property
def adapter(self):
| return self.__adapter
|
'The default configuration used by this connection.'
| @property
def config(self):
| return self.__config
|
'Add an RPC object to the list of pending RPCs.
The argument must be a UserRPC object, not a MultiRpc object.'
| def _add_pending(self, rpc):
| assert (not isinstance(rpc, MultiRpc))
self.__pending_rpcs.add(rpc)
|
'Remove an RPC object from the list of pending RPCs.
If the argument is a MultiRpc object, the wrapped RPCs are removed
from the list of pending RPCs.'
| def _remove_pending(self, rpc):
| if isinstance(rpc, MultiRpc):
for wrapped_rpc in rpc._MultiRpc__rpcs:
self._remove_pending(wrapped_rpc)
else:
try:
self.__pending_rpcs.remove(rpc)
except KeyError:
pass
|
'Check whether an RPC object is currently pending.
Note that \'pending\' in this context refers to an RPC associated
with this connection for which _remove_pending() hasn\'t been
called yet; normally this is called by check_rpc_success() which
itself is called by the various result hooks. A pending RPC may
be in the R... | def is_pending(self, rpc):
| if isinstance(rpc, MultiRpc):
for wrapped_rpc in rpc._MultiRpc__rpcs:
if self.is_pending(wrapped_rpc):
return True
return False
else:
return (rpc in self.__pending_rpcs)
|
'Return (a copy of) the list of currently pending RPCs.'
| def get_pending_rpcs(self):
| return set(self.__pending_rpcs)
|
'Tries to get the datastore type for the given app.
This function is only guaranteed to return something other than
UNKNOWN_DATASTORE when running in production and querying the current app.'
| def get_datastore_type(self, app=None):
| return _GetDatastoreType(app)
|
'Wait for all currently pending RPCs to complete.'
| def wait_for_all_pending_rpcs(self):
| while self.__pending_rpcs:
try:
rpc = apiproxy_stub_map.UserRPC.wait_any(self.__pending_rpcs)
except Exception:
logging.info('wait_for_all_pending_rpcs(): exception in wait_any()', exc_info=True)
continue
if (rpc is None):
logging.debu... |
'Create an RPC object using the configuration parameters.
Args:
config: Optional Configuration object.
Returns:
A new UserRPC object with the designated settings.
NOTES:
(1) The RPC object returned can only be used to make a single call
(for details see apiproxy_stub_map.UserRPC).
(2) To make a call, use one of the spe... | def create_rpc(self, config=None):
| deadline = Configuration.deadline(config, self.__config)
on_completion = Configuration.on_completion(config, self.__config)
callback = None
if (on_completion is not None):
def callback():
return on_completion(rpc)
rpc = apiproxy_stub_map.UserRPC('datastore_v3', deadline, callback... |
'Set the read policy on a request.
This takes the read policy from the config argument or the
configuration\'s default configuration, and if it is
EVENTUAL_CONSISTENCY, sets the failover_ms field in the protobuf.
Args:
request: A protobuf with a failover_ms field.
config: Optional Configuration object.'
| def _set_request_read_policy(self, request, config=None):
| if (not (hasattr(request, 'set_failover_ms') and hasattr(request, 'strong'))):
raise datastore_errors.BadRequestError('read_policy is only supported on read operations.')
if isinstance(config, apiproxy_stub_map.UserRPC):
read_policy = getattr(config, 'read_policy', None)
el... |
'Set the current transaction on a request.
NOTE: This version of the method does nothing. The version
overridden by TransactionalConnection is the real thing.
Args:
request: A protobuf with a transaction field.
Returns:
A datastore_pb.Transaction object or None.'
| def _set_request_transaction(self, request):
| return None
|
'Make an RPC call.
Except for the added config argument, this is a thin wrapper
around UserRPC.make_call().
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
method: The method name.
request: The request protocol buffer.
response: The response protocol buffe... | def make_rpc_call(self, config, method, request, response, get_result_hook=None, user_data=None):
| if isinstance(config, apiproxy_stub_map.UserRPC):
rpc = config
else:
rpc = self.create_rpc(config)
rpc.make_call(method, request, response, get_result_hook, user_data)
self._add_pending(rpc)
return rpc
|
'Check for RPC success and translate exceptions.
This wraps rpc.check_success() and should be called instead of that.
This also removes the RPC from the list of pending RPCs, once it
has completed.
Args:
rpc: A UserRPC or MultiRpc object.
Raises:
Nothing if the call succeeded; various datastore_errors.Error
subclasses ... | def check_rpc_success(self, rpc):
| try:
rpc.wait()
finally:
self._remove_pending(rpc)
try:
rpc.check_success()
except apiproxy_errors.ApplicationError as err:
raise _ToDatastoreError(err)
|
'Internal helper: figures out max_entity_groups_per_rpc for the config.'
| def __get_max_entity_groups_per_rpc(self, config):
| return (Configuration.max_entity_groups_per_rpc(config, self.__config) or self.DEFAULT_MAX_ENTITY_GROUPS_PER_RPC)
|
'Internal helper: extracts the entity group from a key or entity.'
| def __extract_entity_group(self, value):
| if isinstance(value, entity_pb.EntityProto):
value = value.key()
return value.path().element(0)
|
'Internal helper: group pbs by entity group.
Args:
values: The values to be grouped by entity group.
value_to_pb: A function that translates a value to a pb.
Returns:
A list where each element is a list of (pb, index) pairs. Here index is
the location of the value from which pb was derived in the original list.'
| def __group_indexed_pbs_by_entity_group(self, values, value_to_pb):
| indexed_pbs_by_entity_group = collections.defaultdict(list)
for (index, value) in enumerate(values):
pb = value_to_pb(value)
eg = self.__extract_entity_group(pb)
uid = (eg.type(), (eg.id() or eg.name() or ('new', id(eg))))
indexed_pbs_by_entity_group[uid].append((pb, index))
... |
'Internal helper: build a function that ties an index with each result.
Args:
indexes: A list of integers. A value x at location y in the list means
that the result at location y in the result list needs to be at location
x in the list of results returned to the user.'
| def __create_result_index_pairs(self, indexes):
| def create_result_index_pairs(results):
return zip(results, indexes)
return create_result_index_pairs
|
'Builds a function that sorts the indexed results.
Args:
extra_hook: A function that the returned function will apply to its result
before returning.
Returns:
A function that takes a list of results and reorders them to match the
order in which the input values associated with each results were
originally provided.'
| def __sort_result_index_pairs(self, extra_hook):
| def sort_result_index_pairs(result_index_pairs):
results = ([None] * len(result_index_pairs))
for (result, index) in result_index_pairs:
results[index] = result
if (extra_hook is not None):
results = extra_hook(results)
return results
return sort_result_in... |
'Internal helper: repeatedly yield a list of 2 elements.
Args:
indexed_pb_lists_by_eg: A list of lists. The inner lists consist of
objects that all belong to the same entity group.
base_size: An integer representing the base size of an rpc. Used for
splitting operations across multiple RPCs due to size limitations.
m... | def __generate_pb_lists(self, indexed_pb_lists_by_eg, base_size, max_count, max_egs_per_rpc, config):
| max_size = (Configuration.max_rpc_bytes(config, self.__config) or self.MAX_RPC_BYTES)
pbs = []
pb_indexes = []
size = base_size
num_entity_groups = 0
for indexed_pbs in indexed_pb_lists_by_eg:
num_entity_groups += 1
if ((max_egs_per_rpc is not None) and (num_entity_groups > max_e... |
'Internal helper: return request size in bytes.'
| def _get_base_size(self, base_req):
| return base_req.ByteSize()
|
'Synchronous Get operation.
Args:
keys: An iterable of user-level key objects.
Returns:
A list of user-level entity objects and None values, corresponding
1:1 to the argument keys. A None means there is no entity for the
corresponding key.'
| def get(self, keys):
| return self.async_get(None, keys).get_result()
|
'Asynchronous Get operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
keys: An iterable of user-level key objects.
extra_hook: Optional function to be called on the result once the
RPC has completed.
Returns:
A MultiRpc object.'
| def async_get(self, config, keys, extra_hook=None):
| def make_get_call(req, pbs, user_data=None):
req.key_list().extend(pbs)
self._set_request_transaction(req)
resp = datastore_pb.GetResponse()
return self.make_rpc_call(config, 'Get', req, resp, self.__get_hook, user_data)
base_req = datastore_pb.GetRequest()
self._set_request_... |
'Internal method used as get_result_hook for Get operation.'
| def __get_hook(self, rpc):
| self.check_rpc_success(rpc)
entities = []
for group in rpc.response.entity_list():
if group.has_entity():
entity = self.__adapter.pb_to_entity(group.entity())
else:
entity = None
entities.append(entity)
if (rpc.user_data is not None):
entities = rp... |
'Synchronous get indexes operation.
Returns:
user-level indexes representation'
| def get_indexes(self):
| return self.async_get_indexes(None).get_result()
|
'Asynchronous get indexes operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
extra_hook: Optional function to be called once the RPC has completed.
Returns:
A MultiRpc object.'
| def async_get_indexes(self, config, extra_hook=None, _app=None):
| req = api_base_pb.StringProto()
req.set_value(datastore_types.ResolveAppId(_app))
resp = datastore_pb.CompositeIndices()
return self.make_rpc_call(config, 'GetIndices', req, resp, self.__get_indexes_hook, extra_hook)
|
'Internal method used as get_result_hook for Get operation.'
| def __get_indexes_hook(self, rpc):
| self.check_rpc_success(rpc)
indexes = [self.__adapter.pb_to_index(index) for index in rpc.response.index_list()]
if rpc.user_data:
indexes = rpc.user_data(indexes)
return indexes
|
'Synchronous Put operation.
Args:
entities: An iterable of user-level entity objects.
Returns:
A list of user-level key objects, corresponding 1:1 to the
argument entities.
NOTE: If any of the entities has an incomplete key, this will
*not* patch up those entities with the complete key.'
| def put(self, entities):
| return self.async_put(None, entities).get_result()
|
'Asynchronous Put operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
entities: An iterable of user-level entity objects.
extra_hook: Optional function to be called on the result once the
RPC has completed.
Returns:
A MultiRpc object.
NOTE: If any o... | def async_put(self, config, entities, extra_hook=None):
| def make_put_call(req, pbs, user_data=None):
req.entity_list().extend(pbs)
self._set_request_transaction(req)
resp = datastore_pb.PutResponse()
return self.make_rpc_call(config, 'Put', req, resp, self.__put_hook, user_data)
base_req = datastore_pb.PutRequest()
if Configuratio... |
'Internal method used as get_result_hook for Put operation.'
| def __put_hook(self, rpc):
| self.check_rpc_success(rpc)
keys = [self.__adapter.pb_to_key(pb) for pb in rpc.response.key_list()]
if (rpc.user_data is not None):
keys = rpc.user_data(keys)
return keys
|
'Synchronous Delete operation.
Args:
keys: An iterable of user-level key objects.
Returns:
None.'
| def delete(self, keys):
| return self.async_delete(None, keys).get_result()
|
'Asynchronous Delete operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
keys: An iterable of user-level key objects.
extra_hook: Optional function to be called once the RPC has completed.
Returns:
A MultiRpc object.'
| def async_delete(self, config, keys, extra_hook=None):
| def make_delete_call(req, pbs, user_data=None):
req.key_list().extend(pbs)
self._set_request_transaction(req)
resp = datastore_pb.DeleteResponse()
return self.make_rpc_call(config, 'Delete', req, resp, self.__delete_hook, user_data)
base_req = datastore_pb.DeleteRequest()
if ... |
'Internal method used as get_result_hook for Delete operation.'
| def __delete_hook(self, rpc):
| self.check_rpc_success(rpc)
if (rpc.user_data is not None):
rpc.user_data(None)
|
'Syncnronous BeginTransaction operation.
NOTE: In most cases the new_transaction() method is preferred,
since that returns a TransactionalConnection object which will
begin the transaction lazily.
Args:
app: Application ID.
Returns:
A datastore_pb.Transaction object.'
| def begin_transaction(self, app):
| return self.async_begin_transaction(None, app).get_result()
|
'Asynchronous BeginTransaction operation.
Args:
config: A configuration object or None. Defaults are taken from
the connection\'s default configuration.
app: Application ID.
Returns:
A MultiRpc object.'
| def async_begin_transaction(self, config, app):
| if ((not isinstance(app, basestring)) or (not app)):
raise datastore_errors.BadArgumentError(('begin_transaction requires an application id argument (%r)' % (app,)))
req = datastore_pb.BeginTransactionRequest()
req.set_app(app)
if TransactionOptions.xg(config, self.__config):
... |
'Internal method used as get_result_hook for BeginTransaction.'
| def __begin_transaction_hook(self, rpc):
| self.check_rpc_success(rpc)
return rpc.response
|
'Constructor.
All arguments should be specified as keyword arguments.
Args:
adapter: Optional AbstractAdapter subclass instance;
default IdentityAdapter.
config: Optional Configuration object.'
| @_positional(1)
def __init__(self, adapter=None, config=None):
| super(Connection, self).__init__(adapter=adapter, config=config)
self.__adapter = self.adapter
self.__config = self.config
|
'Create a new transactional connection based on this one.
This is different from, and usually preferred over, the
begin_transaction() method; new_transaction() returns a new
TransactionalConnection object.
Args:
config: A configuration object for the new connection, merged
with this connection\'s config.'
| def new_transaction(self, config=None):
| config = self.__config.merge(config)
return TransactionalConnection(adapter=self.__adapter, config=config)
|
'Synchronous AllocateIds operation.
Exactly one of size and max must be specified.
Args:
key: A user-level key object.
size: Optional number of IDs to allocate.
max: Optional maximum ID to allocate.
Returns:
A pair (start, end) giving the (inclusive) range of IDs allocation.'
| def allocate_ids(self, key, size=None, max=None):
| return self.async_allocate_ids(None, key, size, max).get_result()
|
'Asynchronous Get operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
key: A user-level key object.
size: Optional number of IDs to allocate.
max: Optional maximum ID to allocate.
extra_hook: Optional function to be called on the result once the
RPC... | def async_allocate_ids(self, config, key, size=None, max=None, extra_hook=None):
| if (size is not None):
if (max is not None):
raise datastore_errors.BadArgumentError('Cannot allocate ids using both size and max')
if (not isinstance(size, (int, long))):
raise datastore_errors.BadArgumentError(('Invalid size (%r)' % (size,)))
... |
'Internal method used as get_result_hook for AllocateIds.'
| def __allocate_ids_hook(self, rpc):
| self.check_rpc_success(rpc)
pair = (rpc.response.start(), rpc.response.end())
if (rpc.user_data is not None):
pair = rpc.user_data(pair)
return pair
|
'How existing transactions should be handled.
One of NESTED, MANDATORY, ALLOWED, INDEPENDENT. The interpertation of
these types is up to higher level run-in-transaction implementations.
WARNING: Using anything other than NESTED for the propagation flag
can have strange consequences. When using ALLOWED or MANDATORY, if... | @ConfigOption
def propagation(value):
| if (value not in TransactionOptions._PROPAGATION):
raise datastore_errors.BadArgumentError(('Unknown propagation value (%r)' % (value,)))
return value
|
'Whether to allow cross-group transactions.
Raises: datastore_errors.BadArgumentError if value is not a bool.'
| @ConfigOption
def xg(value):
| if (not isinstance(value, bool)):
raise datastore_errors.BadArgumentError(('xg argument should be bool (%r)' % (value,)))
return value
|
'How many retries to attempt on the transaction.
The exact retry logic is implemented in higher level run-in-transaction
implementations.
Raises: datastore_errors.BadArgumentError if value is not an integer or
is not greater than zero.'
| @ConfigOption
def retries(value):
| datastore_types.ValidateInteger(value, 'retries', datastore_errors.BadArgumentError, zero_ok=True)
return value
|
'The application in which to perform the transaction.
Raises: datastore_errors.BadArgumentError if value is not a string
or is the empty string.'
| @ConfigOption
def app(value):
| datastore_types.ValidateString(value, 'app', datastore_errors.BadArgumentError)
return value
|
'Constructor.
All arguments should be specified as keyword arguments.
Args:
adapter: Optional AbstractAdapter subclass instance;
default IdentityAdapter.
config: Optional Configuration object.
transaction: Optional datastore_db.Transaction object.
entity_group: Deprecated, do not use.'
| @_positional(1)
def __init__(self, adapter=None, config=None, transaction=None, entity_group=None):
| super(TransactionalConnection, self).__init__(adapter=adapter, config=config)
self.__adapter = self.adapter
if (transaction is None):
app = TransactionOptions.app(self.config)
app = datastore_types.ResolveAppId(TransactionOptions.app(self.config))
self.__transaction_rpc = self.async_... |
'Internal helper: return size in bytes plus room for transaction.'
| def _get_base_size(self, base_req):
| return ((super(TransactionalConnection, self)._get_base_size(base_req) + self.transaction.lengthString(self.transaction.ByteSize())) + 1)
|
'Set the current transaction on a request.
This calls _get_transaction() (see below). The transaction object
returned is both set as the transaction field on the request
object and returned.
Args:
request: A protobuf with a transaction field.
Returns:
A datastore_pb.Transaction object or None.'
| def _set_request_transaction(self, request):
| if self.__finished:
raise datastore_errors.BadRequestError('Cannot start a new operation in a finished transaction.')
transaction = self.transaction
request.mutable_transaction().CopyFrom(transaction)
return transaction
|
'Finish the current transaction.
This blocks waiting for all pending RPCs to complete, and then
marks the connection as finished. After that no more operations
can be started using this connection.
Returns:
A datastore_pb.Transaction object or None.
Raises:
datastore_errors.BadRequestError if the transaction is alread... | def _end_transaction(self):
| if self.__finished:
raise datastore_errors.BadRequestError('The transaction is already finished.')
self.wait_for_all_pending_rpcs()
assert (not self.get_pending_rpcs())
transaction = self.transaction
self.__finished = True
self.__transaction = None
return transaction
|
'Synchronous Commit operation.
Returns:
True if the transaction was successfully committed. False if
the backend reported a concurrent transaction error.'
| def commit(self):
| rpc = self.create_rpc()
rpc = self.async_commit(rpc)
if (rpc is None):
return True
return rpc.get_result()
|
'Asynchronous Commit operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
Returns:
A MultiRpc object.'
| def async_commit(self, config):
| transaction = self._end_transaction()
if (transaction is None):
return None
resp = datastore_pb.CommitResponse()
rpc = self.make_rpc_call(config, 'Commit', transaction, resp, self.__commit_hook)
return rpc
|
'Internal method used as get_result_hook for Commit.'
| def __commit_hook(self, rpc):
| try:
rpc.check_success()
except apiproxy_errors.ApplicationError as err:
if (err.application_error == datastore_pb.Error.CONCURRENT_TRANSACTION):
return False
else:
raise _ToDatastoreError(err)
else:
return True
|
'Synchronous Rollback operation.'
| def rollback(self):
| rpc = self.async_rollback(None)
if (rpc is None):
return None
return rpc.get_result()
|
'Asynchronous Rollback operation.
Args:
config: A Configuration object or None. Defaults are taken from
the connection\'s default configuration.
Returns:
A MultiRpc object.'
| def async_rollback(self, config):
| transaction = self._end_transaction()
if (transaction is None):
return None
resp = api_base_pb.VoidProto()
rpc = self.make_rpc_call(config, 'Rollback', transaction, resp, self.__rollback_hook)
return rpc
|
'Internal method used as get_result_hook for Rollback.'
| def __rollback_hook(self, rpc):
| self.check_rpc_success(rpc)
|
'Constructor.
Creates an unlimited range.'
| def __init__(self):
| self.__start = self.__end = None
self.__start_inclusive = self.__end_inclusive = False
|
'Filter the range by \'rel_op limit\'.
Args:
rel_op: relational operator from datastore_pb.Query_Filter.
limit: the value to limit the range by.'
| def Update(self, rel_op, limit):
| if (rel_op == datastore_pb.Query_Filter.LESS_THAN):
if ((self.__end is None) or (limit <= self.__end)):
self.__end = limit
self.__end_inclusive = False
elif ((rel_op == datastore_pb.Query_Filter.LESS_THAN_OR_EQUAL) or (rel_op == datastore_pb.Query_Filter.EQUAL)):
if ((sel... |
'Check if the range contains a specific value.
Args:
value: the value to check.
Returns:
True iff value is contained in this range.'
| def Contains(self, value):
| if (self.__start is not None):
if (self.__start_inclusive and (value < self.__start)):
return False
if ((not self.__start_inclusive) and (value <= self.__start)):
return False
if (self.__end is not None):
if (self.__end_inclusive and (value > self.__end)):
... |
'Transforms the range extremes with a function.
The function mapper must preserve order, i.e.
x rel_op y iff mapper(x) rel_op y
Args:
mapper: function to apply to the range extremes.'
| def Remap(self, mapper):
| self.__start = (self.__start and mapper(self.__start))
self.__end = (self.__end and mapper(self.__end))
|
'Evaluate a function on the range extremes.
Args:
mapper: function to apply to the range extremes.
Returns:
(x, y) where x = None if the range has no start,
mapper(start, start_inclusive, False) otherwise
y = None if the range has no end,
mapper(end, end_inclusive, True) otherwise'
| def MapExtremes(self, mapper):
| return ((self.__start and mapper(self.__start, self.__start_inclusive, False)), (self.__end and mapper(self.__end, self.__end_inclusive, True)))
|
'Constructor.
Args:
app: The app this cursor is being created for.'
| def __init__(self, app):
| self.app = app
self.cursor = self._AcquireCursorID()
|
'Acquires the next cursor id in a thread safe manner.'
| @classmethod
def _AcquireCursorID(cls):
| cls._next_cursor_lock.acquire()
try:
cursor_id = cls._next_cursor
cls._next_cursor += 1
finally:
cls._next_cursor_lock.release()
return cursor_id
|
'Constructor.
Args:
query: the query request proto
# the query results, in order, such that results[self.offset+1] is
# the next result
results: list of datastore_pb.EntityProto
order_compare_entities: a __cmp__ function for datastore_pb.EntityProto
that follows sort order as specified by the query'
| def __init__(self, query, results, order_compare_entities):
| super(ListCursor, self).__init__(query.app())
if (query.has_compiled_cursor() and query.compiled_cursor().position_list()):
(self.__last_result, inclusive) = self._DecodeCompiledCursor(query, query.compiled_cursor())
start_cursor_position = ListCursor._GetCursorOffset(results, self.__last_result... |
'Converts a cursor entity into a offset into the result set even if the
cursor_entity no longer exists.
Args:
results: the query\'s results (sequence of datastore_pb.EntityProto)
cursor_entity: the datastore_pb.EntityProto from the compiled query
inclusive: boolean that specifies if to offset past the cursor_entity
com... | @staticmethod
def _GetCursorOffset(results, cursor_entity, inclusive, compare):
| lo = 0
hi = len(results)
if inclusive:
while (lo < hi):
mid = ((lo + hi) // 2)
if (compare(results[mid], cursor_entity) < 0):
lo = (mid + 1)
else:
hi = mid
else:
while (lo < hi):
mid = ((lo + hi) // 2)
... |
'Ensure that the given query matches the query_info.
Args:
query: datastore_pb.Query instance we are chacking
query_info: datastore_pb.Query instance we want to match
Raises BadRequestError on failure.'
| def _ValidateQuery(self, query, query_info):
| error_msg = 'Cursor does not match query: %s'
if (query_info.filter_list() != query.filter_list()):
raise BadRequestError((error_msg % 'filters do not match'))
if (query_info.order_list() != query.order_list()):
raise BadRequestError((error_msg % 'orders do not ... |
'Extract the minimal set of information for query matching.
Args:
query: datastore_pb.Query instance from which to extract info.
Returns:
datastore_pb.Query instance suitable for matching against when
validating cursors.'
| def _MinimalQueryInfo(self, query):
| query_info = datastore_pb.Query()
query_info.set_app(query.app())
for filter in query.filter_list():
query_info.filter_list().append(filter)
for order in query.order_list():
query_info.order_list().append(order)
if query.has_ancestor():
query_info.mutable_ancestor().CopyFrom(... |
'Extract the minimal set of information that preserves entity order.
Args:
entity_proto: datastore_pb.EntityProto instance from which to extract
information
query: datastore_pb.Query instance for which ordering must be preserved.
Returns:
datastore_pb.EntityProto instance suitable for matching against a list of
results... | def _MinimalEntityInfo(self, entity_proto, query):
| entity_info = datastore_pb.EntityProto()
order_names = [o.property() for o in query.order_list()]
entity_info.mutable_key().MergeFrom(entity_proto.key())
entity_info.mutable_entity_group().MergeFrom(entity_proto.entity_group())
for prop in entity_proto.property_list():
if (prop.name() in ord... |
'Converts a compiled_cursor into a cursor_entity.
Returns:
(cursor_entity, inclusive): a datastore_pb.EntityProto and if it should
be included in the result set.'
| def _DecodeCompiledCursor(self, query, compiled_cursor):
| assert (len(compiled_cursor.position_list()) == 1)
position = compiled_cursor.position(0)
entity_as_pb = datastore_pb.EntityProto()
(query_info_encoded, entity_encoded) = position.start_key().split(_CURSOR_CONCAT_STR, 1)
query_info_pb = datastore_pb.Query()
query_info_pb.ParseFromString(query_in... |
'Converts the current state of the cursor into a compiled_cursor.
Args:
query: the datastore_pb.Query this cursor is related to
compiled_cursor: an empty datstore_pb.CompiledCursor'
| def _EncodeCompiledCursor(self, query, compiled_cursor):
| if (self.__last_result is not None):
position = compiled_cursor.add_position()
query_info = self._MinimalQueryInfo(query)
entity_info = self._MinimalEntityInfo(self.__last_result, query)
start_key = _CURSOR_CONCAT_STR.join((query_info.Encode(), entity_info.Encode()))
position... |
'Counts results, up to the query\'s limit.
Note this method does not deduplicate results, so the query it was generated
from should have the \'distinct\' clause applied.
Returns:
int: Result count.'
| def Count(self):
| return self.__count
|
'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'
| def PopulateQueryResult(self, result, count, offset, compile=False):
| 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) and count):
if (count > _MAXIMUM_RESULTS):
... |
'Replaces execute() with a logging variant.'
| def execute(self, sql, *args):
| if args:
parameters = []
for arg in args:
if isinstance(arg, buffer):
parameters.append('<blob>')
else:
parameters.append(repr(arg))
logging.debug('SQL Execute: %s - \n %s', sql, '\n '.join((str(param) for param in par... |
'Replaces executemany() with a logging variant.'
| def executemany(self, sql, seq_parameters):
| seq_parameters_list = list(seq_parameters)
logging.debug('SQL ExecuteMany: %s - \n %s', sql, '\n '.join((str(param) for param in seq_parameters_list)))
return super(SQLiteCursorWrapper, self).executemany(sql, seq_parameters_list)
|
'Replaces executescript() with a logging variant.'
| def executescript(self, sql):
| logging.debug('SQL ExecuteScript: %s', sql)
return super(SQLiteCursorWrapper, self).executescript(sql)
|
'Substitutes standard cursor() with a SQLiteCursorWrapper to log queries.
Substitutes the standard sqlite.Cursor with SQLiteCursorWrapper to ensure
all cursor requests get intercepted.
Returns:
A SQLiteCursorWrapper Instance.'
| def cursor(self):
| return super(SQLiteConnectionWrapper, self).cursor(SQLiteCursorWrapper)
|
'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:
A query cursor to iterate over the query results, or None if the query
is invalid.'
| def Query(self, query, filters, orders):
| kind_range = datastore_stub_util.ParseKindQuery(query, filters, orders)
conn = self._stub._GetConnection()
cursor = None
try:
prefix = self._stub._GetTablePrefix(query)
filters = []
def AddExtremeFilter(extreme, inclusive, is_end):
'Add filter for kind sta... |
'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:
A query cursor to iterate over the query results, or None if the query
is invalid.'
| def Query(self, query, filters, orders):
| property_range = datastore_stub_util.ParsePropertyQuery(query, filters, orders)
keys_only = query.keys_only()
conn = self._stub._GetConnection()
cursor = None
try:
prefix = self._stub._GetTablePrefix(query)
filters = []
def AddExtremeFilter(extreme, inclusive, is_end):
... |
'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:
A query cursor to iterate over the query results, or None if the query
is invalid.'
| def Query(self, query, filters, orders):
| namespace_range = datastore_stub_util.ParseNamespaceQuery(query, filters, orders)
app_str = query.app()
namespace_entities = []
namespaces = self._stub._DatastoreSqliteStub__namespaces
for (app_id, namespace) in sorted(namespaces):
if ((app_id == app_str) and namespace_range.Contains(namespa... |
'Constructor.
Initializes the SQLite database if necessary.
Args:
app_id: string
datastore_file: string, path to sqlite database. Use None to create an
in-memory database.
require_indexes: bool, default False. If True, composite indexes must
exist in index.yaml for queries that need them.
verbose: bool, default False. ... | def __init__(self, app_id, datastore_file, require_indexes=False, verbose=False, service_name='datastore_v3', trusted=False, consistency_policy=None, root_path=None, use_atexit=True, auto_id_policy=datastore_stub_util.SEQUENTIAL):
| datastore_stub_util.BaseDatastore.__init__(self, require_indexes, consistency_policy, (use_atexit and datastore_file), auto_id_policy)
apiproxy_stub.APIProxyStub.__init__(self, service_name)
datastore_stub_util.DatastoreStub.__init__(self, weakref.proxy(self), app_id, trusted, root_path)
self.__datastor... |
'Clears the datastore.'
| def Clear(self):
| conn = self._GetConnection()
try:
datastore_stub_util.BaseDatastore.Clear(self)
datastore_stub_util.DatastoreStub.Clear(self)
c = conn.execute("SELECT tbl_name FROM sqlite_master WHERE type = 'table'")
for row in c.fetchall():
conn.execute(('DROP ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.