Created
July 28, 2017 23:53
-
-
Save otto-gebb/93d021c8fd300646dba0073a77585a94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.NOTES | |
Licensed under WTFPL, Version 2. | |
.SYNOPSIS | |
Extracts the DB-schema from the latest EF migration in the specified database. | |
.DESCRIPTION | |
Writes the extracted schema to the output file in the EDMX format. | |
The "(local)" server is used. | |
.PARAMETER Database | |
The database with EF migrations (in the __MigrationHistory table). | |
.PARAMETER OutFile | |
The file to write the schema to. | |
.LINK | |
Depends on the SQLPS module, see | |
http://guidestomicrosoft.com/2015/01/13/install-sql-server-powershell-module-sqlps/ | |
.Example | |
.\edmx-extract.ps1 -Database my_db -OutFile schema.edmx | |
#> | |
param ( | |
[parameter(mandatory=$true)][string]$Database, | |
[parameter(mandatory=$false)][string]$OutFile = $null | |
) | |
Push-Location | |
Import-Module sqlps -DisableNameChecking | |
Pop-Location | |
$sizeResult = Invoke-Sqlcmd -ServerInstance "(local)" -Database $Database -Query @" | |
SELECT TOP 1 | |
DATALENGTH([Model]) as Size | |
FROM [__MigrationHistory] | |
ORDER BY MigrationId DESC | |
"@ | |
$size = $sizeResult.Size | |
$x = Invoke-Sqlcmd -MaxBinaryLength $size -ServerInstance "(local)" -Database $Database -Query @" | |
SELECT TOP 1 | |
[MigrationId] | |
,[ContextKey] | |
,[Model] | |
,[ProductVersion] | |
FROM [__MigrationHistory] | |
ORDER BY MigrationId DESC | |
"@ | |
if (-not $OutFile) { | |
$OutFile = "$($x.MigrationId).edmx" | |
} | |
[System.IO.Directory]::SetCurrentDirectory(((Get-Location -PSProvider FileSystem).ProviderPath)) | |
$OutFile = [IO.Path]::GetFullPath($OutFile) | |
$bytes = $x.Model | |
$inp = New-Object System.IO.MemoryStream ($bytes, $false) | |
$output = New-Object System.IO.FileStream $OutFile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None) | |
$gzipStream = New-Object System.IO.Compression.GzipStream $inp, ([IO.Compression.CompressionMode]::Decompress) | |
try { | |
$buffer = New-Object byte[](1024); | |
while ($true) { | |
$read = $gzipStream.Read($buffer, 0, 1024) | |
if ($read -le 0) { | |
break; | |
} | |
$output.Write($buffer, 0, $read) | |
} | |
} | |
finally { | |
Write-Verbose "Closing streams and newly decompressed file" | |
$gzipStream.Close(); | |
$output.Close(); | |
$inp.Close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment