forked from bittercoder/Migrator.NET
-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSQLiteTransformationProvider.cs
More file actions
1932 lines (1524 loc) · 71.7 KB
/
SQLiteTransformationProvider.cs
File metadata and controls
1932 lines (1524 loc) · 71.7 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
using DotNetProjects.Migrator.Framework;
using DotNetProjects.Migrator.Providers.Impl.SQLite.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ForeignKeyConstraint = DotNetProjects.Migrator.Framework.ForeignKeyConstraint;
using Index = DotNetProjects.Migrator.Framework.Index;
using DotNetProjects.Migrator.Framework.Extensions;
using DotNetProjects.Migrator.Providers.Models.Indexes;
using DotNetProjects.Migrator.Providers.Models.Indexes.Enums;
using DotNetProjects.Migrator.Framework.Models;
namespace DotNetProjects.Migrator.Providers.Impl.SQLite;
/// <summary>
/// Summary description for SQLiteTransformationProvider.
/// </summary>
public partial class SQLiteTransformationProvider : TransformationProvider
{
private const string IntermediateTableSuffix = "Temp";
public SQLiteTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
: base(dialect, connectionString, null, scope)
{
CreateConnection(providerName);
}
public SQLiteTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
: base(dialect, connection, null, scope)
{
}
protected virtual void CreateConnection(string providerName)
{
if (string.IsNullOrEmpty(providerName))
{
providerName = "System.Data.SQLite";
}
var fac = DbProviderFactoriesHelper.GetFactory(providerName, "System.Data.SQLite", "System.Data.SQLite.SQLiteFactory");
_connection = fac.CreateConnection(); // new SQLiteConnection(_connectionString);
_connection.ConnectionString = _connectionString;
_connection.Open();
}
public override void AddForeignKey(
string name,
string childTable,
string[] childColumns,
string parentTable,
string[] parentColumns,
ForeignKeyConstraintType constraint)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new Exception("The foreign key name is mandatory");
}
var sqliteTableInfo = GetSQLiteTableInfo(childTable);
// Get all unique constraint names if available
var uniqueConstraintNames = sqliteTableInfo.Uniques.Select(x => x.Name).ToList();
// Get all FK constraint names if available
var foreignKeyNames = sqliteTableInfo.ForeignKeys.Select(x => x.Name).ToList();
var names = uniqueConstraintNames.Concat(foreignKeyNames)
.Distinct()
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToList();
if (names.Any(x => x.Equals(name, StringComparison.OrdinalIgnoreCase)))
{
throw new Exception($"Constraint name {name} already exists");
}
var foreignKey = new ForeignKeyConstraint
{
ChildColumns = childColumns,
ChildTable = childTable,
Name = name,
ParentColumns = parentColumns,
ParentTable = parentTable,
};
sqliteTableInfo.ForeignKeys
.Add(foreignKey);
RecreateTable(sqliteTableInfo);
}
public string[] GetColumnDefs(string table, out string compositeDefSql)
{
return ParseSqlColumnDefs(GetSqlCreateTableScript(table), out compositeDefSql);
}
/// <summary>
/// Gets the SQL CREATE TABLE script. Case-insensitive
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public string GetSqlCreateTableScript(string table)
{
string sqlCreateTableScript = null;
using (var cmd = CreateCommand())
using (var reader = ExecuteQuery(cmd, string.Format("SELECT sql FROM sqlite_master WHERE type='table' AND lower(name)=lower('{0}')", table)))
{
if (reader.Read())
{
sqlCreateTableScript = reader.IsDBNull(0) ? null : (string)reader[0];
}
}
return sqlCreateTableScript;
}
public override ForeignKeyConstraint[] GetForeignKeyConstraints(string tableName)
{
List<ForeignKeyConstraint> foreignKeyConstraints = [];
var pragmaForeignKeyListItems = GetForeignKeyListItems(tableName);
var groups = pragmaForeignKeyListItems.GroupBy(x => x.Id);
foreach (var group in groups)
{
var foreignKeyConstraint = new ForeignKeyConstraint
{
Id = group.First().Id,
// SQLite does not support FK names.
ChildColumns = group.OrderBy(x => x.Seq).Select(x => x.From).ToArray(),
ChildTable = tableName,
Match = group.First().Match,
Name = null,
OnDelete = group.First().OnDelete,
OnUpdate = group.First().OnUpdate,
ParentColumns = group.OrderBy(x => x.Seq).Select(x => x.To).ToArray(),
ParentTable = group.First().Table,
};
foreignKeyConstraints.Add(foreignKeyConstraint);
}
if (foreignKeyConstraints.Count == 0)
{
return [];
}
var createTableScript = GetSqlCreateTableScript(tableName);
// GeneratedRegex
var regEx = new Regex(@"CONSTRAINT\s+\w+\s+FOREIGN\s+KEY\s*\([^)]+\)\s+REFERENCES\s+[\w""]+\s*\([^)]+\)");
var matchesCollection = regEx.Matches(createTableScript);
var fkParts = matchesCollection.Cast<Match>().ToList().Where(x => x.Success).Select(x => x.Value).ToList();
if (fkParts.Count != foreignKeyConstraints.Count)
{
throw new Exception($"Cannot extract all foreign keys out of the create table script in SQLite. Did you use a name as foreign key constraint for all constraints in table '{tableName}' in this or older migrations?");
}
List<ForeignKeyExtract> foreignKeyExtracts = [];
foreach (var fkPart in fkParts)
{
var regexParenthesis = new Regex(@"\(([^)]+)\)");
var parenthesisContents = regexParenthesis.Matches(fkPart).Cast<Match>().Select(x => x.Groups[1].Value).ToList();
if (parenthesisContents.Count != 2)
{
throw new Exception("Cannot extract parenthesis of foreign key constraint");
}
var foreignKeyExtract = new ForeignKeyExtract()
{
ChildColumnNames = parenthesisContents[0].Split(',').Select(x => x.Trim()).ToList(),
ForeignKeyString = fkPart,
ParentColumnNames = parenthesisContents[1].Split(',').Select(x => x.Trim()).ToList(),
};
var foreignKeyConstraintNameRegex = new Regex(@"CONSTRAINT\s+(\w+)\s+FOREIGN\s+KEY");
var foreignKeyNameMatch = foreignKeyConstraintNameRegex.Match(fkPart);
if (!foreignKeyNameMatch.Success)
{
throw new Exception("Could not extract the foreign key constraint name");
}
foreignKeyExtract.ForeignKeyName = foreignKeyNameMatch.Groups[1].Value;
foreignKeyExtracts.Add(foreignKeyExtract);
}
foreach (var foreignKeyConstraint in foreignKeyConstraints)
{
foreach (var foreignKeyExtract in foreignKeyExtracts)
{
if (
foreignKeyExtract.ChildColumnNames.SequenceEqual(foreignKeyConstraint.ChildColumns) &&
foreignKeyExtract.ParentColumnNames.SequenceEqual(foreignKeyConstraint.ParentColumns)
)
{
foreignKeyConstraint.Name = foreignKeyExtract.ForeignKeyName;
}
}
}
return foreignKeyConstraints.ToArray();
}
public override void UpdateTargetFromSource(string tableSourceNotQuoted, string tableTargetNotQuoted, ColumnPair[] fromSourceToTargetColumnPairs, ColumnPair[] conditionColumnPairs)
{
if (!TableExists(tableSourceNotQuoted))
{
throw new Exception($"Table '{tableSourceNotQuoted}' given in '{nameof(tableSourceNotQuoted)}' does not exist");
}
if (!TableExists(tableTargetNotQuoted))
{
throw new Exception($"Table '{tableTargetNotQuoted}' given in '{nameof(tableTargetNotQuoted)}' does not exist");
}
if (fromSourceToTargetColumnPairs.Length == 0)
{
throw new Exception($"{nameof(fromSourceToTargetColumnPairs)} is empty.");
}
if (fromSourceToTargetColumnPairs.Any(x => string.IsNullOrWhiteSpace(x.ColumnNameSource) || string.IsNullOrWhiteSpace(x.ColumnNameTarget)))
{
throw new Exception($"One of the strings in {nameof(fromSourceToTargetColumnPairs)} is null or empty");
}
if (conditionColumnPairs.Length == 0)
{
throw new Exception($"{nameof(conditionColumnPairs)} is empty.");
}
if (conditionColumnPairs.Any(x => string.IsNullOrWhiteSpace(x.ColumnNameSource) || string.IsNullOrWhiteSpace(x.ColumnNameTarget)))
{
throw new Exception($"One of the strings in {nameof(conditionColumnPairs)} is null or empty");
}
var tableNameSource = QuoteTableNameIfRequired(tableSourceNotQuoted);
var tableNameTarget = QuoteTableNameIfRequired(tableTargetNotQuoted);
var assignStrings = fromSourceToTargetColumnPairs.Select(x => $"{QuoteColumnNameIfRequired(x.ColumnNameTarget)} = {tableNameSource}.{QuoteColumnNameIfRequired(x.ColumnNameSource)}").ToList();
var conditionStrings = conditionColumnPairs.Select(x => $"{tableNameSource}.{QuoteColumnNameIfRequired(x.ColumnNameSource)} = {tableNameTarget}.{QuoteColumnNameIfRequired(x.ColumnNameTarget)}");
var assignStringsJoined = string.Join(", ", assignStrings);
var conditionStringsJoined = string.Join(" AND ", conditionStrings);
var sql = $"UPDATE {tableNameTarget} SET {assignStringsJoined} FROM {tableNameSource} WHERE {conditionStringsJoined}";
ExecuteNonQuery(sql);
}
private List<PragmaForeignKeyListItem> GetForeignKeyListItems(string tableNameNotQuoted)
{
List<PragmaForeignKeyListItem> pragmaForeignKeyListItems = [];
using (var cmd = CreateCommand())
using (var reader = ExecuteQuery(cmd, $"PRAGMA foreign_key_list('{QuoteTableNameIfRequired(tableNameNotQuoted)}')"))
{
while (reader.Read())
{
var pragmaForeignKeyListItem = new PragmaForeignKeyListItem
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Seq = reader.GetInt32(reader.GetOrdinal("seq")),
Table = reader.GetString(reader.GetOrdinal("table")),
From = reader.GetString(reader.GetOrdinal("from")),
To = reader.GetString(reader.GetOrdinal("to")),
OnUpdate = reader.GetString(reader.GetOrdinal("on_update")),
OnDelete = reader.GetString(reader.GetOrdinal("on_delete")),
Match = reader.GetString(reader.GetOrdinal("match")),
};
pragmaForeignKeyListItems.Add(pragmaForeignKeyListItem);
}
}
return pragmaForeignKeyListItems;
}
public string[] ParseSqlColumnDefs(string sqldef, out string compositeDefSql)
{
if (string.IsNullOrEmpty(sqldef))
{
compositeDefSql = null;
return null;
}
sqldef = sqldef.Replace(Environment.NewLine, " ");
var start = sqldef.IndexOf("(");
// Code to handle composite primary keys /mol
var compositeDefIndex = sqldef.IndexOf("PRIMARY KEY ("); // Not ideal to search for a string like this but I'm lazy
if (compositeDefIndex > -1)
{
compositeDefSql = sqldef.Substring(compositeDefIndex, sqldef.LastIndexOf(")") - compositeDefIndex);
sqldef = sqldef.Substring(0, compositeDefIndex).TrimEnd(',', ' ') + ")";
}
else
{
compositeDefSql = null;
}
var end = sqldef.LastIndexOf(")"); // Changed from 'IndexOf' to 'LastIndexOf' to handle foreign key definitions /mol
sqldef = sqldef.Substring(0, end);
sqldef = sqldef.Substring(start + 1);
var cols = sqldef.Split([',']);
for (var i = 0; i < cols.Length; i++)
{
cols[i] = cols[i].Trim();
}
return cols;
}
/// <summary>
/// Turn something like 'columnName INTEGER NOT NULL' into just 'columnName'
/// </summary>
public string[] ParseSqlForColumnNames(string sqldef, out string compositeDefSql)
{
var parts = ParseSqlColumnDefs(sqldef, out compositeDefSql);
return ParseSqlForColumnNames(parts);
}
public string[] ParseSqlForColumnNames(string[] parts)
{
if (null == parts)
{
return null;
}
for (var i = 0; i < parts.Length; i++)
{
parts[i] = ExtractNameFromColumnDef(parts[i]);
}
return parts;
}
/// <summary>
/// Name is the first value before the space.
/// </summary>
/// <param name="columnDef"></param>
/// <returns></returns>
public static string ExtractNameFromColumnDef(string columnDef)
{
var idx = columnDef.IndexOf(" ");
if (idx > 0)
{
return columnDef.Substring(0, idx);
}
return null;
}
public DbType ExtractTypeFromColumnDef(string columnDef)
{
var idx = columnDef.IndexOf(" ") + 1;
if (idx > 0)
{
var idy = columnDef.IndexOf(" ", idx) - idx;
if (idy > 0)
{
return _dialect.GetDbType(columnDef.Substring(idx, idy));
}
else
{
return _dialect.GetDbType(columnDef.Substring(idx));
}
}
else
{
throw new Exception("Error extracting type from column definition: '" + columnDef + "'");
}
}
public override void RemoveForeignKey(string table, string name)
{
if (!TableExists(table))
{
throw new MigrationException($"Table '{table}' does not exist.");
}
var sqliteTableInfo = GetSQLiteTableInfo(table);
if (!sqliteTableInfo.ForeignKeys.Any(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
{
throw new MigrationException($"Foreign key '{name}' does not exist.");
}
sqliteTableInfo.ForeignKeys.RemoveAll(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
RecreateTable(sqliteTableInfo);
}
public string[] GetCreateIndexSqlStrings(string table)
{
var sqlStrings = new List<string>();
using (var cmd = CreateCommand())
using (var reader = ExecuteQuery(cmd, string.Format("SELECT sql FROM sqlite_master WHERE type='index' AND sql NOT NULL AND lower(tbl_name)=lower('{0}')", table)))
{
while (reader.Read())
{
sqlStrings.Add((string)reader[0]);
}
}
return [.. sqlStrings];
}
public void MoveIndexesFromOriginalTable(string origTable, string newTable)
{
var indexSqls = GetCreateIndexSqlStrings(origTable);
foreach (var indexSql in indexSqls)
{
var origTableStart = indexSql.IndexOf(" ON ", StringComparison.OrdinalIgnoreCase) + 4;
var origTableEnd = indexSql.IndexOf("(", origTableStart);
// First remove original index, because names have to be unique
var createIndexDef = " INDEX ";
var indexNameStart = indexSql.IndexOf(createIndexDef, StringComparison.OrdinalIgnoreCase) + createIndexDef.Length;
ExecuteNonQuery("DROP INDEX " + indexSql.Substring(indexNameStart, origTableStart - 4 - indexNameStart));
// Create index on new table
ExecuteNonQuery(indexSql.Substring(0, origTableStart) + newTable + " " + indexSql.Substring(origTableEnd));
}
}
public override void RemoveColumn(string tableName, string column)
{
// In SQLite we need to recreate the table even if we only want to add, alter or drop a foreign key. So we not only recreate the table given
// as parameter but also the tables with FKs pointing to the column you want to remove.
// In order to perform it smoothly, the PRAGMA foreign keys should be set off.
var isPragmaForeignKeysOn = IsPragmaForeignKeysOn();
if (isPragmaForeignKeysOn)
{
throw new Exception($"{nameof(RemoveColumn)} requires foreign keys off.");
}
if (!TableExists(tableName))
{
throw new MigrationException($"The table '{tableName}' does not exist");
}
if (!ColumnExists(tableName, column))
{
throw new MigrationException($"The table '{tableName}' does not have a column named '{column}'");
}
var sqliteInfoMainTable = GetSQLiteTableInfo(tableName);
var checkConstraints = sqliteInfoMainTable.CheckConstraints;
if (checkConstraints.Any(x => x.CheckConstraintString.Contains(column, StringComparison.OrdinalIgnoreCase)))
{
throw new MigrationException("A check constraint contains the column you want to remove. Remove the check constraint first");
}
if (!sqliteInfoMainTable.ColumnMappings.Any(x => x.OldName == column))
{
throw new MigrationException("Column not found");
}
// We throw if all of the conditions are fulfilled:
// - the unique constraint is a composite constraint (more than one column)
// - the column to be removed is part of the constraint
// In case of single constraint we remove it silently as it is not needed any more
var isColumnInUniqueConstraint = sqliteInfoMainTable.Uniques
.Where(x => x.KeyColumns.Length > 1)
.SelectMany(x => x.KeyColumns)
.Distinct()
.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase));
if (isColumnInUniqueConstraint)
{
StringBuilder stringBuilder = new();
stringBuilder.Append("Found composite unique constraint where the column that you want to remove is part of. Remove the unique constraints first before you remove the column.");
stringBuilder.Append("Other unique constraints(if exists) that contains only the column to be removed are dropped silently.");
throw new Exception(stringBuilder.ToString());
}
var isColumnInIndex = sqliteInfoMainTable.Indexes
.Where(x => x.KeyColumns.Length > 1)
.SelectMany(x => x.KeyColumns)
.Distinct()
.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase));
if (isColumnInIndex)
{
StringBuilder stringBuilder = new();
stringBuilder.Append("Found composite index where the column that you want to remove is part of. Remove the indexes first before you remove the column.");
stringBuilder.Append("Other indexes(if exists) that contains only the column to be removed are dropped silently.");
throw new Exception(stringBuilder.ToString());
}
var isColumnInForeignKey = sqliteInfoMainTable.ForeignKeys
.Where(x => x.ChildColumns.Length > 1)
.SelectMany(x => x.ChildColumns)
.Distinct()
.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase));
if (isColumnInForeignKey)
{
StringBuilder stringBuilder = new();
stringBuilder.Append("Found foreign key with more than two columns with one column is the column you want to remove. Remove the foreign key before you ");
stringBuilder.Append("remove the column. Other foreign keys (if exists) that contain only the column to be removed are dropped silently.");
throw new Exception(stringBuilder.ToString());
}
var allTableNames = GetTables();
// Remove foreign keys with single parent column pointing to the column to be removed.
foreach (var allTableName in allTableNames)
{
if (allTableName == tableName)
{
continue;
}
var sqliteTableInfoOther = GetSQLiteTableInfo(allTableName);
var recreateOtherTable = false;
for (var i = sqliteTableInfoOther.ForeignKeys.Count - 1; i >= 0; i--)
{
if (!sqliteTableInfoOther.ForeignKeys[i].ParentTable.Equals(tableName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (sqliteTableInfoOther.ForeignKeys[i].ParentColumns.Contains(column) && sqliteTableInfoOther.ForeignKeys[i].ParentColumns.Length > 1)
{
StringBuilder stringBuilder = new();
stringBuilder.Append($"You need to delete/adjust the FK in table {allTableName} pointing to {tableName}.");
stringBuilder.Append("Other foreign key if exists with just one parent column we adjust silently.");
throw new Exception(stringBuilder.ToString());
}
if (sqliteTableInfoOther.ForeignKeys[i].ParentColumns.Contains(column) && sqliteTableInfoOther.ForeignKeys[i].ParentColumns.Length == 1)
{
recreateOtherTable = true;
sqliteTableInfoOther.ForeignKeys.RemoveAt(i);
}
}
if (recreateOtherTable)
{
RecreateTable(sqliteTableInfoOther);
}
}
sqliteInfoMainTable.Uniques.RemoveAll(x => x.KeyColumns.Length == 1 && x.KeyColumns[0].Equals(column, StringComparison.OrdinalIgnoreCase));
sqliteInfoMainTable.ColumnMappings.RemoveAll(x => x.OldName.Equals(column, StringComparison.OrdinalIgnoreCase));
sqliteInfoMainTable.Columns.RemoveAll(x => x.Name.Equals(column, StringComparison.OrdinalIgnoreCase));
sqliteInfoMainTable.Indexes.RemoveAll(x => x.KeyColumns.Length == 1 && x.KeyColumns[0].Equals(column, StringComparison.OrdinalIgnoreCase));
sqliteInfoMainTable.ForeignKeys.RemoveAll(x => x.ChildColumns.Length == 1 && x.ChildColumns[0].Equals(column, StringComparison.OrdinalIgnoreCase));
RecreateTable(sqliteInfoMainTable);
}
public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
{
if (!TableExists(tableName))
{
throw new Exception($"Table {tableName} does not exist");
}
var isPragmaForeignKeysOn = IsPragmaForeignKeysOn();
if (isPragmaForeignKeysOn)
{
throw new Exception($"{nameof(RenameColumn)} requires foreign keys off.");
}
// Due to old .Net versions we cannot use ThrowIfNullOrWhitespace
if (string.IsNullOrWhiteSpace(newColumnName))
{
throw new Exception("New column name is null or empty");
}
if (ColumnExists(tableName, newColumnName))
{
throw new MigrationException(string.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
}
if (ColumnExists(tableName, oldColumnName))
{
var sqliteTableInfo = GetSQLiteTableInfo(tableName);
var columnMapping = sqliteTableInfo.ColumnMappings.First(x => x.OldName.Equals(oldColumnName, StringComparison.OrdinalIgnoreCase));
columnMapping.NewName = newColumnName;
var column = sqliteTableInfo.Columns.First(x => x.Name.Equals(oldColumnName, StringComparison.OrdinalIgnoreCase));
column.Name = newColumnName;
foreach (var foreignKey in sqliteTableInfo.ForeignKeys)
{
foreignKey.ChildColumns = [.. foreignKey.ChildColumns.Select(x => x.Equals(oldColumnName, StringComparison.OrdinalIgnoreCase) ? newColumnName : x)];
}
foreach (var index in sqliteTableInfo.Indexes)
{
index.KeyColumns = [.. index.KeyColumns.Select(x => x.Equals(oldColumnName, StringComparison.OrdinalIgnoreCase) ? newColumnName : x)];
}
foreach (var unique in sqliteTableInfo.Uniques)
{
unique.KeyColumns = [.. unique.KeyColumns.Select(x => x.Equals(oldColumnName, StringComparison.OrdinalIgnoreCase) ? newColumnName : x)];
}
RecreateTable(sqliteTableInfo);
var allTables = GetTables();
// Rename in foreign keys of depending tables
foreach (var allTablesItem in allTables)
{
if (allTablesItem == tableName)
{
continue;
}
var sqliteTableInfoOther = GetSQLiteTableInfo(allTablesItem);
foreach (var foreignKey in sqliteTableInfoOther.ForeignKeys)
{
if (foreignKey.ParentTable != tableName)
{
continue;
}
foreignKey.ParentColumns = foreignKey.ParentColumns.Select(x => x == oldColumnName ? newColumnName : x).ToArray();
RecreateTable(sqliteTableInfoOther);
}
}
}
else
{
throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, oldColumnName));
}
}
public override void RemoveColumnDefaultValue(string tableName, string columnName)
{
if (!TableExists(tableName))
{
throw new Exception("Table does not exist");
}
if (!ColumnExists(table: tableName, column: columnName))
{
throw new Exception("Column does not exist");
}
var sqliteTableInfo = GetSQLiteTableInfo(tableName);
var column = sqliteTableInfo.Columns.First(x => x.Name == columnName);
column.DefaultValue = null;
RecreateTable(sqliteTableInfo);
}
public override void AddPrimaryKey(string name, string tableName, params string[] columnNames)
{
if (!TableExists(tableName))
{
throw new Exception("Table does not exist");
}
var sqliteTableInfo = GetSQLiteTableInfo(tableName);
foreach (var column in sqliteTableInfo.Columns)
{
if (columnNames.Any(x => x.Equals(column.Name, StringComparison.OrdinalIgnoreCase)))
{
column.ColumnProperty = column.ColumnProperty.Set(ColumnProperty.PrimaryKey);
}
else
{
column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.PrimaryKey);
}
}
var columnNamesList = columnNames.ToList();
var columnsReordered = sqliteTableInfo.Columns.OrderBy(x =>
{
var index = columnNamesList.IndexOf(x.Name);
return index >= 0 ? index : int.MaxValue;
}).ToList();
sqliteTableInfo.Columns = columnsReordered;
RecreateTable(sqliteTableInfo);
}
public override bool PrimaryKeyExists(string table, string name)
{
var sqliteTableInfo = GetSQLiteTableInfo(table);
// SQLite does not offer named primary keys BUT since there can only be one primary key per table we return true if there is any primary key.
var hasPrimaryKey = sqliteTableInfo.Columns.Any(x => x.ColumnProperty.IsSet(ColumnProperty.PrimaryKey));
return hasPrimaryKey;
}
public override void AddUniqueConstraint(string name, string table, params string[] columns)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new MigrationException("Providing a constraint name is obligatory.");
}
var sqliteTableInfo = GetSQLiteTableInfo(table);
if (sqliteTableInfo.Uniques.Any(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
{
throw new MigrationException("A unique constraint with the same name already exists.");
}
var uniqueConstraint = new Unique() { KeyColumns = columns, Name = name };
sqliteTableInfo.Uniques.Add(uniqueConstraint);
RecreateTable(sqliteTableInfo);
}
public override void RemoveConstraint(string table, string name)
{
var sqliteTableInfo = GetSQLiteTableInfo(table);
sqliteTableInfo.Uniques.RemoveAll(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
sqliteTableInfo.CheckConstraints.RemoveAll(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
RecreateTable(sqliteTableInfo);
}
public SQLiteTableInfo GetSQLiteTableInfo(string tableName)
{
if (!TableExists(tableName))
{
return null;
}
var sqliteTable = new SQLiteTableInfo
{
TableNameMapping = new MappingInfo { OldName = tableName, NewName = tableName },
Columns = GetColumns(tableName).ToList(),
ForeignKeys = GetForeignKeyConstraints(tableName).ToList(),
Indexes = GetIndexes(tableName).ToList(),
Uniques = GetUniques(tableName).ToList(),
CheckConstraints = GetCheckConstraints(tableName)
};
sqliteTable.ColumnMappings = sqliteTable.Columns
.Select(x =>
new MappingInfo
{
OldName = x.Name,
NewName = x.Name
})
.ToList();
return sqliteTable;
}
public bool CheckForeignKeyIntegrity()
{
ExecuteNonQuery("PRAGMA foreign_keys = ON");
using var cmd = CreateCommand();
using var reader = ExecuteQuery(cmd, "PRAGMA foreign_key_check");
if (reader.Read())
{
return false;
}
return true;
}
public bool IsPragmaForeignKeysOn()
{
using var cmd = CreateCommand();
using var reader = ExecuteQuery(cmd, "PRAGMA foreign_keys");
reader.Read();
var isOn = reader.GetInt32(0) == 1;
return isOn;
}
public void SetPragmaForeignKeys(bool isOn)
{
var onOffString = isOn ? "ON" : "OFF";
using var cmd = CreateCommand();
ExecuteQuery(cmd, $"PRAGMA foreign_keys = {onOffString}");
}
public void RecreateTable(SQLiteTableInfo sqliteTableInfo)
{
var sourceTableQuoted = QuoteTableNameIfRequired(sqliteTableInfo.TableNameMapping.OldName);
var targetIntermediateTableQuoted = QuoteTableNameIfRequired($"{sqliteTableInfo.TableNameMapping.NewName}{IntermediateTableSuffix}");
var targetTableQuoted = QuoteTableNameIfRequired($"{sqliteTableInfo.TableNameMapping.NewName}");
var columnDbFields = sqliteTableInfo.Columns.Cast<IDbField>();
var foreignKeyDbFields = sqliteTableInfo.ForeignKeys.Cast<IDbField>();
var indexDbFields = sqliteTableInfo.Indexes.Cast<IDbField>();
var uniqueDbFields = sqliteTableInfo.Uniques.Cast<IDbField>();
var checkConstraintDbFields = sqliteTableInfo.CheckConstraints.Cast<IDbField>();
var dbFields = columnDbFields.Concat(foreignKeyDbFields)
.Concat(uniqueDbFields)
.Concat(checkConstraintDbFields)
.ToArray();
// ToHashSet() not available in older .NET versions so we create it old-fashioned.
var uniqueColumnNames = new HashSet<string>(sqliteTableInfo.Uniques
.SelectMany(x => x.KeyColumns)
.Distinct()
);
// ToHashSet() not available in older .NET versions so we create it old-fashioned.
var columnNames = new HashSet<string>(sqliteTableInfo.Columns
.Select(x => x.Name)
);
// ToHashSet() not available in older .NET versions so we create it old-fashioned.
var newColumnNamesInMapping = new HashSet<string>(sqliteTableInfo.ColumnMappings
.Select(x => x.NewName)
);
if (!columnNames.SetEquals(newColumnNamesInMapping))
{
throw new Exception($"{nameof(columnNames)} and {nameof(newColumnNamesInMapping)} are not equal regarding length and content");
}
if (uniqueColumnNames.Except(columnNames).Any())
{
var firstMissing = uniqueColumnNames.Except(columnNames).First();
throw new Exception($"Detected missing column names OR unique key columns that do not exist in the column list/column mapping. E.g. {firstMissing}");
}
AddTable(targetIntermediateTableQuoted, null, dbFields);
var columnMappings = sqliteTableInfo.ColumnMappings
.Where(x => x.OldName != null)
.OrderBy(x => x.OldName)
.ToList();
var sourceColumnsQuotedString = string.Join(", ", columnMappings.Select(x => QuoteColumnNameIfRequired(x.OldName)));
var targetColumnsQuotedString = string.Join(", ", columnMappings.Select(x => QuoteColumnNameIfRequired(x.NewName)));
using (var cmd = CreateCommand())
{
var sql = $"INSERT INTO {targetIntermediateTableQuoted} ({targetColumnsQuotedString}) SELECT {sourceColumnsQuotedString} FROM {sourceTableQuoted}";
ExecuteQuery(cmd, sql);
}
RemoveTable(sourceTableQuoted);
using (var cmd = CreateCommand())
{
// Rename to original name
var sql = $"ALTER TABLE {targetIntermediateTableQuoted} RENAME TO {targetTableQuoted}";
ExecuteQuery(cmd, sql);
}
foreach (var index in sqliteTableInfo.Indexes)
{
AddIndex(sqliteTableInfo.TableNameMapping.NewName, index);
}
}
[Obsolete]
public override void AddTable(string table, string engine, string columns)
{
throw new NotSupportedException();
}
public override void AddColumn(string table, Column column)
{
if (!TableExists(table))
{
throw new Exception("Table does not exist.");
}
var sqliteInfo = GetSQLiteTableInfo(table);
if (sqliteInfo.ColumnMappings.Select(x => x.OldName).ToList().Contains(column.Name))
{
throw new Exception("Column already exists.");
}
sqliteInfo.ColumnMappings.Add(new MappingInfo { OldName = null, NewName = column.Name });
sqliteInfo.Columns.Add(column);
RecreateTable(sqliteInfo);
}
public override void AddColumn(string table, string columnName, DbType type, int size)
{
var column = new Column(columnName, type, size);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, MigratorDbType type, int size)
{
var column = new Column(columnName, type, size);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, DbType type, ColumnProperty property)
{
var column = new Column(columnName, type, property);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, MigratorDbType type, ColumnProperty property)
{
var column = new Column(columnName, type, property);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, MigratorDbType type, int size, ColumnProperty property,
object defaultValue)
{
var column = new Column(columnName, type, property) { Size = size, DefaultValue = defaultValue };
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, DbType type)
{
var column = new Column(columnName, type);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, MigratorDbType type)
{
var column = new Column(columnName, type);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, DbType type, int size, ColumnProperty property)
{
var column = new Column(columnName, type, size, property);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, MigratorDbType type, int size, ColumnProperty property)
{
var column = new Column(columnName, type, size, property);
AddColumn(table, column);
}
public override void AddColumn(string table, string columnName, DbType type, object defaultValue)
{
var column = new Column(columnName, type, defaultValue);
AddColumn(table, column);
}
public override void AddColumn(string table, string sqlColumn)
{
var column = new Column(sqlColumn);
AddColumn(table, column);
}
public override void ChangeColumn(string table, Column column)
{
if (!TableExists(table))