
    ^                     .   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlmZm	Z	m
Z
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ej*                  ZdZdZ G d d      Zdej2                  defdZdej2                  defdZ	 	 	 	 	 d=dej2                  deej:                  j<                     dee   dee   dee   dee   fdZ 	 	 	 d>dej2                  deej:                  jB                     dee   dee   dee   dee   fdZ"	 	 	 d>dej2                  dej:                  jF                  d ee   dee   dee   f
d!Z$dej2                  dej:                  jB                  d"ee   d#ee   d$ee   f
d%Z%dej2                  dd&d'e&fd(Z'dej2                  d)ed*efd+Z(	 	 	 	 	 	 	 	 	 d?dej2                  d, e
d-d.ee   fg      dej:                  jB                  d/ee   d0ee   d1ee   d2ee   d3ee	eef      d4ee   d5ee   d6ee   d7ee   fd8Z)	 	 	 	 	 	 	 	 	 	 d@dej2                  ded9ed/ee   d0ee   d1ee   d2ee   d3ee	eef      d4ee   d6ee   d7ee   d5ee   dee   fd:Z*	 dAdej2                  dej:                  jB                  d;e&fd<Z+y)Bz.The BigQuery CLI data transfer client library.    )absolute_import)division)print_functionN)AnyDict
NamedTupleOptional)	discovery)utils)bq_api_utils)bq_error)bq_id_utils)bq_processor_utilsauthorization_codeversion_infoc                       e Zd ZdZ	 	 	 	 	 ddee   dee   dee   dee   dee   f
dZ	 dd	eeee	f      d
eee	f   fdZ
	 dd	eeeef      d
eee	f   fdZdefdZd Zded
eeef   fdZy)TransferScheduleArgsz.Arguments to customize data transfer schedule.Nschedule
start_timeend_timedisable_auto_schedulingevent_driven_schedulec                 J    || _         || _        || _        || _        || _        y N)r   r   r   r   r   )selfr   r   r   r   r   s         +platform/bq/clients/client_data_transfer.py__init__zTransferScheduleArgs.__init__   s)     DM DODM#:D !6D    options_to_copyreturnc                    | j                          i }| j                  r | j                  | j                        |d<   |S | j                  ri |d<   |S i |d<   |rd|v rt	        |d         |d<   | j
                  r| j
                  |d   d<   | j                  r!| j                  | j                        |d   d<   | j                  r!| j                  | j                        |d   d<   |S )aM  Returns a dictionary of schedule options v2.

    Args:
      options_to_copy: Existing options to copy from.

    Returns:
      A dictionary of schedule options v2 expected by the
      bigquery.transfers.create and bigquery.transfers.update API methods.

    Raises:
      bq_error.BigqueryError: If shedule options conflict.
    eventDrivenSchedulemanualScheduletimeBasedScheduler   	startTimeendTime)	_validate_schedule_optionsr   _process_event_driven_scheduler   dictr   r   _time_or_infitityr   r   r   optionss      r   to_schedule_options_v2_payloadz3TransferScheduleArgs.to_schedule_options_v2_payload,   s
    	##%G!!'+'J'J

$
$(g#$* N% 
	%	%"$g" N &(g!"	0OC'+/0(
#$ 
37==#$Z0	484J4JOO5
#$[1 
262H2HMM3
#$Y/ Nr   c                     t        |xs i       }| j                  | j                  | j                        |d<   | j                  | j                  | j                        |d<   | j                  |d<   |S )zReturns a dictionary of schedule options.

    Args:
      options_to_copy: Existing options to be copied.

    Returns:
      A dictionary of schedule options expected by the
      bigquery.transfers.create and bigquery.transfers.update API methods.
    r%   r&   disableAutoScheduling)r)   r   r*   r   r   r+   s      r   to_schedule_options_payloadz0TransferScheduleArgs.to_schedule_options_payloadV   so     ?(b)G"!33DOODgk}} 11$--@gi'+'C'CG#$Nr   time_strc                     |xs dS )zCReturns None to indicate Inifinity, if time_str is an empty string.N )r   r1   s     r   r*   z&TransferScheduleArgs._time_or_infitityo   s    tr   c                     t        | j                  | j                  | j                  g      }| j                  du}t        | j                  ||g      dkD  rt        j                  d      y)zsValidates schedule options.

    Raises:
      bq_error.BigqueryError: If the given schedule options conflict.
    N   zThe provided scheduling options conflict. Please specify one of no_auto_scheduling, time-based schedule or event-driven schedule.)	anyr   r   r   r   sumr   r   BigqueryError)r   is_time_based_scheduleis_event_driven_schedules      r   r'   z/TransferScheduleArgs._validate_schedule_optionss   s~     !	7  $99E(("$
 	
 	

 ""O 
