Ejemplo n.º 1
0
        public static object SpannerRestoreDatabase(
            string projectId, string instanceId, string databaseId, string backupId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            InstanceName parentAsInstanceName =
                InstanceName.FromProjectInstance(projectId, instanceId);
            BackupName backupAsBackupName =
                BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);

            // Make the RestoreDatabase request.
            Operation <Database, RestoreDatabaseMetadata> response =
                databaseAdminClient.RestoreDatabase(
                    parentAsInstanceName, databaseId, backupAsBackupName);

            Console.WriteLine("Waiting for the operation to finish");

            // Poll until the returned long-running operation is complete.
            var completedResponse = response.PollUntilCompleted();

            if (completedResponse.IsFaulted)
            {
                Console.WriteLine($"Database Restore Failed: {completedResponse.Exception}");
                return(1);
            }

            RestoreInfo restoreInfo = completedResponse.Result.RestoreInfo;

            Console.WriteLine(
                $"Database {restoreInfo.BackupInfo.SourceDatabase} was restored " +
                $"to {databaseId} from backup {restoreInfo.BackupInfo.Backup}");

            return(0);
        }
Ejemplo n.º 2
0
        public static object SpannerGetBackupOperations(string projectId, string instanceId, string databaseId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            var filter =
                $"(metadata.database:{databaseId}) AND " +
                "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata)";
            ListBackupOperationsRequest request = new ListBackupOperationsRequest
            {
                ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
                Filter = filter
            };

            // List the create backup operations on the database.
            var backupOperations = databaseAdminClient.ListBackupOperations(request);

            foreach (var operation in backupOperations)
            {
                CreateBackupMetadata metadata = operation.Metadata.Unpack <CreateBackupMetadata>();
                Console.WriteLine(
                    $"Backup {metadata.Name} on " +
                    $"database {metadata.Database} is " +
                    $"{metadata.Progress.ProgressPercent}% complete");
            }

            return(0);
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Deletes 5 oldest databases if the number of databases is more than 94.
    /// This is to avoid resource exhausted errors.
    /// </summary>
    private async Task DeleteStaleDatabasesAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = databaseAdminClient.ListDatabases(instanceName);

        if (databases.Count() < 95)
        {
            return;
        }

        var databasesToDelete = databases
                                .OrderBy(db => long.TryParse(
                                             db.DatabaseName.DatabaseId.Replace("my-db-", "").Replace("my-restore-db-", ""),
                                             out long creationDate) ? creationDate : long.MaxValue)
                                .Take(5);

        // Delete the databases.
        foreach (var database in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(database.DatabaseName.DatabaseId);
            }
            catch (Exception) { }
        }
    }
Ejemplo n.º 4
0
        private static int Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2)
            {
                Console.WriteLine("Arguments: <project ID> [instance ID]");
                Console.WriteLine("A default instance ID of 'spannerintegration' will be used if not specified.");
                return(1);
            }
            string projectId    = args[0];
            string instanceId   = args.Length == 2 ? args[1] : "spannerintegration";
            var    client       = DatabaseAdminClient.Create();
            var    instanceName = new InstanceName(projectId, instanceId);
            var    databases    = client.ListDatabases(instanceName).ToList();

            foreach (var database in databases)
            {
                var name = DatabaseName.Parse(database.Name);
                if (name.DatabaseId.StartsWith("testdb"))
                {
                    Console.WriteLine($"Dropping {name.DatabaseId}");
                    client.DropDatabase(name);
                }
            }
            return(0);
        }
        /// <summary>Snippet for CreateDatabase</summary>
        public void CreateDatabase_RequestObject()
        {
            // Snippet: CreateDatabase(CreateDatabaseRequest,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            CreateDatabaseRequest request = new CreateDatabaseRequest
            {
                ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
                CreateStatement      = "",
            };
            // Make the request
            Operation <Database, CreateDatabaseMetadata> response =
                databaseAdminClient.CreateDatabase(request);

            // Poll until the returned long-running operation is complete
            Operation <Database, CreateDatabaseMetadata> completedResponse =
                response.PollUntilCompleted();
            // Retrieve the operation result
            Database result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Database, CreateDatabaseMetadata> retrievedResponse =
                databaseAdminClient.PollOnceCreateDatabase(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Database retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
    private async Task DeleteStaleDatabasesAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = databaseAdminClient.ListDatabases(instanceName, pageSize: 200).ToList();

        if (databases.Count < 50)
        {
            return;
        }

        var deleteCount = Math.Max(30, databases.Count - 50);

        var databasesToDelete = databases
                                .OrderBy(db => long.TryParse(
                                             db.DatabaseName.DatabaseId
                                             .Replace("my-db-", "").Replace("my-restore-db-", "")
                                             .Replace("my-enc-db-", "").Replace("my-enc-restore-db-", ""),
                                             out long creationDate) ? creationDate : long.MaxValue)
                                .Take(deleteCount);

        // Delete the databases.
        foreach (var database in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(database.DatabaseName.DatabaseId);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to delete stale test database {database.DatabaseName.DatabaseId}: {e.Message}");
            }
        }
    }
