# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for bigquery continuous queries"""
from __future__ import annotations
import functools
import inspect
import json
import warnings
from abc import abstractmethod
from datetime import date, datetime
from typing import Optional, Union
import pandas as pd
from google.cloud import bigquery
import bigframes.exceptions as bfe
import bigframes.session
from bigframes import dataframe
from bigframes.core import nodes
from bigframes.core.logging import log_adapter
def _return_type_wrapper(method, cls):
@functools.wraps(method)
def wrapper(*args, **kwargs):
return_value = method(*args, **kwargs)
if isinstance(return_value, dataframe.DataFrame):
return cls._from_table_df(return_value)
return return_value
return wrapper
def _curate_df_doc(doc: Optional[str]):
if not doc:
return doc
# Remove examples, some are not applicable to StreamingDataFrame
doc = doc[: doc.find("**Examples:**")] + doc[doc.find("Args:") :]
doc = doc.replace("dataframe.DataFrame", "streaming.StreamingDataFrame")
doc = doc.replace(" DataFrame", " StreamingDataFrame")
return doc
class StreamingBase:
_session: bigframes.session.Session
@abstractmethod
def _appends_sql(
self, start_timestamp: Optional[Union[int, float, str, datetime, date]]
) -> str:
pass
def to_bigtable(
self,
*,
instance: str,
table: str,
service_account_email: Optional[str] = None,
app_profile: Optional[str] = None,
truncate: bool = False,
overwrite: bool = False,
auto_create_column_families: bool = False,
bigtable_options: Optional[dict] = None,
job_id: Optional[str] = None,
job_id_prefix: Optional[str] = None,
start_timestamp: Optional[Union[int, float, str, datetime, date]] = None,
end_timestamp: Optional[Union[int, float, str, datetime, date]] = None,
) -> bigquery.QueryJob:
"""
Export the StreamingDataFrame as a continue job and returns a
QueryJob object for some management functionality.
This method requires an existing bigtable preconfigured to
accept the continuous query export statement. For instructions
on export to bigtable, see
https://cloud.google.com/bigquery/docs/export-to-bigtable.
Args:
instance (str):
The name of the bigtable instance to export to.
table (str):
The name of the bigtable table to export to.
service_account_email (str):
Full name of the service account to run the continuous query.
Example: accountname@projectname.gserviceaccounts.com
If not provided, the user account will be used, but this
limits the lifetime of the continuous query.
app_profile (str, default None):
The bigtable app profile to export to. If None, no app
profile will be used.
truncate (bool, default False):
The export truncate option, see
https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#bigtable_export_option
overwrite (bool, default False):
The export overwrite option, see
https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#bigtable_export_option
auto_create_column_families (bool, default False):
The auto_create_column_families option, see
https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#bigtable_export_option
bigtable_options (dict, default None):
The bigtable options dict, which will be converted to JSON
using json.dumps, see
https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#bigtable_export_option
If None, no bigtable_options parameter will be passed.
job_id (str, default None):
If specified, replace the default job id for the query,
see job_id parameter of
https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.client.Client#google_cloud_bigquery_client_Client_query
job_id_prefix (str, default None):
If specified, a job id prefix for the query, see
job_id_prefix parameter of
https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.client.Client#google_cloud_bigquery_client_Client_query
start_timestamp (int, float, str, datetime, date, default None):
The starting timestamp for the query. Possible values are to 7 days in the past. If don't specify a timestamp (None), the query will default to the earliest possible time, 7 days ago. If provide a time-zone-naive timestamp, it will be treated as UTC.
Returns:
google.cloud.bigquery.QueryJob:
See https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJob
The ongoing query job can be managed using this object.
For example, the job can be cancelled or its error status
can be examined.
"""
if not isinstance(
start_timestamp, (int,