
    .0                         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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S jrSS jrS rSS jr   SS jrS r    SS jrS rSS jr " S S\5      rg)z%Spanner database sessions API helper.    )absolute_import)division)unicode_literals)encoding)
exceptions)extra_types)http_wrapper)
list_pager)apis)QueryHasDmlc                     U R                   S:X  a  [        R                  R                  U 5      e[        R
                  " U 5      $ )z5Wrap http_wrapper.CheckResponse to skip retry on 501.i  )status_codeapitools_exceptions	HttpErrorFromResponser	   CheckResponse)responses    7lib/googlecloudsdk/api_lib/spanner/database_sessions.pyr   r      s8    S 

'
'
4
4X
>>		#	#H	--    Nc                 6   [        SSS5      n[        R                  " SS5      nUc  UR                  U R	                  5       S9nO:UR                  UR                  US9S9nUR                  UU R	                  5       S9nUR                  R                  U5      $ )zCreate a database session.

Args:
  database_ref: String, The database in which the new session is created.
  creator_role: String, The database role which created this session.

Returns:
  Newly created session.
spannerv1N)database)creatorRole)session)createSessionRequestr   )	_GetClientInstancer   GetMessagesModule6SpannerProjectsInstancesDatabasesSessionsCreateRequestRelativeNameCreateSessionRequestSession%projects_instances_databases_sessionsCreate)database_refcreator_roleclientmsgsreqcreate_session_requests         r   r$   r$   %   s     it4&				4	0$

E
E**, F .C "666 7 8

E
E3**, F .C 
	5	5	<	<S	AAr   c                     [         R                  " SS5      n[         R                  " SS5      nUR                  U R	                  5       US9n[
        R                  " UR                  USSS9$ )z0Lists all active sessions on the given database.r   r   )r   filterNsessions)batch_size_attributefield)r   GetClientInstancer   4SpannerProjectsInstancesDatabasesSessionsListRequestr    r
   YieldFromListr#   )r%   server_filterr'   r(   r)   s        r   Listr4   =   st    !!)T2&				4	0$AA((*= 	B 	B# 
	!	!22	  
 r   c                     [         R                  " SS5      n[         R                  " SS5      nUR                  U R	                  5       S9nUR
                  R                  U5      $ )zDelete a database session.r   r   )name)r   r0   r   6SpannerProjectsInstancesDatabasesSessionsDeleteRequestr    r#   Delete)session_refr'   r(   r)   s       r   r8   r8   M   s_    !!)T2&				4	0$CC##% 	D 	'#		5	5	<	<S	AAr   c                 F    [         R                  " XUS9n[        Ul        U$ )N)http_timeout_sec)r   r0   r   check_response_func)api_nameapi_versionr;   r'   s       r   r   r   V   s&    !!.>@&,&	-r   c                    [        SSU5      n[        R                  " SS5      n[        U5        [	        U UUUUU5      n	UR                  UR                  5       U	S9n
UR                  R                  U
5      n[        U 5      (       aI  USL aD  UR                  UR                  S9n[        U/ UR                  R                  R                  5        U$ )a  Execute an SQL command.

Args:
  sql: String, The SQL to execute.
  query_mode: String, The mode in which to run the query. Must be one of
    'NORMAL', 'PLAN', 'PROFILE', 'WITH_STATS', or 'WITH_PLAN_AND_STATS'.
  session_ref: Session, Indicates that the repo should be created if it does
    not exist.
  read_only_options: The ReadOnly message for a read-only request. It is
    ignored in a DML request.
  request_options: The RequestOptions message that contains the priority.
  enable_partitioned_dml: Boolean, whether partitioned dml is enabled.
  http_timeout_sec: int, Maximum time in seconds to wait for the SQL query to
    complete.

Returns:
  (Repo) The capture repository.
r   r   )r   executeSqlRequestF)metadata)r   r   r   _RegisterCustomMessageCodec_GetQueryRequest:SpannerProjectsInstancesDatabasesSessionsExecuteSqlRequestr    r#   
ExecuteSqlr   	ResultSetrA   Committransactionid)sql
query_moder9   read_only_optionsrequest_optionsenable_partitioned_dmlr;   r'   r(   execute_sql_requestr)   resp
result_sets                r   rE   rE   ]   s    * i/?@&				4	0$d#(	 	GG&&(<O 	H 	Q#		5	5	@	@	E$0E97J
;J//;;>>?	+r   c                 t   ^  S nU 4S jn[         R                  " XS9" T R                  R                  5        g)zBRegister custom message code.

