
    8                        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Zddlm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ d	Zd
ZddddddddZej+                         D  ci c]  \  } }|| 
 c}} Zej/                         ZdedefdZdedefdZdedefdZdededefdZdedefdZdGdZddd edefd!Z d"ee   de
ee
ee
ee	f   f   f   fd#Z! G d$ d%e      Z"d&ee   d"ede"fd'Z#d( Z$d) Z%d*edee   fd+Z&d, Z'd- Z(d. Z)d/ Z*	 	 	 dHd0ee+   d1ee   d2ee   fd3Z, G d4 d5e      Z-	 	 	 dHd6ej\                  j^                  d ed7ee+   d1ee   d8ee   de-fd9Z0	 dId2ee   deee      fd:Z1	 	 	 dHd6ed;ee   d0ee+   d1ee   d<ee   f
d=Z2	 	 	 dHd6ed0ee+   d1ee   d>ee   fd?Z3d@edAe
ee	f   fdBZ4dCedDe
ee	f   dAe
ee	f   dEefdFZ5yc c}} w )Jz#Bigquery Client library for Python.    )absolute_import)division)print_functionN)AnyDictList
NamedTupleOptional	TypedDict)bq_error)bq_id_utilsi zgs://cloudSqlawsazuresqlDataSourcecloudSpannercloudResourcespark)	CLOUD_SQLAWSAzureSQL_DATA_SOURCECLOUD_SPANNERCLOUD_RESOURCESPARKiam_role_idreturnc                     d| z  S )zReturns properties for a connection with IAM role id.

  Args:
    iam_role_id: IAM role id.

  Returns:
    JSON string with properties to create a connection with IAM role id.
  z#{"accessRole": {"iamRoleId": "%s"}} )r   s    'platform/bq/utils/bq_processor_utils.pyMakeAccessRolePropertiesJsonr!   )   s     
/	<<    	tenant_idc                     d| z  S )zReturns properties for a connection with tenant id.

  Args:
    tenant_id: tenant id.

  Returns:
    JSON string with properties to create a connection with customer's tenant
    id.
  z{"customerTenantId": "%s"}r   )r#   s    r    MakeTenantIdPropertiesJsonr%   6   s     
&		11r"   federated_app_client_idc                     d| z  S )a  Returns properties for a connection with a federated app (client) id.

  Args:
    federated_app_client_id: federated application (client) id.

  Returns:
    JSON string with properties to create a connection with customer's federated
    application (client) id.
  z&{"federatedApplicationClientId": "%s"}r   )r&   s    r    +MakeAzureFederatedAppClientIdPropertiesJsonr(   D   s     
24K	KKr"   c                     d| d|dS )a1  Returns properties for a connection with tenant and federated app ids.

  Args:
    tenant_id: tenant id
    federated_app_client_id: federated application (client) id.

  Returns:
    JSON string with properties to create a connection with customer's tenant
    and federated application (client) ids.
  z{"customerTenantId": "z%", "federatedApplicationClientId" : "z"}r   )r#   r&   s     r    4MakeAzureFederatedAppClientAndTenantIdPropertiesJsonr*   T   s     
 r"   namec                 2    t        j                  dd |       S )z-Convert a name with underscores to camelcase.z_[a-z]c                 F    | j                  d      d   j                         S )Nr      )groupupper)matchs    r    <lambda>zToLowerCamel.<locals>.<lambda>l   s    Aq(9(?(?(Ar"   )resub)r+   s    r    ToLowerCamelr5   j   s    	A4	HHr"   c                 P    | j                  d |j                         D               y)zAdds all kwds to config dict, adjusting keys to camelcase.

  Note this does not remove entries that are set to None, however.

  Args:
    config: A configuration dict.
    **kwds: A dict of keys and values to set in the config.
  c              3   B   K   | ]  \  }}|	t        |      |f  y wN)r5   ).0kvs      r    	<genexpr>z"ApplyParameters.<locals>.<genexpr>x   s"     OAa!$s   
