62 lines
2.3 KiB
C#
62 lines
2.3 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using NDB.Infrastructure.DatabaseMigration.Constants;
|
|
using NDB.Infrastructure.DatabaseMigration.DbContexts;
|
|
using NDB.Infrastructure.DatabaseMigration.Entities;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace NDB.Infrastructure.DatabaseMigration.Repositories
|
|
{
|
|
internal class MigrationRepository : IMigrationRepository
|
|
{
|
|
private readonly MigrationDbContext _dbContext;
|
|
|
|
public MigrationRepository(MigrationDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task ExecuteSqlRaw(string sqlRaw)
|
|
{
|
|
await _dbContext.Database.ExecuteSqlRawAsync(sqlRaw);
|
|
}
|
|
|
|
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();
|
|
await _dbContext.Database.CloseConnectionAsync();
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|