forked from bittercoder/Migrator.NET
-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathTransformationProvider.cs
More file actions
2236 lines (1852 loc) · 72.6 KB
/
TransformationProvider.cs
File metadata and controls
2236 lines (1852 loc) · 72.6 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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
//The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in
//compliance with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/
//Software distributed under the License is distributed on an "AS IS"
//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//License for the specific language governing rights and limitations
//under the License.
#endregion
using DotNetProjects.Migrator.Framework;
using DotNetProjects.Migrator.Framework.Loggers;
using DotNetProjects.Migrator.Framework.Models;
using DotNetProjects.Migrator.Framework.SchemaBuilder;
using DotNetProjects.Migrator.Providers.Impl.SQLite;
using DotNetProjects.Migrator.Providers.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using ForeignKeyConstraint = DotNetProjects.Migrator.Framework.ForeignKeyConstraint;
using ForeignKeyConstraintType = DotNetProjects.Migrator.Framework.ForeignKeyConstraintType;
using Index = DotNetProjects.Migrator.Framework.Index;
namespace DotNetProjects.Migrator.Providers;
/// <summary>
/// Base class for every transformation providers.
/// A 'tranformation' is an operation that modifies the database.
/// </summary>
public abstract class TransformationProvider : ITransformationProvider
{
private string _scope;
protected readonly string _connectionString;
protected readonly string _defaultSchema;
private readonly ForeignKeyConstraintMapper constraintMapper = new();
protected List<long> _appliedMigrations;
protected IDbConnection _connection;
protected bool _outsideConnection = false;
protected Dialect _dialect;
private ILogger _logger;
private IDbTransaction _transaction;
protected TransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope)
{
_dialect = dialect;
_connectionString = connectionString;
_defaultSchema = defaultSchema;
_logger = new Logger(false);
_scope = scope;
}
protected TransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope)
{
_dialect = dialect;
_connection = connection;
_outsideConnection = true;
_defaultSchema = defaultSchema;
_logger = new Logger(false);
_scope = scope;
}
public IMigration CurrentMigration { get; set; }
private string _schemaInfotable = "SchemaInfo";
public string SchemaInfoTable
{
get
{
return _schemaInfotable;
}
set
{
_schemaInfotable = value;
}
}
public int? CommandTimeout { get; set; }
public IDialect Dialect
{
get { return _dialect; }
}
public string ConnectionString { get { return _connectionString; } }
/// <summary>
/// Returns the event logger
/// </summary>
public virtual ILogger Logger
{
get { return _logger; }
set { _logger = value; }
}
public virtual ITransformationProvider this[string provider]
{
get
{
if (null != provider && IsThisProvider(provider))
{
return this;
}
return NoOpTransformationProvider.Instance;
}
}
public virtual Index[] GetIndexes(string table)
{
throw new NotImplementedException();
}
public virtual Column[] GetColumns(string table)
{
var columns = new List<Column>();
using (var cmd = CreateCommand())
using (
var reader =
ExecuteQuery(
cmd, string.Format("select COLUMN_NAME, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where table_name = '{0}'", table)))
{
while (reader.Read())
{
var column = new Column(reader.GetString(0), DbType.String);
var nullableStr = reader.GetString(1);
var isNullable = nullableStr == "YES";
column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
columns.Add(column);
}
}
return columns.ToArray();
}
/// <summary>
/// Basic implementation works for Postgre and probably for MySQL (not tested). For Oracle it should be overridden
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
/// <exception cref="MigrationException"></exception>
public virtual ForeignKeyConstraint[] GetForeignKeyConstraints(string table)
{
var constraints = new List<ForeignKeyConstraint>();
var sb = new StringBuilder();
sb.AppendLine("SELECT");
sb.AppendLine(" tc.CONSTRAINT_NAME AS FK_KEY,");
sb.AppendLine(" tc.TABLE_SCHEMA,");
sb.AppendLine(" tc.TABLE_NAME AS CHILD_TABLE,");
sb.AppendLine(" kcu.COLUMN_NAME AS CHILD_COLUMN,");
sb.AppendLine(" ccu.TABLE_NAME AS PARENT_TABLE,");
sb.AppendLine(" ccu.COLUMN_NAME AS PARENT_COLUMN");
sb.AppendLine("FROM ");
sb.AppendLine(" INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ");
sb.AppendLine("JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu");
sb.AppendLine(" ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA");
sb.AppendLine("JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS as rc");
sb.AppendLine(" ON tc.CONSTRAINT_NAME = rc.CONSTRAINT_NAME AND tc.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA");
sb.AppendLine("JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu");
sb.AppendLine(" ON rc.UNIQUE_CONSTRAINT_NAME = ccu.CONSTRAINT_NAME AND rc.UNIQUE_CONSTRAINT_SCHEMA = ccu.CONSTRAINT_SCHEMA");
sb.AppendLine($"WHERE LOWER(tc.TABLE_NAME) = LOWER('{table}') AND tc.CONSTRAINT_TYPE = 'FOREIGN KEY'");
sb.AppendLine("ORDER BY kcu.ORDINAL_POSITION");
var sql = sb.ToString();
List<ForeignKeyConstraintItem> foreignKeyConstraintItems = [];
using (var cmd = CreateCommand())
using (var reader = ExecuteQuery(cmd, sql))
{
while (reader.Read())
{
var constraintItem = new ForeignKeyConstraintItem
{
SchemaName = reader.GetString(reader.GetOrdinal("TABLE_SCHEMA")),
ForeignKeyName = reader.GetString(reader.GetOrdinal("FK_KEY")),
ChildTableName = reader.GetString(reader.GetOrdinal("CHILD_TABLE")),
ChildColumnName = reader.GetString(reader.GetOrdinal("CHILD_COLUMN")),
ParentTableName = reader.GetString(reader.GetOrdinal("PARENT_TABLE")),
ParentColumnName = reader.GetString(reader.GetOrdinal("PARENT_COLUMN"))
};
foreignKeyConstraintItems.Add(constraintItem);
}
}
var schemaChildTableGroups = foreignKeyConstraintItems.GroupBy(x => new { x.SchemaName, x.ChildTableName }).Count();
if (schemaChildTableGroups > 1)
{
throw new MigrationException($"Duplicates found (grouping by schema name and child table name). Since we do not offer schemas in '{nameof(GetForeignKeyConstraints)}' at this moment in time we cannot filter your target schema. Your database use the same table name in different schemas.");
}
var groups = foreignKeyConstraintItems.GroupBy(x => x.ForeignKeyName);
foreach (var group in groups)
{
var first = group.First();
var foreignKeyConstraint = new ForeignKeyConstraint
{
Name = first.ForeignKeyName,
ParentTable = first.ParentTableName,
ParentColumns = [.. group.Select(x => x.ParentColumnName).Distinct()],
ChildTable = first.ChildTableName,
ChildColumns = [.. group.Select(x => x.ChildColumnName).Distinct()]
};
constraints.Add(foreignKeyConstraint);
}
return [.. constraints];
}
public virtual string[] GetConstraints(string table)
{
var constraints = new List<string>();
using (var cmd = CreateCommand())
using (
var reader =
ExecuteQuery(
cmd, string.Format("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE LOWER(TABLE_NAME) = LOWER('{0}')", table)))
{
while (reader.Read())
{
constraints.Add(reader.GetString(0));
}
}
return constraints.ToArray();
}
public virtual Column GetColumnByName(string table, string columnName)
{
var columns = GetColumns(table);
var column = columns.FirstOrDefault(x => x.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)) ??
throw new Exception($"Cannot find column '{columnName}' in table '{table}'");
return column;
}
public virtual int GetColumnContentSize(string table, string columnName)
{
var result = this.ExecuteScalar("SELECT MAX(LENGTH(" + this.QuoteColumnNameIfRequired(columnName) + ")) FROM " + this.QuoteTableNameIfRequired(table));
if (result == DBNull.Value)
{
return 0;
}
return Convert.ToInt32(result);
}
public virtual string[] GetTables()
{
var tables = new List<string>();
using (var cmd = CreateCommand())
using (var reader = ExecuteQuery(cmd, "SELECT table_name FROM INFORMATION_SCHEMA.TABLES"))
{
while (reader.Read())
{
tables.Add((string)reader[0]);
}
}
return tables.ToArray();
}
public virtual void RemoveForeignKey(string table, string name)
{
if (!TableExists(table))
{
throw new MigrationException($"Table '{table}' does not exist.");
}
RemoveConstraint(table, name);
}
public virtual void RemoveConstraint(string table, string name)
{
if (!TableExists(table))
{
throw new MigrationException($"Table '{name}' does not exist");
}
if (!ConstraintExists(table, name))
{
throw new MigrationException($"Constraint '{name}' does not exist");
}
ExecuteNonQuery(string.Format("ALTER TABLE {0} DROP CONSTRAINT {1}", QuoteTableNameIfRequired(table), QuoteConstraintNameIfRequired(name)));
}
public virtual void RemoveAllConstraints(string table)
{
foreach (var constraint in GetConstraints(table))
{
RemoveConstraint(table, constraint);
}
}
public virtual void AddView(string name, string tableName, params IViewField[] fields)
{
var lst =
fields.Where(x => string.IsNullOrEmpty(x.TableName) || x.TableName == tableName)
.Select(x => x.ColumnName)
.ToList();
var nr = 0;
var joins = "";
foreach (var joinTable in fields.Where(x => !string.IsNullOrEmpty(x.TableName) && x.TableName != tableName).GroupBy(x => x.TableName))
{
foreach (var viewField in joinTable)
{
joins += string.Format("JOIN {0} {1} ON {1}.{2} = {3}.{4} ", viewField.TableName, " T" + nr,
viewField.KeyColumnName, viewField.ParentTableName, viewField.ParentKeyColumnName);
lst.Add(" T" + nr + "." + viewField.ColumnName);
}
}
var select = string.Format("SELECT {0} FROM {1} {2}", string.Join(",", lst), tableName, joins);
var sql = string.Format("CREATE VIEW {0} AS {1}", name, select);
ExecuteNonQuery(sql);
}
public virtual void AddView(string name, string tableName, params IViewElement[] viewElements)
{
var selectedColumns = viewElements.Where(x => x is ViewColumn)
.Select(x =>
{
var viewColumn = (ViewColumn)x;
return $"{viewColumn.Prefix}.{viewColumn.ColumnName} {viewColumn.Prefix}{viewColumn.ColumnName}";
})
.ToList();
var joins = string.Empty;
foreach (var viewJoin in viewElements.Where(x => x is ViewJoin).Cast<ViewJoin>())
{
var joinType = string.Empty;
switch (viewJoin.JoinType)
{
case JoinType.LeftJoin:
joinType = "LEFT JOIN";
break;
case JoinType.Join:
joinType = "JOIN";
break;
}
var tableAlias = string.IsNullOrEmpty(viewJoin.TableAlias) ? viewJoin.TableName : viewJoin.TableAlias;
joins += string.Format("{0} {1} {2} ON {2}.{3} = {4}.{5} ", joinType, viewJoin.TableName, tableAlias,
viewJoin.ColumnName, viewJoin.ParentTableName, viewJoin.ParentColumnName);
}
var select = string.Format("SELECT {0} FROM {1} {1} {2}", string.Join(",", selectedColumns), tableName, joins);
var sql = string.Format("CREATE VIEW {0} AS {1}", name, select);
// Works with all DBs. "CREATE OR REPLACE" does not work with SQLite. "DROP IF EXISTS" does not work with oracle.
try
{
ExecuteNonQuery($"DROP VIEW {name}");
}
catch
{
// Works with all DBs. "CREATE OR REPLACE" does not work with SQLite. "DROP IF EXISTS" does not work with oracle.
}
ExecuteNonQuery(sql);
}
/// <summary>
/// Add a new table
/// </summary>
/// <param name="name">Table name</param>
/// <param name="columns">Columns</param>
public virtual void AddTable(string name, params IDbField[] columns)
{
if (this is not SQLiteTransformationProvider && columns.Any(x => x is CheckConstraint))
{
throw new MigrationException($"{nameof(CheckConstraint)}s are currently only supported in SQLite.");
}
// Most databases don't have the concept of a storage engine, so default is to not use it.
AddTable(name, null, columns);
}
/// <summary>
/// Adds a new table
/// </summary>
/// <param name="name">Table name</param>
/// <param name="columns">Columns</param>
/// <param name="engine">the database storage engine to use</param>
public virtual void AddTable(string name, string engine, params IDbField[] fields)
{
var columns = fields.Where(x => x is Column).Cast<Column>().ToArray();
var pks = GetPrimaryKeys(columns);
var compoundPrimaryKey = pks.Count > 1;
var columnProviders = new List<ColumnPropertiesMapper>(columns.Count());
foreach (var column in columns)
{
// Remove the primary key notation if compound primary key because we'll add it back later
if (compoundPrimaryKey && column.IsPrimaryKey)
{
column.ColumnProperty = column.ColumnProperty ^ ColumnProperty.PrimaryKey;
column.ColumnProperty = column.ColumnProperty | ColumnProperty.NotNull; // PK is always not-null
}
var mapper = _dialect.GetAndMapColumnProperties(column);
columnProviders.Add(mapper);
}
var columnsAndIndexes = JoinColumnsAndIndexes(columnProviders);
AddTable(name, engine, columnsAndIndexes);
if (compoundPrimaryKey)
{
AddPrimaryKey(GetPrimaryKeyname(name), name, pks.ToArray());
}
var indexes = fields.Where(x => x is Index).Cast<Index>().ToArray();
foreach (var index in indexes)
{
AddIndex(name, index);
}
var foreignKeys = fields.Where(x => x is ForeignKeyConstraint).Cast<ForeignKeyConstraint>().ToArray();
foreach (var foreignKey in foreignKeys)
{
AddForeignKey(name, foreignKey);
}
}
protected virtual string GetPrimaryKeyname(string tableName)
{
return "PK_" + tableName;
}
public virtual void RemoveTable(string name)
{
if (!TableExists(name))
{
throw new MigrationException(string.Format("Table with name '{0}' does not exist to rename", name));
}
ExecuteNonQuery(string.Format("DROP TABLE {0}", name));
}
public virtual void RenameTable(string oldName, string newName)
{
oldName = QuoteTableNameIfRequired(oldName);
newName = QuoteTableNameIfRequired(newName);
if (TableExists(newName))
{
throw new MigrationException(string.Format("Table with name '{0}' already exists", newName));
}
if (!TableExists(oldName))
{
throw new MigrationException(string.Format("Table with name '{0}' does not exist to rename", oldName));
}
ExecuteNonQuery(string.Format("ALTER TABLE {0} RENAME TO {1}", oldName, newName));
}
public virtual void RenameColumn(string tableName, string oldColumnName, string newColumnName)
{
if (ColumnExists(tableName, newColumnName))
{
throw new MigrationException(string.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
}
if (!ColumnExists(tableName, oldColumnName))
{
throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, oldColumnName));
}
var column = GetColumnByName(tableName, oldColumnName);
var quotedNewColumnName = QuoteColumnNameIfRequired(newColumnName);
ExecuteNonQuery(string.Format("ALTER TABLE {0} RENAME COLUMN {1} TO {2}", tableName, Dialect.Quote(column.Name), quotedNewColumnName));
}
public virtual void RemoveColumn(string tableName, string column)
{
if (!TableExists(tableName))
{
throw new MigrationException($"The table '{tableName}' does not exist");
}
if (!ColumnExists(tableName, column, true))
{
throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, column));
}
var existingColumn = GetColumnByName(tableName, column);
ExecuteNonQuery(string.Format("ALTER TABLE {0} DROP COLUMN {1} ", tableName, Dialect.Quote(existingColumn.Name)));
}
public virtual bool ColumnExists(string table, string column)
{
return ColumnExists(table, column, true);
}
public virtual bool ColumnExists(string table, string column, bool ignoreCase)
{
if (ignoreCase)
{
return GetColumns(table).Any(x => x.Name.Equals(column, StringComparison.OrdinalIgnoreCase));
}
return GetColumns(table).Any(x => x.Name == column);
}
public virtual void ChangeColumn(string table, Column column)
{
var isUniqueSet = column.ColumnProperty.IsSet(ColumnProperty.Unique);
column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.Unique);
var mapper = _dialect.GetAndMapColumnProperties(column);
ChangeColumn(table, mapper.ColumnSql);
if (isUniqueSet)
{
AddUniqueConstraint(string.Format("UX_{0}_{1}", table, column.Name), table, [column.Name]);
}
}
public virtual void RemoveColumnDefaultValue(string table, string column)
{
var sql = string.Format("ALTER TABLE {0} ALTER {1} DROP DEFAULT", table, column);
ExecuteNonQuery(sql);
}
public virtual bool TableExists(string table)
{
throw new NotImplementedException();
}
public virtual bool ViewExists(string view)
{
throw new NotImplementedException();
}
public virtual void SwitchDatabase(string databaseName)
{
_connection.ChangeDatabase(databaseName);
}
public abstract List<string> GetDatabases();
public bool DatabaseExists(string name)
{
return GetDatabases().Any(c => string.Equals(name, c, StringComparison.OrdinalIgnoreCase));
}
public virtual void CreateDatabases(string databaseName)
{
ExecuteNonQuery(string.Format("CREATE DATABASE {0}", databaseName));
}
public virtual void KillDatabaseConnections(string databaseName)
{
//todo, implement this for each DB, no default implementation possible!!!
}
public virtual void DropDatabases(string databaseName)
{
ExecuteNonQuery(string.Format("DROP DATABASE {0}", databaseName));
}
/// <summary>
/// Add a new column to an existing table.
/// </summary>
/// <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="ColumnProperty">ColumnProperty</see>,</param>
/// <param name="defaultValue">Default value</param>
public void AddColumn(string table, string column, DbType type, int size, ColumnProperty property,
object defaultValue)
{
AddColumn(table, column, (MigratorDbType)type, size, property, defaultValue);
}
/// <summary>
/// Add a new column to an existing table.
/// </summary>
/// <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="ColumnProperty">ColumnProperty</see>,</param>
/// <param name="defaultValue">Default value</param>
public virtual void AddColumn(string table, string column, MigratorDbType type, int size, ColumnProperty property,
object defaultValue)
{
var mapper =
_dialect.GetAndMapColumnProperties(new Column(column, type, size, property, defaultValue));
AddColumn(table, mapper.ColumnSql);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, DbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, DbType type)
{
AddColumn(table, column, type, 0, ColumnProperty.Null, null);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, MigratorDbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, MigratorDbType type)
{
AddColumn(table, column, type, 0, ColumnProperty.Null, null);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, DbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, DbType type, int size)
{
AddColumn(table, column, type, size, ColumnProperty.Null, null);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, MigratorDbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, MigratorDbType type, int size)
{
AddColumn(table, column, type, size, ColumnProperty.Null, null);
}
public virtual void AddColumn(string table, string column, DbType type, object defaultValue)
{
AddColumn(table, column, (MigratorDbType)type, defaultValue);
}
public virtual void AddColumn(string table, string column, MigratorDbType type, object defaultValue)
{
var mapper =
_dialect.GetAndMapColumnProperties(new Column(column, type, defaultValue));
AddColumn(table, mapper.ColumnSql);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, DbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, DbType type, ColumnProperty property)
{
AddColumn(table, column, type, 0, property, null);
}
/// <summary>
/// <see cref="TransformationProvider.AddColumn(string, string, MigratorDbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, MigratorDbType type, ColumnProperty property)
{
AddColumn(table, column, type, 0, property, null);
}
/// <summary>
/// <see cref="AddColumn(string, string, DbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, DbType type, int size, ColumnProperty property)
{
AddColumn(table, column, type, size, property, null);
}
/// <summary>
/// <see cref="AddColumn(string, string, MigratorDbType, int, ColumnProperty, object)">
/// AddColumn(string, string, Type, int, ColumnProperty, object)
/// </see>
/// </summary>
public virtual void AddColumn(string table, string column, MigratorDbType type, int size, ColumnProperty property)
{
AddColumn(table, column, type, size, property, null);
}
/// <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 virtual void AddPrimaryKey(string name, string table, params string[] columns)
{
QuoteColumnNamesIfRequired(columns);
table = QuoteTableNameIfRequired(table);
ExecuteNonQuery(
string.Format("ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY ({2}) ", table, name,
string.Join(",", QuoteColumnNamesIfRequired(columns))));
}
public virtual void AddPrimaryKeyNonClustered(string name, string table, params string[] columns)
{
this.AddPrimaryKey(name, table, columns);
}
public virtual void AddUniqueConstraint(string name, string table, params string[] columns)
{
QuoteColumnNamesIfRequired(columns);
table = QuoteTableNameIfRequired(table);
ExecuteNonQuery(string.Format("ALTER TABLE {0} ADD CONSTRAINT {1} UNIQUE({2}) ", table, name, string.Join(", ", columns)));
}
public virtual void AddCheckConstraint(string name, string table, string checkSql)
{
table = QuoteTableNameIfRequired(table);
ExecuteNonQuery(string.Format("ALTER TABLE {0} ADD CONSTRAINT {1} CHECK ({2}) ", table, name, checkSql));
}
/// <summary>
/// Guesses the name of the foreign key and adds it
/// </summary>
public virtual void GenerateForeignKey(string childTable, string childColumn, string parentTable, string parentColumn)
{
AddForeignKey("FK_" + childTable + "_" + parentTable, childTable, childColumn, parentTable, parentColumn);
}
/// <summary>
/// Guesses the name of the foreign key and adds it
/// </see>
/// </summary>
public virtual void GenerateForeignKey(
string childTable,
string[] childColumns,
string parentTable,
string[] parentColumns)
{
AddForeignKey("FK_" + childTable + "_" + parentTable, childTable, childColumns, parentTable, parentColumns);
}
/// <summary>
/// Guesses the name of the foreign key and adds it
/// </summary>
public virtual void GenerateForeignKey(
string childTable,
string childColumn,
string parentTable,
string parentColumn,
ForeignKeyConstraintType constraint)
{
AddForeignKey("FK_" + childTable + "_" + parentTable, childTable, childColumn, parentTable, parentColumn, constraint);
}
/// <summary>
/// Guesses the name of the foreign key and add it
/// </see>
/// </summary>
public virtual void GenerateForeignKey(
string childTable,
string[] childColumns,
string parentTable,
string[] parentColumns,
ForeignKeyConstraintType constraint)
{
AddForeignKey("FK_" + childTable + "_" + parentTable, childTable, childColumns, parentTable, parentColumns, constraint);
}
public virtual void AddForeignKey(string table, ForeignKeyConstraint fk)
{
AddForeignKey(fk.Name, table, fk.ParentColumns, fk.ChildTable, fk.ChildColumns);
}
public virtual void AddForeignKey(string name, string childTable, string childColumn, string parentTable, string parentColumn)
{
try
{
AddForeignKey(name, childTable, [childColumn], parentTable, [parentColumn]);
}
catch (Exception ex)
{
throw new Exception(string.Format("Error occured while adding foreign key: \"{0}\" between table: \"{1}\" and table: \"{2}\" - see inner exception for details", name, parentTable, childTable), ex);
}
}
public virtual void AddForeignKey(string name, string childTable, string[] childColumns, string parentTable, string[] parentColumns)
{
AddForeignKey(name, childTable, childColumns, parentTable, parentColumns, ForeignKeyConstraintType.NoAction);
}
public virtual void AddForeignKey(string name, string childTable, string childColumn, string parentTable, string parentColumn, ForeignKeyConstraintType constraint)
{
AddForeignKey(name, childTable, [childColumn], parentTable, [parentColumn], constraint);
}
public virtual void AddForeignKey(
string name,
string childTable,
string[] childColumns,
string parentTable,
string[] parentColumns,
ForeignKeyConstraintType constraint)
{
childTable = QuoteTableNameIfRequired(childTable);
parentTable = QuoteTableNameIfRequired(parentTable);
QuoteColumnNames(parentColumns);
QuoteColumnNames(childColumns);
var constraintResolved = constraintMapper.SqlForConstraint(constraint);
// TODO Issue #52 still unresolved
var childColumnsString = string.Join(", ", childColumns);
var parentColumnsString = string.Join(", ", parentColumns);
var stringBuilder = new StringBuilder();
stringBuilder.Append($"ALTER TABLE {childTable} ADD CONSTRAINT {name} FOREIGN KEY ({childColumnsString}) REFERENCES {parentTable} ({parentColumnsString})");
stringBuilder.Append($"ON UPDATE {constraintResolved} ON DELETE {constraintResolved}");
ExecuteNonQuery(stringBuilder.ToString());
}
/// <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 table, string name);
public virtual bool PrimaryKeyExists(string table, string name)
{
return ConstraintExists(table, name);
}
public virtual int ExecuteNonQuery(string sql)
{
return ExecuteNonQuery(sql, CommandTimeout ?? 30);
}
public virtual int ExecuteNonQuery(string sql, int timeout)
{
return ExecuteNonQuery(sql, timeout, null);
}
public virtual int ExecuteNonQuery(string sql, int timeout, params object[] args)
{
if (args == null)
{
Logger.Trace(sql);
Logger.ApplyingDBChange(sql);
}
else
{
Logger.Trace(string.Format(sql, args));
Logger.ApplyingDBChange(string.Format(sql, args));
}
using var cmd = BuildCommand(sql);
try
{
cmd.CommandTimeout = timeout;
if (args != null)
{
var index = 0;
foreach (var obj in args)
{
var parameter = cmd.CreateParameter();
ConfigureParameterWithValue(parameter, index, obj);
parameter.ParameterName = GenerateParameterNameParameter(index);
cmd.Parameters.Add(parameter);
++index;
}
}
Logger.Trace(cmd.CommandText);
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Logger.Warn(ex.Message);
throw new MigrationException(string.Format("Error occured executing sql: {0}, see inner exception for details, error: " + ex, sql), ex);
}
}
public List<string> ExecuteStringQuery(string sql, params object[] args)
{
var values = new List<string>();
using (var cmd = CreateCommand())
{
using var reader = ExecuteQuery(cmd, string.Format(sql, args));
while (reader.Read())
{
var value = reader[0];
if (value == null || value == DBNull.Value)
{
values.Add(null);
}
else
{
values.Add(value.ToString());
}
}
}
return values;
}
public virtual void ExecuteScript(string fileName)
{
if (CurrentMigration != null)
{
#if NETSTANDARD
var assembly = CurrentMigration.GetType().GetTypeInfo().Assembly;
#else
var assembly = CurrentMigration.GetType().Assembly;
#endif
string sqlText;
var file = (new System.Uri(assembly.CodeBase)).AbsolutePath;
using (var reader = File.OpenText(file))
{
sqlText = reader.ReadToEnd();
}
ExecuteNonQuery(sqlText);
}
}
/// <summary>
/// Execute an SQL query returning results.
/// </summary>
/// <param name="sql">The SQL text.</param>
/// <param name="cmd">The IDbCommand.</param>
/// <returns>A data iterator, <see cref="System.Data.IDataReader">IDataReader</see>.</returns>
public virtual IDataReader ExecuteQuery(IDbCommand cmd, string sql)
{
Logger.Trace(sql);
cmd.CommandText = sql;
try
{
return cmd.ExecuteReader();
}
catch (Exception ex)
{
Logger.Warn("query failed: {0}", cmd.CommandText);
throw new Exception("Failed to execute sql statement: " + sql, ex);
}
}
public virtual object ExecuteScalar(string sql)
{
Logger.Trace(sql);
using var cmd = BuildCommand(sql);
try
{
return cmd.ExecuteScalar();
}
catch
{
Logger.Warn("Query failed: {0}", cmd.CommandText);
throw;
}
}