N)updateitems)configkwdss     r    ApplyParametersrA   o   s     	--OOOr"   project_referencez,bq_id_utils.ApiClientHelper.ProjectReferencelocationc                 ,    d| j                   z   dz   |z   S )a  Formats a project identifier for data transfers.

  Data transfer API calls take in the format projects/(projectName), so because
  by default project IDs take the format (projectName), add the beginning format
  to perform data transfer commands

  Args:
    project_reference: The project id to format for data transfer commands.
    location: The location id, e.g. 'us' or 'eu'.

  Returns:
    The formatted project name for transfers.
  z	projects/z/locations/)	projectId)rB   rC   s     r    #FormatProjectIdentifierForTransfersrF   {   s     $ 
(22	2]	BX	MMr"   json_stringc                     	 t        j                  |       S # t        $ r }t        j                  d| d|      d}~ww xY w)zAWrapper for standard json parsing, may throw BigQueryClientError.z Error decoding JSON from string : N)jsonloads
ValueErrorr   BigqueryClientError)rG   es     r    	ParseJsonrO      sA    ::k""	 

&
&4?C s    	A ;A c                   (    e Zd ZU ee   ed<   eed<   y)InsertEntry	insert_idrecordN)__name__
__module____qualname__r
   str__annotations__objectr   r"   r    rQ   rQ      s    c]
.r"   rQ   rR   c                     	 t        j                  |      }t        |t              st	        j
                  d      t        | |      S # t        $ r&}t	        j
                  dt        |            d}~ww xY w)zParses a JSON encoded record and returns an InsertEntry.

  Arguments:
    insert_id: Id for the insert, can be None.
    json_string: The JSON encoded data to be converted.

  Returns:
    InsertEntry object for adding to a table.
  zValue is not a JSON objectzCould not parse object: N)	rJ   rK   
isinstancedictr   rM   rQ   rL   rW   )rR   rG   rowrN   s       r    JsonToInsertEntryr^      si    Q
**[
!Cc4 (()EFFy#&&	 Q

&
&s1v'O
PPQs   AA 	A7!A22A7c                 N    | j                  di       }d|v rd|d   v r|d   d   S y)zHelper to return the session id if the job is part of one.

  Args:
    job: a job resource to get statistics and sessionInfo from.

  Returns:
    sessionId, if the job is part of a session.
  
statisticssessionInfo	sessionIdN)get)jobstatss     r    GetSessionIdrf      s;     '',
#%eu]/C C,,	r"   c                     t        d      }	 t        | j                  di       j                               j                  |      j	                         S # t
        $ r Y yw xY w)zHelper for job printing code.)extractloadquerycopyconfigurationN)setrc   keysintersectionpopKeyError)job_info	job_namess     r    GetJobTypeNamert      sX    67)HLL"-2245	i	 	
 
 s   AA 	AAsource_stringc                    | j                  d      D cg c]  }|j                          }}|D cg c]  }|j                  t              s| }}|st	        j
                  d      |rAt        |      t        |      k7  r(t	        j
                  dj                  t                    |S |d   }t        |      dkD  r"t	        j
                  dt        |      fz        t        j                  j                  |      st	        j
                  d|      t        j                  j                  |      st	        j
                  d|      |S c c}w c c}w )	a  Take a source string and return a list of URIs.

  The list will consist of either a single local filename, which
  we check exists and is a file, or a list of gs:// uris.

  Args:
    source_string: A comma-separated list of URIs.

  Returns:
    List of one or more valid URIs, as strings.

  Raises:
    bq_error.BigqueryClientError: if no valid list of sources can be
      determined.
  ,zNo sources specifiedz(All URIs must begin with "{}" if any do.r   r.   z7Local upload currently supports only one file, found %dzSource file not found: zSource path is not a file: )splitstrip
