public async Task UpdateDatabaseWithDefaultLeaderAsync(string projectId, string instanceId, string databaseId, string defaultLeader)
    {
        DatabaseAdminClient databaseAdminClient = await DatabaseAdminClient.CreateAsync();

        var alterDatabaseStatement = @$ "ALTER DATABASE `{databaseId}` SET OPTIONS
                   (default_leader = '{defaultLeader}')";

        // Create the UpdateDatabaseDdl request and execute it.
        var request = new UpdateDatabaseDdlRequest
        {
            DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
            Statements             = { alterDatabaseStatement }
        };
        var operation = await databaseAdminClient.UpdateDatabaseDdlAsync(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 updating database: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }
        Console.WriteLine("Updated default leader");
    }
        private bool HasResourcePrefixHeader(CallSettings callSettings)
        {
            var expectedDatabaseName = DatabaseName.FromProjectInstanceDatabase(
                SpannerClientHelpers.ProjectId, SpannerClientHelpers.Instance,
                SpannerClientHelpers.Database);

            var metadata = new Metadata();
            callSettings.HeaderMutation?.Invoke(metadata);
            Metadata.Entry entry = Assert.Single(metadata, e => e.Key == SpannerClientImpl.ResourcePrefixHeader);
            return expectedDatabaseName.ToString() == entry.Value;
        }
Exemple #3
0
        private static async Task SetupAsync(EmulatorRunner emulatorRunner)
        {
            Console.WriteLine("");
            Console.WriteLine("Starting emulator...");
            emulatorRunner.StartEmulator().WaitWithUnwrappedExceptions();
            Console.WriteLine("");

            DatabaseName databaseName = DatabaseName.FromProjectInstanceDatabase(s_projectId, s_instanceId, s_databaseId);

            await MaybeCreateInstanceOnEmulatorAsync(databaseName.ProjectId, databaseName.InstanceId);
            await MaybeCreateDatabaseOnEmulatorAsync(databaseName);
        }
Exemple #4
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);
    }
        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);
        }
Exemple #6
0
    public async Task <List <string> > GetDatabaseDdlAsync(string projectId, string instanceId, string databaseId)
    {
        DatabaseAdminClient databaseAdminClient = await DatabaseAdminClient.CreateAsync();

        DatabaseName databaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId);
        var          databaseDdl  = await databaseAdminClient.GetDatabaseDdlAsync(databaseName);

        var ddlStatements = new List <string>();

        Console.WriteLine($"DDL statements for database {databaseId}:");
        foreach (var statement in databaseDdl.Statements)
        {
            Console.WriteLine(statement);
            ddlStatements.Add(statement);
        }

        return(ddlStatements);
    }
    public async Task <Backup> CreateBackupWithEncryptionKeyAsync(string projectId, string instanceId, string databaseId, string backupId, CryptoKeyName kmsKeyName)
    {
        // Create a DatabaseAdminClient instance.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

        // Create the CreateBackupRequest with encryption configuration.
        CreateBackupRequest request = new CreateBackupRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            BackupId             = backupId,
            Backup = new Backup
            {
                DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
                ExpireTime             = DateTime.UtcNow.AddDays(14).ToTimestamp(),
            },
            EncryptionConfig = new CreateBackupEncryptionConfig
            {
                EncryptionType            = CreateBackupEncryptionConfig.Types.EncryptionType.CustomerManagedEncryption,
                KmsKeyNameAsCryptoKeyName = kmsKeyName,
            },
        };
        // Execute the CreateBackup request.
        var operation = await databaseAdminClient.CreateBackupAsync(request);

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

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

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

        var backup = completedResponse.Result;

        Console.WriteLine($"Backup {backup.Name} of size {backup.SizeBytes} bytes " +
                          $"was created at {backup.CreateTime} " +
                          $"using encryption key {kmsKeyName}");
        return(backup);
    }
        public static object SpannerCancelBackupOperation(
            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()
            };
            InstanceName parentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId);

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

            // Cancel the operation.
            operation.Cancel();

            // Poll until the long-running operation is complete since the backup wasn't
            // cancelled before it was created.
            Console.WriteLine("Waiting for the operation to finish.");
            Operation <Backup, CreateBackupMetadata> completedOperation =
                operation.PollUntilCompleted();

            if (!completedOperation.IsFaulted)
            {
                Console.WriteLine("Delete backup because it completed before it could be cancelled.");
                BackupName backupAsBackupName =
                    BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);
                databaseAdminClient.DeleteBackup(backupAsBackupName);
            }

            Console.WriteLine($"Create backup operation cancelled: {operation.Name}");
            return(0);
        }
    public async Task <long> CustomTimeoutsAndRetriesAsync(string projectId, string instanceId, string databaseId)
    {
        // Create a SessionPool.
        SpannerClient client      = SpannerClient.Create();
        SessionPool   sessionPool = new SessionPool(client, new SessionPoolOptions());

        // Acquire a session with a read-write transaction to run a query.
        DatabaseName databaseName =
            DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId);
        TransactionOptions transactionOptions = new TransactionOptions
        {
            ReadWrite = new ReadWrite()
        };

        using PooledSession session = await sessionPool.AcquireSessionAsync(
                  databaseName, transactionOptions, CancellationToken.None);

        ExecuteSqlRequest request = new ExecuteSqlRequest
        {
            Sql = "INSERT Singers (SingerId, FirstName, LastName) VALUES (20, 'George', 'Washington')"
        };

        // Prepare the call settings with custom timeout and retry settings.
        CallSettings settings = CallSettings
                                .FromExpiration(Expiration.FromTimeout(TimeSpan.FromSeconds(60)))
                                .WithRetry(RetrySettings.FromExponentialBackoff(
                                               maxAttempts: 12,
                                               initialBackoff: TimeSpan.FromMilliseconds(500),
                                               maxBackoff: TimeSpan.FromMilliseconds(6400),
                                               backoffMultiplier: 1.5,
                                               retryFilter: RetrySettings.FilterForStatusCodes(
                                                   new StatusCode[] { StatusCode.Unavailable, StatusCode.DeadlineExceeded })));

        ResultSet result = await session.ExecuteSqlAsync(request, settings);

        await session.CommitAsync(new CommitRequest(), null);

        return(result.Stats.RowCountExact);
    }
        internal static async Task RunSampleAsync(Func <string, Task> sampleMethod)
        {
            Environment.SetEnvironmentVariable("SPANNER_EMULATOR_HOST", "localhost:9010");
            var emulatorRunner = new EmulatorRunner();

            try
            {
                Console.WriteLine("");
                Console.WriteLine("Starting emulator...");
                emulatorRunner.StartEmulator().WaitWithUnwrappedExceptions();
                Console.WriteLine("");

                var          projectId               = "sample-project";
                var          instanceId              = "sample-instance";
                var          databaseId              = "sample-database";
                DatabaseName databaseName            = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId);
                var          dataSource              = $"Data Source={databaseName}";
                var          connectionStringBuilder = new SpannerConnectionStringBuilder(dataSource)
                {
                    EmulatorDetection = EmulatorDetection.EmulatorOnly,
                };
                await MaybeCreateInstanceOnEmulatorAsync(databaseName.ProjectId, databaseName.InstanceId);
                await MaybeCreateDatabaseOnEmulatorAsync(databaseName);

                await sampleMethod.Invoke(connectionStringBuilder.ConnectionString);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Running sample failed: {e.Message}");
            }
            finally
            {
                Console.WriteLine("");
                Console.WriteLine("Stopping emulator...");
                emulatorRunner.StopEmulator().WaitWithUnwrappedExceptions();
                Console.WriteLine("");
            }
        }
