
    (                        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
 ddlmZ ddl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 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  G d dej:                        Zy)zThe BigQuery CLI copy command.    )absolute_import)division)print_functionN)ListOptionalTuple)flags)bigquery_client)client_dataset)
client_job)client_table)utils)bigquery_command)bq_cached_client)utils_flags)utils_formatting)bq_error)bq_id_utilsc                   f    e Zd ZdZdZdZdZdZdZdZ	dZ
d	ed
ej                  f fdZdej                   deej&                  j(                     deeee   f   fdZdej                   deej&                  j(                     dedej&                  j(                  dedefdZdededee   fdZ xZS )Copyz5cp [-n] <source_table>[,<source_table>]* <dest_table>z**** NOTE! **** z8Dataset %s not found. Please enter a valid dataset name.z\Warning: This operation is a cross-region copy operation. This may incur additional charges.zWarning: This operation is a cross-region copy operation. This may incur additional charges and take a long time to complete.
This command is running in sync mode. It is recommended to use async mode (-sync=false) for cross-region copy operation.z1cp: Proceed with cross-region copy of %s? [y/N]: z7cp: Table %s already exists. Replace the table? [y/N]: z %s, exiting.namefvc                    t         t        |   ||       t        j                  dddd|       t        j                  dddd|       t        j                  d	dd
d|       t        j
                  dd d|       t        j                  dddd|       t        j                  dddd|       t        j                  dd d|       t        j                  ddd|       | j                  |       y )N
no_clobberFz#Do not overwrite an existing table.n)
short_nameflag_valuesforcez1Ignore existing destination tables, don't prompt.fappend_tablezAppend to an existing table.adestination_kms_keyz;Cloud KMS key for encryption of the destination table data.)r   snapshotz(Create a table snapshot of source table.srestorezNRestore table snapshot to a live table. Deprecated, please use clone  instead.r
expirationz?Expiration time, in seconds from now, of the destination table.clonezCreate a clone of source table.)superr   __init__r	   DEFINE_booleanDEFINE_stringDEFINE_integer_ProcessCommandRc)selfr   r   	__class__s      $platform/bq/frontend/command_copy.pyr*   zCopy.__init__6   s   	$tR(	- 
; 
& 
E	 
2 
	 
I	 
9r 	2    clientsource_referencesreturnc                     d}d}t        |      D ]y  \  }}|j                         }t        j                  |j                  |      }|0t        j                  | j                  t        |      fz  ddig       ||}n||k7  std} ||fS  ||fS )a  Checks whether all source datasets are from same region.

    Args:
      client: Bigquery client
      source_references: Source reference

    Returns:
      true  - all source datasets are from the same region. Includes the
              scenario in which there is only one source dataset
      false - all source datasets are not from the same region.
    Raises:
      bq_error.BigqueryNotFoundError: If unable to compute the dataset
        region
    TN	apiclient	referencereasonnotFoundF)		enumerateGetDatasetReferencer   GetDatasetRegionr8   r   BigqueryNotFoundError_DATASET_NOT_FOUNDstr)	r/   r3   r4   "all_source_datasets_in_same_regionfirst_source_region_valsource_datasetsource_regions	            r1   :_CheckAllSourceDatasetsInSameRegionAndGetFirstSourceRegionz?Copy._CheckAllSourceDatasetsInSameRegionAndGetFirstSourceRegionm   s    & *.&-.3..0n$55$$"m 
	,,##s>':&<<z"
 	

 
	$+-/-2*-/BBB# /" ./BBBr2   source_references_strdest_referencedestination_regionc                    |j                         }	 | j                  ||      \  }}|!t        j                  |j                  |      }|0t        j                  | j                  t        |      fz  ddig       |r||k(  ryt        | j                  t        j                  j                  rd| j                  z   nd| j                   z          | j"                  rydt%        j&                  | j(                  |fz        k7  rt        | j*                  |fz         y	y# t
        j                  $ r!}	t        dt        |	      z          Y d}	~	yd}	~	ww xY w)
a  Checks if it is a Cross Region Copy operation and obtains confirmation.

    Args:
      client: Bigquery client
      source_references: Source reference
      source_references_str: Source reference string
      dest_reference: Destination dataset reference
      destination_region: Destination dataset region

    Returns:
      true  - it is not a cross-region operation, or user has used force option,
              or cross-region operation is verified confirmed with user, or
              Insufficient permissions to query datasets for validation
      false - if user did not allow cross-region operation, or
              Dataset does not exist hence operation can't be performed.
    Raises:
      bq_error.BigqueryNotFoundError: If unable to compute the dataset
        region
    Nr7   z^Unable to determine source or destination dataset location, skipping cross-region validation: Tr:   r;   
