How to export SQL Database directly to blob storage programmatically

前端 未结 4 2048
野性不改
野性不改 2020-12-20 02:40

I need to programmatically backup/export a SQL Database (either in Azure, or a compatible-one on-prem) to Azure Storage, and restore it to another SQL Database. I would lik

4条回答
  •  爱一瞬间的悲伤
    2020-12-20 03:23

    Here's an idea:

    Pass the stream to the .ExportBacPac method but hold a reference to it on a different thread where you regularly empty and reset the stream so that there's no memory overflow. I'm assuming here, that Dac does not have any means to access the stream while it is being filled.

    The thing you have to take care of yourself though is thread safety - MemoryStreams are not thread safe by default. So you'd have to write your own locking mechanisms around .Position and .CopyTo. I've not tested this, but if you handle locking correctly I'd assume the .ExportBacPac method won't throw any errors while the other thread accesses the stream.

    Here's a very simple example as pseudo-code just outlining my idea:

    ThreadSafeStream stream = new ThreadSafeStream();
    
    Task task = new Task(async (exitToken) => {
        MemoryStream partialStream = new MemoryStream();
    
        // Check if backup completed
        if (...) 
        {
             exitToken.Trigger();
        }
    
        stream.CopyToThreadSafe(partialStream);
        stream.PositionThreadSafe = 0;
    
        AzureService.UploadToStorage(partialStream);
    
        await Task.Delay(500); // Play around with this - it shouldn't take too long to copy the stream
    });
    
    services.ExportBacpac(stream, "dbnameToBackup");
    
    await TimerService.RunTaskPeriodicallyAsync(task, 500); 
    

提交回复
热议问题