Database has always been an integral part of any application be it Web/Desktop/Mobile. If we give an eagle eye statement to what database is, it can be stated that "Database is a bucket where you can dump all your application data for future reuse". Since the inception of software development industry database has always played an important role, they have been in different formats such as file, binaries, most popular in form of database software such as MS SQL Server, MySQL, Oracle etc.
One of the most important aspects or better to say key pain areas for any application delivery is "how to keep database deployment aligned with application deployment". I remember not too long back, we used to create long scripts for database deployment and pass on to database administrator team, who then used to run them on post-development servers. And then long ping-pong of communication as script failed on other environments lots and lots of pain. Scary one... were the ones where DDL used to corrupt the database or used to hamper other systems using the same database.
With new DevOps way of project execution, we have reached a starting point where database and application deployment can be automated dramatically. This reduces the overhead from DBA and developers ***if you follow the rules :) *****
One of the key components of DevOps automation is reducing humans dependency by scripting every workflow requiring humans. In order show some light to that ideology I have been working on database backup and restore scripts using Powershell, below are the scenarios where this can help:
- Backup database pre-deployment and restore in case of deployment failure
- Version database snapshot with the application, for enabling backward and forward deployment
- Data persistence for disaster recovery
- Specific version rollback for DEV and Test environment

Below is the script which can be used for backup and restore MS SQL Server database. The beauty of the script is you can use the script standalone or inject in a DevOps pipeline process.
The script loads MS SQL Server objects from Gac for any execution of sql scripts or database object access- [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
- $QueryDB= " IF (EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE (name = '"+"$dbname"+"'))) BEGIN Select 1 AS IsDbExist END ELSE BEGIN Select 0 AS IsDbExist END"
- $CDDBCheck= Invoke-Sqlcmd -Query $QueryDB -ServerInstance $($ServerName) -Database $($dbname)
- if( $ExecutionType -eq "backup"){}
- $FileExists = Test-Path $DBBackupPath\$($buildID)
- if($FileExists -eq $False){
- Write-Output "************Folder with Build Id Created************"
- New-Item $DBBackupPath\$($buildID) -type directory
- }
- Backup-SqlDatabase -ServerInstance $($ServerName) -Database $($dbname) -BackupFile "$DBBackupPath\$($buildID)\$($buildID).bak"

Join the conversation! Your thoughts help the community grow.