yF)r=   rH   r   r>   r8   r   BigqueryAccessDeniedErrorprintrA   r?   r@   _NOTEbq_flagsSYNCHRONOUS_MODEvalue_SYNC_FLAG_ENABLED_WARNING_CROSS_REGION_WARNINGr   frontend_utilsPromptYN_CONFIRM_CROSS_REGION_NOT_COPYING)
r/   r3   r4   rI   rJ   rK   destination_datasetrB   rC   errs
             r1   #shouldContinueAfterCrossRegionCheckz(Copy.shouldContinueAfterCrossRegionCheck   sn   6 )<<>

I
I' >(*=
 
	#+<<&&2E
 !**

!
!S)<%=$?
?Z
 
 
 *11	

$$** 	t...D...	 zz
n%%""&;%==  D!6 889= -- 'H
 s   8D E1EEsource_tables
dest_tablec                    t         j                  j                         }|j                  d      D cg c]  }t	        j
                  ||       }}dj                  d |D              }t	        j
                  ||      }| j                  rd}d}	n| j                  rd}d}	nd}d	}	d
}
|	sn| j                  sbt        j                  |j                  |      }
|
r?dt        j                  | j                  |z        k7  rt!        | j"                  |fz         y| j%                  |||||
      syd}| j&                  rd}d}n$| j(                  rd}d}n| j*                  rd}d}nd}||	t-        j.                         |d}t0        j2                  j4                  rt0        j2                  j4                  |d<   | j6                  rd| j6                  i|d<   | j8                  r_t:        j:                  j=                  t?        | j8                  tA        j@                         z               }t        jB                  |      |d<   tE        jF                  |||fi |}|t!        d|d       y
t0        jH                  j4                  s| jK                  |       y
tM        |      dkD  rdnd}t!        d |d!|d"|d#|d$	       t        jN                  tQ        jR                  |             y
c c}w )%zCopies one table to another.

    Examples:
      bq cp dataset.old_table dataset2.new_table
      bq cp --destination_kms_key=kms_key dataset.old_table dataset2.new_table
    ,)id_fallbacks
identifierz, c              3   2   K   | ]  }t        |        y w)N)rA   ).0srcs     r1   	<genexpr>z#Copy.RunWithArgs.<locals>.<genexpr>   s     %L:K3c#h:Ks   WRITE_APPENDTWRITE_EMPTYWRITE_TRUNCATEFNr7   rN   r   copiedSNAPSHOTsnapshottedRESTORErestoredCLONEclonedCOPY)write_dispositionignore_already_existsjob_idoperation_typelocation
kmsKeyNameencryption_configurationdestination_expiration_timezTable 'z' already exists, skipping   r$    Tablez 'z' successfully z to '')*r   ClientGetsplitbq_client_utilsGetTableReferencejoinr    r   r   r   get_table_regionr8   rW   rX   _CONFIRM_OVERWRITErP   rZ   r]   r#   r%   r(   r   get_job_id_from_flagsrR   LOCATIONrT   r"   r'   datetimeutcfromtimestampinttimeFormatRfc3339r   	CopyTablerS   PrintJobStartInfolenPrintJobMessagesr   format_job_info)r/   r^   r_   r3   rf   r4   rI   rJ   rs   rt   rK   	operationrv   kwdsdatetime_utcjob	pluralitys                    r1   RunWithArgszCopy.RunWithArgs   s    $$((*F !&&s++C 	))v#N+   !II%L:K%LL$66
N ("	'"*#  '88$$ 
~'>'>

!
!^
4( ! 	d#8"::;33 I}}!ni	 ni	nin.!6335(	D !**00d:
00*d%& &&77
doo		+
,l -;,H,H
-d() 

!>59C {^EF&&,,
S!./!3#i-y.J
 %%&6&F&Fs&KLms   K')__name__
__module____qualname__usagerQ   r@   rV   rU   rY   r   rZ   rA   r	   
FlagValuesr*   r
   BigqueryClientr   r   ApiClientHelperTableReferencer   boolr   rH   r]   r   r   __classcell__)r0   s   @r1   r   r   !   s2   
E%
%@  
*  NP ,53 5E$4$4 5n&C,,&C k99HHI&C T8C= !	&CPE,,E k99HHIE !	E
 "11@@E E EN^Ms ^M ^M ^Mr2   r   )__doc__
__future__r   r   r   r   r   typingr   r   r   abslr	   rR   clientsr
   r   r   r   r   r   frontendr   r   rW   r   r   r   r   BigqueryCmdr    r2   r1   <module>r      s^    $ &  %   ( (   # "    , % % ,   %  YM'' YMr2   