forked from sergiisyrovatchenko/SQLIndexManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCmdWorker.cs
More file actions
231 lines (191 loc) · 8.35 KB
/
Copy pathCmdWorker.cs
File metadata and controls
231 lines (191 loc) · 8.35 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using SQLIndexManager.Properties;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
namespace SQLIndexManager {
public class CmdWorker {
public CmdWorker(List<CmdArgument> args) {
Host host = new Host();
Settings.Options.IgnorePermissions = false;
Settings.Options.IgnoreReadOnlyFL = false;
foreach (CmdArgument cmd in args) {
switch (cmd.Argument) {
case "connection":
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(cmd.Params[0]);
host.Server = sb.DataSource;
host.AuthType = sb.IntegratedSecurity ? AuthTypes.Windows : AuthTypes.SqlServer;
host.User = sb.UserID;
if (!string.IsNullOrEmpty(sb.InitialCatalog)) {
host.Databases.Add(sb.InitialCatalog);
}
if (!sb.IntegratedSecurity) {
host.Password = sb.Password;
}
Settings.Options.ConnectionTimeout = sb.ConnectTimeout;
break;
case "databases":
host.Databases.Clear();
List<string> dbs = new List<string> (cmd.Params[0].Split(';'));
host.Databases.AddRange(dbs.Where(_ => !string.IsNullOrEmpty(_)).Distinct());
break;
case "connectiontimeout":
Settings.Options.ConnectionTimeout = Convert.ToInt32(cmd.Params[0]);
break;
case "commandtimeout":
Settings.Options.CommandTimeout = Convert.ToInt32(cmd.Params[0]);
break;
case "online":
Settings.Options.Online = true;
break;
case "ignoreheap":
Settings.Options.ScanHeap = false;
break;
case "ignorecolumnstore":
Settings.Options.ScanClusteredColumnstore = false;
Settings.Options.ScanNonClusteredColumnstore = false;
break;
case "ignorebtree":
Settings.Options.ScanClusteredIndex = false;
Settings.Options.ScanNonClusteredIndex = false;
break;
case "maxdop":
Settings.Options.MaxDop = Convert.ToInt32(cmd.Params[0]);
break;
case "rebuildthreshold":
Settings.Options.RebuildThreshold = Convert.ToInt32(cmd.Params[0]);
break;
case "reorganizethreshold":
Settings.Options.ReorganizeThreshold = Convert.ToInt32(cmd.Params[0]);
break;
case "minindexsize":
Settings.Options.MinIndexSize = Convert.ToInt32(cmd.Params[0]);
break;
case "predescribesize":
Settings.Options.PreDescribeSize = Convert.ToInt32(cmd.Params[0]);
break;
case "maxindexsize":
Settings.Options.MaxIndexSize = Convert.ToInt32(cmd.Params[0]);
break;
default:
throw new ArgumentException($"Unknown argument \"{cmd.Argument}\"");
}
}
if (host.Databases.Count == 0)
throw new ArgumentException("No database selected");
using (SqlConnection connection = Connection.Create(host)) {
try {
host.ServerInfo = QueryEngine.GetServerInfo(connection);
}
catch (Exception ex) {
throw new ArgumentException(ex.Message.Replace(". ", "." + Environment.NewLine));
}
finally {
connection.Close();
}
}
if (host.ServerInfo.MajorVersion < Server.Sql2008)
throw new ArgumentException(Resources.MinVersionMessage);
else
Settings.ActiveHost = host;
}
public int FixIndexes() {
Output.Current.Add($"Host: {Settings.ActiveHost}");
using (ConnectionList connectionList = new ConnectionList(Settings.ActiveHost)) {
List<Index> scanIndex = new List<Index>();
Stopwatch watch;
Stopwatch totalWatch = Stopwatch.StartNew();
foreach (var database in Settings.ActiveHost.Databases) {
List<Index> idx = new List<Index>();
watch = Stopwatch.StartNew();
SqlConnection connection = connectionList.Get(database);
if (connection == null) continue;
Output.Current.Add(new string('-', 150));
Output.Current.Add($"Describe: {database}");
short retries = 0;
while (true) {
try {
idx = QueryEngine.GetIndexes(connection);
break;
}
catch (SqlException ex) {
if (!ex.Message.Contains("timeout")) {
throw new ArgumentException($"Error: {ex.Source} {ex.Message}");
}
retries++;
if (retries > 2)
break;
}
}
watch.Stop();
Output.Current.Add($"Pre-describe: {(idx.Count(_ => _.Fragmentation != null))}. " +
$"Post-describe: {(idx.Count(_ => _.Fragmentation == null))}", null, watch.ElapsedMilliseconds);
List<int> clid = new List<int>();
foreach (Index index in idx.Where(_ => _.Fragmentation == null)
.OrderBy(_ => _.ObjectId)
.ThenBy(_ => _.IndexId)
.ThenBy(_ => _.PartitionNumber)) {
try {
connection = connectionList.Get(database);
if (connection == null) break;
if (index.IndexType == IndexType.ColumnstoreClustered || index.IndexType == IndexType.ColumnstoreNonClustered) {
if (!clid.Exists(_ => _ == index.ObjectId)) {
watch = Stopwatch.StartNew();
QueryEngine.GetColumnstoreFragmentation(connection, index, idx);
clid.Add(index.ObjectId);
watch.Stop();
Output.Current.Add(index.ToString(), null, watch.ElapsedMilliseconds);
}
}
else {
watch = Stopwatch.StartNew();
QueryEngine.GetIndexFragmentation(connection, index);
watch.Stop();
Output.Current.Add(index.ToString(), null, watch.ElapsedMilliseconds);
}
}
catch (Exception ex) {
Output.Current.Add($"Failed: {index}", ex.Message);
}
}
scanIndex.AddRange(idx);
}
var fixIndex = scanIndex.Where(_ => _.Fragmentation >= Settings.Options.ReorganizeThreshold
&& _.PagesCount >= Settings.Options.MinIndexSize.PageSize()
&& _.PagesCount <= Settings.Options.MaxIndexSize.PageSize()).ToList();
Output.Current.Add(new string('-', 150));
Output.Current.Add($"Processed: {scanIndex.Count}. Fragmented: {fixIndex.Count}", null, totalWatch.ElapsedMilliseconds);
if (fixIndex.Count > 0) {
totalWatch = Stopwatch.StartNew();
Output.Current.Add("Fix...");
foreach (Index ix in fixIndex) {
if (ix.Fragmentation < Settings.Options.RebuildThreshold && ix.IsAllowReorganize)
ix.FixType = IndexOp.Reorganize;
else if (Settings.Options.Online && ix.IsAllowOnlineRebuild)
ix.FixType = IndexOp.RebuildOnline;
else
ix.FixType = IndexOp.Rebuild;
watch = Stopwatch.StartNew();
SqlConnection connection = connectionList.Get(ix.DatabaseName);
if (connection != null) {
QueryEngine.FixIndex(connection, ix);
}
watch.Stop();
if (string.IsNullOrEmpty(ix.Error))
Output.Current.Add(ix.ToString(),
$"Fragmentation: {ix.Fragmentation:n2}%. " +
$"Size: {(Convert.ToDecimal(ix.PagesCountBefore) * 8).FormatSize()} -> {(Convert.ToDecimal(ix.PagesCount) * 8).FormatSize()}. " +
$"Saved: {(Convert.ToDecimal(ix.PagesCountBefore - ix.PagesCount) * 8).FormatSize()}", watch.ElapsedMilliseconds);
else
Output.Current.Add(ix.ToString(), ix.Error);
}
Output.Current.Add(new string('-', 150));
Output.Current.Add($"Processed: {fixIndex.Count(_ => string.IsNullOrEmpty(_.Error))}. " +
$"Errors: {fixIndex.Count(_ => !string.IsNullOrEmpty(_.Error))}", null, totalWatch.ElapsedMilliseconds);
}
}
return 0;
}
}
}