
                            S 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rSSK	r	SSK
r
SSKrSSKrSSKJrJrJrJrJrJr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%  \RL                  S:  a	  SSK'J(r(J)r)  OSSKJ(r(J)r)  \RT                  r*Sr+\RX                  " S5      r-\RX                  " S5      r.Sr/Sr0Sr1Sr2SSS.r3SSSSSS .r4S! r5S"\S#\64S$ jr7S"\S#\64S% jr8S&\9S'\9S#\\\4   4S( jr:S) r;S*\9S#\94S+ jr<S*\9S#\94S, jr=S*\9S#\\9   4S- jr>S.\9S#\94S/ jr?S0 r@S1\\9   S#\\9\94   4S2 jrAS3\9S#\64S4 jrBS3\9S#\\\9\94      4S5 jrC " S6 S7\D5      rE                        SmS8 jrF                  SnS9 jrGS:\9S#\\\9\4      4S; jrHS<\\9\4   S=\9S#\\9\4   4S> jrIS<\\9\4   S=\9S#\\9\4   4S? jrJS@ rK     SoSA jrLSpSB jrM SpSC\\9   S#\\\9\\9   4      4SD jjrN SpSE\\9   S#\\9   4SF jjrOSpSG jrPSH\9S#\64SI jrQSJ\9SK\9S#\\9   4SL jrRSM rSSN rT SqSO\#R                  R                  SP\!R                  SQ\6S#S4SR jjrXSS rY " ST SU\(5      rZSV\\   SW\\#R                  R                     SX\" SYSZ\64S[\64/5      S\\\Z   S#S4
S] jr[S^ r\S_\9S#S4S` jr]Sa r^Sb r_Sc r`Sd raSe rbSf rcSg rdSh\R                  S#\94Si jreSj\9S#\\9\94   4Sk jrfSl rgg)rz,Python script for interacting with BigQuery.    )absolute_import)division)print_functionN)AnyDictList
NamedTupleOptionalTupleType)app)flags)utils)utils_flags)utils_formatting)	bq_consts)bq_error)bq_id_utils)
stringutil)      )	TypedDictNotRequireda  Use schema inference specifically for Parquet LIST logical type.
 It checks whether the LIST node is in the standard form as documented in:
 https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#lists
  <optional | required> group <name> (LIST) {
    repeated group list {
      <optional | required> <element-type> element;
    }
  }
 Returns the "element" node in list_element_node. The corresponding field for the LIST node in the converted schema is treated as if the node has the following schema:
 repeated <element-type> <name>
 This means nodes "list" and "element" are omitted.

 Otherwise, the LIST node must be in one of the forms described by the backward-compatibility rules as documented in:
 https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#backward-compatibility-rules
 <optional | required> group <name> (LIST) {
   repeated <element-type> <element-name>
 }
 Returns the <element-name> node in list_element_node. The corresponding field for the LIST node in the converted schema is treated as if the node has the following schema:
 repeated <element-type> <name>
 This means the element node is omitted.z[\w-]+z^\[(\S+.+\S+), (\S+.+\S+)\)$
