-
Notifications
You must be signed in to change notification settings - Fork 11
/
AnsiDatabaseRepository.cs
279 lines (246 loc) · 9.25 KB
/
AnsiDatabaseRepository.cs
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
namespace Mite.Core
{
public abstract class AnsiDatabaseRepository : IDatabaseRepository
{
protected string tableName;
protected IDbConnection connection;
protected string filePath;
protected string delimiter = @"^GO";
public virtual void DropMigrationTable()
{
this.connection.Open();
var cmd = this.connection.CreateCommand();
cmd.CommandText = string.Format("drop table {0}", tableName);
cmd.ExecuteNonQuery();
this.connection.Close();
}
public abstract bool MigrationTableExists();
public abstract string GenerateSqlScript(bool includeData);
public abstract MigrationTracker Init();
public void Dispose()
{
connection.Dispose();
}
public IDbConnection Connection
{
get { return connection; }
set { connection = value; }
}
public virtual bool CheckConnection()
{
try
{
connection.Open();
return true;
}
catch (Exception)
{
return false;
}
finally
{
connection.Close();
}
}
public virtual MigrationTracker Create()
{
if (!DatabaseExists())
CreateDatabaseIfNotExists();
var hashes = new Dictionary<string, string>();
//read all the migrations from the database and filesystem and create a MigrationTracker
//this.DatabaseExists() &&
if (this.MigrationTableExists())
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = string.Format("select * from {0}", tableName);
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
hashes.Add(dr["key"].ToString(), dr["hash"].ToString());
}
}
connection.Close();
}
return new MigrationTracker(MigrationHelper.ReadFromDirectory(filePath).ToList(), hashes);
}
public virtual void WriteHash(Migration migration)
{
try
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = $"update {tableName} set `hash`='{migration.Hash}' where `key`='{migration.Version}'";
//TODO: Fix sql injection possibility
//cmd.CommandText = $"update {tableName} set `hash`=@hash where `key`=@key";
//var hashParam = cmd.CreateParameter();
//hashParam.Value = migration.Hash;
//hashParam.ParameterName = "@hash";
//hashParam.DbType = DbType.String;
//var keyParam = cmd.CreateParameter();
//keyParam.ParameterName = "@key";
//keyParam.Value = migration.Hash;
//keyParam.DbType = DbType.String;
//cmd.Parameters.Add(hashParam);
//cmd.Parameters.Add(keyParam);
Console.WriteLine(cmd.CommandText);
cmd.ExecuteNonQuery();
connection.Close();
}catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public virtual MigrationTracker RecordMigration(Migration migration)
{
if (!MigrationTableExists())
{
Init();
}
connection.Open();
var cmd = GetMigrationCmd(migration);
cmd.ExecuteNonQuery();
connection.Close();
return Create();
}
/// <summary>
/// Create a database if it doesn't exists. Throw exception if the database already exists. Used to create a temporary database for verification
/// </summary>
public abstract void CreateDatabaseIfNotExists();
public virtual void DropDatabase()
{
using (var conn = GetConnWithoutDatabaseSpecified())
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "drop database " + this.DatabaseName;
cmd.ExecuteNonQuery();
conn.Close();
}
}
public virtual MigrationTracker ExecuteUp(Migration migration)
{
if (!MigrationTableExists())
Init();
connection.Open();
using (var trans = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var split = new Regex(delimiter, RegexOptions.Multiline | RegexOptions.IgnoreCase);
var statements = split.Split(migration.UpSql);
foreach (var sql in statements)
{
if (string.IsNullOrWhiteSpace(sql))
continue;
try
{
var cmd = connection.CreateCommand();
cmd.Transaction = trans;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Fail executing sql -> {0}", sql);
throw;
}
}
var migrationCmd = GetMigrationCmd(migration);
migrationCmd.Transaction = trans;
migrationCmd.ExecuteNonQuery();
trans.Commit();
}
connection.Close();
return Create();
}
protected abstract IDbCommand GetMigrationCmd(Migration migration);
public virtual MigrationTracker ExecuteDown(Migration migration)
{
if (!MigrationTableExists())
Init();
connection.Open();
using (var trans = connection.BeginTransaction())
{
var split = new Regex(delimiter, RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (var sql in split.Split(migration.DownSql))
{
if (string.IsNullOrEmpty(sql))
continue;
var cmd = connection.CreateCommand();
cmd.Transaction = trans;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
var migrationCmd = connection.CreateCommand();
migrationCmd.Transaction = trans;
migrationCmd.CommandText = string.Format("delete from {0} where `key` = @version", tableName);
var version = migrationCmd.CreateParameter();
version.ParameterName = "version";
version.Value = migration.Version;
migrationCmd.Parameters.Add(version);
migrationCmd.ExecuteNonQuery();
trans.Commit();
}
connection.Close();
return Create();
}
public string DatabaseName
{
get { return connection.Database; }
set
{
connection.Open();
connection.ChangeDatabase(value);
connection.Close();
}
}
public abstract IDbConnection GetConnWithoutDatabaseSpecified();
public virtual bool DatabaseExists()
{
try
{
bool result = false;
using (var conn = GetConnWithoutDatabaseSpecified())
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
var cmd = conn.CreateCommand();
cmd.CommandText = "use " + DatabaseName;
try
{
cmd.ExecuteNonQuery();
result = true;
}
catch (Exception ex)
{
result = false;
}
finally
{
conn.Close();
}
}
return result;
}
catch (Exception ex)
{
return true; //assume it does and proceed.
}
}
public void ForceWriteMigration(Migration migration)
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = $"insert into {tableName} (`key`, `hash`) values('{migration.Version}', '{migration.Hash}')";
cmd.ExecuteNonQuery();
connection.Close();
}
}
}