Exemple #11
0
        internal static async Task RunSampleApp()
        {
            // Set the SPANNER_EMULATOR_HOST environment variable for this process. This
            // ensures that the Entity Framework provider will connect to the emulator
            // instead of to the real Google Cloud Spanner. Remove this line if you want
            // to test the application against a real Spanner database.
            Environment.SetEnvironmentVariable("SPANNER_EMULATOR_HOST", "localhost:9010");
            var emulatorRunner = new EmulatorRunner();

            try
            {
                // This starts an in-mem emulator and creates the sample database.
                await SetupAsync(emulatorRunner);

                // Create the connection string that will be used.
                DatabaseName databaseName     = DatabaseName.FromProjectInstanceDatabase(s_projectId, s_instanceId, s_databaseId);
                var          dataSource       = $"Data Source={databaseName}";
                var          connectionString = new SpannerConnectionStringBuilder(dataSource)
                {
                    EmulatorDetection = EmulatorDetection.EmulatorOrProduction,
                }.ConnectionString;
                Console.WriteLine($"Connecting to database {connectionString}");

                // Create a DbContext that uses our sample Spanner database.
                using var context = new SpannerTutorialContext(connectionString);
                var singer = new Singer
                {
                    SingerId  = Guid.NewGuid(),
                    FirstName = "Bob",
                    LastName  = "Allison",
                };
                context.Singers.Add(singer);
                var album = new Album
                {
                    AlbumId = Guid.NewGuid(),
                    Title   = "Let's Go",
                    Singer  = singer,
                };
                context.Albums.Add(album);
                var track = new Track
                {
                    Album   = album,
                    TrackId = 1L,
                    Title   = "Go, Go, Go",
                };
                context.Tracks.Add(track);

                // This saves all the above changes in one transaction.
                Console.WriteLine($"Writing Singer, Album and Track to the database");
                var count = await context.SaveChangesAsync();

                Console.WriteLine($"{count} records written to the database\n");

                // Get a single entity. Note that the primary key of Track consists
                // of both the parent AlbumId and the Id of the Track.
                var foundTrack = await context.Tracks.FindAsync(album.AlbumId, 1L);

                Console.WriteLine($"Found track {track.Title}");
                // You can use LINQ to query the data that was written.
                var singers = await context.Singers
                              .Where(s => s.FullName == "Bob Allison")
                              .ToListAsync();

                Console.WriteLine($"Found {singers.Count} singer(s) with full name {singers.First().LastName}");
            }
            finally
            {
                Console.WriteLine("");
                Console.WriteLine("Stopping emulator...");
                emulatorRunner.StopEmulator().WaitWithUnwrappedExceptions();
                Console.WriteLine("");
            }
        }