|
| 1 | +// Copyright (c) 2025, Phoenix Contact GmbH & Co. KG |
| 2 | +// Licensed under the Apache License, Version 2.0 |
| 3 | + |
| 4 | +using Microsoft.Data.SqlClient; |
| 5 | +using Microsoft.EntityFrameworkCore; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using Moryx.Model.Configuration; |
| 8 | +using System.ComponentModel; |
| 9 | +using System.Data.Common; |
| 10 | +using System.Text.RegularExpressions; |
| 11 | + |
| 12 | +namespace Moryx.Model.SqlServer; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// Used to configure, create and update data models |
| 16 | +/// </summary> |
| 17 | +[DisplayName("SqlServer Connector")] |
| 18 | +public sealed class SqlServerModelConfigurator : ModelConfiguratorBase<SqlServerDatabaseConfig> |
| 19 | +{ |
| 20 | + /// <inheritdoc /> |
| 21 | + protected override DbConnection CreateConnection(IDatabaseConfig config) |
| 22 | + { |
| 23 | + return CreateConnection(config, true); |
| 24 | + } |
| 25 | + |
| 26 | + /// <inheritdoc /> |
| 27 | + protected override DbConnection CreateConnection(IDatabaseConfig config, bool includeModel) |
| 28 | + { |
| 29 | + return new SqlConnection(BuildConnectionString(config, includeModel)); |
| 30 | + } |
| 31 | + |
| 32 | + /// <inheritdoc /> |
| 33 | + protected override DbCommand CreateCommand(string cmdText, DbConnection connection) |
| 34 | + { |
| 35 | + return new SqlCommand(cmdText, (SqlConnection)connection); |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc /> |
| 39 | + public override async Task DeleteDatabase(IDatabaseConfig config) |
| 40 | + { |
| 41 | + var settings = (SqlServerDatabaseConnectionSettings)config.ConnectionSettings; |
| 42 | + |
| 43 | + // Create connection and prepare command |
| 44 | + await using var connection = new SqlConnection(BuildConnectionString(config, false)); |
| 45 | + |
| 46 | + var sqlCommandText = $"ALTER DATABASE {settings.Database} SET SINGLE_USER WITH ROLLBACK IMMEDIATE;" + |
| 47 | + $"DROP DATABASE [{settings.Database}]"; |
| 48 | + |
| 49 | + await using var command = CreateCommand(sqlCommandText, connection); |
| 50 | + |
| 51 | + // Open connection |
| 52 | + await connection.OpenAsync(); |
| 53 | + await command.ExecuteNonQueryAsync(); |
| 54 | + } |
| 55 | + |
| 56 | + /// <inheritdoc /> |
| 57 | + public override async Task DumpDatabase(IDatabaseConfig config, string targetPath) |
| 58 | + { |
| 59 | + if (!IsValidBackupFilePath(targetPath)) |
| 60 | + throw new ArgumentException("Invalid backup file path."); |
| 61 | + |
| 62 | + var connectionString = CreateConnectionStringBuilder(config); |
| 63 | + |
| 64 | + var dumpName = $"{DateTime.Now:dd-MM-yyyy-hh-mm-ss}_{connectionString.InitialCatalog}.bak"; |
| 65 | + var fileName = Path.Combine(targetPath, dumpName); |
| 66 | + |
| 67 | + await using var connection = new SqlConnection(BuildConnectionString(config, false)); |
| 68 | + await using var command = |
| 69 | + CreateCommand($"BACKUP DATABASE [{connectionString.InitialCatalog}] TO DISK = N'{fileName}' WITH INIT", |
| 70 | + connection); |
| 71 | + |
| 72 | + Logger.Log(LogLevel.Debug, "Starting to dump database with 'BACKUP DATABASE' to: {fileName}", fileName); |
| 73 | + |
| 74 | + await connection.OpenAsync(); |
| 75 | + await command.ExecuteNonQueryAsync(); |
| 76 | + } |
| 77 | + |
| 78 | + private static SqlConnectionStringBuilder CreateConnectionStringBuilder(IDatabaseConfig config, bool includeModel = true) |
| 79 | + { |
| 80 | + var builder = new SqlConnectionStringBuilder(config.ConnectionSettings.ConnectionString) |
| 81 | + { |
| 82 | + InitialCatalog = includeModel ? config.ConnectionSettings.Database : string.Empty |
| 83 | + }; |
| 84 | + |
| 85 | + return builder; |
| 86 | + } |
| 87 | + |
| 88 | + /// <inheritdoc /> |
| 89 | + public override async Task RestoreDatabase(IDatabaseConfig config, string filePath) |
| 90 | + { |
| 91 | + if (!IsValidBackupFilePath(filePath)) |
| 92 | + throw new ArgumentException("Invalid backup file path."); |
| 93 | + |
| 94 | + var connectionString = CreateConnectionStringBuilder(config); |
| 95 | + |
| 96 | + await using var connection = new SqlConnection(BuildConnectionString(config, false)); |
| 97 | + await using var command = CreateCommand($"RESTORE DATABASE [{connectionString.InitialCatalog}] FROM DISK = N'{filePath}' WITH REPLACE", |
| 98 | + connection); |
| 99 | + |
| 100 | + Logger.Log(LogLevel.Debug, "Starting to restore database with 'RESTORE DATABASE' from: {filePath}", filePath); |
| 101 | + |
| 102 | + await connection.OpenAsync(); |
| 103 | + await command.ExecuteNonQueryAsync(); |
| 104 | + } |
| 105 | + |
| 106 | + /// <inheritdoc /> |
| 107 | + public override DbContextOptions BuildDbContextOptions(IDatabaseConfig config) |
| 108 | + { |
| 109 | + var builder = new DbContextOptionsBuilder(); |
| 110 | + builder.UseSqlServer(BuildConnectionString(config, true)); |
| 111 | + |
| 112 | + return builder.Options; |
| 113 | + } |
| 114 | + |
| 115 | + private static string BuildConnectionString(IDatabaseConfig config, bool includeModel) |
| 116 | + { |
| 117 | + if (!IsValidDatabaseName(config.ConnectionSettings.Database)) |
| 118 | + throw new ArgumentException("Invalid database name."); |
| 119 | + |
| 120 | + var builder = CreateConnectionStringBuilder(config, includeModel); |
| 121 | + builder.PersistSecurityInfo = true; |
| 122 | + |
| 123 | + return builder.ToString(); |
| 124 | + } |
| 125 | + |
| 126 | + /// <inheritdoc /> |
| 127 | + protected override DbContext CreateMigrationContext(IDatabaseConfig config) |
| 128 | + { |
| 129 | + var migrationAssemblyType = FindMigrationAssemblyType(typeof(SqlServerDbContextAttribute)); |
| 130 | + |
| 131 | + var builder = new DbContextOptionsBuilder(); |
| 132 | + builder.UseSqlServer( |
| 133 | + BuildConnectionString(config, true), |
| 134 | + x => x.MigrationsAssembly(migrationAssemblyType.Assembly.FullName)); |
| 135 | + |
| 136 | + return CreateContext(migrationAssemblyType, builder.Options); |
| 137 | + } |
| 138 | + |
| 139 | + private static bool IsValidDatabaseName(string dbName) |
| 140 | + { |
| 141 | + // Avoid sql injection by validating the database name |
| 142 | + if (string.IsNullOrWhiteSpace(dbName) || dbName.Length > 128) |
| 143 | + return false; |
| 144 | + |
| 145 | + // Only allow letters, numbers, and underscores |
| 146 | + return Regex.IsMatch(dbName, @"^[A-Za-z0-9_]+$"); |
| 147 | + } |
| 148 | + |
| 149 | + private static bool IsValidBackupFilePath(string filePath) |
| 150 | + { |
| 151 | + // Disallow dangerous characters |
| 152 | + var invalidStrings = new[] { ";", "'", "\"", "--" }; |
| 153 | + return invalidStrings.All(s => !filePath.Contains(s)); |
| 154 | + } |
| 155 | +} |
0 commit comments