startswithGCS_SCHEME_PREFIXr   rM   lenformatospathexistsisfile)ru   sourcesourcesgs_uriss       r    ProcessSourcesr      sI     +8*=*=c*BC*BV\\^*B'C""f&7&78I&Jf7 
  


&
&'=
>>
7|s7|#((
4
;
;<M
N  NQZF
7|a((
C\O  77>>&!(()/
1  77>>&!((-3
5  
.7 Ds   EEEc                 *    | j                  d      d   S )z#Convert a kind to just a type name.#   )	partition)kinds    r    
KindToNamer     s    		Q	r"   c                 L    t         j                         D ]  \  }}|| v s|c S  y r8   )CONNECTION_TYPE_TO_PROPERTY_MAPr>   )
connectiontps      r    GetConnectionTyper     s*    -335daJh 6 
r"   c                    d| v r+t        | d         }|dz   }|| vrdt        d|d|d|       d}| D cg c]  }|j                  d      s| }}t        |      dk7  rt        dt        |      d|      |d	   }|d	   j	                         |dd
 z   }t        t        j                  |d
      }|t        d|       |j                  di | |   S c c}w )z-Construct a Reference from a server response.r   	ReferencezCannot find z in object of type rI    r.   zExpected one Reference, found r   NzUnknown reference type: r   )	r   rL   endswithr|   r0   getattrr   ApiClientHelperCreate)object_infotypenamelower_camelr:   rn   upper_camelreference_types          r    ConstructObjectReferencer     s    {+f-.H[(K+%(K1 
 H">{!ajj&=A{D>
4yA~47It
D  q'KA$$&QR8+;66TJ.
X?
@@				:[!9	:: ?s   CCc                 z    | j                   j                  }|d   j                         |dd z   }|t        |       iS )z,Construct an Object from an ObjectReference.r   r.   N)	__class__rT   lowerr\   )	referencer   r   s      r    ConstructObjectInfor   &  s?      ))(!!#hqrl2+
tI	''r"   max_results
page_tokenfilter_expressionc                 F    t        |       }|||d<   |||d<   |||d<   |S )#Create and populate a list request.
maxResultsfilter	pageToken)r\   )r   r   r   r   requests        r    PrepareListRequestr   -  sB     O''GL")GH%GK	.r"   c                   N    e Zd ZU eed<   ee   ed<   ee   ed<   eee      ed<   y)TransferListRequestparentpageSizer   dataSourceIdsN)rT   rU   rV   rW   rX   r
   intr   r   r"   r    r   r   C  s*    
+SMc]$s)$$r"   r   r   	page_sizedata_source_idsc                     t        t        | |            }|||d<   |||d<   |O|j                  d      }|d   dk(  r|d   j                  d      }||d<   |S t        j                  d	|d   z        |S )
r   r   r   r   :r   r   r.   rw   zSInvalid filter flag values: '%s'. Expected format: '--filter=dataSourceIds:id1,id2')r\   rF   rx   r   BigqueryError)r   rC   r   r   r   r   s         r    PrepareTransferListRequestr   M  s     0HE' #GJ%GK %++C0Oq_,'*005o!0go 
. "">A  
.r"   c                    | y| j                  d      r$	 | j                  d      d   j                  d      S t        j                  d| z   dz         # t        $ r!}t        j                  d| z   dz         |d}~ww xY w)	aE  Parses the state filter for list jobs.

  Args:
    filter_expression: A string containing the state filter, e.g., 'state:done'.

  Returns:
    A single state filter or a list of filters to apply. Returns None if no
    filter is provided.

  Raises:
    bq_error.BigqueryClientError: if the filter expression is invalid.
  Nzstates:r   r.   rw   Invalid flag argument ""z*, the expression must start with "states:")rz   rx   
IndexErrorr   r   )r   rN   s     r    ParseStateFilterExpressionr   k  s     !!),$$S)!,22377 
 
 !
	
6	7   ""
#&7
7#
=s   "A 	A>A99A>run_attemptstatesc                     t        |       }||d<   ||t        kD  rt        }||d<   |t        |      |d<   |||d<   |S )z0Create and populate a transfer run list request.r   
runAttemptr   r   r   )r\   MAX_RESULTSr   )r   r   r   r   r   r   s         r    PrepareTransferRunListRequestr     s_     	"'%',[ k%GJ26:GH%GK	.r"   message_typec                 J   t        |       }||t        kD  rt        }||d<   |||d<   |Jd|v r+	 |j                  d      d   j                  d      }||d	<   |S t	        j
                  d
|z   dz         |S # t        $ r!}t	        j
                  d
|z   dz         |d}~ww xY w)z0Create and populate a transfer log list request.r   Nr   r   zmessageTypes:r   r.   rw   messageTypesr   r   )r\   r   rx   r   r   r   )r   r   r   r   r   rN   s         r    PrepareListTransferLogRequestr     s     	"'[ k%GJ%GK,&#))#.q177<". 
. ""
#l
2S
8  
.  $$%4s:
	s   (A8 8	B"BB"paramsr>   c                     	 t        j                  |       }||d<   |S # t        $ r}t        j                  d      |d}~ww xY w)a  Processes the params flag.

  Args:
    params: The user specified parameters. The parameters should be in JSON
      format given as a string. Ex: --params="{'param':'value'}".
    items: The body that contains information of all the flags set.

  Returns:
    items: The body after it has been updated with the params flag.

  Raises:
    bq_error.BigqueryError: If there is an error with the given params.
  zWParameters should be specified in JSON format when creating the transfer configuration.Nr   )rJ   rK   	Exceptionr   r   )r   r>   parsed_paramsrN   s       r    ProcessParamsFlagr     sT    JJv&M "%/	, 
 

 
 	# s    	A=Arefresh_window_daysdata_source_infodata_sourcec                     d|v r'|d   dk(  r| |d<   |S t        j                  d|z        t        j                  d|z        )a  Processes the Refresh Window Days flag.

  Args:
    refresh_window_days: The user specified refresh window days.
    data_source_info: The data source of the transfer config.
    items: The body that contains information of all the flags set.
    data_source: The data source of the transfer config.

  Returns:
    items: The body after it has been updated with the
    refresh window days flag.
  Raises:
    bq_error.BigqueryError: If the data source does not support (custom)
      window days.
  dataRefreshTypeCUSTOM_SLIDING_WINDOWdata_refresh_window_daysz=Data source '%s' does not support custom refresh window days.z6Data source '%s' does not support refresh window days.)r   r   )r   r   r>   r   s       r    ProcessRefreshWindowDaysFlagr     sg    * **)*.EE*=e&'l""
I 
 
 
 @;N r"   )r   N)NNNr8   )6__doc__
__future__r   r   r   rJ   r~   r3   typingr   r   r   r	   r
   r   utilsr   r   r   r{   r   r>   CONNECTION_PROPERTY_TO_TYPE_MAPrn   CONNECTION_TYPESrW   r!   r%   r(   r*   r5   rA   rF   rO   rQ   r^   rf   rt   r   r   r   r   r   r   r   r   r   ProjectReferencer   r   r   r   r   r   )r   r   s   00r    <module>r      s   * &  %  	 	 C C     &#%#  5::<#<TQAqD<#  3779 
=c 
=c 
=2# 2# 2L LL -0,Is Is I
	PNENN 	N*	#		#tCc3h'(
()	* 
Q}QQ Q,
+# +$s) +\ 
;2( "& $'+	#   }	,%) %  $ $%)**;; } 	
 c] > (,}d3iF "& $ # # 	
 SM. "& $"&	#  3-	<c $sCx. 2!!38n! S>! 	!i#s   G