OpenSource » Database Migrator » Migrator2
Clone URL:  

Migrator Got the sql provider tests running, refactored the way assembly guids are handled.
Made it so that GetColumns returns a more full column definition. Used to only fill out the name.

Working on a new SQLite Provider. Not done yet.

Changeset ed2e87f1c1d8

Parent d9d8922c8e68

by jasoncline

Changes to 11 files · Browse files at ed2e87f1c1d8 Showing diff from parent d9d8922c8e68 Diff from another changeset...

 
165
166
167
168
 
169
170
171
 
165
166
167
 
168
169
170
171
@@ -165,7 +165,7 @@
  #region Private helper methods   private Assembly GetAssembly()   { - return Assembly.LoadFrom(_migrationsAssembly); ; + return Assembly.LoadFrom(_migrationsAssembly);   }     private Migration GetBeginMigration()
 
11
12
13
 
 
14
15
16
 
137
138
139
 
 
 
 
 
 
 
140
141
 
 
 
 
 
142
143
 
11
12
13
14
15
16
17
18
 
139
140
141
142
143
144
145
146
147
148
149
 
150
151
152
153
154
155
156
@@ -11,6 +11,8 @@
 using Migrator.Providers;  using Migrator.Loggers;  using System.Collections.Generic; +using System.Runtime.InteropServices; +using System;    namespace Migrator  { @@ -137,7 +139,18 @@
  }   }   + internal void Prepare(Providers.TransformationProvider _provider,Dictionary<string,Providers.TransformationProvider> dictionary,Dictionary<string,string> dictionary_2) + { + TransformationProvider = _provider; + Databases = this._additionalProviders; + Parameters = this._parameters; + TransformationProvider.Timeout = null; + var guidAttribute = (GuidAttribute)Attribute.GetCustomAttribute(this.GetType().Assembly, typeof(GuidAttribute));   - } + if (guidAttribute == null || guidAttribute.Value == null || guidAttribute.Value.Trim().Equals(String.Empty)) + throw new ArgumentException("No guid identifier detected for migration"); + TransformationProvider.AssemblyId = guidAttribute.Value; + } + }    }
 
47
48
49
50
 
 
 
 
 
 
 
 
51
52
53
54
55
 
 
 
 
 
 
 
56
57
58
59
 
 
 
 
 
 
 
60
61
62
63
 
 
 
 
 
 
64
65
66
67
 
 
 
 
 
 
68
69
70
 
76
77
78
 
 
 
 
 
 
79
80
81
 
104
105
106
107
108
109
110
 
117
118
119
 
 
 
 
 
 
 
 
 
 
120
121
122
123
 
 
 
 
 
 
 
 
 
124
125
126
127
128
129
130
131
132
133
 
136
137
138
139
140
141
142
143
144
145
 
161
162
163
 
 
 
164
165
166
 
192
193
194
 
 
 
195
196
197
 
333
334
335
336
 
337
338
339
 
524
525
526
527
528
529
530
531
532
 
 
 
 
 
 
533
534
535
 
562
563
564
565
566
567
568
569
 
 
570
571
572
 
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
 
109
110
111
112
113
114
115
116
117
118
119
120
 
143
144
145
 
146
147
148
 
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
 
192
193
194
 
 
 
 
195
196
197
 
213
214
215
216
217
218
219
220
221
 
247
248
249
250
251
252
253
254
255
 
391
392
393
 
394
395
396
397
 
582
583
584
 
 
 
 
 
 
585
586
587
588
589
590
591
592
593
 
620
621
622
 
 
 
 
 