r   c                     	 t        j                  |      }d|vrt        j                  d      |S # t        $ r}t        j                  d      |d}~ww xY w)a  Processes the event_driven_schedule given in JSON format.

    Args:
      event_driven_schedule: The user specified event driven schedule. This
        should be in JSON format given as a string. Ex:
        --event_driven_schedule='{"pubsub_subscription":"subscription"}'.

    Returns:
      parsed_event_driven_schedule: The parsed event driven schedule.

    Raises:
      bq_error.BigqueryError: If there is an error with the given params.
    z9Event driven schedule should be specified in JSON format.Npubsub_subscriptionz<Must specify pubsub_subscription in --event_driven_schedule.)jsonloads	Exceptionr   r8   )r   r   parsed_event_driven_schedulees       r   r(   z3TransferScheduleArgs._process_event_driven_schedule   sk    "%)ZZ0E%F"
 $@@""
H  ('  ""
Es   2 	AAA)NNNFNr   )__name__
__module____qualname____doc__r	   strboolr   r   r   r-   r0   r*   r'   r(   r3   r   r   r   r      s    6 !%"& $05-177 3-7 	7
  (~7 &c]7 9=(%d38n5(CH~(V 9=%d38n5CH~2 ,( ( CH~(r   r   transfer_clienttransfer_idc                     | j                         j                         j                         j                  |      j	                         S Nname)projects	locationstransferConfigsgetexecute)rH   rI   s     r   get_transfer_configrS      s5     y{
sswyr   
identifierc                     | j                         j                         j                         j                         j	                  |      j                         S rK   )rN   rO   rP   runsrQ   rR   )rH   rT   s     r   get_transfer_runrW      s<     y{tv
s
swyr   	referencelocation	page_size
page_tokendata_source_idsc                    d}t        j                  |t         j                  j                  d       |#|t        j
                  kD  rt        j
                  }t	        j                  |||||      }|rt	        j                  |        | j                         j                         j                         j                  di |j                         }|j                  dg       }|d|v rt        |      |k  rt	        j                  |||t        |      z
  |d   |      }|rt	        j                  |        | j                         j                         j                         j                  di |j                         }|j                  |j                  dg              nyd|v rt        |      |k  rt        |      dk  rt!        j"                  d       |j                  d      r||j                  d      fS |fS )	a  Return a list of transfer configurations.

  Args:
    transfer_client: the transfer client to use.
    reference: The ProjectReference to list transfer configurations for.
    location: The location id, e.g. 'us' or 'eu'.
    page_size: The maximum number of transfer configurations to return.
    page_token: Current page token (optional).
    data_source_ids: The dataSourceIds to display transfer configurations for.

  Returns:
    A list of transfer configurations.
  Nlist_transfer_configsmethodrP   nextPageTokenr5   z1There are no transfer configurations to be shown.r3   )r   	typecheckApiClientHelperProjectReferencer   MAX_RESULTSPrepareTransferListRequestApplyParametersrN   rO   rP   listrR   rQ   lenextendlogginginfo)	rH   rX   rY   rZ   r[   r\   resultsrequestresults	            r   r^   r^      s   * '!!22$
 %111$00i999j/' &&w/	  "					 	 
  jj*B/Gv%#g,*B$??G$?#
 

,
,W
5o&&(y{ t  wy  ..OR8
9
' v%#g,*B( 7|allFGzz/"vzz/233
r   run_attemptmax_resultsstatesc                 |   t        j                  |t         j                  j                  d       t	        |      }t        j                  |||||      } | j                         j                         j                         j                         j                  di |j                         }|j                  dg       }|d|v rt        |      |k  r|j                  d      }|t        |      z  }t        j                  |||||      } | j                         j                         j                         j                         j                  di |j                         }|j                  |j                  dg              d|v rt        |      |k  r|j                  d      r||j                  d      fS |fS )a7  Return a list of transfer runs.

  Args:
    transfer_client: the transfer client to use.
    reference: The ProjectReference to list transfer runs for.
    run_attempt: Which runs should be pulled. The default value is 'LATEST',
      which only returns the latest run per day. To return all runs, please
      specify 'RUN_ATTEMPT_UNSPECIFIED'.
    max_results: The maximum number of transfer runs to return (optional).
    page_token: Current page token (optional).
    states: States to filter transfer runs (optional).

  Returns:
    A list of transfer runs.
  list_transfer_runsr_   transferRunsra   r3   )r   rb   rc   TransferConfigReferencerF   r   PrepareTransferRunListRequestrN   rO   rP   rV   rh   rR   rQ   ri   rj   )	rH   rX   rp   rq   r[   rr   rn   responsetransfer_runss	            r   rt   rt     s   . !!99!
 )n)<<k:v'o y{tvt	 	
 wy  ,,~r2-