Ejemplo n.º 7
0
        public static object SpannerUpdateBackup(string projectId, string instanceId, string backupId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            // Retrieve existing backup.
            BackupName backupName =
                BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);
            Backup backup = databaseAdminClient.GetBackup(backupName);

            // Add 14 days to the existing ExpireTime.
            backup.ExpireTime = backup.ExpireTime.ToDateTime().AddDays(14).ToTimestamp();

            UpdateBackupRequest backupUpdateRequest = new UpdateBackupRequest
            {
                UpdateMask = new FieldMask()
                {
                    Paths =
                    {
                        "expire_time"
                    }
                },
                Backup = backup
            };

            // Make the UpdateBackup requests.
            var updatedBackup = databaseAdminClient.UpdateBackup(backupUpdateRequest);

            Console.WriteLine($"Updated Backup ExpireTime: {updatedBackup.ExpireTime}");

            return(0);
        }
Ejemplo n.º 8
0
        public static void DelelteDatabases()
        {
            string adminConnectionString = $"Data Source=projects/{projectId}/"
                                           + $"instances/{instanceId}";

            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            InstanceName        instanceName        = InstanceName.FromProjectInstance(projectId, instanceId);
            var databases = databaseAdminClient.ListDatabases(instanceName);

            using (var connection = new SpannerConnection(adminConnectionString))
                foreach (var database in databases)
                {
                    using (var cmd = connection.CreateDdlCommand($@"DROP DATABASE {database.DatabaseName.DatabaseId}"))
                    {
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
        }
Ejemplo n.º 9
0
    public IEnumerable <Operation> ListDatabaseOperations(string projectId, string instanceId)
    {
        // Create the DatabaseAdminClient instance.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

        var filter = "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)";

        ListDatabaseOperationsRequest request = new ListDatabaseOperationsRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            Filter = filter
        };

        // List the optimize restored databases operations on the instance.
        var operations = databaseAdminClient.ListDatabaseOperations(request);

        foreach (var operation in operations)
        {
            OptimizeRestoredDatabaseMetadata metadata =
                operation.Metadata.Unpack <OptimizeRestoredDatabaseMetadata>();
            Console.WriteLine(
                $"Database {metadata.Name} restored from backup is {metadata.Progress.ProgressPercent}% optimized.");
        }

        return(operations);
    }
        /// <summary>Snippet for UpdateDatabaseDdl</summary>
        public void UpdateDatabaseDdl_RequestObject()
        {
            // Snippet: UpdateDatabaseDdl(UpdateDatabaseDdlRequest,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            UpdateDatabaseDdlRequest request = new UpdateDatabaseDdlRequest
            {
                DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
                Statements             = { },
            };
            // Make the request
            Operation <Empty, UpdateDatabaseDdlMetadata> response =
                databaseAdminClient.UpdateDatabaseDdl(request);

            // Poll until the returned long-running operation is complete
            Operation <Empty, UpdateDatabaseDdlMetadata> completedResponse =
                response.PollUntilCompleted();
            // The long-running operation is now complete.

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Empty, UpdateDatabaseDdlMetadata> retrievedResponse =
                databaseAdminClient.PollOnceUpdateDatabaseDdl(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // The long-running operation is now complete.
            }
            // End snippet
        }
Ejemplo n.º 11
0
        public void UpdateDatabaseDdl()
        {
            // Snippet: UpdateDatabaseDdl(string,IEnumerable<string>,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            string formattedDatabase        = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString();
            IEnumerable <string> statements = new List <string>();
            // Make the request
            Operation <Empty> response =
                databaseAdminClient.UpdateDatabaseDdl(formattedDatabase, statements);

            // Poll until the returned long-running operation is complete
            Operation <Empty> completedResponse =
                response.PollUntilCompleted();
            // The long-running operation is now complete.

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Empty> retrievedResponse =
                databaseAdminClient.PollOnceUpdateDatabaseDdl(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // The long-running operation is now complete.
            }
            // End snippet
        }
    /// <summary>
    /// Deletes 10 oldest backups if the number of backups is more than 89.
    /// This is to avoid resource exhausted errors.
    /// </summary>
    private async Task DeleteStaleBackupsAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var backups      = databaseAdminClient.ListBackups(instanceName);

        if (backups.Count() < 90)
        {
            return;
        }

        var backupsToDelete = backups
                              .OrderBy(db => long.TryParse(
                                           db.BackupName.BackupId.Replace("my-enc-backup-", ""),
                                           out long creationDate) ? creationDate : long.MaxValue)
                              .Take(10);

        // Delete the backups.
        foreach (var backup in backupsToDelete)
        {
            try
            {
                await databaseAdminClient.DeleteBackupAsync(backup.BackupName);
            }
            catch (Exception) { }
        }
    }
