DEV Community

Cover image for 💩 Dump a PostgreSQL Database in .NET
Dusty Shaw
Dusty Shaw

Posted on

💩 Dump a PostgreSQL Database in .NET

Firstly, I apologize for the emoji. Secondly, database dumps can be useful for locally storing a snapshot of the current state of your database.
Database dumps can be used to spin up a representation of your database for testing or for other purposes.

In this scenario, I had already created a PostgreSQL database using DBeaver.

1. Create a PowerShell script

Create a PowerShell file called DatabaseDump.ps1 in the root of your project with the following code:

[cmdletbinding()]
param(
    [string]$server="<YOUR_DATABASE_SERVER",
    [int]$port=<YOUR_PORT>,
    [string]$database="<YOUR_DATABASE>",
    [parameter(Mandatory=$true)]
    [string]$user,
    [string]$password,
    [string]$localFolder=".",
    [string]$backupName=((get-date).ToString("yyyyMMdd.hh.mm.ss")+".sql"),
    [string]$schema="<YOUR_SCHEMA>"
)

if($password -eq $null) {
    $ss = read-host "Enter your password" -AsSecureString
    $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
}
docker run --rm -e PGPASSWORD=$password -v "$($localFolder):/usr/backupoutput" -it postgres pg_dump -h $server -p 5432 -U $user -f /usr/backupoutput/$backupName -d $database --schema=$schema
Enter fullscreen mode Exit fullscreen mode

This will create the database dump file in whatever directory the PowerShell file is in.

2. Run the PowerShell File from the command line

In Visual Studio 2022, run the file by entering in the command .\DatabaseDump.ps1.
It will ask for your username and password.
That's it! You should now have a SQL file that contains the DLL and creation scripts of your database.

💬 Comment below you're favorite way to dump :)

Top comments (0)