X
%#m*<{*J<<0jS''k"@@
[+z6g/
"
"
$9;?464	 	
 79  8<<;< X
%#m*<{*J ||O$X\\/:;;
	r   message_typec                 <   t        |      }t        j                  ||||      } | j                         j	                         j                         j                         j                         j                  di |j                         }|j                  dg       }|d|v rt        |      |k  r|d   }|t        |      z  }t        j                  ||||      } | j                         j	                         j                         j                         j                         j                  di |j                         }|j                  |j                  dg              d|v rt        |      |k  r|j                  d      r||j                  d      fS |fS )an  Return a list of transfer run logs.

  Args:
    transfer_client: the transfer client to use.
    reference: The ProjectReference to list transfer run logs for.
    message_type: Message types to return.
    max_results: The maximum number of transfer run logs to return.
    page_token: Current page token (optional).

  Returns:
    A list of transfer run logs.
  )rq   r[   rz   transferMessagesra   r3   )rF   r   PrepareListTransferLogRequestrN   rO   rP   rV   transferLogsrh   rR   rQ   ri   rj   )rH   rX   rz   rq   r[   rn   rx   transfer_logss           r   list_transfer_logsr   A  s   & )n)<<	'o y{tv|~t
  wy  ,,126-
X
%#m*<{*JO,jS''k"@@
!#	g/
"
"
$9;?46<>4
  79  8<<(:B?@% X
%#m*<{*J& \\/"8<<899
	r   r   r   run_timec                 P   t        j                  |t         j                  j                  d       t	        |      }|rd|i}nd||di}| j                         j                         j                         }|j                  ||      j                         }|j                  d      S )ad  Starts manual transfer runs.

  Args:
    transfer_client: the transfer client to use.
    reference: Transfer configuration name for the run.
    start_time: Start time of the range of transfer runs.
    end_time: End time of the range of transfer runs.
    run_time: Specific time for a transfer run.

  Returns:
    The list of started transfer runs.
  start_manual_transfer_runsr_   requestedRunTimerequestedTimeRange)r%   r&   )parentbodyrV   )r   rb   rc   rv   rF   rN   rO   rP   startManualRunsrR   rQ   )	rH   rX   r   r   r   r   r   configs_requestrx   s	            r   r   r   ~  s    & !!99)
 y>&)D 	J8LD $,,.88:JJL/,,F,FNNP(	f	r   z3bq_id_utils.ApiClientHelper.TransferConfigReferencer    c                 @   t        j                  |t         j                  j                  d       	 | j	                         j                         j                         j                  |j                        j                          y# t        j                  $ r Y yw xY w)z$Returns true if the transfer exists.transfer_existsr_   rL   TF)r   rb   rc   rv   rN   rO   rP   rQ   transferConfigNamerR   r   BigqueryNotFoundError)rH   rX   s     r   r   r     s     !!99
((*::<@@)) A gi		'	' s   AB BBproject_referencedata_source_idc                     |dz   |z   }| j                         j                         j                         j                  |      j	                         S )Nz/locations/-/dataSources/rL   )rN   rO   dataSourcesrQ   rR   )rH   r   r   data_source_retrievals       r   _fetch_data_sourcer     sL     55F 
  y{{}
s%s&wyr   id_fallbacksIDS
project_idtarget_datasetdisplay_namerefresh_window_daysparams	auth_infoservice_account_namedestination_kms_keynotification_pubsub_topicschedule_argsc           	         t        j                  |t         j                  j                  d       dt	        j
                  |      j                  z   }t        | |j                        }g }i }|d   |d<   |r||d<   |j                  d       |r|j                  d       ||d	<   |r't        j                  ||      }|j                  d
       |r<t        | ||d         }t        j                  ||||d         }|j                  d       |r4|j                  |j                  d            |d<   |j                  d       |
