
    .0                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ d ZddZddZd ZddZ	 	 	 ddZd Z	 	 	 	 ddZd ZddZ G d de      Zy)z%Spanner database sessions API helper.    )absolute_import)division)unicode_literals)encoding)
exceptions)extra_types)http_wrapper)
list_pager)apis)QueryHasDmlc                     | j                   dk(  rt        j                  j                  |       t	        j
                  |       S )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                 J   t        ddd      }t        j                  dd      }|!|j                  | j	                               }nC|j                  |j                  |            }|j                  || j	                               }|j                  j                  |      S )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                     t        j                  dd      }t        j                  dd      }|j                  | j	                         |      }t        j                  |j                  |dd      S )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                     t        j                  dd      }t        j                  dd      }|j                  | j	                               }|j
                  j                  |      S )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                 L    t        j                  | ||      }t        |_        |S )N)http_timeout_sec)r   r0   r   check_response_func)api_nameapi_versionr;   r'   s       r   r   r   V   s(    !!.>@&,&	-r   c                    t        dd|      }t        j                  dd      }t        |       t	        | |||||      }	|j                  |j                         |	      }
|j                  j                  |
      }t        |       rK|du rG|j                  |j                        }t        |g |j                  j                  j                         |S )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                 x     d } fd} t        j                  ||       j                  j                         y)zHRegister custom message code.

  Args:
    msgs: Spanner v1 messages.
  c                 h    t        j                  t        j                  | j                              S N)entriesr   JsonProtoEncoder	JsonArrayentrymsgs    r   _ToJsonz,_RegisterCustomMessageCodec.<locals>._ToJson   s'    ''cii02 2r   c                 v    j                   j                  t        j                  |       j                        S )NrY   )rF   RowsValueListEntryr   JsonProtoDecoderrU   )datar(   s    r   	_FromJsonz._RegisterCustomMessageCodec.<locals>._FromJson   s3    >>,,**4088 - : :r   encoderdecoderN)r   RegisterCustomMessageCodecrF   r_   )r(   r\   rb   s   `  r   rB   rB      s6    2:*(%%y*
..
+
+-r   c                 n   t        j                  dd      }|du rt        |      }nbt        |       r3|j	                  |j                               }|j                  |      }n$|j	                  |      }|j                  |      }|j                  | ||j                  j                  |      |      S )	a_  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                 n   t        j                  dd      }t        j                  dd      }|j                  |j	                               }|j                  |      }|j                  || j                               }|j                  j                  |      }|j                  |j                        S )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   rp   PartitionedDmlBeginTransactionRequest@SpannerProjectsInstancesDatabasesSessionsBeginTransactionRequestr    r#   BeginTransactionrr   rI   )r9   r'   r(   ru   begin_transaction_reqr)   rP   s          r   ro   ro      s     !!)T2&				4	0$//((* 0 ,66! 7 #MM3&&( 	N 	*# 
	5	5	F	Fs	K$		!	!TWW	!	--r   c           
         t        j                  dd      }t        j                  dd      }|3|j                  | j	                         |j                  ||            }nP|j                  | j	                         |j                  ||j                  |j                                           }|j                  j                  |      S )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   commitRequestrh   )r   singleUseTransaction)
r   r0   r   6SpannerProjectsInstancesDatabasesSessionsCommitRequestr    CommitRequestrp   rq   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                       e Zd ZdZ ej
                  dd      Zed        Zed        Z	ed        Z
ed        Zed        Zy	)
MutationFactoryzFactory 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                 Z    | j                   j                  | j                  ||            S )a7  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tablera   s      r   InsertzMutationFactory.Insert  '     88CMM%$>??r   c                 Z    | j                   j                  | j                  ||            S )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   UpdatezMutationFactory.Update  r   r   c                 Z    | j                   j                  | j                  ||            S )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   zMutationFactory.Delete  s'     88CNN5$$?@@r   c                    d } t        j                  |d      | j                  j                  j                         |j                  |      }|D cg c]  }|j                   }}|D cg c]  }|j                   }}| j                  j                  ||j                  | j                  j                  j	                  |      g      S c c}w c c}w )zFConstructs Write object, which is needed for insert/update operations.c                 h    t        j                  t        j                  | j                              S rT   rV   rZ   s    r   r\   z*MutationFactory._GetWrite.<locals>._ToJson0  '    ))


		
24 4r   Nrc   r^   )columnsr   values)	r   rf   r(   WriteValuesValueListEntryGetJsonDatacol_name	col_valuer6   )r   r   ra   r\   json_columnscoljson_column_namesjson_column_valuess           r   r   zMutationFactory._GetWrite,  s    4'H'''HHNN//1 $$T*L1=>#>3?@<C#--<@88>>!jj33:L3MN  P P ?@s   C-Cc                 l   d } t        j                  |d      | j                  j                  j                         | j                  j                  | j                  j                  j	                  |j                  |            g      }| j                  j                  |j                  |      S )z?Constructs Delete object, which is needed for delete operation.c                 h    t        j                  t        j                  | j                              S rT   rV   rZ   s    r   r\   z+MutationFactory._GetDelete.<locals>._ToJsonF  r   r   Nrc   r^   )r   )r   keySet)r   rf   r(   KeySetKeysValueListEntryGetJsonKeysr8   r6   )r   r   r   r\   key_sets        r   r   zMutationFactory._GetDeleteA  s    
4'H'''HHOO..0 hhoo**1B1B41H*I$o G 88??G?<<r   N)__name__
__module____qualname____doc__r   r   r(   classmethodr   r   r8   r   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   ro   rG   objectr   r   r   r   <module>r      s    , &  ' % > ( ) ' , >.B0 B @D<A $'T-( "&'+%),1$N..!BHW=f W=r   