623
624
625
626
627
@@ -47,24 +47,57 @@
  #endregion     #region Constructors - public Migrator(TransformationProvider defaultProvider, Dictionary<string, TransformationProvider> additionalProviders, Assembly migrationAssembly, ILogger logger) + /// <summary> + /// + /// </summary> + /// <param name="defaultProvider"></param> + /// <param name="additionalProviders"></param> + /// <param name="migrationAssembly"></param> + /// <param name="logger"></param> + public Migrator(TransformationProvider defaultProvider, Dictionary<string, TransformationProvider> additionalProviders, Assembly migrationAssembly, ILogger logger)   : this(defaultProvider, migrationAssembly, logger)   {   this._additionalProviders = additionalProviders;   }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="connectionString"></param> + /// <param name="migrationAssembly"></param> + /// <param name="logger"></param>   public Migrator(string provider, string connectionString, Assembly migrationAssembly, ILogger logger)   : this(CreateProvider(provider, connectionString), migrationAssembly, logger)   { }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="connectionString"></param> + /// <param name="migrationAssembly"></param> + /// <param name="trace"></param>   public Migrator(string provider, string connectionString, Assembly migrationAssembly, bool trace)   : this(CreateProvider(provider, connectionString), migrationAssembly, new Log4NetLogger())   { }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="connectionString"></param> + /// <param name="migrationAssembly"></param>   public Migrator(string provider, string connectionString, Assembly migrationAssembly)   : this(CreateProvider(provider, connectionString), migrationAssembly, new Log4NetLogger())   { }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="migrationAssembly"></param> + /// <param name="trace"></param>   public Migrator(TransformationProvider provider, Assembly migrationAssembly, bool trace)   : this(provider, migrationAssembly, new Log4NetLogger())   { } @@ -76,6 +109,12 @@
  : this(CreateProvider(provider, connectionString), Assembly.GetExecutingAssembly(), new Log4NetLogger())   { }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="migrationAssembly"></param> + /// <param name="logger"></param>   public Migrator(TransformationProvider provider, Assembly migrationAssembly, ILogger logger)   {   _provider = provider; @@ -104,7 +143,6 @@
  }   this._allProviders.Add(_provider);   - AssemblyGuid = (GuidAttribute)Attribute.GetCustomAttribute(migrationAssembly, typeof(GuidAttribute));     // only load the migrations for the given assembly   if (migrationAssembly != null) @@ -117,17 +155,35 @@
  CheckForDuplicatedVersion();   }   + /// <summary> + /// / + /// </summary> + /// <param name="provider"></param> + /// <param name="connectionString"></param> + /// <param name="migrations"></param> + /// <param name="beginMigration"></param> + /// <param name="endMigration"></param> + /// <param name="assemblyAttribute"></param> + /// <param name="logger"></param>   public Migrator(string provider, string connectionString, ArrayList migrations, Migration beginMigration, Migration endMigration, GuidAttribute assemblyAttribute, ILogger logger)   : this(CreateProvider(provider, connectionString), migrations, beginMigration, endMigration, assemblyAttribute, logger)   { }   + /// <summary> + /// + /// </summary> + /// <param name="provider"></param> + /// <param name="migrations"></param> + /// <param name="beginMigration"></param> + /// <param name="endMigration"></param> + /// <param name="assemblyAttribute"></param> + /// <param name="logger"></param>   public Migrator(TransformationProvider provider, ArrayList migrations, Migration beginMigration, Migration endMigration, GuidAttribute assemblyAttribute, ILogger logger)   {   logger = logger ?? new Log4NetLogger();   _provider = provider;   _logger = logger;   _provider.Logger = _logger; - AssemblyGuid = assemblyAttribute;   BeginMigration = beginMigration ?? new NullMigration();   EndMigration = endMigration ?? new NullMigration();   MigrationsTypes.AddRange(migrations); @@ -136,10 +192,6 @@
    #region Properties   /// <summary> - /// The id of the assembly that migrations are being run - /// </summary> - public GuidAttribute AssemblyGuid { get; set; } - /// <summary>   /// The migration that will be run before all others...everytime   /// </summary>   public Migration BeginMigration { get; set; } @@ -161,6 +213,9 @@
  }   }   + /// <summary> + /// + /// </summary>   public Dictionary<string, string> MigrationParameters   {   get { return this._parameters; } @@ -192,6 +247,9 @@
  set { _logger = value; }   }   + /// <summary> + /// + /// </summary>   public string ConnectionString   {   get @@ -333,7 +391,7 @@
  /// If <c>version</c> lower then the current version,   /// the <c>Down()</c> method of previous migration will be invoked.   /// </summary> - /// <param name="version">Version that you wish the database to be at the end of the migration</param> + /// <param name="toVersion">Version that you wish the database to be at the end of the migration</param>   public void MigrateTo(int toVersion)   {   int originalVersion = this.CurrentVersion; @@ -524,12 +582,12 @@
  throw new Exception("No migrations found");   }   - // Enshure that the Schema Info table is created - GuidAttribute guid = AssemblyGuid; - if (guid != null) - _provider.CreateSchemaInfoTable(guid.Value); - else - _provider.CreateSchemaInfoTable(); + //// Enshure that the Schema Info table is created + //GuidAttribute guid = AssemblyGuid; + //if (guid != null) + // _provider.CreateSchemaInfoTable(guid.Value); + //else + // _provider.CreateSchemaInfoTable();     // Print a list of loaded Migrations   _logger.Trace("Loaded migrations:"); @@ -562,11 +620,8 @@
  private Migration InitializeMigration(Migration migration)   {   // initialize Migration variables injected from the Migrator - migration.TransformationProvider = _provider; - _provider.Timeout = null; // reset the Timeout to the default value - migration.Databases = this._additionalProviders; - migration.Parameters = this._parameters; - return migration; + migration.Prepare(_provider, this._additionalProviders, this._parameters); + return migration;   }   #endregion  
 
48
49
50
 
 
 
 
 
 
51
52
53
 
68
69
70
 
71
72
73
 
84
85
86
 
87
88
89
 
48
49
50
51
52
53
54
55
56
57
58
59
 
74
75
76
77
78
79
80
 
91
92
93
94
95
96
97
@@ -48,6 +48,12 @@
  <ItemGroup>   <Reference Include="System" />   <Reference Include="System.Data" /> + <Reference Include="System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86"> + <HintPath>..\..\lib\System.Data.SQLite.DLL</HintPath> + </Reference> + <Reference Include="System.Data.SQLite.Linq, Version=2.0.38.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL"> + <HintPath>..\..\lib\System.Data.SQLite.Linq.dll</HintPath> + </Reference>   <Reference Include="System.Xml" />   <Reference Include="log4net">   <HintPath>..\..\lib\log4net.dll</HintPath> @@ -68,6 +74,7 @@
  </Reference>   </ItemGroup>   <ItemGroup> + <Compile Include="AssemblyInfo.cs" />   <Compile Include="Column.cs" />   <Compile Include="DuplicatedVersionException.cs" />   <Compile Include="IrreversibleMigrationException.cs" /> @@ -84,6 +91,7 @@
  <Compile Include="Migrator.cs" />   <Compile Include="NullMigration.cs" />   <Compile Include="Providers\CascadeBehavior.cs" /> + <Compile Include="Providers\SqliteServerTransformationProvider.cs" />   <Compile Include="Providers\MySqlTransformationProvider.cs" />   <Compile Include="Providers\PostgreSQLTransformationProvider.cs" />   <Compile Include="Providers\ProviderFactory.cs" />
 
16
17
18
19
20
21
 
 
 
22
23
24
 
16
17
18
 
 
 
19
20
21
22
23
24
@@ -16,9 +16,9 @@
  public MySqlTransformationProvider(string constr)   {   _connectionString = constr; - _connection = new MySqlConnection(_connectionString); - _connection.ConnectionString = _connectionString; - _connection.Open(); + Connection = new MySqlConnection(_connectionString); + Connection.ConnectionString = _connectionString; + Connection.Open();   }     public override void AlterColumn(string table, string column, Type type, int size)
 
13
14
15
16
17
 
 
18
19
20
 
13
14
15
 
 
16
17
18
19
20
@@ -13,8 +13,8 @@
  public PostgreSQLTransformationProvider(string constr)   {   _connectionString = constr; - _connection = new NpgsqlConnection(_connectionString); - _connection.Open(); + Connection = new NpgsqlConnection(_connectionString); + Connection.Open();   }   public override void AlterColumn(string table, string column, Type type, int size)   { throw new NotImplementedException("Not implemented in " + this.GetType().ToString()); }
 
23
24
25
26
27
28
29
30
31
32
33
34
 
 
35
36
37
 
348
349
350
351
 
 
 
352
353
354
355
 
 
 
 
 
 
 
 
 
 
 
356
357
358
359
360
361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
363
364
 
479
480
481
 
 
482
483
484
 
589
590
591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
593
594
 
23
24
25
 
26
27
28
29
 
 
 
 
30
31
32
33
34
 
345
346
347
 
348
349
350
351
352
353
 
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
 
510
511
512
513
514
515
516
517
 
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
@@ -23,15 +23,12 @@
  /// </summary>   public class SqlServerTransformationProvider : TransformationProvider   { - private string _connectionString;   private const string OWNER = "[dbo].";     public SqlServerTransformationProvider(string connectionString)   { - _connectionString = connectionString; - _connection = new SqlConnection(); - _connection.ConnectionString = _connectionString; - _connection.Open(); + Connection = new System.Data.SqlClient.SqlConnection(connectionString); + Connection.Open();   }     public override void AddTable(string name, params Column[] columns) @@ -348,17 +345,51 @@
  {   ArrayList columns = new ArrayList();   - using (IDataReader reader = ExecuteQuery(string.Format("select COLUMN_NAME from information_schema.columns where table_name = '{0}';", table))) + var pkey = ColumnsWithConstraint(table, "PRIMARY KEY"); + + using (IDataReader reader = ExecuteQuery(string.Format("select * from information_schema.columns where table_name = '{0}';", table)))   {   while (reader.Read())   { - columns.Add(new Column(reader[0].ToString(), typeof(string))); + var name = reader["COLUMN_NAME"].ToString(); + var isNullable = reader["IS_NULLABLE"].ToString() == "YES"; + var col_default = reader["COLUMN_DEFAULT"].ToString(); + var col_type = reader["DATA_TYPE"].ToString(); + int? max_length = reader["CHARACTER_MAXIMUM_LENGTH"] as int?; + Type actualType = FromSqlType(col_type); + var colProperties = isNullable ? ColumnProperties.Null : ColumnProperties.NotNull; + + if (pkey.Contains(name)) + colProperties = ColumnProperties.PrimaryKey; + columns.Add(new Column(name, actualType, max_length.HasValue ? max_length.Value : 0, colProperties, col_default));   }   }     return (Column[])columns.ToArray(typeof(Column));   }   + private List<String> ColumnsWithConstraint(String table, String constraintType) + { + List<String> columns = new List<string>(); + var query =String.Format( @" + declare @TableName varchar(128) + select @TableName = '{0}' + + select c.COLUMN_NAME + from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk , + INFORMATION_SCHEMA.KEY_COLUMN_USAGE c + where pk.TABLE_NAME = @TableName + and CONSTRAINT_TYPE = '{1}' + and c.TABLE_NAME = pk.TABLE_NAME + and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", table, constraintType); + using(var reader = ExecuteQuery(query)) + while (reader.Read()) + { + columns.Add(reader.GetString(0)); + } + return columns; + } +   public override int Insert(string table, string[] columns, params object[] values)   {   if (columns.Length != values.Length) @@ -479,6 +510,8 @@
  return string.Join(" ", new string[] { col.Name, sqlType, sqlDefault, sqlIdentity, sqlConstraint });   }   + +   /// <summary>   /// Gets the SQL for a value   /// </summary> @@ -589,6 +622,35 @@
  throw new NotSupportedException("Type not supported : " + type.Name);   }   } + + + private Dictionary<string, Type> _type_conversion_map = new Dictionary<string, Type> { + {"ntext", typeof(string)}, + {"text", typeof(string)}, + {"nvarchar", typeof(string)}, + {"varchar", typeof(string)}, + {"int", typeof(int)}, + {"bigint", typeof(long)}, + {"real", typeof(float)}, + {"bit", typeof(bool)}, + {"datetime", typeof(DateTime)}, + {"nchar", typeof(char)}, + {"uniqueidentifier", typeof(Guid)}, + {"image", typeof(byte[])}, + }; + + /// <summary> + /// Gets the .net type from an SQL type + /// </summary> + /// <param name="type"></param> + /// <returns></returns> + private Type FromSqlType(String type) + { + if (_type_conversion_map.ContainsKey(type)) + return _type_conversion_map[type]; + + throw new ArgumentException(); + }   #endregion     public override void AddUniqueConstraint(string constraint, string table, params string[] columns)
 
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
280
 
 
 
 
 
 
 
 
 
 
 
281
282
 
 
 
 
 
 
 
283
284
285
286
287
288
289
290
291
292
293
294
 
 
 
 
 
 
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
 
315
316
317
318
319
320
321
322
 
 
 
 
 
 
 
 
 
 
 
323
324
325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
327
 
 
 
 
 
 
 
328
329
 
 
330
331
 
332
333
334
 
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
 
355
356
357
358
359
360
361
362
 
 
363
364
365
366
367
368
369
370
371
372
373
374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
376
377
378
379
380
381
382
 
 
 
 
 
 
 
383
384
385
386
387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
389
390
391
392
393
394
 
 
 
 
395
396
397
398
399
 
 
 
 
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
416
417
418
419
420
421
 
 
 
 
 
 
422
423
424
 
 
425
426
 
427
428
429
430
431
 
 
 
 
 
 
 
 
 
 
 
 
 
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
 
 
 
 
 
 
 
