Skip to content

Instantly share code, notes, and snippets.

@gunndabad
Created April 29, 2013 13:41
Show Gist options
  • Select an option

  • Save gunndabad/5481638 to your computer and use it in GitHub Desktop.

Select an option

Save gunndabad/5481638 to your computer and use it in GitHub Desktop.
Deploy SQL schema updates atomically from a selection of files.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace DbDeploy
{
class Program
{
private static string _usage = "dbdeploy.exe <connection string> <path to scripts>";
static int Main(string[] args)
{
if (args.Length != 2)
{
Console.Error.WriteLine("Usage: {0}", _usage);
return 1;
}
try
{
string connectionString = args[0];
string[] scripts = Directory.GetFiles(args[1], "*.sql");
DeployScripts(connectionString, scripts);
}
catch (Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
Console.Error.Write(ex.ToString());
return 2;
}
return 0;
}
static void DeployScripts(string connectionString, IEnumerable<string> scriptPaths)
{
Regex go = new Regex(@"^go\b", RegexOptions.IgnoreCase | RegexOptions.Multiline);
IEnumerable<string> sql = scriptPaths.Select(s => go.Split(File.ReadAllText(s)))
.SelectMany(s => s)
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToList();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction txn = conn.BeginTransaction())
{
using (SqlCommand cmd = new SqlCommand() { Connection = conn, Transaction = txn })
{
foreach (string s in sql)
{
cmd.CommandText = s;
cmd.ExecuteNonQuery();
}
}
txn.Commit();
}
conn.Close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment