
    2                     X   S r SSKrSSKrSSKrSSKJr  SSKJr  SSKJ	r	  SSKJ
r
  SSKJr  SSKJr  SS	KJr  S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 rS r S r!S r"S r#\RH                   " S S\RJ                  5      5       r&g)z!Command for spanner samples init.    N)
exceptions)database_operations)database_sessions)	databases)	instances)storage_api)storage_util)base)
ddl_parser)samples)log)
properties)	resources)progress_tracker)files)retryc           	           [         R                  " U 5        g! [        R                   a-    [	        [
        R                  " SR                  U S95      5      ef = f)z*Raise if the given instance doesn't exist.z        Instance '{instance_id}' does not exist. Create it with:

        $ gcloud spanner instances create {instance_id}
        instance_idN)r   Getapitools_exceptionsHttpNotFoundError
ValueErrortextwrapdedentformatr   s    #lib/surface/spanner/samples/init.pycheck_instancer   )   sT    .MM+		.	. .
  F{F+		-. ..s
    AAc                 v   [         R                  " 5       n[        R                  R	                  [
        R                  5      n[        R                  R                  U[
        R                  " U 5      5      [
        R                  " U 5      4/nUR                  U[
        R                  " U 5      S9n[
        R                  " U 5      nU H  nUR                  R                  S5      S   (       d  M(  [        R                  R!                  U5      n["        R$                  R'                  XVR                  R                  S5      S   5      nUR)                  Xg45        M     [
        R*                  " U 5      (       a  [
        R,                  " U 5      nUR                  X(S9n	U	 H  n
[        R                  R!                  U
5      nUR                  R/                  S5      (       a  MD  [
        R0                  " U 5      n["        R$                  R'                  XR                  R                  S5      S   5      nUR)                  X45        M     [3        S U 5       5      (       a  [4        R6                  R9                  SR;                  U 5      5        U H  u  pg[4        R6                  R9                  SR;                  U5      5        ["        R$                  R                  U5      S   n["        R$                  R=                  U5      (       d  [>        R@                  " U5        URC                  XgSS	9  M     g
g
)zDownload schema and binaries for the given sample app.

If the schema and all binaries exist already, skip download. If any file
doesn't exist, download them all.

Args:
  appname: The name of the sample app, should exist in samples.APP_NAMES
)prefix/c              3   n   #    U  H+  u  p[         R                  R                  U5      (       + v   M-     g 7f)N)ospathexists).0_	file_paths      r   	<genexpr>(download_sample_files.<locals>.<genexpr>a   s%     H<<1RWW^^I&	&	&<s   35z'Downloading files for the {} sample appzDownloading {}r   T)	overwriteN)"r   StorageClientr	   BucketReferenceFromUrlr   
GCS_BUCKETObjectReferenceFromBucketRefget_gcs_schema_nameget_local_schema_path
ListBucketget_gcs_bin_prefixget_local_bin_pathnamesplitFromMessager$   r%   joinappendhas_sample_data_statements%get_gcs_data_insert_statements_prefixendswith%get_local_data_insert_statements_pathanyr   statusPrintr   r&   r   MakeDirCopyFileFromGCS)appnamestorage_client
bucket_refgcs_to_localgcs_bin_msgsbin_pathgcs_ref
local_pathinsert_pathgcs_insert_filesinsert_fileinsert_file_refdata_local_path	local_dirs                 r   download_sample_filesrT   6   s    ,,..++33G4F4FG*  //=='--g68009; <,  **33G< + >,''0(g<<c"2&**66w?Gh(:(:3(?(CDJ-.  ''00??HK%000P'$44@@Mo 
			&	&s	+	+EEgNo77<<
//55c:2>j ?78 ( 	H<HHHJJ>EEgNO+	jj'..z:;''--
+A.iWW^^I&&i $$WD$I  , I    c           
          [         R                  " U UUUS9$ ! [        R                   a7    [	        [
        R                  " SR                  XR                  S95      5      e[        R                   a4  n[	        [        R                  " UR                  5      S   S   5      eSnAf[         a    [	        SR                  U5      5      ef = f)z2Wrapper over databases.Create with error handling.)database_dialectz        Database '{database_id}' exists already. Delete it with:

        $ gcloud spanner databases delete {database_id} --instance={instance_id}
        )database_idr   errormessageNzFailed to create database '{}'.)r   Creater   HttpConflictErrorr   r   r   r   instancesId	HttpErrorjsonloadscontent	Exception)instance_refrX   
statementsrW   exs        r   _create_db_oprf   k   s    L)	+ +
 
	.	. M
  F#1I1I  K		LM M 
	&	& A
TZZ

+G4Y?
@@	 L
6==kJ
KKLs    AC6/B%%(Cc                 x   [         R                  " U 5      (       d  [        SR                  U 5      5      e[        R
                  " U5      nUR                  S5       HZ  nU(       d  M  UR                  S5      (       d  M$  [        R                  " SS9R                  [        R                  USU/S SS	9  M\     g
)z3Read and execute all insert statements in one file.{} cannot pre-populate data.
INSERT   )max_retrialsNORMALc                     g)NT )exc_typeargss     r   <lambda>0insert_sample_data_in_one_file.<locals>.<lambda>   s    rU   i  )rq   should_retry_ifsleep_msN)r   r=   r   r   r   ReadFileContentsr9   
startswithr   RetryerRetryOnExceptionr   
ExecuteSql)rF   	file_namesession_refinsert_statementsinsert_statements        r   insert_sample_data_in_one_filer      s    		+	+G	4	4
3::7C
DD,,Y7+11$7&&x00 
MMq!22$$+64	 3  8rU   c                 j   [         R                  " U 5      (       d  [        SR                  U 5      5      e[        R
                  " SR                  U5      SS9   [        R                  " [         R                  " U 5      5      nU H  n[        U UU5        M     SSS5        g! , (       d  f       g= f)zInsert sample data.rh   zPopulating data into `{}`z#Aborting wait for data population.
)aborted_messageN)
r   r=   r   r   r   ProgressTrackerr   GetDirectoryTreeListingr@   r   )rF   rX   r|   
data_files	data_files        r   insert_sample_datar      s    		+	+G	4	4
3::7C
DD''!((5< ..55g>J  	$


    s   AB$$
B2c                 6   [         R                  " U 5      n[         R                  " U 5      n[        R                  " U5      nU[
        R                  :X  at  / nSR                  UR                  S5       Vs/ s H  owR                  S5      (       a  M  UPM     sn5      nUR                  S5       Vs/ s H  o(       d  M  UPM     n	nO[        R                  " U5      n/ n	[        XUU5      n
[        R                  " U
SR                  U5      5        U	(       as  [         R"                  R%                  UUR&                  UR(                  S.SS9n[
        R*                  " X5      n[        R                  " USR                  U5      5        g	g	s  snf s  snf )
z;Create the DB if it doesn't exist already, raise otherwise.ri   z--;zCreating database '{}'r]   
projectsId$spanner.projects.instances.databasesparams
collectionzUpdating database '{}'N)r   r4   get_database_dialectr   rv   r   DATABASE_DIALECT_POSTGRESQLr;   r9   rw   r   PreprocessDDLWithParserrf   r   Awaitr   r   REGISTRYParser]   r   	UpdateDdl)rF   rc   rX   schema_filerW   schema
create_ddllinestmt
update_ddl	create_opdatabase_ref	update_ops                r   check_create_dbr      se   --g6+11':!!+.& >>>JYY ,,t,J,$OOD4I,JLF $*<<#4=#44$#4J=J33F;JJLz,.)I4;;KHJ%%++'33&11
 : , ;L ##L=Ii6==kJL  	K >s   7FF4
FFc                   V    \ rS rSrSrS\R                  " S5      0r\S 5       r	S r
Srg)	Init   zInitialize a Cloud Spanner sample app.

This command creates a Cloud Spanner database in the given instance for the
sample app and loads any initial data required by the application.
EXAMPLESaC            To initialize the 'finance' sample app using instance
          'my-instance', run:

          $ {command} finance --instance-id=my-instance

          To initialize the 'finance-graph' sample app using instance
          'my-instance', run:

          $ {command} finance-graph --instance-id=my-instance
        c                 z    U R                  SSS9  U R                  SS[        SS9  U R                  S[        S	S
9  g)zArgs is called by calliope to gather arguments for this command.

Args:
  parser: An argparse parser that you can use to add arguments that go on
    the command line after this command. Positional arguments are allowed.
rF   z5The sample app name, e.g. "finance", "finance-graph".)help--instance-idTz1The Cloud Spanner instance ID for the sample app.)requiredtyper   --database-idzBID of the new Cloud Spanner database to create for the sample app.)r   r   N)add_argumentstr)parsers    r   Args	Init.Args   s_     O   @	  B
   rU   c                    UR                   n [        R                  " U5        UR                  n[        R                  R                  US[        R                  R                  R                  R                  0SS9nUR                  b  UR                  nO[        R                   " U5      n["        R$                  R'                  SR)                  U5      5         [+        U5        [-        U5        ["        R$                  R'                  SR)                  XbS	95         [/        X%U5        [        R0                  " U5      (       a  [        R                  R                  UUR2                  UR4                  S.SS9n[6        R8                  " U5      n[        R                  R;                  UR<                  SS9n	 [?        X&U	5        [@        RB                  " S5      [6        RD                  " U	5        $ SR)                  X$S9n
UR                  b  U
SR)                  U5      -  n
[@        RB                  " SR)                  U
5      5      $ ! [         a  n[        R
                  " SU5      eSnAff = f! [         a  n[        R
                  " SU5      eSnAff = f! [         a  n[        R
                  " S
U5      eSnAff = f! [F         a    [I        S5      ef = f! [6        RD                  " U	5        f = f)zThis is what gets called when the user runs this command.

Args:
  args: an argparse namespace. All the arguments that were provided to this
    command invocation.

Returns:
  Some value that we want to have printed later.
APPNAMENr   zspanner.projects.instancesr   zChecking instance '{}'r   z@Initializing database '{database_id}' for sample app '{appname}')rX   rF   r   r   r   z-spanner.projects.instances.databases.sessions)relative_namer   zG            Initialization done for your Spanner database.
            zKFailed to insert data for the database. Please fallback to manually insert.z%{appname} --instance-id={instance_id})rF   r   z --database-id {}z          Initialization done. Next, start the backend gRPC service with:

          $ gcloud spanner samples backend {}
          )%rF   r   check_appnamer   calliope_exceptionsBadArgumentExceptionr   r   r   r   r   VALUEScoreproject	GetOrFailrX   get_db_id_for_appr   rB   rC   r   r   rT   r   r=   r]   r   r   r[   ParseRelativeNamer8   r   r   r   Deleterb   SystemError)selfrq   rF   re   r   rc   rX   r   sessionr|   backend_argss              r   RunInit.Run   s    llGDG$ ""K%%++*++0088BB
 0 , 1L #$$k--g6k JJ-44[ABJ[! '" JJJ	K	9;Jg[9 ))'22''--
)55(33 < . l "((6g&&88D 9 k.7=     	  -<CC D l 
			%+22;??__  f\"	$ $K  D44YCCD(  J44_bIIJ  J44_bIIJ&  

 	

 	  -se   I I1 J ;K K 
I.I))I.1
J;JJ
K $J;;K KK K4ro   N)__name__
__module____qualname____firstlineno____doc__r   r   detailed_helpstaticmethodr   r   __static_attributes__ro   rU   r   r   r      s=     (// 
# 
-  *V$rU   r   )'r   r_   r$   r   apitools.base.pyr   r   googlecloudsdk.api_lib.spannerr   r   r   r   googlecloudsdk.api_lib.storager   r	   googlecloudsdk.callioper
   r   "googlecloudsdk.command_lib.spannerr   r   googlecloudsdk.corer   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   r   rT   rf   r   r   r   DefaultUniverseOnlyCommandr   ro   rU   r   <module>r      s    (  	  > > < 4 4 6 7 ( E 9 6 # * ) 8 * *
.2JjL,,(%LP A$4<< A$ A$rU   