
    +7                        S r SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSK	J
r
  SSK	Jr  SS	KJr  SSKJr  SS
KJr  SSKJr  SSKJr  SrSr " S S\R.                  5      r " S S\R.                  5      r " S S\R.                  5      r " S S\R.                  5      rS rS rS rS rS r S r!S r"S r#S r$S  r%S! r&S" r'S*S# jr(S$ r)S% r*S& r+S' r,S( r-S) r.g)+z+Declarative Hooks for BQ surface arguments.    )absolute_import)division)print_function)unicode_literalsN)encoding)
exceptions)util)log)yaml)timesz	gcloud-bqz  Invalid Schema change. Only adding additional columns or relaxing `required`
  fields on existing columns is supported:

  For more details on BigQuery schemas see:
  https://cloud.google.com/bigquery/docs/schemas.c                       \ rS rSrSrSrg)PermissionsFileError,   z4Error if a permissions file is improperly formatted. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       *lib/googlecloudsdk/command_lib/bq/hooks.pyr   r   ,   s    <r   r   c                       \ rS rSrSrSrg)SchemaFileError0   z/Error if a schema file is improperly formatted.r   Nr   r   r   r   r   r   0   s    7r   r   c                       \ rS rSrSrSrg)TableDataFileError4   z3Error if a tabel data file is improperly formatted.r   Nr   r   r   r   r   r   4   s    ;r   r   c                       \ rS rSrSrSrg)SchemaUpdateError8   zError if a schema update fails.r   Nr   r   r   r   r!   r!   8   s    'r   r!   c                     [         R                  " S5      R                  nU (       a  UR                  $ UR                  $ )NBigqueryJobsListRequest)api_utilGetApiMessageProjectionValueValuesEnumfullminimal)show_configprojection_enums     r   JobListProjectionProcessorr,   =   s;    **  		 	  r   c                 ~    U (       a  U $ SR                  [        [        R                  " 5       R                  5      nU$ )Nz{}-{})format_BQ_JOB_ID_PREFIXuuiduuid4hex)