452
453
454
455
456
457
458
459
 
 
 
 
 
 
 
 
 
 
 
 
 
460
461
462
463
464
465
466
467
468
469
470
471
472
473
 
 
 
 
 
 
 
 
 
 
474
475
476
477
478
479
480
481
482
483
484
 
 
 
 
 
 
 
 
 
 
 
485
486
487
488
489
490
491
492
493
494
495
496
 
 
 
 
 
 
 
 
 
 
 
 
497
498
499
500
501
502
503
 
 
 
 
 
 
504
505
 
506
507
 
508
509
510
511
512
513
514
515
516
 
 
 
 
 
 
 
 
517
518
519
520
521
522
523
 
 
524
525
526
527
528
529
530
 
 
 
 
 
 
531
532
533
 
 
 
 
 
 
534
535
536
537
538
539
540
541
542
 
 
543
544
545
546
547
 
 
 
 
 
 
 
 
548
549
550
551
552
553
554
555
556
557
558
 
 
 
 
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
 
 
 
 
 
 
 
 
 
 
576
577
578
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
581
 
 
 
582
583
584
585
586
587
588
589
 
590
591
592
593
594
595
 
 
 
 
 
 
 
596
597
598
599
600
601
602
603
 
 
 
 
 
604
605
606
607
608
609
610
 
 
 
 
 
 
 
611
612
613
614
615
616
617
618
 
 
 
 
 
 
619
620
621
622
623
624
625
626
 
 
 
 
 
 
 
627
628
 
 
 
 
 
 
 
 
 
 
 
629
 
 
 
 
630
631
632
633
 
 
 
 
634
635
636
637
638
 
 
 
 
639
640
641
642
643
 
 
 
 
644
645
646
647
648
 
 
 
 
 
 
 
 
649
650
651
652
653
 
 
654
655
656
657
658
659
660
661
662
 
 
663
664
665
666
667
668
669
 
 
 
 
 
 
670
671
672
673
674
675
676
677
678
679
680
 
 
 
 
681
682
 
 
 
 
683
684
685
686
687
688
689
690
 
 
 
691
692
693
 
 
 
 
 
 
 
 
 
 
 
 
 
694
 
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
280
281
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
284
 
 
 
 
 
 
 
285
286
287
288
289
290
291
292
293
294
295
296
 
 
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
 
317
318
319
320
321
322
323
324
 
325
326
327
 
328
329
 
 
330
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
333
 
 
 
 
 
 
 
334
335
336
 
 
 
 
 
 
 
 
 
 
 
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
 
 
 
 
 
 
 
357
358
359
360
361
362
363
364
 
 
 
 
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
 
 
 
 
391
392
393
394
395
 
 
 
 
396
397
398
399
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
 
 
 
 
 
 
416
417
418
419
420
421
422
 
 
423
424
425
 
426
427
 
 
 
 
428
429
430
431
432
433
434
435
436
437
438
439
440
441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
443
444
445
446
447
448
449
 
 
 
 
 
 
 
450
451
452
453
454
455
456
457
458
459
460
461
462
463
 
 
 
 
 
 
 
 
 
 
 
 
 
464
465
466
467
468
469
470
471
472
473
474
 
 
 
 
 
 
 
 
 
 
475
476
477
478
479
480
481
482
483
484
485
486
 
 
 
 
 
 
 
 
 
 
 
487
488
489
490
491
492
493
494
495
496
497
498
499
 
 
 
 
 
 
500
501
502
503
504
505
506
 
507
508
 
509
510
 
 
 
 
 
 
 
 
511
512
513
514
515
516
517
518
519
 
 
 
 
 
 
520
521
522
 
 
 
 
 
 
523
524
525
526
527
528
529
 
 
530
531
532
533
534
535
536
 
 
 
 
 
 
 
 
537
538
539
 
 
 
 
540
541
542
543
544
545
546
547
548
 
 
 
 
 
 
 
 
 
 
549
550
551
552
553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
555
556
557
558
559
560
561
562
563
564
 
 
 
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
 
582
583
584
585
 
 
 
 
 
 
 
586
587
 
 
 
 
 
588
589
590
591
592
593
594
595
 
 
 
 
 
 
 
596
597
598
599
600
601
 
 
 
 
 
 
602
603
604
605
606
607
608
609
 
 
 
 
 
 
 
610
611
612
613
614
615
616
 
 
 
 
 
 
 
617
618
619
620
621
622
623
624
 
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
 
 
 
642
643
644
645
646
 
 
 
 
647
648
649
650
651
 
 
 
 
652
653
654
655
656
 
 
 
 
657
658
659
660
661
662
663
664
665
 
 
 
 
666
667
668
 
 
 
 
 
 
 
 
669
670
671
 
 
 
 
 
 
672
673
674
675
676
677
678
 
 
 
 
 
 
 
 
 
 
679
680
681
682
683
 
684
685
686
687
688
 
 
 
 
 
 
 