r|
|d<   |j                  d       |t         |v r|j                  t                |t"        |v r|j                  t"               |r|j                  d       |	rdd|	ii|d<   |j                  d       	 | j%                         j'                         j)                         j+                  ||j                  dj-                  |      |dn|j                  t               |dn|j                  t"              |d      j/                          y# t0        j2                  $ rR}|rFdt5        |      v r4t	        j6                  ||      }t1        j8                  d|ddig       |Y d}~yY d}~yd}~ww xY w)a  Updates a transfer config.

  Args:
    transfer_client: the transfer client to use.
    id_fallbacks: IDs to use when they have not been explicitly specified.
    reference: the TransferConfigReference to update.
    target_dataset: Optional updated target dataset.
    display_name: Optional change to the display name.
    refresh_window_days: Optional update to the refresh window days. Some data
      sources do not support this.
    params: Optional parameters to update.
    auth_info: A dict contains authorization info which can be either an
      authorization_code or a version_info that the user input if they want to
      update credentials.
    service_account_name: The service account that the user could act as and
      used as the credential to create transfer runs from the transfer config.
    destination_kms_key: Optional KMS key for encryption.
    notification_pubsub_topic: The Pub/Sub topic where notifications will be
      sent after transfer runs associated with this transfer config finish.
    schedule_args: Optional parameters to customize data transfer schedule.

  Raises:
    BigqueryTypeError: if reference is not a TransferConfigReference.
    bq_error.BigqueryError: required field not given.
  update_transfer_configr_   z	projects/)r   dataSourceIddestinationDatasetIdz&transfer_config.destination_dataset_idztransfer_config.display_namedisplayNameztransfer_config.paramsz(transfer_config.data_refresh_window_daysscheduleOptionsV2z!transfer_config.scheduleOptionsV2r   z)transfer_config.notification_pubsub_topicNr   kms_key_namevalueencryption_configurationz%encryption_configuration.kms_key_name,2)r   rM   
updateMaskauthorizationCodeversionInfoserviceAccountNamex__xgafvzNot found: Dataset)r   rT   Not found: reasonnotFound)r   rb   rc   rv   bq_client_utilsGetProjectReference	projectIdrS   r   appendr   ProcessParamsFlagr   ProcessRefreshWindowDaysFlagr-   rQ   AUTHORIZATION_CODEVERSION_INFOrN   rO   rP   patchjoinrR   r   BigqueryInterfaceErrorrF   GetDatasetReferencer   )rH   r   rX   r   r   r   r   r   r   r   r   r   r   current_configupdate_maskupdate_itemsdata_source_inforA   dataset_references                      r   r   r     s   Z !!99%
 "))|DNN 'y33. +,!/!?,~+9L'(?@56".L%77ML/0 )*N>,J &BB~&	L AB4423	
 $%
 :;0IL,-BC1Y>)*|y8|$-."560L+, >?((*::<BB))88K(%D9==9K+L%-D9==3N/ C 
 gi		(	( .#a&8)==# **.
08Z2H"	 9~s   	BI! !K4AKKdata_sourcec                 r   i }|r||d<   |r||d<   nt        j                  d      ||d<   |r%t        | ||      }t        j                  ||||      }|rt        j
                  ||      }nt        j                  d      |r	|dz   |z   }n|dz   }|