parametersdefaultStorageLocationUristorageDescriptorconnectionId	)tabz\tSkippedCreatedReplacedAlteredDropped)SKIPCREATEREPLACEALTERDROPc                      [         R                  (       a,  [         R                  (       a  [        R                  " S5      egg)z,Validate combinations of global flag values.zDCannot specify both --service_account and --use_gce_service_account.N)FLAGSservice_accountuse_gce_service_accountr   
UsageError     platform/bq/frontend/utils.pyValidateGlobalFlagsr2   R   s/    
u<<
..N   =r0   argsreturnc                  >    SnU  H  nU(       d  M  US-  nM     US:  $ )zValidates that at most one of the argument flags is selected.

Args:
  *args: Each flag to be tested parsed in as a separate arg.

Returns:
  True if more than 1 flag was selected, False if 1 or 0 were selected.
r      r/   r3   countargs      r1   ValidateAtMostOneSelectedr:   Z   s-     %c
sqje  
r0   c                  j    SnU  H'  nU(       d  M  [        U5      " 5       U:w  d  M"  US-  nM)     US:  $ )a  Validates that at most one of the argument flags is selected.

  if the arg exists but the value is the default value,
  then it won't be counted. This is uself when users want to clear the
  value while setting another value. For example, 'update --arg1=0 --arg2=100'
  when arg1 and arg2 shouldn't coexist.

Args:
  *args: Each flag to be tested parsed in as a separate arg.

Returns:
  True if more than 1 flag was selected, False if 1 or 0 were selected.
r   r6   )typer7   s      r1   &ValidateAtMostOneSelectedAllowsDefaultr=   j   s:     %c
stCy{c!qje  
r0   descriptionsourcec                 D   SnUc  X4$ [         R                  R                  U5      (       d  [        R                  " SU< 35      e[         R                  R                  U5      (       d  [        R                  " SU< 35      e[        U5       n [        R                  " U5      nSU;   a  US   n [        R                  " S5        SU;   a  US   nSSS5        X4$ ! [         a#  n[        R                  " SU< SU< 35      eSnAff = f! , (       d  f       X4$ = f)	af  Process "source" parameter used for bq update and bq mk command.

Args:
  description: Description of the dataset.
  source: source file path attached by "--source" parameter.

Returns:
  new description if the source file updates the description, otherwise return
  the original description.
  acl if the source file updates the acl, otherwise return None.
NzSource file not found: zSource path is not a file: r>   zPBoth source file and description flag exist, using the value in the source file.accessz%Error decoding JSON schema from file : )ospathexistsr   r.   isfileopenjsonloadloggingdebug
ValueError)r>   r?   aclfpayloades         r1   ProcessSourcerQ      s    	#^			
..@
AA			
..FD
EEF|q		!g	'	!m, 	
 
W	h   	  NN;A1
E  |  	s+   DAC
D)DDD
Dc                    [         R                  S;   a  [        R                  " U 5        gSU S   S   ;  a  [	        S5        gU S   S   S   nU S   S   R                  SS5      n[         R                  S	:X  a  [	        U5        gU S   S   R                  S
S5      S:X  a-  [	        SU S   S   S   S   < SU S   S   S   S   < S35        gUS:X  a  [	        SU< S35        gUS:X  a  [	        SU< S35        gUS:X  a  [	        SU< S35        gU S   S   S
   S:X  a  [	        S5        g[	        SU< S35        g)zPrints the dry run info.
prettyjsonrH   NtotalBytesProcessed
statisticsqueryzQuery successfully validated. No information about number of bytes processed. To see the full details of the job, run this query with `--format=json` or `--format=prettyjson`.totalBytesProcessedAccuracyPRECISEcsvstatementType 	LOAD_DATAzcQuery successfully validated. Assuming the files are not modified, running this query will process loadQueryStatistics
inputFilesz files loading inputFileBytesz bytes of data.zdQuery successfully validated. Assuming the tables are not modified, running this query will process LOWER_BOUNDzsQuery successfully validated. Assuming the tables are not modified, running this query will process lower bound of UPPER_BOUNDzsQuery successfully validated. Assuming the tables are not modified, running this query will process upper bound of CREATE_MODELzQuery successfully validated. The number of bytes that will be processed by this query cannot be calculated automatically. More information about this can be seen in https://cloud.google.com/bigquery-ml/pricing#dry_runzU of data and the accuracy is unknown because of federated tables or clustered tables.)r+   formatbq_utilsPrintFormattedJsonObjectprintget)job	num_bytesnum_bytes_accuracys      r1   PrintDryRunInforl      s   
\\++%%c*
 #l"3G"<<		5
 ,()>?)<(155#Y \\U	)
<!%%or:kI ,()>?M,()>?"		 
y	(AJM 
}	, 
 
}	,  
\	7	#O	4	FC	
 	 #%	
r0   messagec                      [        U 5      $ ! [         aS    [        R                  R	                  5       (       a  [        S5        O[        S5        [        R                  " S5         g f = f)Nz
Got EOF; exiting.z1
Got EOF; exiting. Is your input from a terminal?r6   )inputEOFErrorsysstdinisattyrg   exitrm   s    r1   RawInputrv      sP    >	 
yy!"@AHHQKs   
 AA*)A*c                 ~    [         R                  (       a  [        SU < 35        g[        U 5      R	                  5       $ )z=Prompts user with message, return key pressed or '' on enter.z2Running --headless, accepting default for prompt: r\   )r+   headlessrg   rv   lowerru   s    r1   PromptWithDefaultrz      s+    
^^	G
MN	'		 	 	""r0   c                 <    SnUS;  a  [        U 5      nUS;  a  M  U$ )zFPrompts user with message, returning the key 'y', 'n', or '' on enter.N)ynr\   )rz   )rm   responses     r1   PromptYNr      s(    (& )H 	&	/r0   field_delimiterc                 V    U c  U $ U R                  5       n[        R                  X5      $ )z2Validates and returns the correct field_delimiter.)ry   _DELIMITER_MAPrh   )r   keys     r1   NormalizeFieldDelimiterr     s1      	#			C	11r0   c                 <    U S;  a  [         R                  " S5      eg)a  Validates the string provided is one the API accepts.

Should not receive None as an input, since that will fail the comparison.
Args:
  hive_partitioning_mode: String representing which hive partitioning mode is
    requested.  Only 'AUTO' and 'STRINGS' are supported.
)AUTOSTRINGSCUSTOMzXOnly the following hive partitioning modes are supported: "AUTO", "STRINGS" and "CUSTOM"Nr   r.   )hive_partitioning_modes    r1   ValidateHivePartitioningOptionsr     s)     #@@
..	!  Ar0   labelsc                    0 nU  H|  nUR                  S5      u  p4nUR                  5       nX1;   a  [        R                  " SU-  5      eUR                  5       (       d  M\  UR                  5       XR                  5       '   M~     U$ )a.  Parses a list of user-supplied strings representing labels.

Args:
  labels: A list of user-supplied strings representing labels.  It is expected
    to be in the format "key:value".

Returns:
  A dict mapping label keys to label values.

Raises:
  UsageError: Incorrect label arguments were supplied.
:z,Cannot specify label key "%s" multiple times)	partitionstripr   r.   )r   labels_dict	key_valuek_vs         r1   ParseLabelsr     st     +i!!#&GA!		ANNIAMNNwwyy wwyk'')  
r0   valuec                 \    U R                  5       S:H  =(       d    U R                  5       S:H  $ )N	UNBOUNDEDNULL)upperr   s    r1   IsRangeBoundaryUnboundedr   5  s#    	+	%	@&)@@r0   c                 f    [         R                  U 5      nU(       d  g UR                  5       u  p#X#4$ N)_RANGE_PATTERNmatchgroups)r   r   startends       r1   ParseRangeStringr   9  s-    


u
%%	||~*%	r0   c                      ^  \ rS rSrSrU 4S jr\S 5       r\S 5       r\S 5       r	\S 5       r
\S\4S	 j5       r\S\4S
 j5       r\S 5       r\S\4S j5       rS\4S jrSrU =r$ )TablePrinteriA  z?Base class for printing a table, with a default implementation.c                 t   > [         [        U ]  5         UR                  5        H  u  p#[	        XU5        M     g r   )superr   __init__itemssetattr)selfkwdsr   r   	__class__s       r1   r   TablePrinter.__init__D  s,    	,&(jjl
d #r0   c                 <   [        U[        R                  5      (       a}  U  Hv  nUS   R                  5       S:X  a  [        R
                  " SUS   -  5      eUR                  SS5      R                  5       S:X  d  M\  [        R
                  " SUS   -  5      e   g g )	Nr<   RECORDzCError printing table: Cannot print record field "%s" in CSV format.namemodeNULLABLEREPEATEDzEError printing table: Cannot print repeated field "%s" in CSV format.)
isinstancetable_formatterCsvFormatterr   r   r.   rh   )fields	formatterfields      r1   _ValidateFieldsTablePrinter._ValidateFieldsJ  s    )_99::%= H,. f	  99VZ(..0J>. v	    ;r0   c                     [         R                  " 5       n[        U R                  S/ 5      U5       H-  u  pE[        R                  XEU5      X4R                  SS5      '   M/     U$ )z0Returns bq-specific formatting of a RECORD type.r   r   r\   )collectionsOrderedDictziprh   r   NormalizeField)r   r   use_full_timestampresultsubfieldsubvalues         r1   _NormalizeRecordTablePrinter._NormalizeRecord_  s]     $$&F!%))Hb"95A)5)D)D
0*f\\&"%& B Mr0   c                 H    U(       a  U$ [         R                   R                  S[         R                  R                  S9[         R                  " [        U5      S9-   nUR                  SS9nUR                  SS9nUR                  S5      $ ! [        [        4 a     gf = f)	z3Returns bq-specific formatting of a TIMESTAMP type.r   )tz)secondsN)tzinfo)microsecond z<date out of range for display>)
datetimefromtimestamptimezoneutc	timedeltafloatreplace	isoformatrL   OverflowError)unused_fieldr   r   dates       r1   _NormalizeTimestamp TablePrinter._NormalizeTimestampi  s    /	  ..(##'' / 
uU|45 ||4|( |||*~~c""& /./s   B BB B! B!c                    [        U5      nUc  gUu  pEU R                  S5      R                  S5      R                  5       S:w  aO  [        U5      (       a  UR                  5       OUn[        U5      (       a  UR                  5       OUnSU< SU< S3$ [        U5      (       a  UR                  5       nO[        R                  XU5      n[        U5      (       a  UR                  5       nO[        R                  XU5      nSU< SU< S3$ )z/Returns bq-specific formatting of a RANGE type.z<invalid range>rangeElementTyper<   	TIMESTAMP[, ))r   rh   r   r   r   r   )r   r   r   parsedr   r   normalized_startnormalized_ends           r1   _NormalizeRangeTablePrinter._NormalizeRange}  s     e$F~JEyy#$((0668KG7>>ekkmEe3C88CIIKcc #&&&&%99
*  $$yy{n#77
(n *>::r0   r   c                     Uc  gU R                  SS5      R                  5       S:X  a'  U Vs/ s H  n[        R                  XU5      PM     sn$ [        R                  XU5      $ s  snf )z*Returns bq-specific formatting of a field.Nr   r\   r   )rh   r   r   _NormalizeSingleValuer   r   r   s      r1   r   TablePrinter.NormalizeField  ss     }yy""$
2 e 
,
,U;M
N  --e<NOO	s    A&c                 b   U R                  SS5      R                  5       S:X  a  [        R                  XU5      $ U R                  SS5      R                  5       S:X  a  [        R	                  XU5      $ U R                  SS5      R                  5       S:X  a  [        R                  XU5      $ U$ )z+Returns formatting of a single field value.r<   r\   r   r   RANGE)rh   r   r   r   r   r   r   s      r1   r   "TablePrinter._NormalizeSingleValue  s     yy""$0**59KLL	62		$	$	&+	5--e<NOO	62		$	$	&'	1))%8JKKLr0   c                     [        U [        5      (       d  [        U [        5      (       a  [        R                  " U SSS9$ U $ )z@Converts dicts and lists to JSON; returns everything else as-is.),r   F)
separatorsensure_ascii)r   dictlistrH   dumpsr   s    r1   MaybeConvertToJsonTablePrinter.MaybeConvertToJson  s5     %*UD"9"9ZZ*5IILr0   c           	         [        X5       VVs/ s H  u  pE[        R                  XEU5      PM     nnn[        U[        R
                  5      (       d  [        [        R                  U5      n[        U[        R                  5      (       a  U Vs/ s H	  oUc  SOUPM     nnU$ [        U[        R
                  5      (       d  U Vs/ s H	  oUc  SOUPM     nnU$ s  snnf s  snf s  snf )z9Convert fields in a single row to bq-specific formatting.r\   r   )	r   r   r   r   r   JsonFormattermapr   r   )r   rowr   r   r   r   valuess          r1   	FormatRowTablePrinter.FormatRow  s    
  ,,LE 	##E2DE,  
 i!>!>??<22F;f)_99::<BCF5m.FfC M 	?#@#@AA@FGu-U2fGM DGs   "CC!C&c                    ^^^ [         R                  " SS9mU R                  TT5        TR                  T5        TR	                  UUU4S jU 5       5        TR                  5         g )Nprettysecondary_formatc              3   T   >#    U  H  n[         R                  TUTT5      v   M     g 7fr   )r   r   ).0r   r   r   r   s     r1   	<genexpr>*TablePrinter.PrintTable.<locals>.<genexpr>  s-      C 	vsI7IJJs   %()r   get_formatter_from_flagsr   	AddFieldsAddRowsPrint)r   r   rowsr   r   s    ` `@r1   
PrintTableTablePrinter.PrintTable  sX    44hOI+   OOr0   r/   )__name__
__module____qualname____firstlineno____doc__r   staticmethodr   r   r   r   boolr   r   r   r   r  __static_attributes____classcell__)r   s   @r1   r   r   A  s    G   (   / /& ; ;4 	Pt 	P 	P d     D     r0   r   c                     / SQnU U;  a  [         R                  " SU -  5      eSU 0nUb  UUS'   Ub  UUS'   Ub  UUS'   Ub  UUS'   Ub  UUS	'   Ub  UUS
'   Ub  UUS'   Ub-  SS/nUU;  a  [         R                  " SU-  5      eSUS'   UUS'   Ub  UUS'   US   S:X  a{  U(       a  SUS'   [        R                  " S5      US'   O[        R                  " S5      US'   UUS   S'   U=(       d    SUS   S'   Ub  UUS   S'   Ub  UUS   S'   Ub  UUS   S'   GO,US   S:X  a!  Ub  U(       a  SUS'   SU=(       d    S0US'   GOUS   S:X  a*  Ub  U(       a  SUS'   O[        R                  " S 5      US!'   OUS   S":X  a  S#U	0US$'   Ub  UUS%'   OUS   S&:X  a  U
UUS'.US('   Ub  UUS%'   OUS   S):X  a	  Ub  UUS%'   OUS   S*:X  d	  US   S+:X  aw  US   S*:X  a  S,OS-n Ub  U(       a  U(       a  [         R                  " S.U < S/35      eSUS'   [	        UR                  S05      5      S1:w  a  [         R                  " S2U < S335      eU(       a  SUS4'   Ub+  [        U5        0 nUUS5'   Ub  UUS6'   UUS7'   U(       a  SUS8'   U(       a  [        R                  " U5      n S9U 0US:'   U(       a  UUS;'   UR                  S05      US<'   U$ ! [         a  n![         R                  " S=U!-  5      eSn!A!ff = f)>a  Creates an external table definition with the given URIs and the schema.

Arguments:
  source_format: Format of source data. For CSV files, specify 'CSV'. For
    Google spreadsheet files, specify 'GOOGLE_SHEETS'. For newline-delimited
    JSON, specify 'NEWLINE_DELIMITED_JSON'. For Cloud Datastore backup,
    specify 'DATASTORE_BACKUP'. For Avro files, specify 'AVRO'. For Orc files,
    specify 'ORC'. For Parquet files, specify 'PARQUET'. For Iceberg tables,
    specify 'ICEBERG'.
  source_uris: Comma separated list of URIs that contain data for this table.
  schema: Either an inline schema or path to a schema file.
  autodetect: Indicates if format options, compression mode and schema be auto
    detected from the source data. True - means that autodetect is on, False
    means that it is off. None means format specific default: - For CSV it
    means autodetect is OFF - For JSON it means that autodetect is ON. For
    JSON, defaulting to autodetection is safer because the only option
    autodetected is compression. If a schema is passed, then the user-supplied
    schema is used.
  connection_id: The user flag with the same name defined for the _Load
    BigqueryCmd
  ignore_unknown_values:  Indicates if BigQuery should allow extra values that
    are not represented in the table schema. If true, the extra values are
    ignored. If false, records with extra columns are treated as bad records,
    and if there are too many bad records, an invalid error is returned in the
    job result. The default value is false. The sourceFormat property
    determines what BigQuery treats as an extra value: - CSV: Trailing columns
    - JSON: Named values that don't match any column names.
  hive_partitioning_mode: Enables hive partitioning.  AUTO indicates to
    perform automatic type inference.  STRINGS indicates to treat all hive
    partition keys as STRING typed.  No other values are accepted.
  hive_partitioning_source_uri_prefix: Shared prefix for all files until hive
    partitioning encoding begins.
  require_hive_partition_filter: The user flag with the same name defined for
    the _Load BigqueryCmd
  use_avro_logical_types: The user flag with the same name defined for the
    _Load BigqueryCmd
  parquet_enum_as_string: The user flag with the same name defined for the
    _Load BigqueryCmd
  parquet_enable_list_inference: The user flag with the same name defined for
    the _Load BigqueryCmd
  metadata_cache_mode: Enables metadata cache for an external table with a
    connection. Specify 'AUTOMATIC' to automatically refresh the cached
    metadata. Specify 'MANUAL' to stop the automatic refresh.
  object_metadata: Object Metadata Type.
  preserve_ascii_control_characters: The user flag with the same name defined
    for the _Load BigqueryCmd
  reference_file_schema_uri: The user flag with the same name defined for the
    _Load BigqueryCmd
  encoding: Encoding types for CSV files. Available options are: 'UTF-8',
    'ISO-8859-1', 'UTF-16BE', 'UTF-16LE', 'UTF-32BE', and 'UTF-32LE'. The
    default value is 'UTF-8'.
  file_set_spec_type: Set how to discover files given source URIs. Specify
    'FILE_SYSTEM_MATCH' (default behavior) to expand source URIs by listing
    files from the underlying object store. Specify
    'NEW_LINE_DELIMITED_MANIFEST' to parse the URIs as new line delimited
    manifest files, where each line contains a URI (No wild-card URIs are
    supported).
  null_marker: Specifies a string that represents a null value in a CSV file.
  null_markers: Specifies a list of strings that represent null values in a
    CSV file.
  time_zone: Specifies the time zone for a CSV or JSON file.
  date_format: Specifies the date format for a CSV or JSON file.
  datetime_format: Specifies the datetime format for a CSV or JSON file.
  time_format: Specifies the time format for a CSV or JSON file.
  timestamp_format: Specifies the timestamp format for a CSV or JSON file.
  source_column_match: Controls the strategy used to match loaded columns to
    the schema.
  parquet_map_target_type: Indicate the target type for parquet maps. If
    unspecified, we represent parquet maps as map {repeated key_value {key,
    value}}. This option can simplify this by omiting the key_value record if
    it's equal to ARRAY_OF_STRUCT.
  timestamp_target_precision: Precision (maximum number of total digits in
    base 10) for seconds of TIMESTAMP type.

Returns:
  A python dictionary that contains a external table definition for the given
  format with the most common options set.
)	CSVNEWLINE_DELIMITED_JSONDATASTORE_BACKUP
DELTA_LAKEAVROORCPARQUETGOOGLE_SHEETSICEBERGz%s is not a supported format.sourceFormatNfileSetSpecTypemetadataCacheModetimeZone
dateFormatdatetimeFormat
timeFormattimestampFormat	DIRECTORYSIMPLEz+%s is not a supported Object Metadata Type.objectMetadatatimestampTargetPrecisionr  T
autodetectzg
            {
                "quote": '"',
                "encoding": "UTF-8"
            }
        
csvOptionsa  
            {
                "allowJaggedRows": false,
                "fieldDelimiter": ",",
                "allowQuotedNewlines": false,
                "quote": '"',
                "skipLeadingRows": 0,
                "encoding": "UTF-8"
            }
        preserveAsciiControlCharacterszUTF-8encoding
nullMarkernullMarkerssourceColumnMatchr  jsonOptionsr  zJ
            {
                "skipLeadingRows": 0
            }
        googleSheetsOptionsr  useAvroLogicalTypesavroOptionsreferenceFileSchemaUrir  )enumAsStringenableListInferencemapTargetTypeparquetOptionsr  r   r  Icebergz
Delta LakezCannot create z" table from user-specified schema.r   r6   z%Must provide only one source_uri for z table.ignoreUnknownValuesr   sourceUriPrefixhivePartitioningOptionsrequirePartitionFilterr   schemar   
sourceUrisz2Error occurred while creating table definition: %s)
r   r.   yaml	safe_loadlensplitr   bq_client_utils
ReadSchemarL   )"source_formatsource_urisrB  r-  connection_idignore_unknown_valuesr   #hive_partitioning_source_uri_prefixrequire_hive_partition_filteruse_avro_logical_typesparquet_enum_as_stringparquet_enable_list_inferencemetadata_cache_modeobject_metadata!preserve_ascii_control_charactersreference_file_schema_urir0  file_set_spec_typenull_markernull_markers	time_zonedate_formatdatetime_formattime_formattimestamp_formatsource_column_matchparquet_map_target_typetimestamp_target_precisionsupported_formatsexternal_table_defsupported_obj_metadata_typeshive_partitioning_optionsr   rP   s"                                     r1   CreateExternalTableDefinitionrf    sQ   X^
 --NN:]JKK(-8%.@*+&0C,-'0$)4&"-<)*)4&#.>*+"&18%<"	 <	<nn9OK
 	
 ,0(-<)*!-7Q34.)U2	+/<(+/>> ; ,<( ,0>> 	; 	,<( , &
* 6>5H&z2		 9D<(6		!:F<(7		(   	<(	
 
N	+/G	G		z+/<(+5x7J7*K'	N	+	>		z+/<(48NN D 501
 
N	+v	5
!7+' 
#	.7P34	N	+y	80!>2.)*
 
#	.7P34	N	+u	4	"	.7P34>*i7n-=  /9<  
 
	
fnn
 	

 *.&	[s#	$	)nn@MO
 	

 26./ )%&<="$*@'	,	8/ 	""34 7P23	&>B!":;))&1f&.%7"+8('2'8'8'=|$	 
..<q@ s   KK	 	
K1K,,K1c                    [         R                  R                  U 5      n[         R                  R                  U5      (       a,   [	        U5       n[
        R                  " U5      sSSS5        $ SnSnSnSU -  nU R                  S5      n[        U5      S:X  a  US   nOr[        U5      S	:X  a.  US   R                  S
5      S:  a  US   nUS   nO@US   nUS   nO5[        U5      S:X  a  US   nUS   nUS	   nO[        R                  " U5      eUR                  S5      nUS:  a  UnOUSU nUUS-   S nU(       d  [        R                  " U5      e[        UUUSU40 SU_SU_SU_SU_SU_SU_SU_SU_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_SU_6$ ! , (       d  f       g= f! [
        R                  R                   a#  n[        R                  " SU< SU< 35      eSnAff = f) ah  Returns a ExternalDataConfiguration from the file or specification string.

Determines if the input string is a file path or a string,
then returns either the parsed file contents, or the parsed configuration from
string. The file content is expected to be JSON representation of
ExternalDataConfiguration. The specification is expected to be of the form
schema@format=uri i.e. schema is separated from format and uri by '@'. If the
uri itself contains '@' or '=' then the JSON file option should be used.
"format=" can be omitted for CSV files.

Raises:
  UsageError: when incorrect usage or invalid args are used.
Nz8Error decoding YAML external table definition from file rB   r  zError decoding external_table_definition. external_table_definition should either be the name of a JSON file or the text representation of an external table definition. Given:%s@r6   r      z://r   =TrP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r`  ra  )rC   rD   
expanduserrF   rG   rD  rE  error	YAMLErrorr   r.   rG  rF  findrf  )file_path_or_simple_specrP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r`  ra  maybe_filepathexternal_config_filerP   rJ  rB  rL  	error_msgpartsformat_and_uriseparator_posuris                                 r1   GetExternalDataConfigrw    sv   D 77%%&>?.WW^^N###7~~23   MFM	 
"#I %**3/E
5zQQxn	Uq 
qu		"qa qq	UqQxfQxnAhmNN9%%"'',Mqc$Q}5m=1,./cNN9%% )  6  6 'D 0 ( +L #< .   "  !"  #$ (%&  '( *)* 0+, !8-. $>/ s  :: NNQ  s6   F, F&	F, 
F)%F, )F, ,G-
G((G-file_path_or_json_stringc                 @   [         R                  R                  U 5      n[         R                  R                  U5      (       a,   [	        U5       n[
        R                  " U5      sSSS5        $  [
        R                  " U 5      $ ! , (       d  f       g= f! [
        R                  R                   a#  n[        R                  " SU< SU< 35      eSnAff = f! [
        R                  R                   a#  n[        R                  " SU < SU< 35      eSnAff = f)a  Returns a JSON object from the file or a JSON string.

Determines if the input string is a file path or a string,
then returns either the parsed file contents, or the parsed JSON from
string. The file content is expected to be a JSON string.

Args:
  file_path_or_json_string: Path to the JSON file or a JSON string.

Raises:
  UsageError: when incorrect usage or invalid args are used.
NzError decoding JSON from file rB   z Error decoding JSON from string )rC   rD   rk  rF   rG   rH   rI   decoderJSONDecodeErrorr   r.   loads)rx  rp  	json_filerP   s       r1   GetJsonr~  X  s     77%%&>?.WW^^N##9yy#  ZZ011  <<'' NN4BA
F  <<'' NN%q* sN   B B&	B 1C 
BB B C6CCD:DDcurrent_optionsexternal_options_strc                 0   U R                  [        5      b!  U [            Vs0 s H  o"S_M     snU [        '   U R                  [        5      b!  U [            Vs0 s H  o"S_M     snU [        '   [        U5      n[        U;   a6  U R	                  [        0 5        U [           R                  U[           5        O	SU [        '   [        U;   a  U[           U [        '   O	SU [        '   [        U;   a  U[           U [        '   U $ SU [        '   U $ s  snf s  snf )a  Updates the external catalog table options.

Args:
  current_options: The current external catalog table options.
  external_options_str: The new external catalog table options as a JSON
    string or a file path.

Returns:
  The updated external catalog table options.
N)rh   _PARAMETERS_KEY_STORAGE_DESCRIPTOR_KEYr~  
setdefaultupdate_CONNECTION_ID_KEY)r  r  r   #external_catalog_table_options_dicts       r1   !UpdateExternalCatalogTableOptionsr  z  s0     )5(9(9A49(OO$
 01=()@A0AA4A0O+, )00D(E%;;3O$+++O< (,OO$ CC+,CD +, 04O+,>>*M+O&'
 
 +/O&'	=(0s   DDc                    U R                  [        5      b!  U [            Vs0 s H  o"S_M     snU [        '   [        U5      n[        U;   aB  U R                  [        0 5        U[           R	                  5        H  u  pEXP[           U'   M     O	SU [        '   [
        U;   a  U[
           U [
        '   U $ SU [
        '   U $ s  snf )a  Updates the external catalog dataset options.

Args:
  current_options: The current external catalog dataset options.
  external_options_str: The new external catalog dataset options as a JSON
    string or a file path.

Returns:
  The updated external catalog dataset options.
N)rh   r  r~  r  r   !_DEFAULT_STORAGE_LOCATION_URI_KEY)r  r  r   %external_catalog_dataset_options_dictr   r   s         r1   #UpdateExternalCatalogDatasetOptionsr    s      )5(9(9A49(OO$ +22F*G'==3;eg
 /4o&s+
 (,OO$&*OO-.OP 56
 
 :>O56	%(s   B?c                     [         R                  " SS9n[        R                  " U[        R
                  R                  5        UR                  U 5        UR                  5         g)zPrints the page token in the pretty format.

Args:
  page_token: The dictionary mapping of pageToken with string 'nextPageToken'.
r   r  N)	r   r  r   configure_formatterr   ApiClientHelperNextPageTokenReferenceAddDictr
  )
page_tokenr   s     r1   PrintPageTokenr    sM     22HM)&&,,CC J//r0   c                     0 nSnSnSnSn	Sn
U b  XU'   Ub  US-  XW'   Ub  X%U'   Ub  Ub  UXY'   O[         R                  " S5      eUb  U(       a  UXZ'   U(       a  Xe;  a  S	XV'   Xu;   a  XW   S
::  a  SXW'   U$ g)a  Parses time partitioning from the arguments.

Args:
  partitioning_type: type for the time partitioning. Supported types are HOUR,
    DAY, MONTH, and YEAR. The default value is DAY when other arguments are
    specified, which generates one partition per day.
  partitioning_expiration: number of seconds to keep the storage for a
    partition. A negative value clears this setting.
  partitioning_field: if not set, the table is partitioned based on the
    loading time; if set, the table is partitioned based on the value of this
    field.
  partitioning_minimum_partition_date: lower boundary of partition date for
    field based partitioning table.
  partitioning_require_partition_filter: if true, queries on the table must
    have a partition filter so not all partitions are scanned.

Returns:
  Time partitioning if any of the arguments is not None, otherwise None.

Raises:
  UsageError: when failed to parse.
r<   expirationMsr   minimumPartitionDaterA  Ni  zYNeed to specify --time_partitioning_field for --time_partitioning_minimum_partition_date.DAYr   r   )partitioning_typepartitioning_expirationpartitioning_field#partitioning_minimum_partition_date%partitioning_require_partition_filtertime_partitioningkey_typekey_expiration	key_fieldkey_minimum_partition_datekey_require_partition_filters              r1   ParseTimePartitioningr    s    < (!.)5!9""3h((?$(F%##5i (4%
- 3 NN8  +6
/ 5 ($)!+-2*.'r0   c                 R    U c  gSS/nX;  a  [         R                  " S5      eSU -   $ )zParses the file set specification type from the arguments.

Args:
  file_set_spec_type: specifies how to discover files given source URIs.

Returns:
  file set specification type.
Raises:
  UsageError: when an illegal value is passed.
NFILE_SYSTEM_MATCHNEW_LINE_DELIMITED_MANIFESTznError parsing file_set_spec_type, only FILE_SYSTEM_MATCH, NEW_LINE_DELIMITED_MANIFEST or no value are acceptedFILE_SET_SPEC_TYPE_r   )rW  valid_spec_typess     r1   ParseFileSetSpecTyper  '  sC     )+HI/
..	?  
!3	33r0   clustering_fieldsc                 @    U S:X  a  0 $ U b  SU R                  S5      0$ g)a~  Parses clustering from the arguments.

Args:
  clustering_fields: Comma-separated field names.

Returns:
  Clustering if any of the arguments is not None, otherwise None. Special
  case if clustering_fields is passed in as an empty string instead of None,
  in which case we'll return {}, to support the scenario where user wants to
  update a table and remove the clustering spec.
r\   Nr   r   )rG  )r  s    r1   ParseClusteringr  =  s1     "I$'--c233r0   numeric_type_conversion_modec                 D    U c  gU S:X  a  g[         R                  " S5      e)a  Parses the numeric type conversion mode from the arguments.

Args:
  numeric_type_conversion_mode: specifies how the numeric values are handled
    when the value is out of scale.

Returns:
  The conversion mode.

Raises:
  UsageError: when an illegal value is passed.
NROUNDNUMERIC_TYPE_VALUE_ROUNDzOError parsing numeric_type_conversion_mode, only ROUND or no value are acceptedr   )r  s    r1   ParseNumericTypeConversionModer  T  s.      ")#w.%
..	 r0   c                     0 nSnSnSnSnSnU bX  U R                  S5      n[        U5      S:w  a  [        R                  " S	5      eUS
   X'   0 nUS   X'   US   X'   US   X'   XU'   U(       a  U$ g)a/  Parses range partitioning from the arguments.

Args:
  range_partitioning_spec: specification for range partitioning in the format
    of field,start,end,interval.

Returns:
  Range partitioning if range_partitioning_spec is not None, otherwise None.
Raises:
  UsageError: when the spec fails to parse.
r   ranger   r   intervalNr      zjError parsing range_partitioning. range_partitioning should be in the format of "field,start,end,interval"r   r6   ri  r   rG  rF  r   r.   )	range_partitioning_specrange_partitioningr  	key_rangekey_range_startkey_range_endkey_range_intervalrs  
range_specs	            r1   ParseRangePartitioningr  o  s     ))/-!(#))#.E
5zQNN5  %*!H!J"'(J %aJ%*1XJ"$.y!r0   printable_job_infoc                 $    SU ;   =(       d    SU ;   $ )zBReturns True iff the job is successful and is a DML/DDL query job.Affected RowsDDL Operation Performedr/   )r  s    r1   IsSuccessfulDmlOrDdlJobr    s      ++ 9	"&8	8r0   
dataset_id	object_idc                     [         R                  " SU 5      (       d  gSnSn[         R                  " US-   U-   U5      nU(       d  gUR                  S5      $ )av  If we have a session temporary object, returns the user name of the object.

Args:
  dataset_id: Dataset of object
  object_id: Id of object

Returns:
  If the object is a session temp object, the name of the object after
  stripping out internal stuff such as session prefix and signature encodings.

  If the object is not a session temp object, the return value is None.
z_[0-9a-f]{40}Nz>_[0-9a-f]{8}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{12}_z(?:_b0a98f6_.*)?z(.*?)r6   )re	fullmatchgroup)r  r  session_prefix_regexpopt_signature_encoding_regexpr   s        r1   MaybeGetSessionTempObjectNamer    s_     
oz	2	2 G  #5
,,g%(EEy% 
	Qr0   c                 @    [        U 5      nU(       a  [        U5        gg)aa  Prints additional info from a job formatted for printing.

If the job had a fatal error, non-fatal warnings are not shown.

If any error/warning does not have a 'message' key, printable_job_info must
have 'jobReference' identifying the job.

For DML queries prints number of affected rows.
For DDL queries prints the performed operation and the target.
N)GetJobMessagesForPrintingrg   )r  messagess     r1   PrintJobMessagesr    s     ''9:(	(O r0   c                    / nSnSU ;   a  U S   nU S   S:X  aL  U S   S   nU S   R                  S/ 5      n[        R                  " X3U5      nUR                  SU< S	35        GOZSU S   ;   a  U S   S   nUR                  S
[	        U5      S:X  a  SOS-  5        SnU HQ  nSU;  a  SnM  SU;   a  SUS   < SUS   < 3n	OUS   n	U	b  U	R                  S5      n	UR                  SU	-  5        MS     U(       a  UR                  SU-  5        GOSU ;   a  UR                  SU S   -  5        GOSU ;   Ga  U S   n
U
R                  S5      nU
R                  S5      nU
R                  S5      n[        R                  U R                  S5      5      nU(       Ga  U(       Ga  U(       Ga  U(       Ga  SU ;   a)  U S   nUR                  SR                  UUUUUS 95        GOS!U ;   Ga;  S"U S!   ;   Ga1  S#U S!   ;   as  UR                  [        R                  " U5      < S$[        R                  " U5      < S%[        R                  " U5      < S%[        R                  " U5      < S	35        GOPS&U S!   ;   a  SnU R                  S5      S';   a  S(U< S%U< S)3nUR                  [        R                  " U5      < S*[        R                  " U5      < S%[        R                  " U5      < S%[        R                  " U5      < S	[        R                  " U5      < 3	5        GOUR                  [        R                  " U5      < S+[        R                  " U5      < S%[        R                  " U5      < S%[        R                  " U5      < S	35        S,U ;   a  U S,   nUS   nS-U;   a  U S!   S.:X  a  S/nOS0nUR                  S1[        R                  " U5      < S2[        R                  " U5      < S3[        R                  " U5      < S4[        R                  " U5      < S53	5        S6U;   a  UR                  S75        GO{S8U ;   a  U S8   nUR                  S5      nUR                  S5      nUR                  S95      n[        R                  U R                  S5      5      n[        UU5      nUb  UR                  U< S:U< 35        OUR                  U< S+U< S%U< S%U< 35        OS;U ;   a  U S;   nUR                  S5      nUR                  S5      nUR                  S5      nUR                  S<5      n[        R                  U R                  S5      5      nU(       a>  U(       a7  U(       a0  U(       a)  U(       a"  UR                  S=R                  UUUUUS>95        OS?U ;   a  UR                  S@5        SAU ;   a  UR                  SBU SA   -  5        S	R                  U5      $ )CzKSimilar to _PrintJobMessages(), but returns a string, rather than printing.z	(unknown)jobReferenceStateFAILUREstatuserrorResulterrorsz(Error encountered during job execution:

z,Warning%s encountered during job execution:
r6   r\   sFrm   Tlocationr   z] zutf-8z%s
z)Use "bq show -j %s" to view job warnings.r  zNumber of affected rows: %s
zDDL Target Table	projectId	datasetIdtableIdr  z$DDL Affected Row Access Policy CountzF{op} {count} row access policies on table {project}.{dataset}.{table}
)opr8   projectdatasettablezStatement TypeINDEXSEARCH_INDEXz search index on table .VECTOR_INDEX)r&   r'   zPlease query z9.INFORMATION_SCHEMA to check the progress  of the index.
z vector index on table r   zDefault Connection Statsprovisionedrc   modelr  zDefault connection created for z [z] in project [z] in region [z]
permissionUpdatedz<Your IAM policy has been updated for the default connection
zDDL Target Routine	routineIdz temporary routine zDDL Target Row Access PolicypolicyIdzD{op} row access policy {policy} on table {project}.{dataset}.{table})r  policyr  r  r  	AssertionzAssertion successfulz
Session IdzIn session: %s)rh   r   CreateBigqueryErrorappendrF  encode_DDL_OPERATION_MAPrd   r   
ensure_strr  join)r  result_linesjob_referror_resulterror_lsrl  warningsrecommend_showwrm   ddl_target_table
project_idr  table_idr  $ddl_affected_row_access_policy_countindex_progress_instructiondefault_connection_statslocation_idtarget_typeddl_target_routine
routine_idtemp_object_nameddl_target_row_access_policyrow_access_policy_ids                            r1   r  r    s   ,')) 0G  I-%h/>L!(+//"=H((XNE;@B %h//!(+H5H7X!#2	. N 
!	?!":)='iL'NN7+'FW,-  EOP,,'*<_*MM //)*<=!%%k2J!%%k2J##I.H			89
B
 jX"	/3E	E/A20
, 	,,2F:"" -3 -		
 0
0+,<==/0@AA


 ''+''
3''
3''1 12BCC')
$##$=> C  Z*)& 

 ''+''
3''
3''1''(BC	 	 %%b)%%j1%%j1%%h/	
 &);;%7(&
"  
++66!"23~E#k#k ))+6))(3))*5))+6	 !$<<O 11+,@A#''4J#''4J#''4J			89
B 5ZL#r;KLMz:z
B &);;#5&$  .11+>J-11+>J+//	:H7;;JG			89
B jX2F2
P6)    	 ((./''(+=l+KKL	<	  r0   	referencecustom_formatprint_referencec                    US:X  aB  SU ;  d	  SU S   ;  a  [         R                  " S5      e[        R                  " U S   S   5        g	[        R
                  S;   a  [        R                  " U 5        g	[        R
                  S;   Ga   [        R                  " 5       n[        R                  " U[        U5      UU S9  [        R                  " U [        U5      5      n U (       a  UR                  U 5        UR                  (       a2  U(       a+  [        UR                  R                  5       < SU< S35        UR!                  5         [        5         [#        U[$        R&                  R(                  5      (       a  [+        U 5        g	g	[        R                  " 5       nUR-                  [/        U R1                  5       5      5        UR                  U 5        UR!                  5         g	)
z'Prints the object with various formats.rB  r   z/Unable to retrieve schema from specified table.rS   Nsparser   )print_formatobject_infor   r  N)r   r.   re   rf   r+   rd   r   r  r   r  r<   format_info_by_typer  typenamerg   
capitalizer
  r   r   r  JobReferencer  
AddColumnsr   keys)r  r  r  r	  r   s        r1   PrintObjectInfor    sk    h{"hk(6K&KNNLMM%%k(&;H&EF||--%%k2||11446I((Y"	 #66T)_K $o++668)DEOO	G)[88EEFF{# G 446Ik..012k"OOr0   c           	         [         R                  S;   a  [        R                  " U 5        g [         R                  S;   a  U (       d  g [        R
                  " 5       n[        R                  " X!SS9  [        [        [        R                  " [        R                  US9U 5      5      nU H  nUR                  U5        M     UR                  5         g U (       ak  [        R
                  " 5       nUR                  [        U S   R!                  5       5      5        U  H  nUR                  U5        M     UR                  5         g g )NrS   r  r   )r  )object_typer   )r+   rd   re   rf   r   r  r   r  r   r   	functoolspartialr  r  r
  r  r  )object_infosobjects_typer   formatted_infosinfos        r1   PrintObjectsArrayr    s    
\\++%%l3||11446I((f  44( 	
O    OO446Il1o22456 OO r0   c                   D    \ rS rSr% Sr\\   \S'   Sr\\	\      \S'   Sr
g)ResourceMetadatai  Ntokenunreachabler/   )r  r  r  r  r!  r   str__annotations__r"  r   r  r/   r0   r1   r   r     s$     %S	 (,+{49%,r0   r   objects_listr  passed_flagsPassedFlagsprint_last_tokenprint_unreachableobjects_metadatac                 2   [         R                  S;   a~  UR                  (       d  UR                  (       aC  SU 0nUR                  (       a  SU;   a  US   US'   UR                  (       a  SU;   a  US   US'   OU n[        R
                  " U5        g[         R                  S;   aq  [        X5        Uc  gUR                  (       a  SU;   a  [        SUS   -   5        UR                  (       a(  SU;   a!  [        SS	R                  US   5      -   5        gggg)
a  Prints the objects array with metadata configured to print using flags.

If there is no `objects_metadata` passed in, then this function has the same
behaviour as `PrintObjectsArray`.

Different metadata can be printed by setting flags in `passed_flags`. With
a `format` of 'sparse' or 'pretty' then nothing will be printed if no flags
are set. With a format of 'prettyjson' or 'json' then the `objects_list`
will be printed as a `results` value even if no flags are set to print
metadata but if some are set, these will also be printed.

Arguments:
  objects_list: The list of resources to print.
  objects_type: The type of the resources to be printed.
  passed_flags: Flags used to configure the printing behaviour.
  objects_metadata: Optional metadata to be printed.
rS   resultsr!  r"  r  Nz
Next token: z
Unreachable: r   )	r+   rd   r(  r)  re   rf   r  rg   r  )r%  r  r&  r*  json_objects        r1   PrintObjectsArrayWithMetadatar.    s    : \\++$$(F(F-k		&	&76F+F/8G		'	'M=M,M%5m%DM" k%%k2||11l1$$4D)D/889%%-;K*K		*:=*I JJK +L% 2r0   c                 8   U c  g/ n/ nU  H  nUR                  S5       H  n[        R                  R                  U5      (       a5  [	        U5       nUR                  UR                  5       5        SSS5        M\  UR                  S5      (       d  [        R                  " S5      eUR                  U5        M     M     / nU(       a  U H  nUR                  SU05        M     U(       a  U H  nUR                  SU05        M     U$ ! , (       d  f       M  = f)zParses UDF resources from an array of resource URIs.

Arguments:
  udf_resources: Array of udf resource URIs.

Returns:
  Array of UDF resources parsed into the format expected by the BigQuery API
  client.
Nr   zgs://z>Non-inline resources must be Google Cloud Storage (gs://) URIs
inlineCoderesourceUri)
rG  rC   rD   rF   rG   r  read
startswithr   r.   )udf_resourcesinline_udf_resourcesexternal_udf_resourcesurisrv  udf_fileudfsudf_codes           r1   ParseUdfResourcesr;    s     dzz#			#Y(

%
%hmmo
6 Y ~~g&&N  	%%c*   
$(
kk<*+ )%
kk=#&' &	+ Ys    D


Ddataset_namec                 r    [         R                  " SU 5      nU(       d  [        R                  " SU -  5      eg)zA regex to ensure the dataset name is valid.


Arguments:
  dataset_name: string name of the dataset to be validated.

Raises:
  UsageError: An error occurred due to invalid dataset string.
z[a-zA-Z0-9\_]{1,1024}zvDataset name: %s is invalid, must be letters (uppercase or lowercase), numbers, and underscores up to 1024 characters.N)r  r  r   r.   )r<  is_valids     r1   ValidateDatasetNamer?  %  s;     \\2LA(	
..	)	*  
r0   c                 *   U (       d  g/ nU  Hp  n[         R                  R                  U5      (       a/  [        U5       nU[        R
                  " U5      -  nSSS5        MV  UR                  [        U5      5        Mr     U$ ! , (       d  f       M  = f)ar  Parses query parameters from an array of name:type:value.

Arguments:
  parameters: An iterable of string-form query parameters: name:type:value.
    Name may be omitted to indicate a positional parameter: :type:value. Type
    may be omitted to indicate a string: name::value, or ::value.

Returns:
  A list of query parameters in the form for the BigQuery API client.
N)rC   rD   rF   rG   rH   rI   r  ParseParameter)r   r,  param_stringrN   s       r1   ParseParametersrC  8  ss     
' l	ww~~l##499Q<  nn^L12 ! 
.	 s   B
B	c                 t    U R                  SS5      n[        U5      S:w  a  [        R                  " S5      eU$ )Nr   r6   ri  zQuery parameters must be of the form: "name:type:value", ":type:value", or "name::value". An empty name produces a positional parameter. An empty type produces a STRING parameter.r  )rB  rG  s     r1   
SplitParamrE  O  s<    


S!
$%Z1_
..	5  
,r0   c                     [        U 5      u  p [        U 5      u  p#WWS.nU(       a  XS'   U$ ! [        R                   a3  n[	        SU< SU< 35        [
        R                  " S5         SnANTSnAff = f)z?Parse a string of the form <name><type>:<value> into each part.zError parsing parameter rB   r6   N)parameterTypeparameterValuer   )rE  ParseParameterTypeAndValuer   r.   rg   rq   rt   )rB  r   	type_dict
value_dictrP   r   s         r1   rA  rA  [  sl    !,/$6|DI '*E&	6N	- 
 	dA
67HHQKKs   . A5)A00A5c                 ^    [        U 5      u  pU(       d  Sn[        U5      nU[        X25      4$ )zCParse a string of the form <recursive_type>:<value> into each part.STRING)rE  ParseParameterTypeParseParameterValue)rB  type_stringvalue_stringrJ  s       r1   rI  rI  i  s2    (6+	K -)	'	@	@@r0   c                    SU R                  5       0nU R                  5       R                  S5      (       a'  U R                  S5      (       a  S[        U SS 5      S.nU R                  S5      (       a'  U R                  S5      (       a  S	[	        U S
S 5      S.nU R                  S5      (       a'  U R                  S5      (       a  S[        U SS 5      S.nU (       d  [
        R                  " S5      eU$ )zDParse a parameter type string into a JSON dict for the BigQuery API.r<   zARRAY<>ARRAY   )r<   	arrayTypezSTRUCT<STRUCT   )r<   structTypeszRANGE<r   )r<   r   zQuery parameter missing type)r   r3  endswithrN  ParseStructTyper   r.   )rP  rJ  s     r1   rN  rN  r  s    {((*+)##H--+2F2Fs2K2K'Ab(9:I I&&;+?+?+D+D&{1R'89I H%%+*>*>s*C*C.{1R/@AI 

..7
88	r0   c                 l    / n[        U 5       H"  u  p#UR                  [        U5      US.5        M$     U$ )z9Parse a Struct QueryParameter type into a JSON dict form.)r<   r   )StructTypeSplitr  rN  )rP  subtypesr   sub_types       r1   r\  r\    s4    ('4ndOO/94HI 5	/r0   c              #     #    U (       a  U R                  SS5      S   nSU;   au  SnSn[        UR                  S5      [        U 5      5       H%  nX   S:X  a  US-  nX   S:X  a  US-  nUS:X  d  M%    O   US:w  a  [        R
                  " S5      eU SUS-    nU [        U5      S-   S n UR                  SS5      n[        U5      S:w  a  [        R
                  " S	5      eUv   U (       a  M  gg7f)
zyYields single field-name, sub-types tuple from a StructType string.

Raises:
  UsageError: When a field name is missing.
r   r6   r   <rS  zMalformatted struct typeNri  z'Struct parameter missing name for field)rG  r  rn  rF  r   r.   )rP  	next_spanangle_countisplitss        r1   r^  r^    s      	!!#q)!,I
ik
aY^^C(#k*:;!>S 

+>S 

+!
 < 
	nn788gA&ic)nq023K__T1%F
6{aNNDEE
L' 	s   A,C12A;C1/C1datetime_objc                 *    U R                  S5      S-   $ )a  Formats a datetime.datetime object (UTC) in RFC3339.

https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#timestamp

Args:
  datetime_obj: A datetime.datetime object representing a datetime in UTC.

Returns:
  The string representation of the date in RFC3339.
TZ)r   )rg  s    r1   FormatRfc3339rk    s     
			$s	**r0   range_valuec                 V    [        U 5      nUc  [        R                  " SU  S35      eU$ )a  Parse a range parameter value string into its components.

Args:
  range_value: A range value string of the form "[<start>, <end>)".

Returns:
  A tuple (<start>, <end>).

Raises:
  app.UsageError: if the input range value string was not formatted correctly.
zInvalid range parameter value: z%. Expected format: "[<start>, <end>)")r   r   r.   )rl  r   s     r1   ParseRangeParameterValuern    s<     K(&^
..
)+ 7 	  
-r0   c                 d   SU ;   a  [        U[        5      (       a   US:X  a  SS0$ [        R                  " U5      n[	        U S    Vs/ s H  o"S   US   4PM     sn5      n0 nUR                  5        H  u  pV[        X5   U5      XE'   M     SU0$ SU ;   ad  [        U[        5      (       a!  US:X  a  SS0$  [        R                  " U5      nU Vs/ s H  n[        U S   U5      PM     nnU(       d  S0 0$ SU0$ SU ;   a8  US:X  a  SS0$ [        U5      u  pS[        U S   U5      [        U S   U	5      S.0$ SUS:w  a  U0$ S0$ s  snf ! [        R                  R                   aA    [        R                  " 5       S	   n[        R                  " S
U-  5      R                  U5      ef = fs  snf )zParse a parameter value of type `type_dict` from value_input.

Arguments:
  type_dict: The JSON-dict type as which to parse `value_input`.
  value_input: Either a string representing the value, or a JSON dict for
    array and value types.
rZ  r   structValuesNr   r<   rW  arrayValuesri  z Error parsing string as JSON: %sr   r   
rangeValue)r   r   )r   r#  rH   r|  r   r   rO  rz  r{  rq   exc_infor   r.   with_tracebackrn  )
rJ  value_inputxtype_mapr   
field_namer   tbr   r   s
             r1   rO  rO    s    i+s##		%%JJ{+kY}5MN5Mi6+5MNOHF(..0
.x/CUKf 1F##I+s##		t$$jj- AL@K1Ik2A6   r]6""9$fD!!)+6JE(3E)FN&y1C'DcJ
  +"7;	BBT	BBC O \\)) \\^Ann.<

.
	s   E7E F-AF*)NFNNNFFFNNFNNNNNNNNNNNNN)FFFNNNNNNNNNNNNNNN)NNNNNr   )T)hr  
__future__r   r   r   r   r   r  rH   rJ   rC   r  rq   typingr   r   r   r	   r
   r   r   abslr   r   rD  r   re   clientsr   rH  frontendr   r   r   r   r   pyglibr   version_infotyping_extensionsr   r   r+   "PARQUET_LIST_INFERENCE_DESCRIPTIONcompileCONNECTION_ID_PATTERNr   r  r  r  r  r   r  r2   r  r:   r=   r#  rQ   rl   rv   rz   r   r   r   r   r   r   objectr   rf  rw  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  	ReferenceCustomPrintFormatr  r  r   r.  r;  r?  rC  rE  rA  rI  rN  r\  r^  rk  rn  rO  r/   r0   r1   <module>r     s   2 &  %      	 	 
 E E E      ,   %     g66+ 	P #( 

9- ;<$? !- #  
  S T  # $ *#s #C #E#s(O #L?
Dc c #s #s #c hsm 	2S 	2S 	2S	 d38n 0AC AD AC HU38_$= N6 Nl (,"&  "'&+" #9J^ ! "'&*" #'vr!d38nD/#s(^// 
#s(^/d##s(^## 
#s(^#L  (,*.DN4. (,}d3S	>"#0 37"*3-c]6%P   #c]< t!v !	&**44& ..& 	&
 
&R<-y -
.Ls).L{22<<=.L & $'	
.L /0.L 
.Lb!Hc d &.	A.8+ 1 1 +c +# %S/ *.Cr0   