job_id_argjob_ids     r   JobIdProcessorr5   G   s-    >>+TZZ\-=-=>&	-r   c                 "   [         R                  " S5      R                  n / n[        R                  " U S   5      nUR                  SS5      nU(       a  [        U[        5      (       d  [        S5      eU HT  n[        R                  " X5      n[        U5      (       a  UR                  U5        M<  [        SR                  U5      5      e   [        US S9$ ! [        R                   a  n[        S	R                  U5      5      eSnAff = f)
a  Builds a bigquery AccessValueListEntry array from input file.

Expects YAML or JSON formatted file.

Args:
  input_file: input file contents from argparse namespace.

Raises:
  PermissionsFileError: if the file contents are not a valid JSON or YAML
    file.

Returns:
  [AccessValueListEntry]: Array of AccessValueListEntry messages specifying
    access permissions defined input file.
Datasetr   accessNz>Error parsing permissions file: no access list defined in filezBError parsing permissions file: invalid permission definition [{}]c                     U R                   $ N)rolexs    r   <lambda>*PermissionsFileProcessor.<locals>.<lambda>s   s    166r   keyz#Error parsing permissions file [{}])r%   r&   AccessValueListEntryr   loadget
isinstancelistr   r   PyValueToMessage_ValidatePermissionappendr.   sortedYAMLParseError)
input_fileaccess_value_msgpermissions_arraypermissions_from_fileaccess_yaml
permissionypes          r   PermissionsFileProcessorrS   O   s      ++I6KK IIjm4155hE 
3H$(O(O 
J  -,,-=Kj	Z	(	(  ,"F:& 	 - #)9::			 
-44S9 s   B8C D/D		Dc                     U R                   =(       dE    U R                  =(       d2    U R                  =(       d    U R                  =(       d    U R                  =(       a    U R
                  nU$ r:   )domainuserByEmailspecialGroupviewgroupByEmailr;   )permission_objis_valids     r   rH   rH   z   sc     %		#	#%		$	$% 
		% 
	$	$ 	  
/r   c                     [         R                  " [        R                  R                  5       U 5      n[	        [
        R                  " UR                  5       5      5      S-  $ )z;Convert commandline duration into epoch timeoffset (in ms).i  )r   GetDateTimePlusDurationdatetimenowinttimemktime	timetuple)expire_durationts     r   ProcessTableExpirationrf      sB    ##H$5$5$9$9$;_M!	T[['	(4	//r   c           	      R   [         R                  " S5      n[         R                  " S5      n [        R                  " U 5      nUR	                  SS5      nU(       a  [        U[        5      (       d  [        S5      e/ nU H2  nU" US   US   UR	                  SS	5      S
9nUR                  U5        M4     U" [        US S9S9$ ! [        R                   a  n[        SR                  U5      5      eSnAf[        [        4 a  n[        SR                  U5      5      eSnAff = f)1Convert Input JSON file into TableSchema message.TableSchemaTableFieldSchemaschemaNz?Error parsing schema file: no schema field list defined in filenametypemodeNULLABLE)rl   rm   rn   c                     U R                   $ r:   rl   r<   s    r   r>   ,BqTableSchemaFileProcessor.<locals>.<lambda>   s    QVVr   r@   fieldszError parsing schema file [{}]z8Error parsing schema file, invalid field definition [{}])r%   r&   r   rC   rD   rE   rF   r   rI   rJ   rK   r.   AttributeErrorKeyError)	file_argtable_schema_typeschema_field_typeschema_json
all_fieldsfield	new_fieldrR   es	            r   BqTableSchemaFileProcessorr      s   ,,];,,-?@))H%K//(D1Kjd;;
K  J#V}V}yy,i
 	"  F:;K$LMM			 H
:AA#F
GG
(	# 
BII!L s$   BC D&C44D&D!!D&c           	         [         R                  " S5      nUR                  n[         R                  " S5      n [        R                  " U 5      nU(       a  [        U[        5      (       d  [        S5      e/ nU H,  nUR                  U" [        R                  " Xc5      S95        M.     U$ ! [        R                   a  n[        SR                  U5      5      eSnAff = f)rh   TableDataInsertAllRequest
JsonObjectz8Error parsing data file: no data records defined in file)jsonzError parsing data file [{}]N)r%   r&   RowsValueListEntryr   rC   rE   rF   r   rI   r   DictToMessagerK   r.   )rw   data_insert_request_typeinsert_row_typedata_row_type	data_jsonrowsrowrR   s           r   BqTableDataFileProcessorr      s    %334OP,??/((6-I		(#IJy$77
D  D
kk
x55cI
J 
 K			 I
;BB3G
HHIs   A2B- -C CC c                 L    A UR                   (       d  SUR                  l         U$ )zCEnsure that view parameters are set properly tables create request.N)rX   table)refargsrequests      r   SetViewParametersr      s    		GMM	.r   c                     A UR                   R                  R                  nUR                  nUR                  (       a  [        X45      (       a  [        X45        U$ )z.Process the overwrite flag on datasets create.)datasetdatasetReference	datasetId	projectId	overwrite_DatasetExists_TryDeleteDataset)r   r   r   
dataset_id
project_ids        r   ProcessDatasetOverwriter      sD    	//99*  *	^^j--
/	.r   c                     U R                   nU R                  5       nU R                  nUR                  (       a  [	        X4U5      (       a  [        X4U5        U$ )z,Process the overwrite flag on tables create.)r   Namer   r   _TableExists_TryDeleteTable)r   r   r   r   table_idr   s         r   ProcessTableOverwriter      sB    }}*XXZ(}}*	^^J*55jJ7	.r   c                 r   UR                   nUR                  nUR                  (       d	  U(       d  U$ [        U R	                  5       R                  5       U R                  5       U R                  5      nUR                  n[        XVU5      n[        R                  " S5      nU" US9UR                   l        U$ )aS  Process schema Updates (additions/mode changes) for the request.

Retrieves the current table schema for ref and attempts to merge in the schema
provided in the requests. This is necessary since the API backend does not
handle PATCH semantics for schema updates (e.g. process the deltas) so we must
always send the fully updated schema in the requests.

Args:
  ref: resource reference for table.
  args: argparse namespace for requests
  request: BigqueryTablesPatchRequest object

Returns:
  request: updated requests

Raises:
  SchemaUpdateError: table not found or invalid an schema change.
ri   rs   )
r   relax_columnsrk   _TryGetCurrentSchemaParentr   r   _GetUpdatedSchemar%   r&   )	r   r   r   r   relaxed_columnsoriginal_schemanew_schema_columnsupdated_fieldsrx   s	            r   ProcessSchemaUpdater      s    & --%&&/	oN(	jjl388:s}}/ ||$?. ,,];*.A'--	.r   c                    [         R                  " 5       nUR                  n[         R                  " S5      nU" XUS9n UR	                  U5      nU(       a  UR
                  S:w  a  [        SR                  U5      5      e UR                  $ ! [        R                   a    [        SR                  X U5      5      ef = f)a  Try to retrieve the current BigQuery TableSchema for a table_ref.

  Tries to fetch the schema of an existing table. Raises SchemaUpdateError if
  table is not found or if table is not of type 'TABLE'.

Args:
  dataset_id: the dataset id containing the table.
  table_id: the table id for the table.
  project_id: the project id containing the dataset and table.

Returns:
  schema: the table schema object

Raises:
  SchemaUpdateError: table not found or invalid table type.
BigqueryTablesGetRequestr   tableIdr   TABLEzBSchema modifications only supported on TABLE objects received [{}]#Table with id [{}:{}:{}] not found.)r%   GetApiClienttablesr&   Getrm   r!   r.   apitools_exceptionsHttpNotFoundErrorrk   )r   r   r   clientserviceget_request_typeget_requestr   s           r   r   r     s    "   "&MM'++,FG 
+KK$EEJJ')++16%=  * 
 
	.	. 
-44H	
 s    AB 0B?c                     U (       a'  U R                    Vs0 s H  o3R                  U_M     snO0 nU(       a  [        X$5      nU(       a  [        UR                   U5      n[	        UR                  5       S S9$ s  snf )zAUpdate original_schema by adding and/or relaxing mode on columns.c                     U R                   $ r:   rq   r<   s    r   r>   #_GetUpdatedSchema.<locals>.<lambda>D  s    qvvr   r@   )rt   rl   _GetRelaxedCols_AddNewColsToSchemarJ   values)r   new_columnsr   forig_field_maps        r   r   r   8  sn     6E/0010Qvvqy01"  $_EN(););^LN	%%'-=	>> 2s   A9c                 r    UR                  5       nU  H   nX1;   a  SX#   l        M  [        [        5      e   U$ )a  Change mode to `NULLABLE` for columns in existing schema.

  Tries set mode on existing columns in orig_schema_map to `NULLABLE`. Raises
  SchemaUpdateError if column is not found in orig_schema_map.

Args:
  relaxed_columns: [string] the list columns to relax required mode for.
  orig_schema_map: {string: TableSchemaField} map of field name to
    TableSchemaField objects representing the original schema.

Returns:
  updated_schema_map: {string: TableSchemaField} map of field name to
    TableSchemaField objects representing the updated schema.

Raises:
  SchemaUpdateError: if any of the fields to be relaxed are not in the
    original schema.
ro   )copyrn   r!   _INVALID_SCHEMA_UPDATE_MESSAGE)r   orig_schema_mapupdated_schema_mapcols       r   r   r   G  sC    & '++-c
%/"<==	 
 
r   c                     UR                  5       nU  H0  nUR                  U;   a  [        [        5      eX2UR                  '   M2     U$ )a_  Add new columns to an existing schema.

  Tries add new fields to an existing schema. Raises SchemaUpdateError
  if column already exists in the orig_schema_map.

Args:
  new_fields: [TableSchemaField] the list columns add to schema.
  orig_schema_map: {string: TableSchemaField} map of field name to
    TableSchemaField objects representing the original schema.

Returns:
  updated_schema_map: {string: TableSchemaField} map of field name to
    TableSchemaField objects representing the updated schema.

Raises:
  SchemaUpdateError: if any of the fields to be relaxed are not in the
    original schema.
)r   rl   r!   r   )
new_fieldsr   r   r}   s       r   r   r   c  sI    & '++-i~~(<==)2y~~&  
r   c                     [         R                  " 5       nUR                  n[         R                  " S5      nU" XS9n UR	                  U5        g! [
        R                   a(    [        R                  " SR                  X5      5         gf = f)GValidate a resource of the given type with specified ID already exists.BigqueryDatasetsGetRequest)r   r   Tz"Dataset with id [{}:{}] not found.F)
r%   r   datasetsr&   r   r   r   r
   infor.   )r   r   r   r   r   r   s         r   r   r   ~  s}      "&OO'++,HI :L+KK		.	. HH,33JK 
s   A 9BBc                 $   [         R                  " 5       nUR                  n[         R                  " S5      nU" XUS9n UR	                  U5        g! [
        R                   a)    [        R                  " SR                  X U5      5         gf = f)r   r   r   Tr   F)
r%   r   r   r&   r   r   r   r
   r   r.   )r   r   r   r   r   r   r   s          r   r   r     s      "&MM'++,FG 
+KK		.	. HH-44H	
 
s    A :BBc                     [         R                  " 5       nUR                  n[         R                  " S5      nU" XSS9nUR	                  U5        [
        R                  " SR                  X5      5        g)6Try to delete a dataset, propagating error on failure.BigqueryDatasetsDeleteRequestT)r   r   deleteContentszDeleted dataset [{}:{}]N)r%   r   r   r&   Deleter
   r   r.   )r   r   r   r   delete_request_typedelete_requests         r   r   r     s`      "&OO' ../NO&. 
.. (($++JCDr   c                     [         R                  " 5       nUR                  n[         R                  " S5      nU" XUS9nUR	                  U5        [
        R                  " SR                  X U5      5        g)r   BigqueryTablesDeleteRequestr   zDeleted table [{}:{}:{}]N)r%   r   r   r&   r   r
   r   r.   )r   r   r   r   r   r   r   s          r   r   r     sb      "&MM' ../LM&
. 
.. ((%,,ZXNOr   )NN)/r   
__future__r   r   r   r   r^   ra   r0   apitools.base.pyr   r   r   googlecloudsdk.api_lib.bqr	   r%   googlecloudsdk.corer
   r   googlecloudsdk.core.utilr   r/   r   Errorr   r   r   r!   r,   r5   rS   rH   rf   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s    2 &  % '    % > 6 * # $ *   "5 =:++ =8j&& 8<)) <(
(( (
!(V0@I4

$N%P?86"*	E	Pr   