Skip to content

Instantly share code, notes, and snippets.

@itssimple
Last active October 3, 2017 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itssimple/aaa1e3fa1e4a115e50aacb6f5d682b79 to your computer and use it in GitHub Desktop.
Save itssimple/aaa1e3fa1e4a115e50aacb6f5d682b79 to your computer and use it in GitHub Desktop.
DbUp ScriptProvider
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