public static string[] ReadSQLFileSectionsFromResource(string resourceFileName, IEnumerable<string> skipSections)
{
if (string.IsNullOrEmpty(resourceFileName)) return new string[] { };
if (!resourceFileName.ToLower().EndsWith(".sql")) return new string[] { };
var skipSectionsLowered = new List<string>();
if (skipSections != null)
skipSections.Where(x => x != null).ToList().ForEach(x => skipSectionsLowered.Add(x.ToLower()));
#region Load Full Script
var asm = Assembly.GetExecutingAssembly();
var manifestStream = asm.GetManifestResourceStream(resourceFileName);
var fullScript = string.Empty;
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(manifestStream))
{
fullScript = sr.ReadToEnd();
}
}
catch { }
finally
{
manifestStream.Close();
}
#endregion
var retval = new ArrayList();
var sb = new StringBuilder();
var allLines = fullScript.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
var skippingQueue = new List<string>();
foreach (var lineText in allLines)
{
//If we are currently NOT skipping script then process the SQL
//Check to determine if this is a skip section start
if (lineText.ToUpper().StartsWith("--##SECTION BEGIN ["))
{
var sectionName = GetSkipSectionName(lineText).ToLower();
if (skipSectionsLowered.Contains(sectionName))
{
//We are now skipping script
skippingQueue.Add(sectionName);
}
}
else if (lineText.ToUpper().StartsWith("--##SECTION END [") && skippingQueue.Count > 0)
{
var sectionName = GetSkipSectionName(lineText).ToLower();
if (skippingQueue.Last().ToLower() == sectionName)
{
//We are now skipping script
skippingQueue.RemoveAt(0);
}
}
else if (skippingQueue.Count == 0)
{
if (lineText.ToUpper().Trim() == "GO")
{
var s = sb.ToString();
s = s.Trim();
retval.Add(s);
sb = new StringBuilder();
}
else
{
var s = lineText;
if (s.EndsWith("\r")) s = lineText.Substring(0, lineText.Length - 1);
sb.AppendLine(s);
}
}
}
//Last string
if (!string.IsNullOrEmpty(sb.ToString()))
retval.Add(sb.ToString());
return (string[])retval.ToArray(typeof(string));
}