Args:
  msgs: Spanner v1 messages.
c                 f    [         R                  " [         R                  " U R                  S95      $ N)entriesr   JsonProtoEncoder	JsonArrayentrymsgs    r   _ToJson,_RegisterCustomMessageCodec.<locals>._ToJson   s'    ''cii02 2r   c                 r   > TR                   R                  [        R                  " U 5      R                  S9$ )NrY   )rF   RowsValueListEntryr   JsonProtoDecoderrU   )datar(   s    r   	_FromJson._RegisterCustomMessageCodec.<locals>._FromJson   s3    >>,,**4088 - : :r   encoderdecoderN)r   RegisterCustomMessageCodecrF   r`   )r(   r\   rc   s   `  r   rB   rB      s2    2: %%*
..
+
+-r   c                 ^   [         R                  " SS5      nUSL a  [        U5      nO[[        U 5      (       a-  UR	                  UR                  5       S9nUR                  US9nOUR	                  US9nUR                  US9nUR                  U UUR                  R                  U5      US9$ )	aG  Formats the request based on whether the statement contains DML.

Args:
  sql: String, The SQL to execute.
  query_mode: String, The mode in which to run the query. Must be one of
    'NORMAL', 'PLAN', 'PROFILE', 'WITH_STATS', or 'WITH_PLAN_AND_STATS'.
  session_ref: Reference to the session.
  read_only_options: The ReadOnly message for a read-only request. It is
    ignored in a DML request.
  request_options: The RequestOptions message that contains the priority.
  enable_partitioned_dml: Boolean, whether partitioned dml is enabled.

Returns:
  ExecuteSqlRequest parameters
r   r   T	readWrite)begin)readOnly)	singleUse)rJ   requestOptions	queryModerH   )	r   r   _GetPartitionedDmlTransactionr   TransactionOptions	ReadWriteTransactionSelectorExecuteSqlRequestQueryModeValueValuesEnum)	rJ   rK   r9   rL   rM   rN   r(   rH   transaction_optionss	            r   rC   rC      s    * 
			4	0$t#/<K311DNN<L1M**1D*EK11" 2 $**5H*IK			
$&&??
K	 
  
 r   c                 Z   [         R                  " SS5      n[         R                  " SS5      nUR                  UR	                  5       S9nUR                  US9nUR                  UU R                  5       S9nUR                  R                  U5      nUR                  UR                  S9$ )zCreates a transaction for Partitioned DML.

Args:
  session_ref: Reference to the session.

Returns:
  TransactionSelector with the id property.
r   r   )partitionedDml)options)beginTransactionRequestr   )rI   )r   r0   r   rr   PartitionedDmlBeginTransactionRequest@SpannerProjectsInstancesDatabasesSessionsBeginTransactionRequestr    r#   BeginTransactionrt   rI   )r9   r'   r(   rw   begin_transaction_reqr)   rP   s          r   rq   rq      s     !!)T2&				4	0$//((* 0 ,66! 7 #MM3&&( 	N 	*# 
	5	5	F	Fs	K$		!	!TWW	!	--r   c           
         [         R                  " SS5      n[         R                  " SS5      nUb,  UR                  U R	                  5       UR                  XS9S9nOGUR                  U R	                  5       UR                  UUR                  UR                  5       S9S9S9nUR                  R                  U5      $ )a  Commit a transaction through a session.

In Cloud Spanner, each session can have at most one active transaction at a
time. In order to avoid retrying aborted transactions by accident, this
request uses a temporary single use transaction instead of a previously
started transaction to execute the mutations.
Note: this commit is non-idempotent.

Args:
  session_ref: Session, through which the transaction would be committed.
  mutations: A list of mutations, each represents a modification to one or
      more Cloud Spanner rows.
  transaction_id: An optional string for the transaction id.

Returns:
  The Cloud Spanner timestamp at which the transaction committed.