Ejemplo n.º 13
0
    public IEnumerable <Database> GetDatabases()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        InstanceName        instanceName        = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases = databaseAdminClient.ListDatabases(instanceName);

        return(databases);
    }
Ejemplo n.º 14
0
    private async Task DeleteStaleBackupsAndDatabasesAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = databaseAdminClient.ListDatabases(instanceName)
                           .Where(c => c.DatabaseName.DatabaseId.StartsWith("my-db-") || c.DatabaseName.DatabaseId.StartsWith("my-restore-db-"));
        var databasesToDelete = new List <string>();

        // Delete all the databases created before 48 hrs.
        var timestamp = DateTimeOffset.UtcNow.AddHours(-48).ToUnixTimeMilliseconds();

        foreach (var database in databases)
        {
            var databaseId = database.DatabaseName.DatabaseId.Replace("my-restore-db-", "").Replace("my-db-", "");
            if (long.TryParse(databaseId, out long dbCreationTime) && dbCreationTime <= timestamp)
            {
                databasesToDelete.Add(database.DatabaseName.DatabaseId);
            }
        }

        await Console.Out.WriteLineAsync($"{databasesToDelete.Count} old databases found.");

        // Get backups.
        ListBackupsRequest request = new ListBackupsRequest
        {
            ParentAsInstanceName = instanceName,
            Filter = $"database:my-db-"
        };
        var backups = databaseAdminClient.ListBackups(request);

        // Backups that belong to the databases to be deleted.
        var backupsToDelete = backups.Where(c => databasesToDelete.Contains(DatabaseName.Parse(c.Database).DatabaseId));

        await Console.Out.WriteLineAsync($"{backupsToDelete.Count()} old backups found.");

        // Delete the backups.
        foreach (var backup in backupsToDelete)
        {
            try
            {
                DeleteBackupSample deleteBackupSample = new DeleteBackupSample();
                deleteBackupSample.DeleteBackup(ProjectId, InstanceId, backup.BackupName.BackupId);
            }
            catch (Exception) { }
        }

        // Delete the databases.
        foreach (var databaseId in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(databaseId);
            }
            catch (Exception) { }
        }
    }
 /// <summary>Snippet for GetDatabaseDdl</summary>
 public void GetDatabaseDdl()
 {
     // Snippet: GetDatabaseDdl(DatabaseName,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]");
     // Make the request
     GetDatabaseDdlResponse response = databaseAdminClient.GetDatabaseDdl(database);
     // End snippet
 }
 /// <summary>Snippet for GetIamPolicy</summary>
 public void GetIamPolicy()
 {
     // Snippet: GetIamPolicy(string,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     string formattedResource = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString();
     // Make the request
     Policy response = databaseAdminClient.GetIamPolicy(formattedResource);
     // End snippet
 }
 /// <summary>Snippet for TestIamPermissions</summary>
 public void TestIamPermissions()
 {
     // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     string formattedResource         = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString();
     IEnumerable <string> permissions = new List <string>();
     // Make the request
     TestIamPermissionsResponse response = databaseAdminClient.TestIamPermissions(formattedResource, permissions);
     // End snippet
 }
 /// <summary>Snippet for SetIamPolicy</summary>
 public void SetIamPolicy()
 {
     // Snippet: SetIamPolicy(string,Policy,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     string formattedResource = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString();
     Policy policy            = new Policy();
     // Make the request
     Policy response = databaseAdminClient.SetIamPolicy(formattedResource, policy);
     // End snippet
 }
