desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Reads the datastore from disk. Noop for compatibility with file stub.'
def Read(self):
pass
'Closes the SQLite connection and releases the files.'
def Close(self):
conn = self._GetConnection() conn.close()
'Returns a comma separated list of sqlite substitution parameters. Args: size: Number of parameters in returned list. Returns: A comma separated list of substitution parameters.'
@staticmethod def __MakeParamList(size):
return ','.join(('?' * size))
'Returns the kind of the Entity or Key. It selects the kind of the last element of the entity_group element list, as it contains the most specific type of the key. Args: key: A Key or EntityProto Returns: The kind of the sent Key or Entity'
@staticmethod def __GetEntityKind(key):
if isinstance(key, entity_pb.EntityProto): key = key.key() return key.path().element_list()[(-1)].type()
'Encodes a protobuf using sortable_pb_encoder to preserve entity order. Using sortable_pb_encoder, encodes the protobuf, while using the ordering semantics for the datastore, and validating for the special case of uservalues ordering. Args: pb: An Entity protobuf. Returns: A buffer holding the encoded protobuf.'
@staticmethod def __EncodeIndexPB(pb):
if (isinstance(pb, entity_pb.PropertyValue) and pb.has_uservalue()): userval = entity_pb.PropertyValue() userval.mutable_uservalue().set_email(pb.uservalue().email()) userval.mutable_uservalue().set_auth_domain(pb.uservalue().auth_domain()) userval.mutable_uservalue().set_gaiaid(0) ...
'Adds a parameter to the query parameters.'
@staticmethod def __AddQueryParam(query_params, param):
query_params.append(param) return len(query_params)
'Transforms a filter list into an SQL WHERE clause. Args: filter_list: The list of (property, operator, value) filters to transform. A value_type of -1 indicates no value type comparison should be done. params: out: A list of parameters to pass to the query. Returns: An SQL \'where\' clause.'
@staticmethod def _CreateFilterString(filter_list, params):
clauses = [] for (prop, operator, value) in filter_list: if (operator == datastore_pb.Query_Filter.EXISTS): continue sql_op = _OPERATOR_MAP[operator] value_index = DatastoreSqliteStub.__AddQueryParam(params, value) clauses.append(('%s %s :%d' % (prop, sql_op, va...
'Returns an \'ORDER BY\' clause from the given list of orders. Args: order_list: A list of (field, order) tuples. Returns: An SQL ORDER BY clause.'
@staticmethod def __CreateOrderString(order_list):
orders = ', '.join((('%s %s' % (x[0], _ORDER_MAP[x[1]])) for x in order_list)) if orders: orders = ('ORDER BY ' + orders) return orders
'Retrieves a connection to the SQLite DB. Returns: An SQLite connection object.'
def _GetConnection(self):
self.__connection_lock.acquire() return self.__connection
'Releases a connection for use by other operations. If a transaction is supplied, no action is taken. Args: conn: An SQLite connection object.'
def _ReleaseConnection(self, conn):
conn.commit() self.__connection_lock.release()
'Ensures the relevant tables and indexes exist. Args: conn: An SQLite database connection. prefix: The namespace prefix to configure. app_id: The app ID. name_space: The per-app namespace name.'
def __ConfigureNamespace(self, conn, prefix, app_id, name_space):
format_args = {'app_id': app_id, 'name_space': name_space, 'prefix': prefix} conn.executescript((_NAMESPACE_SCHEMA % format_args)) conn.commit()
'Writes index data to disk. Args: conn: An SQLite connection. app: The app ID to write indexes for.'
def __WriteIndexData(self, conn, app):
indices = datastore_pb.CompositeIndices() for index in self.GetIndexes(app, True, self._app_id): indices.index_list().append(index) conn.execute('UPDATE Apps SET indexes = ? WHERE app_id = ?', (app, buffer(indices.Encode())))
'Returns the namespace prefix for a query. Args: data: An Entity, Key or Query PB, or an (app_id, ns) tuple. Returns: A valid table prefix'
def _GetTablePrefix(self, data):
if isinstance(data, entity_pb.EntityProto): data = data.key() if (not isinstance(data, tuple)): data = (data.app(), data.name_space()) prefix = ('%s!%s' % data).replace('"', '""') if (data not in self.__namespaces): self.__namespaces.add(data) self.__ConfigureNamespace(se...
'Deletes rows from a table. Args: conn: An SQLite connection. paths: Paths to delete. table: The table to delete from. Returns: The number of rows deleted.'
def __DeleteRows(self, conn, paths, table):
c = conn.execute(('DELETE FROM "%s" WHERE __path__ IN (%s)' % (table, self.__MakeParamList(len(paths)))), paths) return c.rowcount
'Deletes rows from the specified table that index the keys provided. Args: conn: A database connection. keys: A list of keys to delete index entries for. table: The table to delete from. Returns: The number of rows deleted.'
def __DeleteEntityRows(self, conn, keys, table):
keys = sorted(((x.app(), x.name_space(), x) for x in keys)) for ((app_id, ns), group) in itertools.groupby(keys, (lambda x: x[:2])): path_strings = [self.__EncodeIndexPB(x[2].path()) for x in group] prefix = self._GetTablePrefix((app_id, ns)) return self.__DeleteRows(conn, path_strings, ...
'Deletes entities from the index. Args: conn: An SQLite connection. keys: A list of keys to delete.'
def __DeleteIndexEntries(self, conn, keys):
self.__DeleteEntityRows(conn, keys, 'EntitiesByProperty')
'Inserts or updates entities in the DB. Args: conn: A database connection. entities: A list of entities to store.'
def __InsertEntities(self, conn, entities):
def RowGenerator(entities): for (unused_prefix, e) in entities: (yield (self.__EncodeIndexPB(e.key().path()), self.__GetEntityKind(e), buffer(e.Encode()))) entities = sorted(((self._GetTablePrefix(x), x) for x in entities)) for (prefix, group) in itertools.groupby(entities, (lambda x: x[...
'Inserts index entries for the supplied entities. Args: conn: A database connection. entities: A list of entities to create index entries for.'
def __InsertIndexEntries(self, conn, entities):
def RowGenerator(entities): for (unused_prefix, e) in entities: for p in e.property_list(): (yield (self.__GetEntityKind(e), p.name(), self.__EncodeIndexPB(p.value()), self.__EncodeIndexPB(e.key().path()))) entities = sorted(((self._GetTablePrefix(x), x) for x in entities)) ...
'The main RPC entry point. service must be \'datastore_v3\'.'
def MakeSyncCall(self, service, call, request, response, request_id=None):
self.AssertPbIsInitialized(request) try: apiproxy_stub.APIProxyStub.MakeSyncCall(self, service, call, request, response, request_id) except sqlite3.OperationalError as e: raise apiproxy_errors.ApplicationError(datastore_pb.Error.INTERNAL_ERROR, e.args[0]) self.AssertPbIsInitialized(respo...
'Raises an exception if the given PB is not initialized and valid.'
def AssertPbIsInitialized(self, pb):
explanation = [] assert pb.IsInitialized(explanation), explanation pb.Encode()
'Transform a list of filters into a more usable form. Args: filters: A list of filter PBs. query: The query to generate filter info for. Returns: A dict mapping property names to lists of (op, value) tuples.'
def __GenerateFilterInfo(self, filters, query):
filter_info = {} for filt in filters: assert (filt.property_size() == 1) prop = filt.property(0) value = prop.value() if (prop.name() == '__key__'): value = ReferencePropertyToReference(value.referencevalue()) assert (value.app() == query.app()) ...
'Transform a list of orders into a more usable form. Args: orders: A list of order PBs. Returns: A list of (property, direction) tuples.'
def __GenerateOrderInfo(self, orders):
orders = [(order.property(), order.direction()) for order in orders] if (orders and (orders[(-1)] == ('__key__', datastore_pb.Query_Order.ASCENDING))): orders.pop() return orders
'Returns a (min, max) range that encompasses the given prefix. Args: prefix: A string prefix to filter for. Must be a PB encodable using __EncodeIndexPB. Returns: (min, max): Start and end string values to filter on.'
def __GetPrefixRange(self, prefix):
ancestor_min = self.__EncodeIndexPB(prefix) ancestor_max = buffer((str(ancestor_min) + '\xfb\xff\xff\xff\x89')) return (ancestor_min, ancestor_max)
'Performs kind only, kind and ancestor, and ancestor only queries.'
def __KindQuery(self, query, filter_info, order_info):
if (not (set(filter_info.keys()) | set((x[0] for x in order_info))).issubset(['__key__'])): return None if (len(order_info) > 1): return None filters = [] filters.extend((('__path__', op, value) for (op, value) in filter_info.get('__key__', []))) if query.has_kind(): filters....
'Performs queries satisfiable by the EntitiesByProperty table.'
def __SinglePropertyQuery(self, query, filter_info, order_info):
property_names = set(filter_info.keys()) property_names.update((x[0] for x in order_info)) if (len(property_names) != 1): return None property_name = property_names.pop() filter_ops = filter_info.get(property_name, []) if (len([1 for (o, _) in filter_ops if (o == datastore_pb.Query_Filte...
'Executes a query using a \'star schema\' based on EntitiesByProperty. A \'star schema\' is a join between an objects table (Entities) and multiple instances of a facts table (EntitiesByProperty). Ideally, this will result in a merge join if the only filters are inequalities and the sort orders match those in the index...
def __StarSchemaQueryPlan(self, query, filter_info, order_info):
filter_sets = [] for (name, filter_ops) in filter_info.items(): filter_sets.extend(((name, [x]) for x in filter_ops if (x[0] == datastore_pb.Query_Filter.EQUAL))) ineq_ops = [x for x in filter_ops if (x[0] != datastore_pb.Query_Filter.EQUAL)] if ineq_ops: filter_sets.append((...
'Last resort query plan that executes queries requring composite indexes. Args: query: The datastore_pb.Query PB. filter_info: A dict mapping properties filtered on to (op, value) tuples. order_info: A list of (property, direction) tuples. Returns: (query, params): An SQL query string and list of parameters for it.'
def __LastResortQuery(self, query, filter_info, order_info):
return self.__StarSchemaQueryPlan(query, filter_info, order_info)
'Returns a query cursor for the provided query. Args: conn: The SQLite connection. query: A datastore_pb.Query protobuf. Returns: A QueryCursor object.'
def _GetQueryCursor(self, query, filters, orders, index_list):
if (query.has_kind() and (query.kind() in self._pseudo_kinds)): cursor = self._pseudo_kinds[query.kind()].Query(query, filters, orders) datastore_stub_util.Check(cursor, 'Could not create query for pseudo-kind') else: orders = datastore_stub_util._GuessOrders(filters, orde...
'Constructor. Args: path_entry: The entry in sys.path. This should be the name of an existing zipfile possibly with a path separator and a prefix path within the archive appended, e.g. /x/django.zip or /x/django.zip/foo/bar. Raises: ZipImportError if the path_entry does not represent a valid zipfile with optional pref...
def __init__(self, path_entry):
archive = path_entry prefix = '' while (not os.path.lexists(archive)): (head, tail) = os.path.split(archive) if (head == archive): msg = ('Nothing found for %r' % path_entry) raise ZipImportError(msg) archive = head prefix = os.path.join(tail,...
'Return a string representation matching zipimport.c.'
def __repr__(self):
name = self.archive if self.prefix: name = os.path.join(name, self.prefix) return ('<zipimporter object "%s">' % name)
'Internal helper for find_module() and load_module(). Args: fullmodname: The dot-separated full module name, e.g. \'django.core.mail\'. Returns: A tuple (submodname, is_package, relpath) where: submodname: The final component of the module name, e.g. \'mail\'. is_package: A bool indicating whether this is a package. re...
def _get_info(self, fullmodname):
parts = fullmodname.split('.') submodname = parts[(-1)] for (suffix, is_package) in _SEARCH_ORDER: relpath = os.path.join(self.prefix, (submodname + suffix.replace('/', os.sep))) try: self.zipfile.getinfo(relpath.replace(os.sep, '/')) except KeyError: pass ...
'Internal helper for load_module(). Args: fullmodname: The dot-separated full module name, e.g. \'django.core.mail\'. Returns: A tuple (submodname, is_package, fullpath, source) where: submodname: The final component of the module name, e.g. \'mail\'. is_package: A bool indicating whether this is a package. fullpath: T...
def _get_source(self, fullmodname):
(submodname, is_package, relpath) = self._get_info(fullmodname) fullpath = ('%s%s%s' % (self.archive, os.sep, relpath)) source = self.zipfile.read(relpath.replace(os.sep, '/')) source = source.replace('\r\n', '\n') source = source.replace('\r', '\n') return (submodname, is_package, fullpath, sou...
'PEP-302-compliant find_module() method. Args: fullmodname: The dot-separated full module name, e.g. \'django.core.mail\'. path: Optional and ignored; present for API compatibility only. Returns: None if the module isn\'t found in the archive; self if it is found.'
def find_module(self, fullmodname, path=None):
try: (submodname, is_package, relpath) = self._get_info(fullmodname) except ImportError: return None else: return self
'PEP-302-compliant load_module() method. Args: fullmodname: The dot-separated full module name, e.g. \'django.core.mail\'. Returns: The module object constructed from the source code. Raises: SyntaxError if the module\'s source code is syntactically incorrect. ImportError if there was a problem accessing the source cod...
def load_module(self, fullmodname):
(submodname, is_package, fullpath, source) = self._get_source(fullmodname) code = compile(source, fullpath, 'exec') mod = sys.modules.get(fullmodname) try: if (mod is None): mod = sys.modules[fullmodname] = types.ModuleType(fullmodname) mod.__loader__ = self mod.__fil...
'Return (binary) content of a data file in the zipfile.'
def get_data(self, fullpath):
prefix = os.path.join(self.archive, '') if fullpath.startswith(prefix): relpath = fullpath[len(prefix):] elif os.path.isabs(fullpath): raise IOError(("Absolute path %r doesn't start with zipfile name %r" % (fullpath, prefix))) else: relpath = fullpath ...
'Return whether a module is a package.'
def is_package(self, fullmodname):
(submodname, is_package, relpath) = self._get_info(fullmodname) return is_package
'Return bytecode for a module.'
def get_code(self, fullmodname):
(submodname, is_package, fullpath, source) = self._get_source(fullmodname) return compile(source, fullpath, 'exec')
'Return source code for a module.'
def get_source(self, fullmodname):
(submodname, is_package, fullpath, source) = self._get_source(fullmodname) return source
'Add header for field key handling repeats.'
def addheader(self, key, value):
prev = self.dict.get(key) if (prev is None): self.dict[key] = value else: combined = ', '.join((prev, value)) self.dict[key] = combined
'Add more field data from a continuation line.'
def addcontinue(self, key, more):
prev = self.dict[key] self.dict[key] = ((prev + '\n ') + more)
'Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to backspace over it; it is never included in the r...
def readheaders(self):
self.dict = {} self.unixfrom = '' self.headers = hlist = [] self.status = '' headerseen = '' firstline = 1 startofline = unread = tell = None if hasattr(self.fp, 'unread'): unread = self.fp.unread elif self.seekable: tell = self.fp.tell while True: if tell...
'Provide a default host, since the superclass requires one.'
def __init__(self, host='', port=None, strict=None):
if (port == 0): port = None self._setup(self._connection_class(host, port, strict))
'Accept arguments to set the host/port, since the superclass doesn\'t.'
def connect(self, host=None, port=None):
self.__init__(host, port)
'Provide a getfile, since the superclass\' does not use this concept.'
def getfile(self):
return self.file
'The superclass allows only one value argument.'
def putheader(self, header, *values):
self._conn.putheader(header, '\r\n DCTB '.join([str(v) for v in values]))
'Compat definition since superclass does not define it. Returns a tuple consisting of: - server status code (e.g. \'200\' if all goes well) - server "reason" corresponding to status code - any RFC822 headers in the response from the server'
def getreply(self):
response = self._conn.getresponse() self.headers = response.msg self.file = response.fp return (response.status, response.reason, response.msg)
'dup() -> socket object Return a new socket object connected to the same system resource.'
def dup(self):
return _socketobject(_sock=self._sock)
'makefile([mode[, bufsize]]) -> file object Return a regular file object corresponding to the socket. The mode and bufsize arguments are as for the built-in open() function.'
def makefile(self, mode='r', bufsize=(-1)):
return _fileobject(self._sock, mode, bufsize)
'Create a new instance of LooseVersion. Args: version: iterable containing the version values.'
def __init__(self, version):
self.version = tuple(map(str, version))
'Parse a version string and create a new LooseVersion instance. Args: string: dot delimited version string. Returns: A distutils.version.LooseVersion compatible object.'
@classmethod def parse(cls, string):
return cls(string.split('.'))
'Initializer. Args: conn: A Connection object. use_dict_cursor: Optional boolean to convert each row of results into a dictionary. Defaults to False. fetch_size: An integer, batch size to fetch the result set from server if streaming. Defaults to None.'
def __init__(self, conn, use_dict_cursor=False, fetch_size=None):
self._conn = conn self._open = True self._use_dict_cursor = use_dict_cursor self._fetch_size = fetch_size self.arraysize = 1 self._executed = None self.lastrowid = None self._Reset()
'Marks the cursor as unusable for further operations.'
def close(self):
self._CheckOpen() self._open = False
'Get the JDBC type which corresponds to the given Python object type.'
def _GetJdbcTypeForArg(self, arg):
arg_jdbc_type = _PYTHON_TYPE_TO_JDBC_TYPE.get(type(arg)) if arg_jdbc_type: return arg_jdbc_type for (python_t, jdbc_t) in _PYTHON_TYPE_TO_JDBC_TYPE.items(): if isinstance(arg, python_t): return jdbc_t try: return self._GetJdbcTypeForArg(arg[0]) except TypeError: ...
'Converts a variable to a type and value. Args: arg: Any tuple, string, numeric, or datetime object. Returns: A (int, str) tuple, representing a JDBC type and encoded value. Raises: TypeError: The argument is not a recognized type.'
def _EncodeVariable(self, arg):
arg_jdbc_type = self._GetJdbcTypeForArg(arg) value = self._conn.encoders[type(arg)](arg, self._conn.encoders) return (arg_jdbc_type, value)
'Converts a type and value to a variable. Args: datatype: An integer. value: A string. Returns: An object of some appropriate type. Raises: InterfaceError: datatype is not a recognized JDBC type. ValueError: The value could not be parsed.'
def _DecodeVariable(self, datatype, value):
converter = self._conn.converter.get(datatype) if (converter is None): raise InterfaceError(('unknown JDBC type %d' % datatype)) return converter(value)
'Add args to the request BindVariableProto list. Args: statement: The SQL statement. args: Sequence of arguments to turn into BindVariableProtos. bind_variable_factory: A callable which returns new BindVariableProtos. direction: The direction to set for all variables in the request. Raises: InterfaceError: Unknown type...
def _AddBindVariablesToRequest(self, statement, args, bind_variable_factory, direction=client_pb2.BindVariableProto.IN):
if isinstance(args, dict): args = _ConvertArgsDictToList(statement, args) for (i, arg) in enumerate(args): bv = bind_variable_factory() bv.position = (i + 1) bv.direction = direction if (arg is None): bv.type = jdbc_type.NULL else: try: ...
'Send an ExecRequest and handle the response. Args: request: The sql_pb2.ExecRequest to send. Returns: The client_pb2.ResultProto returned by the server. Raises: DatabaseError: A SQL exception occurred. OperationalError: RPC problem.'
def _DoExec(self, request):
if self._fetch_size: request.options.fetch_size = self._fetch_size response = self._conn.MakeRequest('Exec', request) return self._HandleResult(response.result)
'Returns a list of tuples describing the columns in the result set. Args: result: The client_pb2.ResultProto to process. Returns: A sequence of sequences describing the columns in the result set. Returns None if column description is not present in the result proto.'
def _GetDescription(self, result):
if (not result.rows.columns): return None return [(column.label, column.type, column.display_size, None, column.precision, column.scale, column.nullable) for column in result.rows.columns]
'Handle the ResultProto from an Exec/ExecOp call. Args: result: The client_pb2.ResultProto to handle. Returns: The given client_pb2.ResultProto. Raises: DatabaseError: A SQL exception occurred.'
def _HandleResult(self, result):
if result.HasField('rows'): description = self._GetDescription(result) if description: self._description = description if (not self._rows): self._rows = collections.deque() new_rows = self._GetRows(result) if (new_rows is not None): if (sel...
'Returns a sequence of sequences containing the result set. Args: result: The client_pb2.ResultProto to process. Returns: A sequence of sequences, or an empty sequence when result set is empty. Returns None if result set is not present.'
def _GetRows(self, result):
if (not result.rows.tuples): return None assert self._description, 'Column descriptions do not exist.' column_names = [col[0] for col in self._description] rows = [] for tuple_proto in result.rows.tuples: row = [] nulls = set(tuple_proto.nulls) value_index...
'Prepares and executes a database operation (query or command). Args: statement: A string, a SQL statement. args: A sequence or mapping of arguments matching the statement\'s bind variables, if any. Raises: InterfaceError: Unknown type used as a bind variable. DatabaseError: A SQL exception occurred. OperationalError: ...
def execute(self, statement, args=None):
self._CheckOpen() self._Reset() request = sql_pb2.ExecRequest() request.options.include_generated_keys = True if (args is not None): if (not hasattr(args, '__iter__')): args = [args] self._AddBindVariablesToRequest(statement, args, request.bind_variable.add) request.s...
'Prepares and executes a database operation for given parameter sequences. Args: statement: A string, a SQL statement. seq_of_args: A sequence, each entry of which is a sequence or mapping of arguments matching the statement\'s bind variables, if any. Raises: InterfaceError: Unknown type used as a bind variable. Databa...
def executemany(self, statement, seq_of_args):
self._CheckOpen() self._Reset() request = sql_pb2.ExecRequest() request.options.include_generated_keys = True args = None for args in seq_of_args: if (not hasattr(args, '__iter__')): args = [args] bbv = request.batch.batch_bind_variable.add() self._AddBindVari...
'Fetches more rows from the server for a previously executed statement.'
def _FetchMoreRows(self):
request = sql_pb2.ExecRequest() request.statement_id = self._statement_id self._DoExec(request)
'Calls a stored database procedure with the given name. Args: procname: A string, the name of the stored procedure. args: A sequence of parameters to use with the procedure. Returns: A modified copy of the given input args. Input parameters are left untouched, output and input/output parameters replaced with possibly n...
def callproc(self, procname, args=()):
self._CheckOpen() self._Reset() request = sql_pb2.ExecRequest() request.statement_type = sql_pb2.ExecRequest.CALLABLE_STATEMENT request.statement = ('CALL %s(%s)' % (procname, ','.join(('?' * len(args))))) self._AddBindVariablesToRequest(request.statement, args, request.bind_variable.add, dir...
'Advance to the next result set. Returns: True if there was an available set to advance to, otherwise, None. Raises: InternalError: The cursor has been closed, or no statement has been executed yet. DatabaseError: A SQL exception occurred. OperationalError: RPC problem.'
def nextset(self):
self._CheckOpen() self._CheckExecuted('nextset() called before execute') self._rows = collections.deque() self._rowcount = (-1) if (not self._more_results): return None request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.NEXT_RESULT request.op.statemen...
'Fetches the next row of a query result set. Returns: A sequence, or None when no more data is available. Raises: InternalError: The cursor has been closed, or no statement has been executed yet.'
def fetchone(self):
self._CheckOpen() self._CheckExecuted('fetchone() called before execute') if ((not self._rows) and self._more_rows): self._FetchMoreRows() try: return self._rows.popleft() except IndexError: return None
'Fetches the next set of rows of a query result. Args: size: The maximum number of rows to return; by default, self.arraysize. Returns: A sequence of sequences, or an empty sequence when no more data is available. Raises: InternalError: The cursor has been closed, or no statement has been executed yet.'
def fetchmany(self, size=None):
self._CheckOpen() self._CheckExecuted('fetchmany() called before execute') if (size is None): size = self.arraysize while (self._more_rows and (size > len(self._rows))): self._FetchMoreRows() if (size >= len(self._rows)): rows = self._rows self._rows = collec...
'Fetches all remaining rows of a query result. Returns: A sequence of sequences, or an empty sequence when no more data is available. Raises: InternalError: The cursor has been closed, or no statement has been executed yet.'
def fetchall(self):
self._CheckOpen() self._CheckExecuted('fetchall() called before execute') while self._more_rows: self._FetchMoreRows() rows = self._rows self._rows = collections.deque() return tuple(rows)
'Creates a new SQL Service connection. Args: dsn: A string, the SQL Service job path or host:port. instance: A string, the SQL Service instance name, often a username. database: A string, semantics defined by the backend. user: A string, database user name. password: A string, database password. deadline_seconds: A flo...
def __init__(self, dsn, instance, database=None, user='root', password=None, deadline_seconds=60.0, conv=None, query_deadline_seconds=86400.0, retry_interval_seconds=30.0):
self._dsn = dsn if (not instance): raise TypeError(('Invalid value for instance (%s)' % instance)) self._instance = instance self._database = database self._user = user self._password = password self._deadline_seconds = deadline_seconds self._connection_id = None ...
'Opens a connection to SQL Service.'
def OpenConnection(self):
request = sql_pb2.OpenConnectionRequest() request.client_type = client_pb2.CLIENT_TYPE_PYTHON_DBAPI prop = request.property.add() prop.key = 'autoCommit' prop.value = 'false' if self._user: prop = request.property.add() prop.key = 'user' prop.value = self._user if sel...
'Setup a transport client to communicate with rdbms. This is a template method to provide subclasses with a hook to perform any necessary client initialization while opening a connection to rdbms.'
def SetupClient(self):
pass
'Makes the connection and all its cursors unusable. The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection.'
def close(self):
self.CheckOpen() request = sql_pb2.CloseConnectionRequest() try: self.MakeRequest('CloseConnection', request) except DatabaseError: pass self._connection_id = None
'Commits any pending transaction to the database. Raises: DatabaseError: A SQL exception occurred. OperationalError: RPC problem.'
def commit(self):
self.CheckOpen() request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.COMMIT self.MakeRequest('ExecOp', request)
'Rolls back any pending transaction to the database. Raises: DatabaseError: A SQL exception occurred. OperationalError: RPC problem.'
def rollback(self):
self.CheckOpen() request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.ROLLBACK self.MakeRequest('ExecOp', request)
'Changes whether there is an implicit commit after each statement. By default, transactions must be explicitly committed. Args: value: A boolean. Raises: DatabaseError: A SQL exception occurred. OperationalError: RPC problem.'
def autocommit(self, value):
self.CheckOpen() request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.SET_AUTO_COMMIT request.op.auto_commit = value self.MakeRequest('ExecOp', request)
'Returns a cursor for the current connection. Args: **kwargs: Optional keyword args to pass into cursor. Returns: A Cursor object.'
def cursor(self, **kwargs):
return Cursor(self, **kwargs)
'Makes an ApiProxy request, and possibly raises an appropriate exception. Args: stub_method: A string, the name of the method to call. request: A protobuf; \'instance\' and \'connection_id\' will be set when available. Returns: A protobuf. Raises: DatabaseError: Error from SQL Service server.'
def MakeRequest(self, stub_method, request):
request.instance = self._instance if (self._connection_id is not None): request.connection_id = self._connection_id if (stub_method in ('Exec', 'ExecOp', 'GetMetadata')): self._idempotent_request_id += 1 request.request_id = self._idempotent_request_id response = self._MakeRe...
'Makes a retriable request. Args: stub_method: A string, the name of the method to call. request: A protobuf. Returns: A protobuf. Raises: DatabaseError: Error from SQL Service server.'
def _MakeRetriableRequest(self, stub_method, request):
absolute_deadline_seconds = (time.clock() + self._query_deadline_seconds) response = self.MakeRequestImpl(stub_method, request) if (not response.HasField('sql_exception')): return response sql_exception = response.sql_exception if (sql_exception.application_error_code != client_error_code_pb...
'Retries request with the given request id. Continues to retry until either the deadline has expired or the response has been received. Args: stub_method: A string, the name of the original method that triggered the retry. request_id: An integer, the request id used in the original request absolute_deadline_seconds: An...
def _Retry(self, stub_method, request_id, absolute_deadline_seconds):
request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.RETRY request.op.request_id = request_id request.connection_id = self._connection_id request.instance = self._instance while True: seconds_remaining = (absolute_deadline_seconds - time.clock()) if (seconds_rem...
'Converts the cached response or RPC error. Args: stub_method: A string, the name of the original method that triggered the retry. exec_op_response: A protobuf, the retry response that contains either the RPC error or the cached response. Returns: A protobuf, the cached response. Raises: DatabaseError: If the cached re...
def _ConvertCachedResponse(self, stub_method, exec_op_response):
if exec_op_response.HasField('cached_rpc_error'): raise InternalError(('%d: %s' % (exec_op_response.cached_rpc_error.error_code, exec_op_response.cached_rpc_error.error_message))) if (not exec_op_response.HasField('cached_payload')): raise InternalError('Invalid exec op response f...
'Returns a string that represents the server version number. Non-standard; Provided for API compatibility with MySQLdb. Returns: The server version number string.'
def get_server_info(self):
self.CheckOpen() request = sql_pb2.MetadataRequest() request.metadata = client_pb2.METADATATYPE_DATABASE_METADATA_BASIC response = self.MakeRequest('GetMetadata', request) return response.jdbc_database_metadata.database_product_version
'Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by clients that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary. Non-standard. You should assume th...
def ping(self, reconnect=False):
self.CheckOpen() request = sql_pb2.ExecOpRequest() request.op.type = client_pb2.OpProto.PING try: self.MakeRequest('ExecOp', request) except DatabaseError: if (not reconnect): raise self._connection_id = None self.OpenConnection()
'Constructs an RdbmsGoogleApiClient. Args: api_url: The base of the URL for the rdbms Google API. oauth_credentials_path: The filesystem path to use for OAuth 2.0 credentials storage. oauth_storage: A client.Storage instance to use for OAuth 2.0 credential storage instead of the default file based storage. developer_ke...
def __init__(self, api_url='https://www.googleapis.com/sql/v1/', oauth_credentials_path=None, oauth_storage=None, developer_key=None):
self._api_url = api_url self._developer_key = developer_key if (oauth_storage is None): if (oauth_credentials_path is None): oauth_credentials_path = os.path.expanduser(rdbms.OAUTH_CREDENTIALS_PATH) oauth_storage = oauth_file.Storage(oauth_credentials_path) credentials = oaut...
'Executes a request to the Google API server. Args: method: The method to invoke. request: The request protocol buffer from sql_pb2. response_class: The response protocol buffer class from sql_pb2. Returns: A protocol buffer instance of the given response_class type.'
def _MakeRequest(self, method, request, response_class):
pb_model = model.ProtocolBufferModel(response_class) query_params = {} if self._developer_key: query_params['key'] = self._developer_key (headers, unused_params, query, body) = pb_model.request({}, {}, query_params, request) request = http.HttpRequest(self._transport, pb_model.response, ((se...
'Constructs a GoogleApiConnection. In addition to all of the arguments taken by rdbms.Connection.__init__, this also accepts the following optional keyword arguments: oauth_credentials_path: The filesystem path to the file used for OAuth 2.0 credential storage. oauth_storage: A client.Storage instance to use for OAuth ...
def __init__(self, *args, **kwargs):
self._oauth_credentials_path = kwargs.pop('oauth_credentials_path', None) self._oauth_storage = kwargs.pop('oauth_storage', None) self._developer_key = kwargs.pop('developer_key', None) super(GoogleApiConnection, self).__init__(*args, **kwargs)
'Opens a Google API connection to rdbms.'
def SetupClient(self):
kwargs = {'developer_key': self._developer_key, 'oauth_storage': self._oauth_storage} if self._dsn: kwargs['api_url'] = self._dsn if self._oauth_credentials_path: kwargs['oauth_credentials_path'] = self._oauth_credentials_path self._client = RdbmsGoogleApiClient(**kwargs)
'Makes a Google API request, and possibly raises an appropriate exception. Args: stub_method: A string, the name of the method to call. request: A protobuf; \'instance\' and \'connection_id\' will be set when available. Returns: A protobuf. Raises: OperationalError: httplib2 transport failure, or non 2xx http response....
def MakeRequestImpl(self, stub_method, request):
try: response = getattr(self._client, stub_method)(request) except (errors.Error, client.Error, httplib2.HttpLib2Error) as e: raise OperationalError(('could not connect: ' + str(e))) return response
'Creates the protocol buffer response object for stub_method.'
def _CreateResponse(self, stub_method):
if (stub_method == 'OpenConnection'): return sql_pb2.OpenConnectionResponse() elif (stub_method == 'CloseConnection'): return sql_pb2.CloseConnectionResponse() elif (stub_method == 'Exec'): return sql_pb2.ExecResponse() elif (stub_method == 'ExecOp'): return sql_pb2.ExecO...
'Makes an ApiProxy request, and possibly raises an appropriate exception. Args: stub_method: A string, the name of the method to call. request: A protobuf; \'instance\' and \'connection_id\' will be set when available. Returns: A protobuf. Raises: OperationalError: ApiProxy failure.'
def MakeRequestImpl(self, stub_method, request):
response = self._CreateResponse(stub_method) try: apiproxy_stub_map.MakeSyncCall('rdbms', stub_method, request, response) except apiproxy_errors.ApplicationError as e: raise OperationalError(('could not connect: ' + str(e))) return response
'Perform an OAuth 2.0 oob flow. After the flow completes, instructions are provided to manually store the OAuth2 refresh_token in the project settings file.'
def handle_noargs(self, **unused_options):
flow = rdbms_googleapi.GetFlow() self.stdout.write(('\nGo to the following link in your browser:\n%s\n\n' % flow.step1_get_authorize_url('oob'))) accepted = 'n' while (accepted.lower() == 'n'): accepted = raw_input('Have you authorized me? (y/n) ') code = ...
'Returns the query last executed by the given cursor. Placeholders found in the given sql string will be replaced with actual values from the params list. Args: cursor: The database Cursor. sql: The raw query containing placeholders. params: The sequence of parameters. Returns: The string representing the query last ex...
def last_executed_query(self, cursor, sql, params):
return backends.BaseDatabaseOperations.last_executed_query(self, cursor, sql, params)
'Disable ping on every operation.'
def _valid_connection(self):
if (self.connection is not None): if ((time.time() - self._last_ping_time) < PING_INTERVAL_SECS): return True else: self._last_ping_time = time.time() return super(DatabaseWrapper, self)._valid_connection() else: return False
'Start an interactive database shell.'
def runshell(self):
settings_dict = self.connection.settings_dict args = [self.executable_name] args = ['', settings_dict.get('INSTANCE')] database = settings_dict.get('NAME') if database: args.append(database) from google.storage.speckle.python.tool import google_sql google_sql.main(args)
'Connect to the actual underlying database, using the driver. Args: host: The host where the database lives. port: The TCP port to use when connecting. (UNUSED) user: The user to use when connecting. password: The password to use when connecting. database: A DatabaseConfig instance containing the instance id and databa...
def do_connect(self, host, port, user, password, database):
dbi = self.get_import() return dbi.connect(host, database.instance, database=database.name, user=user, password=password, oauth_credentials_path=database.oauth_credentials_path)
'Quit the google_sql. Same as exit.'
def do_quit(self, args):
return self.do_exit(args)
'Builds an output PrettyTable from the results in the given cursor.'
def _BuildTable(self, cursor):
if (not cursor.description): return None column_names = [column[0] for column in cursor.description] table = prettytable.PrettyTable(column_names) rows = cursor.fetchall() if (not rows): return table for (i, col) in enumerate(rows[0]): table.set_field_align(column_names[i...
'Overrides SQLCmd.__handle_select to display output with prettytable.'
def _SQLCmd__handle_select(self, args, cursor, command='select'):
self._SQLCmd__exec_SQL(cursor, command, args) table = self._BuildTable(cursor) if table: output = table.get_string() if isinstance(output, unicode): print output.encode(self.output_encoding) else: print output
'Make a Exec RPC call. Args: request: a ExecRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with response. Returns: Th...
def Exec(self, request, rpc=None, callback=None, response=None):
if (response is None): response = ExecResponse return self._MakeCall(rpc, self._full_name_Exec, 'Exec', request, response, callback, self._protorpc_Exec)
'Make a ExecOp RPC call. Args: request: a ExecOpRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with response. Returns...
def ExecOp(self, request, rpc=None, callback=None, response=None):
if (response is None): response = ExecOpResponse return self._MakeCall(rpc, self._full_name_ExecOp, 'ExecOp', request, response, callback, self._protorpc_ExecOp)
'Make a GetMetadata RPC call. Args: request: a MetadataRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with response. ...
def GetMetadata(self, request, rpc=None, callback=None, response=None):
if (response is None): response = MetadataResponse return self._MakeCall(rpc, self._full_name_GetMetadata, 'GetMetadata', request, response, callback, self._protorpc_GetMetadata)