Last active
October 3, 2017 10:43
-
-
Save itssimple/aaa1e3fa1e4a115e50aacb6f5d682b79 to your computer and use it in GitHub Desktop.
DbUp ScriptProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DbUp.Engine; | |
using System; | |
using System.Collections.Generic; | |
using DbUp.Engine.Transactions; | |
using System.Reflection; | |
using System.Linq; | |
using System.ComponentModel; | |
namespace DevDBScriptRunner | |
{ | |
public class DBScriptProvider : IScriptProvider | |
{ | |
private readonly Assembly assembly; | |
private readonly Func<string, bool> filter; | |
private readonly object[] arguments; | |
public DBScriptProvider(Assembly assembly, Func<string, bool> filter, params object[] arguments) | |
{ | |
this.assembly = assembly; | |
this.filter = filter; | |
this.arguments = arguments; | |
} | |
public IEnumerable<SqlScript> GetScripts(IConnectionManager connectionManager) | |
{ | |
List<SqlScript> scripts = new List<SqlScript>(); | |
scripts.AddRange( | |
this.assembly.GetManifestResourceNames() | |
.Where(this.filter).ToArray() | |
.Select(resource => | |
SqlScript.FromStream(resource, this.assembly.GetManifestResourceStream(resource)) | |
) | |
); | |
var script = typeof(IScript); | |
scripts.AddRange( | |
connectionManager.ExecuteCommandsWithManagedConnection( | |
dbCommandFactory => | |
{ | |
var _types = this.assembly.GetTypes() | |
.Where(type => type.IsClass && script.IsAssignableFrom(type)) | |
.Select(t2 => new | |
{ | |
Type = t2, | |
Description = string.Join(", ", t2.CustomAttributes?.Where(t3 => t3.AttributeType == typeof(DescriptionAttribute)).SelectMany(ca => ca.ConstructorArguments.Select(c => c.Value))) ?? "" | |
}); | |
var onlyDescription = _types.Select(t => t.Description).Where(this.filter); | |
return _types.Where(i => onlyDescription.Contains(i.Description)).Select(s => | |
(SqlScript)new LazySqlScript( | |
s.Type.FullName + ".cs", | |
() => ((IScript)Activator.CreateInstance(s.Type, this.arguments)).ProvideScript(dbCommandFactory) | |
) | |
); | |
} | |
) | |
); | |
return scripts.OrderBy(s => s.Name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment