+154
-38
lines changedFilter options
+154
-38
lines changed Original file line number Diff line number Diff line change
@@ -64,6 +64,35 @@ public static void Start(SchemaBuilder sb)
64
64
65
65
return false;
66
66
};
67
+
68
+
Administrator.AvoidSimpleGenerate = () =>
69
+
{
70
+
if(SqlMigrationRunner.MigrationDirectoryIsEmpty())
71
+
{
72
+
Console.WriteLine("Your SQL Migrations Directory is empty.");
73
+
74
+
if (SafeConsole.Ask("Do you want to create the INITIAL SQL Migration instead?"))
75
+
{
76
+
SqlMigrationRunner.CreateInitialMigration();
77
+
SqlMigrationRunner.SqlMigrations();
78
+
return true;
79
+
}
80
+
}
81
+
else
82
+
{
83
+
var hasInitial = SqlMigrationRunner.ReadMigrationsDirectory(silent: true).MinBy(a => a.Version)?.Comment.Contains("Initial Migration");
84
+
85
+
Console.WriteLine("You have an Initial SQL Migration.");
86
+
87
+
if (SafeConsole.Ask("Do you want to run the SQL Migrations instead?"))
88
+
{
89
+
SqlMigrationRunner.SqlMigrations();
90
+
return true;
91
+
}
92
+
}
93
+
94
+
return false;
95
+
};
67
96
}
68
97
}
69
98
@@ -90,24 +119,24 @@ public static void EnsureMigrationTable<T>() where T : Entity
90
119
{
91
120
using (var tr = new Transaction())
92
121
{
93
-
if (Administrator.ExistsTable<T>())
94
-
return;
122
+
if (!Administrator.ExistsTable<T>())
123
+
{
124
+
var table = Schema.Current.Table<T>();
125
+
var sqlBuilder = Connector.Current.SqlBuilder;
95
126
96
-
var table = Schema.Current.Table<T>();
97
-
var sqlBuilder = Connector.Current.SqlBuilder;
127
+
if (!table.Name.Schema.IsDefault() && !Administrator.ExistSchema(table.Name.Schema))
128
+
sqlBuilder.CreateSchema(table.Name.Schema).ExecuteLeaves();
98
129
99
-
if (!table.Name.Schema.IsDefault() && !Database.View<SysSchemas>().Any(s => s.name == table.Name.Schema.Name))
100
-
sqlBuilder.CreateSchema(table.Name.Schema).ExecuteLeaves();
130
+
sqlBuilder.CreateTableSql(table).ExecuteLeaves();
101
131
102
-
sqlBuilder.CreateTableSql(table).ExecuteLeaves();
132
+
foreach (var i in table.GeneratAllIndexes().Where(i => !(i is PrimaryKeyIndex)))
133
+
{
134
+
sqlBuilder.CreateIndex(i, checkUnique: null).ExecuteLeaves();
135
+
}
103
136
104
-
foreach (var i in table.GeneratAllIndexes().Where(i => !(i is PrimaryKeyIndex)))
105
-
{
106
-
sqlBuilder.CreateIndex(i, checkUnique: null).ExecuteLeaves();
137
+
SafeConsole.WriteLineColor(ConsoleColor.White, "Table " + table.Name + " auto-generated...");
107
138
}
108
139
109
-
SafeConsole.WriteLineColor(ConsoleColor.White, "Table " + table.Name + " auto-generated...");
110
-
111
140
tr.Commit();
112
141
}
113
142
}
Original file line number Diff line number Diff line change
@@ -20,15 +20,41 @@ public static void SqlMigrations(bool autoRun)
20
20
{
21
21
List<MigrationInfo> list = ReadMigrationsDirectory();
22
22
23
-
SetExecuted(list);
23
+
if (!autoRun && !Connector.Current.HasTables() && list.Count == 0)
24
+
{
25
+
if (!SafeConsole.Ask("Create initial migration?"))
26
+
return;
24
27
25
-
if (!Prompt(list, autoRun) || autoRun)
26
-
return;
28
+
CreateInitialMigration();
29
+
}
30
+
else
31
+
{
32
+
SetExecuted(list);
33
+
34
+
if (!Prompt(list, autoRun) || autoRun)
35
+
return;
36
+
}
27
37
}
28
38
}
29
39
40
+
public static void CreateInitialMigration()
41
+
{
42
+
var script = Schema.Current.GenerationScipt(databaseNameReplacement: DatabaseNameReplacement)!;
43
+
44
+
string version = DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss");
45
+
46
+
string comment = "Initial Migration";
47
+
48
+
string fileName = version + "_" + FileNameValidatorAttribute.RemoveInvalidCharts(comment) + ".sql";
49
+
50
+
File.WriteAllText(Path.Combine(MigrationsDirectory, fileName), script.ToString(), Encoding.UTF8);
51
+
}
52
+
30
53
private static void SetExecuted(List<MigrationInfo> migrations)
31
54
{
55
+
if (!Connector.Current.HasTables())
56
+
return;
57
+
32
58
MigrationLogic.EnsureMigrationTable<SqlMigrationEntity>();
33
59
34
60
var first = migrations.FirstOrDefault();
@@ -60,15 +86,30 @@ private static void SetExecuted(List<MigrationInfo> migrations)
60
86
migrations.Sort(a => a.Version);
61
87
}
62
88
63
-
public static List<MigrationInfo> ReadMigrationsDirectory()
89
+
public static bool MigrationDirectoryIsEmpty()
64
90
{
65
-
Console.WriteLine();
66
-
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, "Reading migrations from: " + MigrationsDirectory);
91
+
return !Directory.Exists(MigrationsDirectory) || Directory.EnumerateFiles(MigrationsDirectory).IsEmpty();
92
+
}
67
93
68
-
if (!Directory.Exists(MigrationsDirectory))
94
+
public static List<MigrationInfo> ReadMigrationsDirectory(bool silent = false)
95
+
{
96
+
if (silent)
69
97
{
70
-
Directory.CreateDirectory(MigrationsDirectory);
71
-
SafeConsole.WriteLineColor(ConsoleColor.White, "Directory " + MigrationsDirectory + " auto-generated...");
98
+
if (!Directory.Exists(MigrationsDirectory))
99
+
return new List<MigrationInfo>();
100
+
}
101
+
else
102
+
{
103
+
if (!Directory.Exists(MigrationsDirectory))
104
+
{
105
+
Directory.CreateDirectory(MigrationsDirectory);
106
+
SafeConsole.WriteLineColor(ConsoleColor.White, "Directory " + MigrationsDirectory + " auto-generated...");
107
+
}
108
+
else
109
+
{
110
+
Console.WriteLine();
111
+
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, "Reading migrations from: " + MigrationsDirectory);
112
+
}
72
113
}
73
114
74
115
Regex regex = new Regex(@"(?<version>\d{4}\.\d{2}\.\d{2}\-\d{2}\.\d{2}\.\d{2})(_(?<comment>.+))?\.sql");
@@ -211,6 +252,8 @@ private static void Execute(MigrationInfo mi)
211
252
212
253
SqlPreCommandExtensions.ExecuteScript(title, text);
213
254
255
+
MigrationLogic.EnsureMigrationTable<SqlMigrationEntity>();
256
+
214
257
new SqlMigrationEntity
215
258
{
216
259
VersionNumber = mi.Version,
Original file line number Diff line number Diff line change
@@ -11,14 +11,17 @@ namespace Signum.Engine;
11
11
12
12
public static class Administrator
13
13
{
14
+
public static Func<bool>? OnTotalGeneration;
15
+
14
16
public static void TotalGeneration()
15
17
{
16
-
foreach (var db in Schema.Current.DatabaseNames())
17
-
{
18
-
Connector.Current.CleanDatabase(db);
19
-
SafeConsole.WriteColor(ConsoleColor.DarkGray, '.');
20
-
}
18
+
CleanAllDatabases();
21
19
20
+
ExecuteGenerationScript();
21
+
}
22
+
23
+
public static void ExecuteGenerationScript()
24
+
{
22
25
SqlPreCommandConcat totalScript = (SqlPreCommandConcat)Schema.Current.GenerationScipt()!;
23
26
foreach (SqlPreCommand command in totalScript.Commands)
24
27
{
@@ -27,6 +30,15 @@ public static void TotalGeneration()
27
30
}
28
31
}
29
32
33
+
private static void CleanAllDatabases()
34
+
{
35
+
foreach (var db in Schema.Current.DatabaseNames())
36
+
{
37
+
Connector.Current.CleanDatabase(db);
38
+
SafeConsole.WriteColor(ConsoleColor.DarkGray, '.');
39
+
}
40
+
}
41
+
30
42
public static string GenerateViewCodes(params string[] tableNames) => tableNames.ToString(tn => GenerateViewCode(tn), "\r\n\r\n");
31
43
32
44
public static string GenerateViewCode(string tableName) => GenerateViewCode(ObjectName.Parse(tableName, Schema.Current.Settings.IsPostgres));
@@ -77,12 +89,13 @@ private static string GenerateColumnCode(DiffColumn c)
77
89
return Schema.Current.GenerationScipt();
78
90
}
79
91
80
-
92
+
93
+
public static Func<bool>? AvoidSimpleGenerate;
81
94
82
95
public static void NewDatabase()
83
96
{
84
97
var databaseName = Connector.Current.DatabaseName();
85
-
if (Database.View<SysTables>().Any())
98
+
if (Connector.Current.HasTables())
86
99
{
87
100
SafeConsole.WriteLineColor(ConsoleColor.Red, $"Are you sure you want to delete all the data in the database '{databaseName}'?");
88
101
Console.Write($"Confirm by writing the name of the database:");
@@ -95,8 +108,16 @@ public static void NewDatabase()
95
108
}
96
109
}
97
110
98
-
Console.Write("Creating new database...");
99
-
Administrator.TotalGeneration();
111
+
Console.Write("Cleaning database...");
112
+
using(Connector.CommandTimeoutScope(5 * 60))
113
+
CleanAllDatabases();
114
+
Console.WriteLine("Done.");
115
+
116
+
if (AvoidSimpleGenerate?.Invoke() == true)
117
+
return;
118
+
119
+
Console.Write("Generating new database database...");
120
+
ExecuteGenerationScript();
100
121
Console.WriteLine("Done.");
101
122
}
102
123
@@ -262,7 +283,13 @@ join s in Database.View<SysSchemas>() on t.schema_id equals s.schema_id
262
283
}
263
284
}
264
285
286
+
public static bool ExistSchema(SchemaName name)
287
+
{
288
+
if (Schema.Current.Settings.IsPostgres)
289
+
return Database.View<PgNamespace>().Any(ns => ns.nspname == name.Name);
265
290
291
+
return Database.View<SysSchemas>().Any(s => s.name == name.Name);
292
+
}
266
293
267
294
public static List<T> TryRetrieveAll<T>(Replacements replacements)
268
295
where T : Entity
@@ -582,7 +609,7 @@ from ifk in targetTable.IncommingForeignKeys()
582
609
ParentColumn = parentTable.Columns().SingleEx(c => c.column_id == ifk.ForeignKeyColumns().SingleEx().parent_column_id).name,
583
610
}).ToList());
584
611
585
-
foreignKeys.ForEach(fk => sqlBuilder.AlterTableDropConstraint(fk.ParentTable!, fk.Name! /*CSBUG*/).ExecuteLeaves());
612
+
foreignKeys.ForEach(fk => sqlBuilder.AlterTableDropConstraint(fk.ParentTable!, fk.Name).ExecuteLeaves());
586
613
587
614
return new Disposable(() =>
588
615
{
Original file line number Diff line number Diff line change
@@ -26,12 +26,19 @@ public static class SchemaGenerator
26
26
{
27
27
var sqlBuilder = Connector.Current.SqlBuilder;
28
28
Schema s = Schema.Current;
29
+
29
30
List<ITable> tables = s.GetDatabaseTables().Where(t => !s.IsExternalDatabase(t.Name.Schema.Database)).ToList();
30
31
31
32
SqlPreCommand? createTables = tables.Select(t => sqlBuilder.CreateTableSql(t)).Combine(Spacing.Double)?.PlainSqlCommand();
32
33
34
+
if (createTables != null)
35
+
createTables.GoAfter = true;
36
+
33
37
SqlPreCommand? foreignKeys = tables.Select(sqlBuilder.AlterTableForeignKeys).Combine(Spacing.Double)?.PlainSqlCommand();
34
38
39
+
if (foreignKeys != null)
40
+
foreignKeys.GoAfter = true;
41
+
35
42
SqlPreCommand? indices = tables.Select(t =>
36
43
{
37
44
var allIndexes = t.GeneratAllIndexes().Where(a => !(a is PrimaryKeyIndex)); ;
@@ -45,17 +52,24 @@ public static class SchemaGenerator
45
52
46
53
}).NotNull().Combine(Spacing.Double)?.PlainSqlCommand();
47
54
55
+
if (indices != null)
56
+
indices.GoAfter = true;
48
57
49
58
return SqlPreCommand.Combine(Spacing.Triple, createTables, foreignKeys, indices);
50
59
}
51
60
52
61
public static SqlPreCommand? InsertEnumValuesScript()
53
62
{
54
-
return (from t in Schema.Current.Tables.Values
55
-
let enumType = EnumEntity.Extract(t.Type)
56
-
where enumType != null
57
-
select EnumEntity.GetEntities(enumType).Select((e, i) => t.InsertSqlSync(e, suffix: t.Name.Name + i)).Combine(Spacing.Simple)
63
+
var result = (from t in Schema.Current.Tables.Values
64
+
let enumType = EnumEntity.Extract(t.Type)
65
+
where enumType != null
66
+
select EnumEntity.GetEntities(enumType).Select((e, i) => t.InsertSqlSync(e, suffix: t.Name.Name + i)).Combine(Spacing.Simple)
58
67
).Combine(Spacing.Double)?.PlainSqlCommand();
68
+
69
+
if (result != null)
70
+
result.GoAfter = true;
71
+
72
+
return result;
59
73
}
60
74
61
75
public static SqlPreCommand? PostgresExtensions()
@@ -90,7 +104,6 @@ select EnumEntity.GetEntities(enumType).Select((e, i) => t.InsertSqlSync(e, suff
90
104
if (!connector.AllowsSetSnapshotIsolation)
91
105
return null;
92
106
93
-
94
107
var list = connector.Schema.DatabaseNames().Select(a => a?.Name).ToList();
95
108
96
109
if (list.Contains(null))
@@ -112,6 +125,7 @@ select EnumEntity.GetEntities(enumType).Select((e, i) => t.InsertSqlSync(e, suff
112
125
).Combine(Spacing.Double);
113
126
114
127
return cmd;
128
+
115
129
}
116
130
117
131
private static bool SnapshotIsolationEnabled(DatabaseName dbName)
Original file line number Diff line number Diff line change
@@ -130,7 +130,7 @@ public static void ExecuteScript(string title, string script)
130
130
{
131
131
using (Connector.CommandTimeoutScope(Timeout))
132
132
{
133
-
var regex = new Regex(@" *(GO|USE \w+|USE \[[^\]]+\]) *(\r?\n|$)", RegexOptions.IgnoreCase);
133
+
var regex = new Regex(@"^ *(GO|USE \w+|USE \[[^\]]+\]) *(\r?\n|$)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
134
134
135
135
var parts = regex.Split(script);
136
136
Original file line number Diff line number Diff line change
@@ -459,14 +459,17 @@ public Table View(Type viewType)
459
459
return ViewBuilder.NewView(viewType);
460
460
}
461
461
462
+
463
+
462
464
public event Func<SqlPreCommand?> Generating;
463
-
internal SqlPreCommand? GenerationScipt()
465
+
public SqlPreCommand? GenerationScipt(string? databaseNameReplacement = null)
464
466
{
465
467
OnBeforeDatabaseAccess();
466
468
467
469
if (Generating == null)
468
470
return null;
469
471
472
+
using (databaseNameReplacement == null ? null : ObjectName.OverrideOptions(new ObjectNameOptions { DatabaseNameReplacement = databaseNameReplacement }))
470
473
using (CultureInfoUtils.ChangeBothCultures(ForceCultureInfo))
471
474
using (ExecutionMode.Global())
472
475
{
You can’t perform that action at this time.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4