Ejemplo n.º 19
0
    public void DeleteBackup(string projectId, string instanceId, string backupId)
    {
        // Create the DatabaseAdminClient instance.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

        // Make the DeleteBackup request.
        BackupName backupName = BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);

        databaseAdminClient.DeleteBackup(backupName);

        Console.WriteLine("Backup deleted successfully.");
    }
Ejemplo n.º 20
0
        public void DropDatabase()
        {
            // Snippet: DropDatabase(string,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            string formattedDatabase = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString();

            // Make the request
            databaseAdminClient.DropDatabase(formattedDatabase);
            // End snippet
        }
Ejemplo n.º 21
0
    public void TestCreateBackup()
    {
        var databaseAdminClient = DatabaseAdminClient.Create();
        var database            = databaseAdminClient.GetDatabase(DatabaseName.FromProjectInstanceDatabase(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.BackupDatabaseId));
        var earliestVersionTime = database.EarliestVersionTime.ToDateTime();

        CreateBackupSample createBackupSample = new CreateBackupSample();
        // Backup already exists since it was created in the test setup so it should throw an exception.
        var exception = Assert.Throws <RpcException>(()
                                                     => createBackupSample.CreateBackup(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.BackupDatabaseId, _spannerFixture.BackupId, earliestVersionTime));

        Assert.Equal(StatusCode.AlreadyExists, exception.StatusCode);
    }
Ejemplo n.º 22
0
    public IEnumerable <Database> ListDatabases(string projectId, string instanceId)
    {
        var databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName        = InstanceName.FromProjectInstance(projectId, instanceId);
        var databases           = databaseAdminClient.ListDatabases(instanceName);

        foreach (var database in databases)
        {
            Console.WriteLine($"Default leader for database {database.DatabaseName.DatabaseId}: {database.DefaultLeader}");
        }

        return(databases);
    }