r|
j                         |d<   |	r|	|d	<   |r	d
d|ii|d<   | j                         j                         j                         j                  |||dn|j                  t              |dn|j                  t              |      j                         }|d   S )a  Create a transfer config corresponding to TransferConfigReference.

  Args:
    transfer_client: the transfer client to use.
    reference: the TransferConfigReference to create.
    data_source: The data source for the transfer config.
    target_dataset: The dataset where the new transfer config will exist.
    display_name: A display name for the transfer config.
    refresh_window_days: Refresh window days for the transfer config.
    params: Parameters for the created transfer config. The parameters should be
      in JSON format given as a string. Ex: --params="{'param':'value'}". The
      params should be the required values needed for each data source and will
      vary.
    auth_info: A dict contains authorization info which can be either an
      authorization_code or a version_info that the user input if they need
      credentials.
    service_account_name: The service account that the user could act as and
      used as the credential to create transfer runs from the transfer config.
    notification_pubsub_topic: The Pub/Sub topic where notifications will be
      sent after transfer runs associated with this transfer config finish.
    schedule_args: Optional parameters to customize data transfer schedule.
    destination_kms_key: Optional KMS key for encryption.
    location: The location where the new transfer config will run.

  Raises:
    BigqueryNotFoundError: if a requested item is not found.
    bq_error.BigqueryError: if a required field isn't provided.

  Returns:
    The generated transfer configuration name.
  r   r   z A display name must be provided.r   zParameters must be provided.z/locations/z/locations/-r   r   r   r   r   N)r   r   r   r   r   rM   )r   r8   r   r   r   r   r-   rN   rO   rP   createrQ   r   r   rR   )rH   rX   r   r   r   r   r   r   r   r   r   r   rY   create_itemsr   r   new_transfer_configs                    r   create_transfer_configr   P  s   \ , +9L'(".L

 
 !C
DD!,,~ )K &BB-|[L %77ML

 
 !?
@@&1F 'F446 $% 0IL,-"560L+,
  y{v'dY]];M-N  }}\*1  
 wy $ 
V	$$r   ignore_not_foundc                    t        j                  |t         j                  j                  d       	 | j	                         j                         j                         j                  |j                        j                          y# t        j                  $ r)}|st        j                  d|ddig       |Y d}~yd}~ww xY w)a  Deletes TransferConfigReference reference.

  Args:
    transfer_client: the transfer client to use.
    reference: the TransferConfigReference to delete.
    ignore_not_found: Whether to ignore "not found" errors.

  Raises:
    BigqueryTypeError: if reference is not a TransferConfigReference.
    bq_error.BigqueryNotFoundError: if reference does not exist and
      ignore_not_found is False.
  delete_transfer_configr_   rL   r   r   r   N)r   rb   rc   rv   rN   rO   rP   deleter   rR   r   r   )rH   rX   r   rA   s       r   r   r     s    $ !!99%
((*::<CC)) D gi		'	' **&
(8Z*@" s   AB CB>>C)NNNNN)NNN)	NNNNNNNNN)
NNNNNNNNNN)F),rE   
__future__r   r   r   r=   rk   typingr   r   r   r	   googleapiclientr
   clientsr   r   r   r   r   r   Servicer   r   r   ResourcerF   rS   rW   rc   rd   intr^   rv   rt   TransferRunReferencer   r   rG   r   r   r   r   r   r3   r   r   <module>r      s   4 &  %   2 2 % ,    $


 * I( I(X);); # i&8&8 c  IM"# $%)D''D33DDED smD }	D
 D c]DV "& $ ;'';33KKL; #; #	;
 ; SM;B #'!% $:'':**??: 3-: #	:
 :z$''$**BB$ $ sm	$
 sm$N''D 
('' 6 %)"&)- *.*.)-/348#B''B8C=)	
B **BBB SMB 3-B "#B SMB S#X'B #3-B "#B   (}!B" 01#BR %)"&)- *.*./348)-"q%''q%q% q% SM	q%
 3-q% "#q% SMq% S#X'q% #3-q%  (}q% 01q% "#q% smq%n #''**BB r   