Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _table_arg_to_table(value, default_project=None): if isinstance(value, six.string_types): value = TableReference.from_string(value, default_project=default_project) if isinstance(value, TableReference): value = Table(value) if isinstance(...
[ "Helper to convert a string or TableReference to a Table.\n\n This function keeps Table and other kinds of objects unchanged.\n " ]
Please provide a description of the function:def from_string(cls, table_id, default_project=None): from google.cloud.bigquery.dataset import DatasetReference ( output_project_id, output_dataset_id, output_table_id, ) = _helpers._parse_3_part_id( ...
[ "Construct a table reference from table ID string.\n\n Args:\n table_id (str):\n A table ID in standard SQL format. If ``default_project``\n is not specified, this must included a project ID, dataset\n ID, and table ID, each separated by ``.``.\n ...
Please provide a description of the function:def from_api_repr(cls, resource): from google.cloud.bigquery.dataset import DatasetReference project = resource["projectId"] dataset_id = resource["datasetId"] table_id = resource["tableId"] return cls(DatasetReference(projec...
[ "Factory: construct a table reference given its API representation\n\n Args:\n resource (Dict[str, object]):\n Table reference representation returned from the API\n\n Returns:\n google.cloud.bigquery.table.TableReference:\n Table reference parsed f...
Please provide a description of the function:def to_bqstorage(self): if bigquery_storage_v1beta1 is None: raise ValueError(_NO_BQSTORAGE_ERROR) table_ref = bigquery_storage_v1beta1.types.TableReference() table_ref.project_id = self._project table_ref.dataset_id = se...
[ "Construct a BigQuery Storage API representation of this table.\n\n Install the ``google-cloud-bigquery-storage`` package to use this\n feature.\n\n If the ``table_id`` contains a partition identifier (e.g.\n ``my_table$201812``) or a snapshot identifier (e.g.\n ``mytable@12345678...
Please provide a description of the function:def encryption_configuration(self): prop = self._properties.get("encryptionConfiguration") if prop is not None: prop = EncryptionConfiguration.from_api_repr(prop) return prop
[ "google.cloud.bigquery.table.EncryptionConfiguration: Custom\n encryption configuration for the table.\n\n Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`\n if using default encryption.\n\n See `protecting data with Cloud KMS keys\n <https://cloud.google.com...
Please provide a description of the function:def time_partitioning(self): prop = self._properties.get("timePartitioning") if prop is not None: return TimePartitioning.from_api_repr(prop)
[ "google.cloud.bigquery.table.TimePartitioning: Configures time-based\n partitioning for a table.\n\n Raises:\n ValueError:\n If the value is not :class:`TimePartitioning` or :data:`None`.\n " ]
Please provide a description of the function:def partition_expiration(self): warnings.warn( "This method will be deprecated in future versions. Please use " "Table.time_partitioning.expiration_ms instead.", PendingDeprecationWarning, stacklevel=2, ...
[ "Union[int, None]: Expiration time in milliseconds for a partition.\n\n If :attr:`partition_expiration` is set and :attr:`type_` is\n not set, :attr:`type_` will default to\n :attr:`~google.cloud.bigquery.table.TimePartitioningType.DAY`.\n " ]
Please provide a description of the function:def clustering_fields(self): prop = self._properties.get("clustering") if prop is not None: return list(prop.get("fields", ()))
[ "Union[List[str], None]: Fields defining clustering for the table\n\n (Defaults to :data:`None`).\n\n Clustering fields are immutable after table creation.\n\n .. note::\n\n As of 2018-06-29, clustering fields cannot be set on a table\n which does not also have time partioni...
Please provide a description of the function:def clustering_fields(self, value): if value is not None: prop = self._properties.setdefault("clustering", {}) prop["fields"] = value else: if "clustering" in self._properties: del self._properties[...
[ "Union[List[str], None]: Fields defining clustering for the table\n\n (Defaults to :data:`None`).\n " ]
Please provide a description of the function:def expires(self): expiration_time = self._properties.get("expirationTime") if expiration_time is not None: # expiration_time will be in milliseconds. return google.cloud._helpers._datetime_from_microseconds( 1...
[ "Union[datetime.datetime, None]: Datetime at which the table will be\n deleted.\n\n Raises:\n ValueError: For invalid value types.\n " ]
Please provide a description of the function:def external_data_configuration(self): prop = self._properties.get("externalDataConfiguration") if prop is not None: prop = ExternalConfig.from_api_repr(prop) return prop
[ "Union[google.cloud.bigquery.ExternalConfig, None]: Configuration for\n an external data source (defaults to :data:`None`).\n\n Raises:\n ValueError: For invalid value types.\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): from google.cloud.bigquery import dataset if ( "tableReference" not in resource or "tableId" not in resource["tableReference"] ): raise KeyError( "Resource...
[ "Factory: construct a table given its API representation\n\n Args:\n resource (Dict[str, object]):\n Table resource representation from the API\n\n Returns:\n google.cloud.bigquery.table.Table: Table parsed from ``resource``.\n\n Raises:\n KeyErro...
Please provide a description of the function:def partitioning_type(self): warnings.warn( "This method will be deprecated in future versions. Please use " "TableListItem.time_partitioning.type_ instead.", PendingDeprecationWarning, stacklevel=2, ) ...
[ "Union[str, None]: Time partitioning of the table if it is\n partitioned (Defaults to :data:`None`).\n " ]
Please provide a description of the function:def items(self): for key, index in six.iteritems(self._xxx_field_to_index): yield (key, copy.deepcopy(self._xxx_values[index]))
[ "Return items as ``(key, value)`` pairs.\n\n Returns:\n Iterable[Tuple[str, object]]:\n The ``(key, value)`` pairs representing this row.\n\n Examples:\n\n >>> list(Row(('a', 'b'), {'x': 0, 'y': 1}).items())\n [('x', 'a'), ('y', 'b')]\n " ]
Please provide a description of the function:def get(self, key, default=None): index = self._xxx_field_to_index.get(key) if index is None: return default return self._xxx_values[index]
[ "Return a value for key, with a default value if it does not exist.\n\n Args:\n key (str): The key of the column to access\n default (object):\n The default value to use if the key does not exist. (Defaults\n to :data:`None`.)\n\n Returns:\n ...
Please provide a description of the function:def _get_next_page_response(self): params = self._get_query_params() if self._page_size is not None: params["maxResults"] = self._page_size return self.api_request( method=self._HTTP_METHOD, path=self.path, query_param...
[ "Requests the next page from the path provided.\n\n Returns:\n Dict[str, object]:\n The parsed JSON response of the next page's contents.\n " ]
Please provide a description of the function:def _to_dataframe_tabledata_list(self, dtypes, progress_bar=None): column_names = [field.name for field in self.schema] frames = [] for page in iter(self.pages): current_frame = self._to_dataframe_dtypes(page, column_names, dtype...
[ "Use (slower, but free) tabledata.list to construct a DataFrame." ]
Please provide a description of the function:def _to_dataframe_bqstorage(self, bqstorage_client, dtypes, progress_bar=None): if bigquery_storage_v1beta1 is None: raise ValueError(_NO_BQSTORAGE_ERROR) if "$" in self._table.table_id: raise ValueError( "Rea...
[ "Use (faster, but billable) BQ Storage API to construct DataFrame." ]
Please provide a description of the function:def _get_progress_bar(self, progress_bar_type): if tqdm is None: if progress_bar_type is not None: warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3) return None description = "Downloading" unit ...
[ "Construct a tqdm progress bar object, if tqdm is installed." ]
Please provide a description of the function:def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None): if pandas is None: raise ValueError(_NO_PANDAS_ERROR) return pandas.DataFrame()
[ "Create an empty dataframe.\n\n Args:\n bqstorage_client (Any):\n Ignored. Added for compatibility with RowIterator.\n dtypes (Any):\n Ignored. Added for compatibility with RowIterator.\n progress_bar_type (Any):\n Ignored. Added f...
Please provide a description of the function:def from_api_repr(cls, api_repr): instance = cls(api_repr["type"]) instance._properties = api_repr return instance
[ "Return a :class:`TimePartitioning` object deserialized from a dict.\n\n This method creates a new ``TimePartitioning`` instance that points to\n the ``api_repr`` parameter as its internal properties dict. This means\n that when a ``TimePartitioning`` instance is stored as a property of\n ...
Please provide a description of the function:def _generate_faux_mime_message(parser, response): # We coerce to bytes to get consistent concat across # Py2 and Py3. Percent formatting is insufficient since # it includes the b in Py3. content_type = _helpers._to_bytes(response.headers.get("content-ty...
[ "Convert response, content -> (multipart) email.message.\n\n Helper for _unpack_batch_response.\n " ]
Please provide a description of the function:def _unpack_batch_response(response): parser = Parser() message = _generate_faux_mime_message(parser, response) if not isinstance(message._payload, list): raise ValueError("Bad response: not multi-part") for subrequest in message._payload: ...
[ "Convert requests.Response -> [(headers, payload)].\n\n Creates a generator of tuples of emulating the responses to\n :meth:`requests.Session.request`.\n\n :type response: :class:`requests.Response`\n :param response: HTTP response / headers from a request.\n " ]
Please provide a description of the function:def _do_request(self, method, url, headers, data, target_object): if len(self._requests) >= self._MAX_BATCH_SIZE: raise ValueError( "Too many deferred requests (max %d)" % self._MAX_BATCH_SIZE ) self._requests....
[ "Override Connection: defer actual HTTP request.\n\n Only allow up to ``_MAX_BATCH_SIZE`` requests to be deferred.\n\n :type method: str\n :param method: The HTTP method to use in the request.\n\n :type url: str\n :param url: The URL to send the request to.\n\n :type heade...
Please provide a description of the function:def _prepare_batch_request(self): if len(self._requests) == 0: raise ValueError("No deferred requests") multi = MIMEMultipart() for method, uri, headers, body in self._requests: subrequest = MIMEApplicationHTTP(metho...
[ "Prepares headers and body for a batch request.\n\n :rtype: tuple (dict, str)\n :returns: The pair of headers and body of the batch request to be sent.\n :raises: :class:`ValueError` if no requests have been deferred.\n " ]
Please provide a description of the function:def _finish_futures(self, responses): # If a bad status occurs, we track it, but don't raise an exception # until all futures have been populated. exception_args = None if len(self._target_objects) != len(responses): rais...
[ "Apply all the batch responses to the futures created.\n\n :type responses: list of (headers, payload) tuples.\n :param responses: List of headers and payloads from each response in\n the batch.\n\n :raises: :class:`ValueError` if no requests have been deferred.\n ...
Please provide a description of the function:def finish(self): headers, body = self._prepare_batch_request() url = "%s/batch/storage/v1" % self.API_BASE_URL # Use the private ``_base_connection`` rather than the property # ``_connection``, since the property may be this ...
[ "Submit a single `multipart/mixed` request with deferred requests.\n\n :rtype: list of tuples\n :returns: one ``(headers, payload)`` tuple per deferred request.\n " ]
Please provide a description of the function:def _restart_on_unavailable(restart): resume_token = b"" item_buffer = [] iterator = restart() while True: try: for item in iterator: item_buffer.append(item) if item.resume_token: r...
[ "Restart iteration after :exc:`.ServiceUnavailable`.\n\n :type restart: callable\n :param restart: curried function returning iterator\n " ]
Please provide a description of the function:def read(self, table, columns, keyset, index="", limit=0, partition=None): if self._read_request_count > 0: if not self._multi_use: raise ValueError("Cannot re-use single-use snapshot.") if self._transaction_id is None...
[ "Perform a ``StreamingRead`` API request for rows in a table.\n\n :type table: str\n :param table: name of the table from which to fetch data\n\n :type columns: list of str\n :param columns: names of columns to be retrieved\n\n :type keyset: :class:`~google.cloud.spanner_v1.keyset...
Please provide a description of the function:def execute_sql( self, sql, params=None, param_types=None, query_mode=None, partition=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ): ...
[ "Perform an ``ExecuteStreamingSql`` API request.\n\n :type sql: str\n :param sql: SQL query statement\n\n :type params: dict, {str -> column value}\n :param params: values for parameter replacement. Keys must match\n the names used in ``sql``.\n\n :type para...
Please provide a description of the function:def partition_read( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): if not self._multi_use: raise ValueError("Cannot use single-use snapshot.")...
[ "Perform a ``ParitionRead`` API request for rows in a table.\n\n :type table: str\n :param table: name of the table from which to fetch data\n\n :type columns: list of str\n :param columns: names of columns to be retrieved\n\n :type keyset: :class:`~google.cloud.spanner_v1.keyset....
Please provide a description of the function:def partition_query( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ): if not self._multi_use: raise ValueError("Cannot use single-use snapshot.") ...
[ "Perform a ``ParitionQuery`` API request.\n\n :type sql: str\n :param sql: SQL query statement\n\n :type params: dict, {str -> column value}\n :param params: values for parameter replacement. Keys must match\n the names used in ``sql``.\n\n :type param_types...
Please provide a description of the function:def _make_txn_selector(self): if self._transaction_id is not None: return TransactionSelector(id=self._transaction_id) if self._read_timestamp: key = "read_timestamp" value = _datetime_to_pb_timestamp(self._read_t...
[ "Helper for :meth:`read`." ]
Please provide a description of the function:def begin(self): if not self._multi_use: raise ValueError("Cannot call 'begin' on single-use snapshots") if self._transaction_id is not None: raise ValueError("Read-only transaction already begun") if self._read_requ...
[ "Begin a read-only transaction on the database.\n\n :rtype: bytes\n :returns: the ID for the newly-begun transaction.\n\n :raises ValueError:\n if the transaction is already begun, committed, or rolled back.\n " ]
Please provide a description of the function:def to_user_agent(self): # Note: the order here is important as the internal metrics system # expects these items to be in specific locations. ua = "" if self.user_agent is not None: ua += "{user_agent} " ua += ...
[ "Returns the user-agent string for this client info." ]
Please provide a description of the function:def read_rows( self, read_position, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): gapic_client = super(BigQueryStorageClient, self) stream...
[ "\n Reads rows from the table in the format prescribed by the read\n session. Each response contains one or more table rows, up to a\n maximum of 10 MiB per response; read requests which attempt to read\n individual rows larger than this will fail.\n\n Each request also returns a ...
Please provide a description of the function:def make_trace_api(client): generated = trace_service_client.TraceServiceClient( credentials=client._credentials, client_info=_CLIENT_INFO ) return _TraceAPI(generated, client)
[ "\n Create an instance of the gapic Trace API.\n\n Args:\n client (~google.cloud.trace.client.Client): The client that holds\n configuration details.\n\n Returns:\n A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the\n proper configurations.\n " ]
Please provide a description of the function:def patch_traces(self, project_id, traces): traces_pb = _traces_mapping_to_pb(traces) self._gapic_api.patch_traces(project_id, traces_pb)
[ "\n Sends new traces to Stackdriver Trace or updates existing traces.\n\n Args:\n project_id (Optional[str]): ID of the Cloud project where the trace\n data is stored.\n traces (dict): Required. The traces to be patched in the API call.\n " ]
Please provide a description of the function:def get_trace(self, project_id, trace_id): trace_pb = self._gapic_api.get_trace(project_id, trace_id) trace_mapping = _parse_trace_pb(trace_pb) return trace_mapping
[ "\n Gets a single trace by its ID.\n\n Args:\n trace_id (str): ID of the trace to return.\n project_id (str): Required. ID of the Cloud project where the trace\n data is stored.\n\n Returns:\n A Trace dict.\n " ]
Please provide a description of the function:def list_traces( self, project_id, view=None, page_size=None, start_time=None, end_time=None, filter_=None, order_by=None, page_token=None, ): page_iter = self._gapic_api.list_traces...
[ "\n Returns of a list of traces that match the filter conditions.\n\n Args:\n project_id (Optional[str]): ID of the Cloud project where the trace\n data is stored.\n\n view (Optional[~google.cloud.trace_v1.gapic.enums.\n ListTracesRequest.ViewType]):...
Please provide a description of the function:def _item_to_bucket(iterator, item): name = item.get("name") bucket = Bucket(iterator.client, name) bucket._set_properties(item) return bucket
[ "Convert a JSON bucket to the native object.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The iterator that has retrieved the item.\n\n :type item: dict\n :param item: An item to be converted to a bucket.\n\n :rtype: :class:`.Bucket`\n :returns: The next ...
Please provide a description of the function:def create_anonymous_client(cls): client = cls(project="<none>", credentials=AnonymousCredentials()) client.project = None return client
[ "Factory: return client with anonymous credentials.\n\n .. note::\n\n Such a client has only limited access to \"public\" buckets:\n listing their contents and downloading their blobs.\n\n :rtype: :class:`google.cloud.storage.client.Client`\n :returns: Instance w/ anonymous ...
Please provide a description of the function:def get_service_account_email(self, project=None): if project is None: project = self.project path = "/projects/%s/serviceAccount" % (project,) api_response = self._base_connection.api_request(method="GET", path=path) retu...
[ "Get the email address of the project's GCS service account\n\n :type project: str\n :param project:\n (Optional) Project ID to use for retreiving GCS service account\n email address. Defaults to the client's project.\n\n :rtype: str\n :returns: service account ema...
Please provide a description of the function:def bucket(self, bucket_name, user_project=None): return Bucket(client=self, name=bucket_name, user_project=user_project)
[ "Factory constructor for bucket object.\n\n .. note::\n This will not make an HTTP request; it simply instantiates\n a bucket object owned by this client.\n\n :type bucket_name: str\n :param bucket_name: The name of the bucket to be instantiated.\n\n :type user_project:...
Please provide a description of the function:def get_bucket(self, bucket_name): bucket = Bucket(self, name=bucket_name) bucket.reload(client=self) return bucket
[ "Get a bucket by name.\n\n If the bucket isn't found, this will raise a\n :class:`google.cloud.exceptions.NotFound`.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START get_bucket]\n :end-before: [END get_bucket]\n\n This implements \"...
Please provide a description of the function:def create_bucket(self, bucket_name, requester_pays=None, project=None): bucket = Bucket(self, name=bucket_name) if requester_pays is not None: bucket.requester_pays = requester_pays bucket.create(client=self, project=project) ...
[ "Create a new bucket.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START create_bucket]\n :end-before: [END create_bucket]\n\n This implements \"storage.buckets.insert\".\n\n If the bucket already exists, will raise\n :class:`google.c...
Please provide a description of the function:def list_buckets( self, max_results=None, page_token=None, prefix=None, projection="noAcl", fields=None, project=None, ): if project is None: project = self.project if project i...
[ "Get all buckets in the project associated to the client.\n\n This will not populate the list of blobs available in each\n bucket.\n\n .. literalinclude:: snippets.py\n :start-after: [START list_buckets]\n :end-before: [END list_buckets]\n\n This implements \"storag...
Please provide a description of the function:def _make_job_id(job_id, prefix=None): if job_id is not None: return job_id elif prefix is not None: return str(prefix) + str(uuid.uuid4()) else: return str(uuid.uuid4())
[ "Construct an ID for a new job.\n\n :type job_id: str or ``NoneType``\n :param job_id: the user-provided job ID\n\n :type prefix: str or ``NoneType``\n :param prefix: (Optional) the user-provided prefix for a job ID\n\n :rtype: str\n :returns: A job ID\n " ]
Please provide a description of the function:def _check_mode(stream): mode = getattr(stream, "mode", None) if isinstance(stream, gzip.GzipFile): if mode != gzip.READ: raise ValueError( "Cannot upload gzip files opened in write mode: use " "gzip.GzipFile...
[ "Check that a stream was opened in read-binary mode.\n\n :type stream: IO[bytes]\n :param stream: A bytes IO object open for reading.\n\n :raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute\n and is not among ``rb``, ``r+b`` or ``rb+``.\n " ]
Please provide a description of the function:def get_service_account_email(self, project=None): if project is None: project = self.project path = "/projects/%s/serviceAccount" % (project,) api_response = self._connection.api_request(method="GET", path=path) return ap...
[ "Get the email address of the project's BigQuery service account\n\n Note:\n This is the service account that BigQuery uses to manage tables\n encrypted by a key in KMS.\n\n Args:\n project (str, optional):\n Project ID to use for retreiving service acco...
Please provide a description of the function:def list_projects(self, max_results=None, page_token=None, retry=DEFAULT_RETRY): return page_iterator.HTTPIterator( client=self, api_request=functools.partial(self._call_api, retry), path="/projects", item_to_v...
[ "List projects for the project associated with this client.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list\n\n :type max_results: int\n :param max_results: (Optional) maximum number of projects to return,\n If not passed, defau...
Please provide a description of the function:def list_datasets( self, project=None, include_all=False, filter=None, max_results=None, page_token=None, retry=DEFAULT_RETRY, ): extra_params = {} if project is None: project = ...
[ "List datasets for the project associated with this client.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list\n\n Args:\n project (str):\n Optional. Project ID to use for retreiving datasets. Defaults\n to the client's proj...
Please provide a description of the function:def dataset(self, dataset_id, project=None): if project is None: project = self.project return DatasetReference(project, dataset_id)
[ "Construct a reference to a dataset.\n\n :type dataset_id: str\n :param dataset_id: ID of the dataset.\n\n :type project: str\n :param project: (Optional) project ID for the dataset (defaults to\n the project of the client).\n\n :rtype: :class:`google.cloud....
Please provide a description of the function:def create_dataset(self, dataset, exists_ok=False, retry=DEFAULT_RETRY): if isinstance(dataset, str): dataset = DatasetReference.from_string( dataset, default_project=self.project ) if isinstance(dataset, Datas...
[ "API call: create the dataset via a POST request.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert\n\n Args:\n dataset (Union[ \\\n :class:`~google.cloud.bigquery.dataset.Dataset`, \\\n :class:`~google.cloud.bigquery.datas...
Please provide a description of the function:def create_table(self, table, exists_ok=False, retry=DEFAULT_RETRY): table = _table_arg_to_table(table, default_project=self.project) path = "/projects/%s/datasets/%s/tables" % (table.project, table.dataset_id) data = table.to_api_repr() ...
[ "API call: create a table via a PUT request\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert\n\n Args:\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.table.TableRefer...
Please provide a description of the function:def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY): if isinstance(dataset_ref, str): dataset_ref = DatasetReference.from_string( dataset_ref, default_project=self.project ) api_response = self._call_api(r...
[ "Fetch the dataset referenced by ``dataset_ref``\n\n Args:\n dataset_ref (Union[ \\\n :class:`~google.cloud.bigquery.dataset.DatasetReference`, \\\n str, \\\n ]):\n A reference to the dataset to fetch from the BigQuery API.\n I...
Please provide a description of the function:def get_model(self, model_ref, retry=DEFAULT_RETRY): if isinstance(model_ref, str): model_ref = ModelReference.from_string( model_ref, default_project=self.project ) api_response = self._call_api(retry, method...
[ "[Beta] Fetch the model referenced by ``model_ref``.\n\n Args:\n model_ref (Union[ \\\n :class:`~google.cloud.bigquery.model.ModelReference`, \\\n str, \\\n ]):\n A reference to the model to fetch from the BigQuery API.\n If a...
Please provide a description of the function:def get_table(self, table, retry=DEFAULT_RETRY): table_ref = _table_arg_to_table_ref(table, default_project=self.project) api_response = self._call_api(retry, method="GET", path=table_ref.path) return Table.from_api_repr(api_response)
[ "Fetch the table referenced by ``table``.\n\n Args:\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.table.TableReference`, \\\n str, \\\n ]):\n A reference to the table to f...
Please provide a description of the function:def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY): partial = dataset._build_resource(fields) if dataset.etag is not None: headers = {"If-Match": dataset.etag} else: headers = None api_response = se...
[ "Change some fields of a dataset.\n\n Use ``fields`` to specify which fields to update. At least one field\n must be provided. If a field is listed in ``fields`` and is ``None`` in\n ``dataset``, it will be deleted.\n\n If ``dataset.etag`` is not ``None``, the update will only\n s...
Please provide a description of the function:def update_model(self, model, fields, retry=DEFAULT_RETRY): partial = model._build_resource(fields) if model.etag: headers = {"If-Match": model.etag} else: headers = None api_response = self._call_api( ...
[ "[Beta] Change some fields of a model.\n\n Use ``fields`` to specify which fields to update. At least one field\n must be provided. If a field is listed in ``fields`` and is ``None``\n in ``model``, it will be deleted.\n\n If ``model.etag`` is not ``None``, the update will only succeed i...
Please provide a description of the function:def update_table(self, table, fields, retry=DEFAULT_RETRY): partial = table._build_resource(fields) if table.etag is not None: headers = {"If-Match": table.etag} else: headers = None api_response = self._call_a...
[ "Change some fields of a table.\n\n Use ``fields`` to specify which fields to update. At least one field\n must be provided. If a field is listed in ``fields`` and is ``None``\n in ``table``, it will be deleted.\n\n If ``table.etag`` is not ``None``, the update will only succeed if\n ...
Please provide a description of the function:def list_models( self, dataset, max_results=None, page_token=None, retry=DEFAULT_RETRY ): if isinstance(dataset, str): dataset = DatasetReference.from_string( dataset, default_project=self.project ) ...
[ "[Beta] List models in the dataset.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list\n\n Args:\n dataset (Union[ \\\n :class:`~google.cloud.bigquery.dataset.Dataset`, \\\n :class:`~google.cloud.bigquery.dataset.DatasetRefere...
Please provide a description of the function:def delete_dataset( self, dataset, delete_contents=False, retry=DEFAULT_RETRY, not_found_ok=False ): if isinstance(dataset, str): dataset = DatasetReference.from_string( dataset, default_project=self.project ...
[ "Delete a dataset.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete\n\n Args\n dataset (Union[ \\\n :class:`~google.cloud.bigquery.dataset.Dataset`, \\\n :class:`~google.cloud.bigquery.dataset.DatasetReference`, \\\n ...
Please provide a description of the function:def delete_model(self, model, retry=DEFAULT_RETRY, not_found_ok=False): if isinstance(model, str): model = ModelReference.from_string(model, default_project=self.project) if not isinstance(model, (Model, ModelReference)): rai...
[ "[Beta] Delete a model\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete\n\n Args:\n model (Union[ \\\n :class:`~google.cloud.bigquery.model.Model`, \\\n :class:`~google.cloud.bigquery.model.ModelReference`, \\\n ...
Please provide a description of the function:def delete_table(self, table, retry=DEFAULT_RETRY, not_found_ok=False): table = _table_arg_to_table_ref(table, default_project=self.project) if not isinstance(table, TableReference): raise TypeError("Unable to get TableReference for table...
[ "Delete a table\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete\n\n Args:\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.table.TableReference`, \\\n st...
Please provide a description of the function:def _get_query_results( self, job_id, retry, project=None, timeout_ms=None, location=None ): extra_params = {"maxResults": 0} if project is None: project = self.project if timeout_ms is not None: extra_p...
[ "Get the query results object for a query job.\n\n Arguments:\n job_id (str): Name of the query job.\n retry (google.api_core.retry.Retry):\n (Optional) How to retry the RPC.\n project (str):\n (Optional) project ID for the query job (defaults to...
Please provide a description of the function:def job_from_resource(self, resource): config = resource.get("configuration", {}) if "load" in config: return job.LoadJob.from_api_repr(resource, self) elif "copy" in config: return job.CopyJob.from_api_repr(resource, ...
[ "Detect correct job type from resource and instantiate.\n\n :type resource: dict\n :param resource: one job resource from API response\n\n :rtype: One of:\n :class:`google.cloud.bigquery.job.LoadJob`,\n :class:`google.cloud.bigquery.job.CopyJob`,\n :...
Please provide a description of the function:def cancel_job(self, job_id, project=None, location=None, retry=DEFAULT_RETRY): extra_params = {"projection": "full"} if project is None: project = self.project if location is None: location = self.location ...
[ "Attempt to cancel a job from a job ID.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel\n\n Arguments:\n job_id (str): Unique job identifier.\n\n Keyword Arguments:\n project (str):\n (Optional) ID of the project which o...
Please provide a description of the function:def list_jobs( self, project=None, max_results=None, page_token=None, all_users=None, state_filter=None, retry=DEFAULT_RETRY, min_creation_time=None, max_creation_time=None, ): extra...
[ "List jobs for the project associated with this client.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/list\n\n Args:\n project (str, optional):\n Project ID to use for retreiving datasets. Defaults\n to the client's project.\n ...
Please provide a description of the function:def load_table_from_uri( self, source_uris, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ): job_id = _make_job_id(...
[ "Starts a job for loading data into a table from CloudStorage.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load\n\n Arguments:\n source_uris (Union[str, Sequence[str]]):\n URIs of data files to be loaded; in format\n ...
Please provide a description of the function:def load_table_from_file( self, file_obj, destination, rewind=False, size=None, num_retries=_DEFAULT_NUM_RETRIES, job_id=None, job_id_prefix=None, location=None, project=None, job_config=...
[ "Upload the contents of this table from a file-like object.\n\n Similar to :meth:`load_table_from_uri`, this method creates, starts and\n returns a :class:`~google.cloud.bigquery.job.LoadJob`.\n\n Arguments:\n file_obj (file): A file handle opened in binary mode for reading.\n ...
Please provide a description of the function:def load_table_from_dataframe( self, dataframe, destination, num_retries=_DEFAULT_NUM_RETRIES, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, ): job_i...
[ "Upload the contents of a table from a pandas DataFrame.\n\n Similar to :meth:`load_table_from_uri`, this method creates, starts and\n returns a :class:`~google.cloud.bigquery.job.LoadJob`.\n\n Arguments:\n dataframe (pandas.DataFrame):\n A :class:`~pandas.DataFrame` c...
Please provide a description of the function:def _do_resumable_upload(self, stream, metadata, num_retries): upload, transport = self._initiate_resumable_upload( stream, metadata, num_retries ) while not upload.finished: response = upload.transmit_next_chunk(tran...
[ "Perform a resumable upload.\n\n :type stream: IO[bytes]\n :param stream: A bytes IO object open for reading.\n\n :type metadata: dict\n :param metadata: The metadata associated with the upload.\n\n :type num_retries: int\n :param num_retries: Number of upload retries. (Dep...
Please provide a description of the function:def _initiate_resumable_upload(self, stream, metadata, num_retries): chunk_size = _DEFAULT_CHUNKSIZE transport = self._http headers = _get_upload_headers(self._connection.USER_AGENT) upload_url = _RESUMABLE_URL_TEMPLATE.format(project...
[ "Initiate a resumable upload.\n\n :type stream: IO[bytes]\n :param stream: A bytes IO object open for reading.\n\n :type metadata: dict\n :param metadata: The metadata associated with the upload.\n\n :type num_retries: int\n :param num_retries: Number of upload retries. (De...
Please provide a description of the function:def _do_multipart_upload(self, stream, metadata, size, num_retries): data = stream.read(size) if len(data) < size: msg = _READ_LESS_THAN_SIZE.format(size, len(data)) raise ValueError(msg) headers = _get_upload_headers...
[ "Perform a multipart upload.\n\n :type stream: IO[bytes]\n :param stream: A bytes IO object open for reading.\n\n :type metadata: dict\n :param metadata: The metadata associated with the upload.\n\n :type size: int\n :param size: The number of bytes to be uploaded (which wi...
Please provide a description of the function:def copy_table( self, sources, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ): job_id = _make_job_id(job_id, job_i...
[ "Copy one or more tables to another table.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy\n\n Arguments:\n sources (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.t...
Please provide a description of the function:def extract_table( self, source, destination_uris, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ): job_id = _make_job_id(job_id...
[ "Start a job to extract a table into Cloud Storage files.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract\n\n Arguments:\n source (Union[ \\\n :class:`google.cloud.bigquery.table.Table`, \\\n :class:`google.c...
Please provide a description of the function:def query( self, query, job_config=None, job_id=None, job_id_prefix=None, location=None, project=None, retry=DEFAULT_RETRY, ): job_id = _make_job_id(job_id, job_id_prefix) if projec...
[ "Run a SQL query.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query\n\n Arguments:\n query (str):\n SQL query to be executed. Defaults to the standard SQL\n dialect. Use the ``job_config`` parameter to change dia...
Please provide a description of the function:def insert_rows(self, table, rows, selected_fields=None, **kwargs): table = _table_arg_to_table(table, default_project=self.project) if not isinstance(table, Table): raise TypeError(_NEED_TABLE_ARGUMENT) schema = table.schema ...
[ "Insert rows into a table via the streaming API.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll\n\n Args:\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.table....
Please provide a description of the function:def insert_rows_json( self, table, json_rows, row_ids=None, skip_invalid_rows=None, ignore_unknown_values=None, template_suffix=None, retry=DEFAULT_RETRY, ): # Convert table to just a refere...
[ "Insert rows into a table without applying local type conversions.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll\n\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table` \\\n :class:`~google.cloud.bigquery.table.TableRefer...
Please provide a description of the function:def list_partitions(self, table, retry=DEFAULT_RETRY): table = _table_arg_to_table_ref(table, default_project=self.project) meta_table = self.get_table( TableReference( self.dataset(table.dataset_id, project=table.project)...
[ "List the partitions in a table.\n\n Arguments:\n table (Union[ \\\n :class:`~google.cloud.bigquery.table.Table`, \\\n :class:`~google.cloud.bigquery.table.TableReference`, \\\n str, \\\n ]):\n The table or reference from which...
Please provide a description of the function:def list_rows( self, table, selected_fields=None, max_results=None, page_token=None, start_index=None, page_size=None, retry=DEFAULT_RETRY, ): table = _table_arg_to_table(table, default_proj...
[ "List the rows of the table.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/list\n\n .. note::\n\n This method assumes that the provided schema is up-to-date with the\n schema as defined on the back-end: if the two schemas are not\n id...
Please provide a description of the function:def _schema_from_json_file_object(self, file_obj): json_data = json.load(file_obj) return [SchemaField.from_api_repr(field) for field in json_data]
[ "Helper function for schema_from_json that takes a\n file object that describes a table schema.\n\n Returns:\n List of schema field objects.\n " ]
Please provide a description of the function:def _schema_to_json_file_object(self, schema_list, file_obj): json.dump(schema_list, file_obj, indent=2, sort_keys=True)
[ "Helper function for schema_to_json that takes a schema list and file\n object and writes the schema list to the file object with json.dump\n " ]
Please provide a description of the function:def schema_from_json(self, file_or_path): if isinstance(file_or_path, io.IOBase): return self._schema_from_json_file_object(file_or_path) with open(file_or_path) as file_obj: return self._schema_from_json_file_object(file_obj...
[ "Takes a file object or file path that contains json that describes\n a table schema.\n\n Returns:\n List of schema field objects.\n " ]
Please provide a description of the function:def schema_to_json(self, schema_list, destination): json_schema_list = [f.to_api_repr() for f in schema_list] if isinstance(destination, io.IOBase): return self._schema_to_json_file_object(json_schema_list, destination) with ope...
[ "Takes a list of schema field objects.\n\n Serializes the list of schema field objects as json to a file.\n\n Destination is a file path or a file object.\n " ]
Please provide a description of the function:def _update_from_pb(self, instance_pb): if not instance_pb.display_name: # Simple field (string) raise ValueError("Instance protobuf does not contain display_name") self.display_name = instance_pb.display_name self.configuration_...
[ "Refresh self from the server-provided protobuf.\n\n Helper for :meth:`from_pb` and :meth:`reload`.\n " ]
Please provide a description of the function:def from_pb(cls, instance_pb, client): match = _INSTANCE_NAME_RE.match(instance_pb.name) if match is None: raise ValueError( "Instance protobuf name was not in the " "expected format.", instance_pb.name, ...
[ "Creates an instance from a protobuf.\n\n :type instance_pb:\n :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`\n :param instance_pb: A instance protobuf object.\n\n :type client: :class:`~google.cloud.spanner_v1.client.Client`\n :param client: The client that ow...
Please provide a description of the function:def copy(self): new_client = self._client.copy() return self.__class__( self.instance_id, new_client, self.configuration_name, node_count=self.node_count, display_name=self.display_name, ...
[ "Make a copy of this instance.\n\n Copies the local data stored as simple types and copies the client\n attached to this instance.\n\n :rtype: :class:`~google.cloud.spanner_v1.instance.Instance`\n :returns: A copy of the current instance.\n " ]
Please provide a description of the function:def create(self): api = self._client.instance_admin_api instance_pb = admin_v1_pb2.Instance( name=self.name, config=self.configuration_name, display_name=self.display_name, node_count=self.node_count, ...
[ "Create this instance.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance\n\n .. note::\n\n Uses the ``project`` and ``instance_id`` on the current\n :class:`Instance` in add...
Please provide a description of the function:def exists(self): api = self._client.instance_admin_api metadata = _metadata_with_prefix(self.name) try: api.get_instance(self.name, metadata=metadata) except NotFound: return False return True
[ "Test whether this instance exists.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig\n\n :rtype: bool\n :returns: True if the instance exists, else false\n " ]
Please provide a description of the function:def reload(self): api = self._client.instance_admin_api metadata = _metadata_with_prefix(self.name) instance_pb = api.get_instance(self.name, metadata=metadata) self._update_from_pb(instance_pb)
[ "Reload the metadata for this instance.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig\n\n :raises NotFound: if the instance does not exist\n " ]
Please provide a description of the function:def update(self): api = self._client.instance_admin_api instance_pb = admin_v1_pb2.Instance( name=self.name, config=self.configuration_name, display_name=self.display_name, node_count=self.node_count, ...
[ "Update this instance.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance\n\n .. note::\n\n Updates the ``display_name`` and ``node_count``. To change those\n values before u...
Please provide a description of the function:def delete(self): api = self._client.instance_admin_api metadata = _metadata_with_prefix(self.name) api.delete_instance(self.name, metadata=metadata)
[ "Mark an instance and all of its databases for permanent deletion.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance\n\n Immediately upon completion of the request:\n\n * Billing will ce...
Please provide a description of the function:def database(self, database_id, ddl_statements=(), pool=None): return Database(database_id, self, ddl_statements=ddl_statements, pool=pool)
[ "Factory to create a database within this instance.\n\n :type database_id: str\n :param database_id: The ID of the instance.\n\n :type ddl_statements: list of string\n :param ddl_statements: (Optional) DDL statements, excluding the\n 'CREATE DATABSE' stateme...
Please provide a description of the function:def list_databases(self, page_size=None, page_token=None): metadata = _metadata_with_prefix(self.name) page_iter = self._client.database_admin_api.list_databases( self.name, page_size=page_size, metadata=metadata ) page_it...
[ "List databases for the instance.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases\n\n :type page_size: int\n :param page_size:\n Optional. The maximum number of databases in ...
Please provide a description of the function:def _item_to_database(self, iterator, database_pb): return Database.from_pb(database_pb, self, pool=BurstyPool())
[ "Convert a database protobuf to the native object.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The iterator that is currently in use.\n\n :type database_pb: :class:`~google.spanner.admin.database.v1.Database`\n :param database_pb: A database re...
Please provide a description of the function:def _blocking_poll(self, timeout=None): if self._result_set: return retry_ = self._retry.with_deadline(timeout) try: retry_(self._done_or_raise)() except exceptions.RetryError: raise concurrent.fu...
[ "Poll and wait for the Future to be resolved.\n\n Args:\n timeout (int):\n How long (in seconds) to wait for the operation to complete.\n If None, wait indefinitely.\n " ]
Please provide a description of the function:def result(self, timeout=None): self._blocking_poll(timeout=timeout) if self._exception is not None: # pylint: disable=raising-bad-type # Pylint doesn't recognize that this is valid in this case. raise self._excep...
[ "Get the result of the operation, blocking if necessary.\n\n Args:\n timeout (int):\n How long (in seconds) to wait for the operation to complete.\n If None, wait indefinitely.\n\n Returns:\n google.protobuf.Message: The Operation's result.\n\n ...
Please provide a description of the function:def add_done_callback(self, fn): if self._result_set: _helpers.safe_invoke_callback(fn, self) return self._done_callbacks.append(fn) if self._polling_thread is None: # The polling thread will exit on its ...
[ "Add a callback to be executed when the operation is complete.\n\n If the operation is not already complete, this will start a helper\n thread to poll for the status of the operation in the background.\n\n Args:\n fn (Callable[Future]): The callback to execute when the operation\n ...