Ejemplo n.º 23
0
    public async Task <Database> CreateDatabaseWithEncryptionKeyAsync(string projectId, string instanceId, string databaseId, CryptoKeyName kmsKeyName)
    {
        // Create a DatabaseAdminClient instance that can be used to execute a
        // CreateDatabaseRequest with custom encryption configuration options.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        // Define create table statement for table #1.
        var createSingersTable =
            @"CREATE TABLE Singers (
                     SingerId INT64 NOT NULL,
                     FirstName STRING(1024),
                     LastName STRING(1024),
                     ComposerInfo BYTES(MAX)
                 ) PRIMARY KEY (SingerId)";
        // Define create table statement for table #2.
        var createAlbumsTable =
            @"CREATE TABLE Albums (
                     SingerId INT64 NOT NULL,
                     AlbumId INT64 NOT NULL,
                     AlbumTitle STRING(MAX)
                 ) PRIMARY KEY (SingerId, AlbumId),
                 INTERLEAVE IN PARENT Singers ON DELETE CASCADE";

        // Create the CreateDatabase request with encryption configuration and execute it.
        var request = new CreateDatabaseRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            CreateStatement      = $"CREATE DATABASE `{databaseId}`",
            ExtraStatements      = { createSingersTable, createAlbumsTable },
            EncryptionConfig     = new EncryptionConfig
            {
                KmsKeyNameAsCryptoKeyName = kmsKeyName,
            },
        };
        var operation = await databaseAdminClient.CreateDatabaseAsync(request);

        // Wait until the operation has finished.
        Console.WriteLine("Waiting for the operation to finish.");
        var completedResponse = await operation.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating database: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        var database = completedResponse.Result;

        Console.WriteLine($"Database {database.Name} created with encryption key {database.EncryptionConfig.KmsKeyName}");

        return(database);
    }
 /// <summary>Snippet for GetIamPolicy</summary>
 public void GetIamPolicy_RequestObject()
 {
     // Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     GetIamPolicyRequest request = new GetIamPolicyRequest
     {
         Resource = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(),
     };
     // Make the request
     Policy response = databaseAdminClient.GetIamPolicy(request);
     // End snippet
 }
 /// <summary>Snippet for GetDatabaseDdl</summary>
 public void GetDatabaseDdl_RequestObject()
 {
     // Snippet: GetDatabaseDdl(GetDatabaseDdlRequest,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     GetDatabaseDdlRequest request = new GetDatabaseDdlRequest
     {
         DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
     };
     // Make the request
     GetDatabaseDdlResponse response = databaseAdminClient.GetDatabaseDdl(request);
     // End snippet
 }
 /// <summary>Snippet for SetIamPolicy</summary>
 public void SetIamPolicy_RequestObject()
 {
     // Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     SetIamPolicyRequest request = new SetIamPolicyRequest
     {
         Resource = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(),
         Policy   = new Policy(),
     };
     // Make the request
     Policy response = databaseAdminClient.SetIamPolicy(request);
     // End snippet
 }
 /// <summary>Snippet for TestIamPermissions</summary>
 public void TestIamPermissions_RequestObject()
 {
     // Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings)
     // Create client
     DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
     // Initialize request argument(s)
     TestIamPermissionsRequest request = new TestIamPermissionsRequest
     {
         Resource    = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(),
         Permissions = { },
     };
     // Make the request
     TestIamPermissionsResponse response = databaseAdminClient.TestIamPermissions(request);
     // End snippet
 }
        /// <summary>Snippet for DropDatabase</summary>
        public void DropDatabase_RequestObject()
        {
            // Snippet: DropDatabase(DropDatabaseRequest,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            DropDatabaseRequest request = new DropDatabaseRequest
            {
                DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
            };

            // Make the request
            databaseAdminClient.DropDatabase(request);
            // End snippet
        }
        /// <summary>Snippet for ListDatabases</summary>
        public void ListDatabases_RequestObject()
        {
            // Snippet: ListDatabases(ListDatabasesRequest,CallSettings)
            // Create client
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            // Initialize request argument(s)
            ListDatabasesRequest request = new ListDatabasesRequest
            {
                ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
            };
            // Make the request
            PagedEnumerable <ListDatabasesResponse, Database> response =
                databaseAdminClient.ListDatabases(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Database item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListDatabasesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Database item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int             pageSize   = 10;
            Page <Database> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Database item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 30
0
        public static object SpannerCreateBackup(
            string projectId, string instanceId, string databaseId, string backupId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            // Initialize request parameters.
            Backup backup = new Backup
            {
                DatabaseAsDatabaseName =
                    DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
                ExpireTime  = DateTime.UtcNow.AddDays(14).ToTimestamp(),
                VersionTime = DateTime.UtcNow.ToTimestamp(),
            };
            InstanceName parentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId);

            // Make the CreateBackup request.
            Operation <Backup, CreateBackupMetadata> response =
                databaseAdminClient.CreateBackup(parentAsInstanceName, backup, backupId);

            Console.WriteLine("Waiting for the operation to finish.");

            // Poll until the returned long-running operation is complete.
            Operation <Backup, CreateBackupMetadata> completedResponse =
                response.PollUntilCompleted();

            if (completedResponse.IsFaulted)
            {
                Console.WriteLine($"Error while creating backup: {completedResponse.Exception}");
                return(1);
            }

            Console.WriteLine($"Backup created successfully.");

            // GetBackup to get more information about the created backup.
            BackupName backupName =
                BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);

            backup = databaseAdminClient.GetBackup(backupName);
            Console.WriteLine($"Backup {backup.Name} of size {backup.SizeBytes} bytes " +
                              $"was created at {backup.CreateTime} from {backup.Database} " +
                              $"and is in state {backup.State}" +
                              $"and has version time {backup.VersionTime}");
            return(0);
        }