r   r   )	mutationstransactionId)r   commitRequestrj   )r   singleUseTransaction)
r   r0   r   6SpannerProjectsInstancesDatabasesSessionsCommitRequestr    CommitRequestrr   rs   r#   rG   )r9   r   transaction_idr'   r(   r)   s         r   rG   rG      s    $ !!)T2&				4	0$

E
E((*(( ) ? F @C
 
E
E((*((!%!8!8..* "9 ", ) - F .C 
	5	5	<	<S	AAr   c                       \ rS rSrSr\R                  " SS5      r\S 5       r	\S 5       r
\S 5       r\S 5       r\S	 5       rS
rg)MutationFactory   zFactory that creates and returns a mutation object in Cloud Spanner.

A Mutation represents a sequence of inserts, updates and deletes that can be
applied to rows and tables in a Cloud Spanner database.
r   r   c                 R    U R                   R                  U R                  X5      S9$ )a  Constructs an INSERT mutation, which inserts a new row in a table.

Args:
  table: String, the name of the table.
  data: A collections.OrderedDict, the keys of which are the column names
    and values are the column values to be inserted.

Returns:
  An insert mutation operation.
)insertr(   Mutation	_GetWriteclstablerb   s      r   InsertMutationFactory.Insert  %     88CMM%$>??r   c                 R    U R                   R                  U R                  X5      S9$ )a  Constructs an UPDATE mutation, which updates a row in a table.

Args:
  table: String, the name of the table.
  data: An ordered dictionary where the keys are the column names and values
    are the column values to be updated.

Returns:
  An update mutation operation.
)updater   r   s      r   UpdateMutationFactory.Update  r   r   c                 R    U R                   R                  U R                  X5      S9$ )zConstructs a DELETE mutation, which deletes a row in a table.

Args:
  table: String, the name of the table.
  keys: String list, the primary key values of the row to delete.

Returns:
  A delete mutation operation.
)delete)r(   r   
_GetDelete)r   r   keyss      r   r8   MutationFactory.Delete  s%     88CNN5$?@@r   c                    S n[         R                  " USS9" U R                  R                  R                  5        UR                  U5      nU Vs/ s H  oUR                  PM     nnU Vs/ s H  oUR                  PM     nnU R                  R                  UUR                  U R                  R                  R	                  US9/S9$ s  snf s  snf )zFConstructs Write object, which is needed for insert/update operations.c                 f    [         R                  " [         R                  " U R                  S95      $ rT   rV   rZ   s    r   r\   *MutationFactory._GetWrite.<locals>._ToJson0  '    ))


		
24 4r   Nre   r_   )columnsr   values)	r   rh   r(   WriteValuesValueListEntryGetJsonDatacol_name	col_valuer6   )r   r   rb   r\   json_columnscoljson_column_namesjson_column_valuess           r   r   MutationFactory._GetWrite,  s    4 '''HHNN//1 $$T*L1=>#>3?@<C--<@88>>!jj33:L3MN  P P ?@s   C-Cc                 V   S n[         R                  " USS9" U R                  R                  R                  5        U R                  R                  U R                  R                  R	                  UR                  U5      S9/S9nU R                  R                  UR                  US9$ )z?Constructs Delete object, which is needed for delete operation.c                 f    [         R                  " [         R                  " U R                  S95      $ rT   rV   rZ   s    r   r\   +MutationFactory._GetDelete.<locals>._ToJsonF  r   r   Nre   r_   )r   )r   keySet)r   rh   r(   KeySetKeysValueListEntryGetJsonKeysr8   r6   )r   r   r   r\   key_sets        r   r   MutationFactory._GetDeleteA  s    
4 '''HHOO..0 hhoo**1B1B41H*I$o G 88??G?<<r    N)__name__
__module____qualname____firstlineno____doc__r   r   r(   classmethodr   r   r8   r   r   __static_attributes__r   r   r   r   r      s    
 
			4	0$@ @ @ @ 
A 
A P P( = =r   r   )N)NNFN)NNNF)r   
__future__r   r   r   apitools.base.pyr   r   r   r   r	   r
   googlecloudsdk.api_lib.utilr   &googlecloudsdk.command_lib.spanner.sqlr   r   r$   r4   r8   r   rE   rB   rC   rq   rG   objectr   r   r   r   <module>r      s    , &  ' % > ( ) ' , >.B0 B @D<A $'T-( "&'+%),1$N..!BHW=f W=r   