689
690
691
692
 
 
693
694
695
696
697
698
699
700
701
702
703
704
705
706
@@ -26,669 +26,681 @@
   namespace Migrator.Providers  { - /// <summary> - /// Base class for every transformation providers. - /// A 'tranformation' is an operation that modifies the database. - /// </summary> - public abstract class TransformationProvider : IDisposable - { - private const string SCHEMA_INFO_TABLE = "SchemaInfo"; - private const string VERSION_COLUMN = "Version"; - private const string ASSEMBLY_ID_COLUMN = "AssemblyId"; + /// <summary> + /// Base class for every transformation providers. + /// A 'tranformation' is an operation that modifies the database. + /// </summary> + public abstract class TransformationProvider : IDisposable + { + protected const string SCHEMA_INFO_TABLE = "SchemaInfo"; + protected const string VERSION_COLUMN = "Version"; + protected const string ASSEMBLY_ID_COLUMN = "AssemblyId";   - private ILogger _logger = new NullLogger(); - protected IDbConnection _connection; - private IDbTransaction _transaction; - private string _assemblyId = null; - private bool _cacheConvertedValues = true; - private int? _timeout = null; - public delegate U ConvertColumnDelegate<T, U>(T currentValue, IDataReader row); + private ILogger _logger = new NullLogger(); + private IDbConnection _connection; + private IDbTransaction _transaction; + private string _assemblyId = null; + private bool _cacheConvertedValues = true; + private int? _timeout = null; + public delegate U ConvertColumnDelegate<T, U>(T currentValue, IDataReader row);   - #region Properties - public String AssemblyId - { - get { return this._assemblyId; } - } + #region Properties + public String AssemblyId + { + get { return this._assemblyId; } + internal set { this._assemblyId = value; } + }   - /// <summary> - /// States weither to cache a conversion value or to invoke the conversion function every time. Defaults to cached. - /// </summary> - public Boolean CacheConvertedValues - { - get { return _cacheConvertedValues; } - set { _cacheConvertedValues = value; } - } + /// <summary> + /// States weither to cache a conversion value or to invoke the conversion function every time. Defaults to cached. + /// </summary> + public Boolean CacheConvertedValues + { + get { return _cacheConvertedValues; } + set { _cacheConvertedValues = value; } + }   - public IDbConnection Connection - { - get { return _connection; } - set { _connection = value; } - } - /// <summary> - /// Returns the event logger - /// </summary> - virtual public ILogger Logger - { - get { return _logger; } - set { _logger = value; } - } + public IDbConnection Connection + { + get { return _connection; } + set { _connection = value; } + } + /// <summary> + /// Returns the event logger + /// </summary> + virtual public ILogger Logger + { + get { return _logger; } + set { _logger = value; } + }   - public string ConnectionString - { - get { return _connection != null ? (string)_connection.ConnectionString.Clone() : null; } - } + public string ConnectionString + { + get { return Connection != null ? (string)Connection.ConnectionString.Clone() : null; } + }   - public int? Timeout - { - get { return this._timeout == null || this._timeout == 0 ? null : this._timeout; } - set { this._timeout = value; } - } - #endregion - - #region Add Column/Table/PK/FK/Constraint - /// <summary> - /// Add a new column to an existing table. - /// </summary> - /// <exception cref="NotSupportedException"> - /// Thrown if the <c>type</c> is not supported by the provider - /// </exception> - /// <param name="table">Table to which to add the column</param> - /// <param name="column">Column name</param> - /// <param name="type">Date type of the column</param> - /// <param name="size">Max length of the column</param> - /// <param name="property">Properties of the column, see <see cref="ColumnProperties">ColumnProperties</see>,</param> - /// <param name="defaultValue">Default value</param> - public abstract void AddColumn(string table, string column, Type type, int size, ColumnProperties property, object defaultValue); + public int? Timeout + { + get { return this._timeout == null || this._timeout == 0 ? null : this._timeout; } + set { this._timeout = value; } + } + #endregion   - /// <summary> - /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> - /// AddColumn(string, string, Type, int, ColumnProperties, object) - /// </see> - /// </summary> - public virtual void AddColumn(string table, string column, Type type) - { - AddColumn(table, column, type, 0, ColumnProperties.Null, null); - } + #region Add Column/Table/PK/FK/Constraint + /// <summary> + /// Add a new column to an existing table. + /// </summary> + /// <exception cref="NotSupportedException"> + /// Thrown if the <c>type</c> is not supported by the provider + /// </exception> + /// <param name="table">Table to which to add the column</param> + /// <param name="column">Column name</param> + /// <param name="type">Date type of the column</param> + /// <param name="size">Max length of the column</param> + /// <param name="property">Properties of the column, see <see cref="ColumnProperties">ColumnProperties</see>,</param> + /// <param name="defaultValue">Default value</param> + public abstract void AddColumn(string table, string column, Type type, int size, ColumnProperties property, object defaultValue);   - /// <summary> - /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> - /// AddColumn(string, string, Type, int, ColumnProperties, object) - /// </see> - /// </summary> - public virtual void AddColumn(string table, string column, Type type, int size) - { - AddColumn(table, column, type, size, ColumnProperties.Null, null); - } + /// <summary> + /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> + /// AddColumn(string, string, Type, int, ColumnProperties, object) + /// </see> + /// </summary> + public virtual void AddColumn(string table, string column, Type type) + { + AddColumn(table, column, type, 0, ColumnProperties.Null, null); + }   - /// <summary> - /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> - /// AddColumn(string, string, Type, int, ColumnProperties) - /// </see> - /// </summary> - public virtual void AddColumn(string table, string column, Type type, ColumnProperties property) - { - AddColumn(table, column, type, 0, property, null); - } + /// <summary> + /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> + /// AddColumn(string, string, Type, int, ColumnProperties, object) + /// </see> + /// </summary> + public virtual void AddColumn(string table, string column, Type type, int size) + { + AddColumn(table, column, type, size, ColumnProperties.Null, null); + }   - /// <summary> - /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> - /// AddColumn(string, string, Type, int, ColumnProperties) - /// </see> - /// </summary> - public virtual void AddColumn(string table, string column, Type type, int size, ColumnProperties property) - { - AddColumn(table, column, type, size, property, null); - } + /// <summary> + /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> + /// AddColumn(string, string, Type, int, ColumnProperties) + /// </see> + /// </summary> + public virtual void AddColumn(string table, string column, Type type, ColumnProperties property) + { + AddColumn(table, column, type, 0, property, null); + }   - /// <summary> - /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> - /// AddColumn(string, string, Type, int, ColumnProperties, object) - /// </see> - /// </summary> - public virtual void AddColumn(string table, string column, Type type, ColumnProperties property, object defaultValue) - { - AddColumn(table, column, type, 0, property, defaultValue); - } + /// <summary> + /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> + /// AddColumn(string, string, Type, int, ColumnProperties) + /// </see> + /// </summary> + public virtual void AddColumn(string table, string column, Type type, int size, ColumnProperties property) + { + AddColumn(table, column, type, size, property, null); + }   - /// <summary> - /// Implements 'Alter Table' functionality common in most SQL variants. - /// </summary> - /// <param name="table">Table Name</param> - /// <param name="column">Column Name to alter</param> - /// <param name="dataType">new typw of the Column</param> - /// <param name="size">new size of the Column</param> - /// <param name="props">New Column Properties</param> - /// <param name="defaultValue">new Default Value</param> - public abstract void AlterColumn(string table, string column, Type type, int size); + /// <summary> + /// <see cref="TransformationProvider.AddColumn(string, string, Type, int, ColumnProperties, object)"> + /// AddColumn(string, string, Type, int, ColumnProperties, object) + /// </see> + /// </summary> + public virtual void AddColumn(string table, string column, Type type, ColumnProperties property, object defaultValue) + { + AddColumn(table, column, type, 0, property, defaultValue); + }   - /// <summary> - /// Implements 'Alter Table' functionality common in most SQL variants. - /// </summary> - /// <remarks>Transformation providers that dont support all possible functionality are free to work around the problem OR throw an exception. - /// If an exception is thrown please include the specific functionality that isnt implemented in the exception message. E.g. SqlLite cant alter columns to be primary keys.</remarks> - /// <param name="table">Table Name</param> - /// <param name="column">Column Name to alter</param> - /// <param name="dataType">new typw of the Column</param> - /// <param name="size">new size of the Column</param> - /// <param name="props">New Column Properties</param> - /// <param name="defaultValue">new Default Value</param> - public abstract void AlterColumn(string table, string column, Type dataType, int size, ColumnProperties props, object defaultValue); + /// <summary> + /// Implements 'Alter Table' functionality common in most SQL variants. + /// </summary> + /// <param name="table">Table Name</param> + /// <param name="column">Column Name to alter</param> + /// <param name="dataType">new typw of the Column</param> + /// <param name="size">new size of the Column</param> + /// <param name="props">New Column Properties</param> + /// <param name="defaultValue">new Default Value</param> + public abstract void AlterColumn(string table, string column, Type type, int size);   - /// <summary> - /// Implements 'Alter Table' functionality common in most SQL variants. - /// </summary> - /// <param name="table">Table Name</param> - /// <param name="column">Column Name to alter</param> - /// <param name="dataType">new type of the Column</param> - /// <param name="props">New Column Properties</param> - /// <param name="defaultValue">new Default Value</param> - public virtual void AlterColumn(string table, string column, Type dataType, ColumnProperties props, object defaultValue) - { - AlterColumn(table, column, dataType, 0, props, defaultValue); - } - - /// <summary> - /// Append a primary key to a table. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="table">Table name</param> - /// <param name="columns">Primary column names</param> - public abstract void AddPrimaryKey(string name, string table, params string[] columns); + /// <summary> + /// Implements 'Alter Table' functionality common in most SQL variants. + /// </summary> + /// <remarks>Transformation providers that dont support all possible functionality are free to work around the problem OR throw an exception. + /// If an exception is thrown please include the specific functionality that isnt implemented in the exception message. E.g. SqlLite cant alter columns to be primary keys.</remarks> + /// <param name="table">Table Name</param> + /// <param name="column">Column Name to alter</param> + /// <param name="dataType">new typw of the Column</param> + /// <param name="size">new size of the Column</param> + /// <param name="props">New Column Properties</param> + /// <param name="defaultValue">new Default Value</param> + public abstract void AlterColumn(string table, string column, Type dataType, int size, ColumnProperties props, object defaultValue);   - /// <summary> - /// Add a new table - /// </summary> - /// <param name="name">Table name</param> - /// <param name="columns">Columns</param> - /// <example> - /// Adds the Test table with two columns: - /// <code> - /// Database.AddTable("Test", - /// new Column("Id", typeof(int), ColumnProperties.PrimaryKey), - /// new Column("Title", typeof(string), 100) - /// ); - /// </code> - /// </example> - public abstract void AddTable(string name, params Column[] columns); + /// <summary> + /// Implements 'Alter Table' functionality common in most SQL variants. + /// </summary> + /// <param name="table">Table Name</param> + /// <param name="column">Column Name to alter</param> + /// <param name="dataType">new type of the Column</param> + /// <param name="props">New Column Properties</param> + /// <param name="defaultValue">new Default Value</param> + public virtual void AlterColumn(string table, string column, Type dataType, ColumnProperties props, object defaultValue) + { + AlterColumn(table, column, dataType, 0, props, defaultValue); + }   - /// <summary> - /// Append a foreign key (relation) between two tables. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> - /// <param name="foreignKeyColumn">The Foreign Key column name</param> - /// <param name="entityTable">The table that contains the Entity the Foreign Key references</param> - /// <param name="primaryKeyColumn">The Primary Key column in the Entity table</param> - public virtual void AddForeignKey(string name, string foreignKeyTable, string foreignKeyColumn, string entityTable, string primaryKeyColumn) - { - AddForeignKey(name, foreignKeyTable, new string[] { foreignKeyColumn }, entityTable, new string[] { primaryKeyColumn }); - } + /// <summary> + /// Append a primary key to a table. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="table">Table name</param> + /// <param name="columns">Primary column names</param> + public abstract void AddPrimaryKey(string name, string table, params string[] columns);   - /// <summary> - /// Append a foreign key (relation) between two tables. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> - /// <param name="foreignKeyColumn">The Foreign Key column name</param> - /// <param name="entityTable">The table that contains the Entity the Foreign Key references</param> - /// <param name="primaryKeyColumn">The Primary Key column in the Entity table</param> - /// <param name="cascade">What Cascading should be performed</param> - public virtual void AddForeignKey(string name, string foreignKeyTable, string foreignKeyColumn, string entityTable, string primaryKeyColumn, CascadeBehavior cascade) - { - AddForeignKey(name, foreignKeyTable, new string[] { foreignKeyColumn }, entityTable, new string[] { primaryKeyColumn }, cascade); - } + /// <summary> + /// Add a new table + /// </summary> + /// <param name="name">Table name</param> + /// <param name="columns">Columns</param> + /// <example> + /// Adds the Test table with two columns: + /// <code> + /// Database.AddTable("Test", + /// new Column("Id", typeof(int), ColumnProperties.PrimaryKey), + /// new Column("Title", typeof(string), 100) + /// ); + /// </code> + /// </example> + public abstract void AddTable(string name, params Column[] columns);   - /// <summary> - /// Append a foreign key (relation) between two tables. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> - /// <param name="foreignKeyColumns">The Foreign Key columns name</param> - /// <param name="entityTableName">The table that contains the Entity the Foreign Key references</param> - /// <param name="primaryKeyColumns">The Primary Key columns in the Entity table</param> - /// <param name="cascade">What Cascading should be performed</param> - public virtual void AddForeignKey(string name, string foreignKeyTable, string[] foreignKeyColumns, string entityTableName, string[] primaryKeyColumns, CascadeBehavior cascade) - { - throw new NotImplementedException(); - } + /// <summary> + /// Append a foreign key (relation) between two tables. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> + /// <param name="foreignKeyColumn">The Foreign Key column name</param> + /// <param name="entityTable">The table that contains the Entity the Foreign Key references</param> + /// <param name="primaryKeyColumn">The Primary Key column in the Entity table</param> + public virtual void AddForeignKey(string name, string foreignKeyTable, string foreignKeyColumn, string entityTable, string primaryKeyColumn) + { + AddForeignKey(name, foreignKeyTable, new string[] { foreignKeyColumn }, entityTable, new string[] { primaryKeyColumn }); + }   - /// <summary> - /// <see cref="TransformationProvider.AddForeignKey(string, string, string, string, string)"> - /// AddForeignKey(string, string, string, string, string) - /// </see> - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> - /// <param name="foreignKeyColumns">The Foreign Key columns name</param> - /// <param name="entityTableName">The table that contains the Entity the Foreign Key references</param> - /// <param name="primaryKeyColumns">The Primary Key columns in the Entity table</param> - public abstract void AddForeignKey(string name, string foreignKeyTable, string[] foreignKeyColumns, string entityTableName, string[] primaryKeyColumns); + /// <summary> + /// Append a foreign key (relation) between two tables. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> + /// <param name="foreignKeyColumn">The Foreign Key column name</param> + /// <param name="entityTable">The table that contains the Entity the Foreign Key references</param> + /// <param name="primaryKeyColumn">The Primary Key column in the Entity table</param> + /// <param name="cascade">What Cascading should be performed</param> + public virtual void AddForeignKey(string name, string foreignKeyTable, string foreignKeyColumn, string entityTable, string primaryKeyColumn, CascadeBehavior cascade) + { + AddForeignKey(name, foreignKeyTable, new string[] { foreignKeyColumn }, entityTable, new string[] { primaryKeyColumn }, cascade); + }   - /// <summary> - /// Add unique constraint - /// </summary> - /// <param name="constraint">Name of the Constraint</param> - /// <param name="table">Name of the table to add the constraint to</param> - /// <param name="columns">Columns to constrain to uniqueness</param> - public abstract void AddUniqueConstraint(string constraint, string table, params string[] columns); + /// <summary> + /// Append a foreign key (relation) between two tables. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> + /// <param name="foreignKeyColumns">The Foreign Key columns name</param> + /// <param name="entityTableName">The table that contains the Entity the Foreign Key references</param> + /// <param name="primaryKeyColumns">The Primary Key columns in the Entity table</param> + /// <param name="cascade">What Cascading should be performed</param> + public virtual void AddForeignKey(string name, string foreignKeyTable, string[] foreignKeyColumns, string entityTableName, string[] primaryKeyColumns, CascadeBehavior cascade) + { + throw new NotImplementedException(); + }   - /// <summary> - /// Removes an existing constraint from a table - /// </summary> - /// <param name="table">Name of the table</param> - /// <param name="constraint">Name of the Constraint</param> - public abstract void RemoveConstraint(string constraint, string table); + /// <summary> + /// <see cref="TransformationProvider.AddForeignKey(string, string, string, string, string)"> + /// AddForeignKey(string, string, string, string, string) + /// </see> + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="foreignKeyTable">Table to add the constraint to. Usually the table with the reference to an Entity in another table.</param> + /// <param name="foreignKeyColumns">The Foreign Key columns name</param> + /// <param name="entityTableName">The table that contains the Entity the Foreign Key references</param> + /// <param name="primaryKeyColumns">The Primary Key columns in the Entity table</param> + public abstract void AddForeignKey(string name, string foreignKeyTable, string[] foreignKeyColumns, string entityTableName, string[] primaryKeyColumns);   - #endregion + /// <summary> + /// Add unique constraint + /// </summary> + /// <param name="constraint">Name of the Constraint</param> + /// <param name="table">Name of the table to add the constraint to</param> + /// <param name="columns">Columns to constrain to uniqueness</param> + public abstract void AddUniqueConstraint(string constraint, string table, params string[] columns);   - /// <summary> - /// Starts a transaction. Called by the migration mediator. - /// </summary> - public void BeginTransaction() - { - if (_transaction == null && _connection != null) - { - EnsureHasConnection(); - _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted); - } - } + /// <summary> + /// Removes an existing constraint from a table + /// </summary> + /// <param name="table">Name of the table</param> + /// <param name="constraint">Name of the Constraint</param> + public abstract void RemoveConstraint(string constraint, string table);   - /// <summary> - /// Builds a command using the current transaction - /// </summary> - /// <param name="sql"></param> - /// <returns></returns> - public IDbCommand BuildCommand(string sql) - { - IDbCommand cmd = _connection.CreateCommand(); - cmd.CommandText = sql; - cmd.CommandType = CommandType.Text; - if (this.Timeout != null) - cmd.CommandTimeout = this.Timeout.Value; - BeginTransaction(); - if (_transaction != null) - { - cmd.Transaction = _transaction; - } - return cmd; - } + #endregion   - /// <summary> - /// Determines of a column exists. - /// </summary> - /// <param name="table">Table name</param> - /// <param name="column">Column name</param> - /// <returns><c>true</c> if the column exists</returns> - public abstract bool ColumnExists(string table, string column); + /// <summary> + /// Starts a transaction. Called by the migration mediator. + /// </summary> + public void BeginTransaction() + { + if (_transaction == null && Connection != null) + { + EnsureHasConnection(); + _transaction = Connection.BeginTransaction(IsolationLevel.ReadCommitted); + } + }   - #region Convert Column - public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc); + /// <summary> + /// Builds a command using the current transaction + /// </summary> + /// <param name="sql"></param> + /// <returns></returns> + public IDbCommand BuildCommand(string sql) + { + IDbCommand cmd = Connection.CreateCommand(); + cmd.CommandText = sql; + cmd.CommandType = CommandType.Text; + if (this.Timeout != null) + cmd.CommandTimeout = this.Timeout.Value; + BeginTransaction(); + if (_transaction != null) + { + cmd.Transaction = _transaction; + } + return cmd; + }   - public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size); + /// <summary> + /// Determines of a column exists. + /// </summary> + /// <param name="table">Table name</param> + /// <param name="column">Column name</param> + /// <returns><c>true</c> if the column exists</returns> + public abstract bool ColumnExists(string table, string column);   - public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size, ColumnProperties property); + #region Convert Column + public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc);   - public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, ColumnProperties property); + public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size);   - public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size, object defaultValue, ColumnProperties property); - #endregion + public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size, ColumnProperties property);   - /// <summary> - /// Commit the current transaction. Called by the migrations mediator. - /// </summary> - public void Commit() - { - if (_transaction != null && _connection != null && _connection.State == ConnectionState.Open) - { - try - { - _transaction.Commit(); - } - catch (Exception ex) - { - this.Rollback(); - throw; - } - } - _transaction = null; - } + public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, ColumnProperties property);   - /// <summary> - /// Determines if a constraint exists. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="table">Table owning the constraint</param> - /// <returns><c>true</c> if the constraint exists.</returns> - public abstract bool ConstraintExists(string name, string table); + public abstract bool ConvertColumn<T, U>(string table, string column, string tempColumn, ConvertColumnDelegate<T, U> convertFunc, int size, object defaultValue, ColumnProperties property); + #endregion   - /// <summary> - /// Creates the Schema Info Table - /// </summary> - /// <remarks> This includes opperations to update the SchemaInfo table in the case where it - /// already existed but the AssemblyId column is missing - /// </remarks> - /// <param name="assemblyId"></param> - public virtual void CreateSchemaInfoTable(String asseblyId) - { - this._assemblyId = asseblyId; - EnsureHasConnection(); + /// <summary> + /// Commit the current transaction. Called by the migrations mediator. + /// </summary> + public void Commit() + { + if (_transaction != null && Connection != null && Connection.State == ConnectionState.Open) + { + try + { + _transaction.Commit(); + } + catch (Exception ex) + { + this.Rollback(); + throw; + } + } + _transaction = null; + }   - // Does the old style schema info (without the assembly id column) table exist? - int version = 0; - if (this.TableExists(SCHEMA_INFO_TABLE) && !this.ColumnExists(SCHEMA_INFO_TABLE, ASSEMBLY_ID_COLUMN)) - { - version = this.GetVersion(this._assemblyId); - this.RemoveTable(SCHEMA_INFO_TABLE); - } + /// <summary> + /// Determines if a constraint exists. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="table">Table owning the constraint</param> + /// <returns><c>true</c> if the constraint exists.</returns> + public abstract bool ConstraintExists(string name, string table);   - // create the table - if (!this.TableExists(SCHEMA_INFO_TABLE)) - { - Column[] columns = new Column[] { + /// <summary> + /// Creates the Schema Info Table + /// </summary> + /// <remarks> This includes opperations to update the SchemaInfo table in the case where it + /// already existed but the AssemblyId column is missing + /// </remarks> + /// <param name="assemblyId"></param> + public virtual void CreateSchemaInfoTable() + { + EnsureHasConnection(); + + // Does the old style schema info (without the assembly id column) table exist? + int version = 0; + if (this.TableExists(SCHEMA_INFO_TABLE) && !this.ColumnExists(SCHEMA_INFO_TABLE, ASSEMBLY_ID_COLUMN)) + { + version = this.GetVersion(AssemblyId); + this.RemoveTable(SCHEMA_INFO_TABLE); + } + + // create the table + if (!this.TableExists(SCHEMA_INFO_TABLE)) + { + Column[] columns = new Column[] {   new Column(VERSION_COLUMN, typeof(int), ColumnProperties.NotNull),   new Column(ASSEMBLY_ID_COLUMN, typeof(string), 255,ColumnProperties.PrimaryKey)   }; - this.AddTable(SCHEMA_INFO_TABLE, columns); - this.InsertVersionRecord(this._assemblyId); - this.SetVersion(version, this._assemblyId); // bring over any previous verion - } + this.AddTable(SCHEMA_INFO_TABLE, columns); + this.InsertVersionRecord(AssemblyId); + this.SetVersion(version, AssemblyId); // bring over any previous verion + }   - // enchure that a version info record exists for the given assemblyId - if (!VersionRecordExists(this._assemblyId)) - this.InsertVersionRecord(this._assemblyId); - } + // enchure that a version info record exists for the given assemblyId + if (!VersionRecordExists(AssemblyId)) + this.InsertVersionRecord(AssemblyId); + }   - /// <summary> - /// Copies rows from one table to another - /// </summary> - /// <param name="fromTable">The name of the table being copied from</param> - /// <param name="toTable">The table being copied to...</param> - /// <param name="fromColumns">The names of the columns being copied. These must be in the same order as the names of the matching <see cref="toColumns"/></param> - /// <param name="toColumns">The names of the columns in the toTable that match the columns in the fromTable</param> - /// <param name="fromWhere">Where statement that filters the from table.</param> - public void CopyFromTable(string fromTable, string toTable, string[] fromColumns, string[] toColumns, string fromWhere) - { - if (fromColumns.Length != toColumns.Length) - { - throw new ArgumentOutOfRangeException("FromColumns and toColumns must have matching numbers."); - } + /// <summary> + /// Copies rows from one table to another + /// </summary> + /// <param name="fromTable">The name of the table being copied from</param> + /// <param name="toTable">The table being copied to...</param> + /// <param name="fromColumns">The names of the columns being copied. These must be in the same order as the names of the matching <see cref="toColumns"/></param> + /// <param name="toColumns">The names of the columns in the toTable that match the columns in the fromTable</param> + /// <param name="fromWhere">Where statement that filters the from table.</param> + public void CopyFromTable(string fromTable, string toTable, string[] fromColumns, string[] toColumns, string fromWhere) + { + if (fromColumns.Length != toColumns.Length) + { + throw new ArgumentOutOfRangeException("FromColumns and toColumns must have matching numbers."); + }   - string sql = string.Format("Insert Into [{0}] ({1}) Select {2} From [{3}] {4} ", - toTable, - string.Join(", ", toColumns), - string.Join(", ", fromColumns), - fromTable, - fromWhere.Length > 1 ? "Where " + fromWhere : ""); + string sql = string.Format("Insert Into [{0}] ({1}) Select {2} From [{3}] {4} ", + toTable, + string.Join(", ", toColumns), + string.Join(", ", fromColumns), + fromTable, + fromWhere.Length > 1 ? "Where " + fromWhere : "");   - this.Logger.Trace("Copying from table [{0}]", sql); - this.ExecuteNonQuery(sql); + this.Logger.Trace("Copying from table [{0}]", sql); + this.ExecuteNonQuery(sql);   - } + }   - public void CreateSchemaInfoTable() - { - this.CreateSchemaInfoTable(null); - } + /// <summary> + /// Get or set the current version of the database. + /// This determines if the migrator should migrate up or down + /// in the migration numbers. + /// </summary> + /// <remark> + /// This value should not be modified inside a migration. + /// </remark> + public virtual int CurrentVersion + { + get { return GetVersion(AssemblyId); } + set { SetVersion(value, AssemblyId); } + }   - /// <summary> - /// Get or set the current version of the database. - /// This determines if the migrator should migrate up or down - /// in the migration numbers. - /// </summary> - /// <remark> - /// This value should not be modified inside a migration. - /// </remark> - public virtual int CurrentVersion - { - get - { - return GetVersion(this._assemblyId); - } - set - { - SetVersion(value, this._assemblyId); - } - } + protected void EnsureHasConnection() + { + if (Connection.State != ConnectionState.Open) + { + Connection.Open(); + } + }   - protected void EnsureHasConnection() - { - if (_connection.State != ConnectionState.Open) - { - _connection.Open(); - } - } + /// <summary> + /// Execute a raw SQl statement that will not produce a result set (e.g. Update, Insert, Delete etc.) + /// </summary> + /// <param name="sql">Raw SQL statement</param> + /// <returns>the number of rows affected</returns> + public int ExecuteNonQuery(string sql) + { + this.Logger.Trace(sql); + using (IDbCommand cmd = BuildCommand(sql)) + { + return cmd.ExecuteNonQuery(); + } + }   - /// <summary> - /// Execute a raw SQl statement that will not produce a result set (e.g. Update, Insert, Delete etc.) - /// </summary> - /// <param name="sql">Raw SQL statement</param> - /// <returns>the number of rows affected</returns> - public int ExecuteNonQuery(string sql) - { - this.Logger.Trace(sql); - using (IDbCommand cmd = BuildCommand(sql)) - { - return cmd.ExecuteNonQuery(); - } - } + /// <summary> + /// Execute a raw SQl statement that will not produce a result set (e.g. Update, Insert, Delete etc.) + /// </summary> + /// <param name="format">Raw SQL string to format into</param> + /// <param name="args">Arguments to use against the formatted string</param> + /// <returns>The number of rows affected</returns> + public int ExecuteNonQuery(string format, params object[] args) + { + return ExecuteNonQuery(string.Format(format, args)); + }   - /// <summary> - /// Execute a raw SQl statement that will not produce a result set (e.g. Update, Insert, Delete etc.) - /// </summary> - /// <param name="format">Raw SQL string to format into</param> - /// <param name="args">Arguments to use against the formatted string</param> - /// <returns>The number of rows affected</returns> - public int ExecuteNonQuery(string format, params object[] args) - { - return ExecuteNonQuery(string.Format(format, args)); - } + /// <summary> + /// Execute an SQL query returning results. + /// </summary> + /// <param name="sql">The SQL command.</param> + /// <returns>A data iterator, <see cref="System.Data.IDataReader">IDataReader</see>.</returns> + public IDataReader ExecuteQuery(string sql) + { + this.Logger.Trace(sql); + IDbCommand cmd = BuildCommand(sql); + return cmd.ExecuteReader(); + }   - /// <summary> - /// Execute an SQL query returning results. - /// </summary> - /// <param name="sql">The SQL command.</param> - /// <returns>A data iterator, <see cref="System.Data.IDataReader">IDataReader</see>.</returns> - public IDataReader ExecuteQuery(string sql) - { - this.Logger.Trace(sql); - IDbCommand cmd = BuildCommand(sql); - return cmd.ExecuteReader(); - } + /// <summary> + /// Execute an SQL query returning the first result cast to type T. + /// </summary> + /// <param name="sql">The SQL command.</param> + /// <returns>A data iterator, <see cref="System.Data.IDataReader">IDataReader</see>.</returns> + internal T ExecuteQuery<T>(string sql) + { + var reader = ExecuteQuery(sql); + if (reader.Read()) + return (T)reader.GetValue(0); + return default(T); + }   - public object ExecuteScalar(string sql) - { - this.Logger.Trace(sql); - IDbCommand cmd = BuildCommand(sql); - return cmd.ExecuteScalar(); - } + public object ExecuteScalar(string sql) + { + this.Logger.Trace(sql); + IDbCommand cmd = BuildCommand(sql); + return cmd.ExecuteScalar(); + }   - public abstract Column[] GetColumns(string table); + public abstract Column[] GetColumns(string table);   - public abstract string[] GetTables(); + public abstract string[] GetTables();   - /// <summary> - /// Get the version from the SchemaInfo Table - /// </summary> - /// <returns>The current version</returns> - protected virtual int GetVersion(String assemblyId) - { - return (int)ExecuteScalar(String.Format("SELECT TOP 1 Version FROM SchemaInfo WHERE AssemblyId='{0}'", assemblyId)); - } + /// <summary> + /// Get the version from the SchemaInfo Table + /// </summary> + /// <returns>The current version</returns> + protected virtual int GetVersion(String assemblyId) + { + if (assemblyId == null) return 0; // No schema info. + if (!TableExists(SCHEMA_INFO_TABLE)) return 0;   - [Obsolete("Use the other Insert variant, this one is not safe!")] - public virtual int Insert(string table, params string[] columnValues) - { - string[] columns = new string[columnValues.Length]; - string[] values = new string[columnValues.Length]; - int i = 0; + return (int)ExecuteScalar(String.Format("SELECT Version FROM {1} WHERE AssemblyId='{0}'", assemblyId, SCHEMA_INFO_TABLE)); + }   - foreach (string cs in columnValues) - { - columns[i] = cs.Split('=')[0]; - values[i] = cs.Split('=')[1]; - i++; - } + [Obsolete("Use the other Insert variant, this one is not safe!")] + public virtual int Insert(string table, params string[] columnValues) + { + string[] columns = new string[columnValues.Length]; + string[] values = new string[columnValues.Length]; + int i = 0;   - return ExecuteNonQuery(string.Format("INSERT INTO {0} ({1}) VALUES ({2})", table, string.Join(", ", columns), string.Join(", ", values))); - } + foreach (string cs in columnValues) + { + columns[i] = cs.Split('=')[0]; + values[i] = cs.Split('=')[1]; + i++; + }   - /// <summary> - /// Insert a row into a table - /// </summary> - /// <param name="table">The name of the table</param> - /// <param name="columns">A list of column names</param> - /// <param name="values">A list of primitive values that can be converted to SQL by the TransformationProvider</param> - /// <returns></returns> - public abstract int Insert(string table, string[] columns, params object[] values); + return ExecuteNonQuery(string.Format("INSERT INTO {0} ({1}) VALUES ({2})", table, string.Join(", ", columns), string.Join(", ", values))); + }   - protected virtual void InsertVersionRecord(String assemblyId) - { - ExecuteNonQuery(string.Format("INSERT INTO SchemaInfo (Version, AssemblyId) VALUES (0, '{0}')", assemblyId)); - } + /// <summary> + /// Insert a row into a table + /// </summary> + /// <param name="table">The name of the table</param> + /// <param name="columns">A list of column names</param> + /// <param name="values">A list of primitive values that can be converted to SQL by the TransformationProvider</param> + /// <returns></returns> + public abstract int Insert(string table, string[] columns, params object[] values);   - /// <param name="commandText">Format String</param> - /// <param name="parameters">Arguments to use against the formatted string</param> - /// <returns>Int</returns> - public int ParameterizedNonQuery(string commandText, Dictionary<String, Object> parameters) - { - IDbCommand cmd = BuildCommand(commandText); - cmd.Prepare(); - foreach (String key in parameters.Keys) - { - Object value = parameters[key]; + protected virtual void InsertVersionRecord(String assemblyId) + { + ExecuteNonQuery(string.Format("INSERT INTO {1} (Version, AssemblyId) VALUES (0, '{0}')", assemblyId, SCHEMA_INFO_TABLE)); + }   - IDbDataParameter dataParam = cmd.CreateParameter(); - dataParam.ParameterName = key; - dataParam.Value = value; - Type type = value.GetType(); - if (type == typeof(String)) - dataParam.DbType = DbType.String; - else if (type == typeof(Int32)) - dataParam.DbType = DbType.Int32; - else if (type == typeof(DateTime)) - dataParam.DbType = DbType.DateTime; - else if (type == typeof(TimeSpan)) - dataParam.DbType = DbType.UInt64; - else if (type == typeof(Guid)) - dataParam.DbType = DbType.Guid; - else if (type == typeof(Boolean)) - dataParam.DbType = DbType.Boolean; + /// <param name="commandText">Format String</param> + /// <param name="parameters">Arguments to use against the formatted string</param> + /// <returns>Int</returns> + public int ParameterizedNonQuery(string commandText, Dictionary<String, Object> parameters) + { + IDbCommand cmd = BuildCommand(commandText); + cmd.Prepare(); + foreach (String key in parameters.Keys) + { + Object value = parameters[key];   - cmd.Parameters.Add(dataParam); - } - return cmd.ExecuteNonQuery(); + IDbDataParameter dataParam = cmd.CreateParameter(); + dataParam.ParameterName = key; + dataParam.Value = value; + Type type = value.GetType(); + if (type == typeof(String)) + dataParam.DbType = DbType.String; + else if (type == typeof(Int32)) + dataParam.DbType = DbType.Int32; + else if (type == typeof(DateTime)) + dataParam.DbType = DbType.DateTime; + else if (type == typeof(TimeSpan)) + dataParam.DbType = DbType.UInt64; + else if (type == typeof(Guid)) + dataParam.DbType = DbType.Guid; + else if (type == typeof(Boolean)) + dataParam.DbType = DbType.Boolean;   - } + cmd.Parameters.Add(dataParam); + } + return cmd.ExecuteNonQuery();   - #region Remove Column/Table/Constraint/FK - /// <summary> - /// Removes a column from a table - /// </summary> - /// <param name="table">table containing the column</param> - /// <param name="column">column name</param> - public abstract void RemoveColumn(string table, string column); + }   - /// <summary> - /// Remove a table from the database. - /// </summary> - /// <param name="name">Table name</param> - public abstract void RemoveTable(string name); + #region Remove Column/Table/Constraint/FK + /// <summary> + /// Removes a column from a table + /// </summary> + /// <param name="table">table containing the column</param> + /// <param name="column">column name</param> + public abstract void RemoveColumn(string table, string column);   - /// <summary> - /// Rename a Column - /// </summary> - /// <param name="table">Table containing the Column to be Renames</param> - /// <param name="column">Column to be renamed</param> - /// <param name="newName">New name of the column</param> - public abstract void RenameColumn(string table, string column, string newName); + /// <summary> + /// Remove a table from the database. + /// </summary> + /// <param name="name">Table name</param> + public abstract void RemoveTable(string name);   - /// <summary> - /// Rename a Table - /// </summary> - /// <param name="table">Name of the table to be renames</param> - /// <param name="newName">New name of the table</param> - public abstract void RenameTable(string table, string newName); + /// <summary> + /// Rename a Column + /// </summary> + /// <param name="table">Table containing the Column to be Renames</param> + /// <param name="column">Column to be renamed</param> + /// <param name="newName">New name of the column</param> + public abstract void RenameColumn(string table, string column, string newName);   - /// <summary> - /// Removes a constraint. - /// </summary> - /// <param name="name">Constraint name</param> - /// <param name="table">Table owning the constraint</param> - public abstract void RemoveForeignKey(string name, string table); - #endregion + /// <summary> + /// Rename a Table + /// </summary> + /// <param name="table">Name of the table to be renames</param> + /// <param name="newName">New name of the table</param> + public abstract void RenameTable(string table, string newName);   - /// <summary> - /// Rollback the current migration. Called by the migration mediator. - /// </summary> - public virtual void Rollback() - { - if (_transaction != null && _connection != null && _connection.State == ConnectionState.Open) - { + /// <summary> + /// Removes a constraint. + /// </summary> + /// <param name="name">Constraint name</param> + /// <param name="table">Table owning the constraint</param> + public abstract void RemoveForeignKey(string name, string table); + #endregion   - _transaction.Rollback(); + /// <summary> + /// Rollback the current migration. Called by the migration mediator. + /// </summary> + public virtual void Rollback() + { + if (_transaction != null && Connection != null && Connection.State == ConnectionState.Open) + { + _transaction.Rollback(); + } + _transaction = null; + }   + public IDataReader Select(string what, string from) + { + return Select(what, from, "1=1"); + }   - } - _transaction = null; - } + public virtual IDataReader Select(string what, string from, string where) + { + return ExecuteQuery(string.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where)); + }   - public IDataReader Select(string what, string from) - { - return Select(what, from, "1=1"); - } + public object SelectScalar(string what, string from) + { + return SelectScalar(what, from, "1=1"); + }   - public virtual IDataReader Select(string what, string from, string where) - { - return ExecuteQuery(string.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where)); - } + public virtual object SelectScalar(string what, string from, string where) + { + return ExecuteScalar(string.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where)); + }   - public object SelectScalar(string what, string from) - { - return SelectScalar(what, from, "1=1"); - } + /// <summary> + /// Set the current version in the SchemaInfo Table + /// </summary> + /// <param name="version">the new version to set</param> + protected virtual void SetVersion(int version, String assemblyId) + { + if (assemblyId == null) + throw new ArgumentException();   - public virtual object SelectScalar(string what, string from, string where) - { - return ExecuteScalar(string.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where)); - } + if (!TableExists(SCHEMA_INFO_TABLE)) + CreateSchemaInfoTable();   - /// <summary> - /// Set the current version in the SchemaInfo Table - /// </summary> - /// <param name="version">the new version to set</param> - protected virtual void SetVersion(int version, String assemblyId) - { - ExecuteNonQuery(string.Format("UPDATE SchemaInfo SET Version={0} WHERE AssemblyId='{1}'", version, assemblyId)); - } + ExecuteNonQuery(string.Format("UPDATE {2} SET Version={0} WHERE AssemblyId='{1}'", version, assemblyId, SCHEMA_INFO_TABLE)); + }   - /// <summary> - /// Determines if a table exists. - /// </summary> - /// <param name="table">Table name</param> - /// <returns><c>true</c> if the table exists</returns> - public abstract bool TableExists(string table); + /// <summary> + /// Determines if a table exists. + /// </summary> + /// <param name="table">Table name</param> + /// <returns><c>true</c> if the table exists</returns> + public abstract bool TableExists(string table);   - public virtual int Update(string table, params string[] columnValues) - { - return ExecuteNonQuery(string.Format("UPDATE {0} SET {1}", table, string.Join(", ", columnValues))); - } - - protected virtual bool VersionRecordExists(String assemblyId) - { - int? ver = (int?)ExecuteScalar(String.Format("SELECT TOP 1 Version FROM SchemaInfo WHERE AssemblyId='{0}'", assemblyId)); - return ver != null; - } + public virtual int Update(string table, params string[] columnValues) + { + return ExecuteNonQuery(string.Format("UPDATE {0} SET {1}", table, string.Join(", ", columnValues))); + }   - #region IDisposable Members + protected virtual bool VersionRecordExists(String assemblyId) + { + if (assemblyId == null) return false; // No schema info. + if (!TableExists(SCHEMA_INFO_TABLE)) return false;   - public virtual void Dispose() - { - if (this.Connection != null) - { - this.Connection.Dispose(); - } - } + int? ver = (int?)ExecuteScalar(String.Format("SELECT Version FROM {1} WHERE AssemblyId='{0}'", assemblyId, SCHEMA_INFO_TABLE)); + return ver != null; + }   - #endregion - } + #region IDisposable Members + + public virtual void Dispose() + { + if (this.Connection != null && this.Connection.State == ConnectionState.Open) + { + this.Connection.Close(); + this.Connection.Dispose(); + } + } + + #endregion + }  }
 
61
62
63
 
64
65
66
 
74
75
76
 
 
 
 
 
77
78
 
 
61
62
63
64
65
66
67
 
75
76
77
78
79
80
81
82
83
84
 
@@ -61,6 +61,7 @@
  <Compile Include="MigrationTestCase.cs" />   <Compile Include="MigrationTypeComparerTest.cs" />   <Compile Include="MigratorTest.cs" /> + <Compile Include="Providers\SqliteServerTransformationProviderTest.cs" />   <Compile Include="Providers\MySqlTransformationProviderTest.cs" />   <Compile Include="Providers\PostgreSQLTransformationProviderTest.cs" />   <Compile Include="Providers\SqlServerTransformationProviderTest.cs" /> @@ -74,5 +75,10 @@
  <Name>Migrator</Name>   </ProjectReference>   </ItemGroup> + <ItemGroup> + <None Include="App.config"> + <SubType>Designer</SubType> + </None> + </ItemGroup>   <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />  </Project> \ No newline at end of file
 
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
 
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
@@ -12,30 +12,111 @@
 using System;  using System.Configuration;  using NUnit.Framework; +using System.Collections.Generic; +using System.Text;    namespace Migrator.Providers.Tests  { - [TestFixture, Category("SqlServer")] - public class SqlServerTransformationProviderTest : TransformationProviderBase - { - [SetUp] - public void SetUp() - { -#if DOTNET2 - string constr = ConfigurationManager.AppSettings["SqlServerConnectionString"]; -#else - string constr = ConfigurationSettings.AppSettings["SqlServerConnectionString"]; -#endif - if (constr == null) - throw new ArgumentNullException("SqlServerConnectionString", "No config file"); + [TestFixture, Category("SqlServer")] + public class SqlServerTransformationProviderTest : TransformationProviderBase + { + private static string constr = ConfigurationManager.AppSettings["SqlServerConnectionString"];   - _provider = new SqlServerTransformationProvider(constr); - _provider.BeginTransaction(); - - _provider.AddTable("Test2", - new Column("Id", typeof(int), ColumnProperties.PrimaryKeyWithIdentity), - new Column("TestId", typeof(int))); - } - - } + [TestFixtureSetUp] + public void FixtureSetup() + { + if (constr == null) + throw new ArgumentNullException("SqlServerConnectionString", "No config file"); + + DropTestDatabase(); + RunSQL(String.Format("Create Database {0};", DatabaseName)); + _provider = new SqlServerTransformationProvider(constr); + _provider.AssemblyId = Guid.NewGuid().ToString(); + } + + [TestFixtureTearDown] + public void FixtureTeardown() + { + _provider.Dispose(); + DropTestDatabase(); + } + + [SetUp] + public void SetUp() + { + _provider.BeginTransaction(); + + _provider.AddTable("Test2", + new Column("Id", typeof(int), ColumnProperties.PrimaryKeyWithIdentity), + new Column("TestId", typeof(int))); + } + + [TearDown] + public new void TearDown() + { + _provider.Rollback(); + } + + + + public void DropTestDatabase() + { + RunSQL(String.Format(@" + IF EXISTS (SELECT name FROM sys.databases WHERE name = N'MigratorTests') + Begin + Drop Database {0}; + End", DatabaseName)); + } + + public void RunSQL(String sql) + { + var connection = new System.Data.SqlClient.SqlConnection(ConnectionStringSansDatabase()); + connection.Open(); + + var command = connection.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); + command.Connection.Close(); + command.Dispose(); + connection.Close(); + connection.Dispose(); + } + + private string DatabaseName + { + get + { + var parsed = ParseConnectionString(constr); + if (parsed.ContainsKey("initial catalog")) + return parsed["initial catalog"]; + return null; + } + } + + private string ConnectionStringSansDatabase() + { + StringBuilder builder = new StringBuilder(); + var parsed = ParseConnectionString(constr); + foreach (var part in parsed) + { + if (!part.Key.Equals("initial catalog", StringComparison.InvariantCultureIgnoreCase)) + builder.Append(String.Format("{0}={1};", part.Key, part.Value)); + } + return builder.ToString(); + } + + private Dictionary<String, String> ParseConnectionString(String connectionString) + { + var parsed = new Dictionary<String, String>(); + foreach (var part in connectionString.Split(';')) + { + if (part == null || part.Trim().Equals(String.Empty)) continue; + + var portions = part.Split('='); + parsed[portions[0].ToLowerInvariant()] = portions[1]; + } + return parsed; + } + + }  }
This file's diff was not loaded because this changeset is very large. Load changes