-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSql.ps1
184 lines (165 loc) · 5.25 KB
/
Sql.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
function ExecuteScript() {
param(
[parameter(mandatory=$true)]
[System.Data.SqlClient.SqlConnection]$SqlConnection,
[parameter(mandatory=$true)]
$sqlScript,
[hashtable]$variables = $NULL)
if( test-path $sqlScript -erroraction SilentlyContinue ) {
$sqlScriptFile = $sqlScript
$lines = Get-Content $sqlScript
} else {
$sqlScriptFile = "unknown"
$lines = $sqlScript.Split( "`r`n" )
}
$lines += "GO"
$Query = ""
$batchNumber = 0
$batchLines = 0
for ( $lineNumber = 0; $lineNumber -lt $lines.Length; $lineNumber++ ) {
if( $lines[$lineNumber] -match '^\s*GO\s*$' ) {
$batchNumber++
$Query = EvaluateSqlScriptVariables $Query $variables
$Query = $Query.Trim()
if( $Query.Length -eq 0 ) {
continue
}
try {
$null = ExecuteNonQuery $SqlConnection $Query
} catch {
$msg = New-Object "System.Text.StringBuilder"
$null = $msg.AppendLine( "Error executing batch #" + $batchNumber + ": " + $_ )
$null = $msg.AppendLine( "At " + $sqlScriptFile + ":" + ($lineNumber - $batchLines + 1) + " to " + $lineNumber )
$null = $msg.AppendLine( "===BATCH START===" )
$null = $msg.AppendLine( $Query )
$null = $msg.AppendLine( "===BATCH END===" )
throw $msg.ToString()
}
$Query = ""
$batchLines = 0
continue
}
$Query += $lines[$lineNumber]
$Query += [Environment]::NewLine
$batchLines++
}
}
function EvaluateSqlScriptVariables( [string]$sqlScriptText, [hashtable]$variables = $NULL )
{
if( !$variables -or $variables.Count -eq 0 ) { return $sqlScriptText }
if ($variables -and $variables.Count -gt 0) {
foreach($key in $variables.keys) {
$val = $variables[$key]
Write-Debug "Evaluating \$\($key\) to $val"
$sqlScriptText = $sqlScriptText -replace "\$\($key\)", $val
}
}
return $sqlScriptText
}
function ExecuteNonQuery( $SqlConnection, $CommandText )
{
$SqlCommand = DbCommand $SqlConnection $CommandText
try {
try {
return $SqlCommand.ExecuteNonQuery()
} catch {
$msg = New-Object "System.Text.StringBuilder"
$null = $msg.AppendLine( "Error executing sql: " + $_ )
$null = $msg.AppendLine( "===BATCH START===" )
$null = $msg.AppendLine( $CommandText )
$null = $msg.AppendLine( "===BATCH END===" )
throw $msg.ToString()
}
} finally {
$SqlCommand.Dispose()
}
}
function ExecuteScalar( $SqlConnection, $CommandText )
{
$SqlCommand = DbCommand $SqlConnection $CommandText
try {
return $SqlCommand.ExecuteScalar()
} finally {
$SqlCommand.Dispose()
}
}
function ExecuteTable( $SqlConnection, $CommandText )
{
$cmd = DbCommand $SqlConnection $CommandText
try {
$adapter = new-object System.Data.SqlClient.SqlDataAdapter
$adapter.SelectCommand = $cmd
$ds = new-object System.Data.DataSet
$rows = $adapter.Fill( $ds )
return $ds.Tables[0]
} finally {
$cmd.Dispose()
}
}
function DbExists( [string]$Server='(local)', [string]$Database, [string]$Username = $NULL, [string]$Password = $NULL )
{
$conn = DbConnect $server "master" $username $password
try {
$compatlevel = ExecuteScalar $conn "SELECT compatibility_level FROM sys.databases WHERE name = '$Database'"
if( $compatlevel -ne $null ) {
Write-Verbose "Database $database exists on server $server ( compat level = $compatlevel )"
return $true
} else { return $false }
} finally {
$conn.Dispose()
}
}
function DbConnect( [string]$Server='(local)', [string]$Database='master', [string]$Username = $NULL, [string]$Password = $NULL )
{
if( [String]::IsNullOrEmpty( $Database ) ) {
$Database = "master"
}
# handles the InfoMessage event so we can print any status
# information back out to the screen
$SqlConnection_InfoMessage = [System.Data.SqlClient.SqlInfoMessageEventHandler]{
foreach ( $SqlError in $_.Errors ) {
if ( $SqlError.Class -eq 0 ) {
Write-Host $SqlError.Message
} else {
Write-Warning $SqlError.Message + ($SqlError | select * -ex Message | Out-String)
}
}
}
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = BuildConnectionString $Server $Database $Username $Password
Write-Verbose "Using connection string '$($SqlConnection.ConnectionString)'"
$SqlConnection.add_InfoMessage($SqlConnection_InfoMessage)
try {
$SqlConnection.Open()
} catch {
throw "Failed to open SQL connection to '$server', database '$database': $_"
}
return $SqlConnection
}
function DbCommand( $SqlConnection = $(throw "Not a valid connection"), $CommandText )
{
if( $SqlConnection -eq $null )
{
throw "Invalid connection. Connection is null"
}
if( [String]::IsNullOrEmpty( $CommandText ) )
{
throw "Command text is null or empty"
}
$SqlCommand = New-Object System.Data.SqlClient.SqlCommand
$SqlCommand.Connection = $SqlConnection
# 30 min timeout required for long running commands such as BACKUP DATABASE
$SqlCommand.CommandTimeout = 1800
$SqlCommand.CommandText = $CommandText
$SqlCommand.CommandType = 'Text'
Write-Verbose "Creating command for: $CommandText"
return $SqlCommand
}
function BuildConnectionString( $server, $database, $username, $password )
{
if( [String]::IsNullOrEmpty( $Username ) -or $Password -eq $NULL ) {
return "Server=$server;Database=$database;Trusted_Connection=True;"
} else {
return "Server=$Server;Database=$database;UID=$Username;PWD=$Password"
}
}