2022-01-21 11:19:51 +02:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2023-01-12 01:01:36 +02:00
|
|
|
|
using Netmash.Infrastructure.DatabaseMigration.Constants;
|
|
|
|
|
using Netmash.Infrastructure.DatabaseMigration.DbContexts;
|
|
|
|
|
using Netmash.Infrastructure.DatabaseMigration.Entities;
|
2022-02-16 19:09:06 +02:00
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
2022-01-21 11:19:51 +02:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2023-01-12 01:01:36 +02:00
|
|
|
|
namespace Netmash.Infrastructure.DatabaseMigration.Repositories
|
2022-01-21 11:19:51 +02:00
|
|
|
|
{
|
|
|
|
|
internal class MigrationRepository : IMigrationRepository
|
|
|
|
|
{
|
|
|
|
|
private readonly MigrationDbContext _dbContext;
|
|
|
|
|
|
|
|
|
|
public MigrationRepository(MigrationDbContext dbContext)
|
|
|
|
|
{
|
|
|
|
|
_dbContext = dbContext;
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-22 01:54:19 +02:00
|
|
|
|
public async Task ExecuteSqlRaw(string sqlRaw)
|
2022-01-21 11:19:51 +02:00
|
|
|
|
{
|
2022-01-22 01:54:19 +02:00
|
|
|
|
await _dbContext.Database.ExecuteSqlRawAsync(sqlRaw);
|
2022-01-21 11:19:51 +02:00
|
|
|
|
}
|
2022-02-16 19:09:06 +02:00
|
|
|
|
|
|
|
|
|
public async Task<bool> MigrationTablesAreSet(DatabaseType databaseType)
|
|
|
|
|
{
|
|
|
|
|
var query = databaseType switch
|
|
|
|
|
{
|
|
|
|
|
DatabaseType.SQLServer => "select count(1) from sys.objects where name = 'MigrationSignature' and type = 'U' and SCHEMA_NAME(schema_id)='migration'",
|
|
|
|
|
DatabaseType.SQLite => "select count(1) from sqlite_master where type='table' and name='MigrationSignature';",
|
|
|
|
|
_ => throw new NotImplementedException($"DatabaseMigration type {databaseType} is not implemented"),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
|
|
|
|
|
{
|
|
|
|
|
command.CommandText = query;
|
|
|
|
|
await _dbContext.Database.OpenConnectionAsync();
|
|
|
|
|
var result = await command.ExecuteScalarAsync();
|
2022-02-18 08:56:07 +02:00
|
|
|
|
await _dbContext.Database.CloseConnectionAsync();
|
2022-02-16 19:09:06 +02:00
|
|
|
|
|
|
|
|
|
return result != null && result != DBNull.Value && Convert.ToInt32(result) > 0;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task<MigrationSignature> GetLastMigrationSignature()
|
|
|
|
|
{
|
|
|
|
|
var query = _dbContext.MigrationSignatures
|
|
|
|
|
.Include(z => z.MigratedVersions).ThenInclude(z => z.Scripts)
|
|
|
|
|
.OrderByDescending(z => z.MigrationDate)
|
|
|
|
|
.AsSplitQuery();
|
|
|
|
|
|
|
|
|
|
return query.FirstOrDefaultAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task AddMigrationSignature(MigrationSignature migrationSignature)
|
|
|
|
|
{
|
|
|
|
|
await _dbContext.MigrationSignatures.AddAsync(migrationSignature);
|
|
|
|
|
await _dbContext.SaveChangesAsync();
|
|
|
|
|
}
|
2022-01-21 11:19:51 +02:00
|
|
|
|
}
|
|
|
|
|
}
|