Skip to content

Instantly share code, notes, and snippets.

@pocheptsov
Created September 5, 2013 19:25
Show Gist options
  • Save pocheptsov/6454895 to your computer and use it in GitHub Desktop.
Save pocheptsov/6454895 to your computer and use it in GitHub Desktop.
Run sql scripts from directory, where script filename has a convention - [int number]_any_nam_after.sql ordered by [int number], execution break in case of any exception. ScriptCs format was used as a script language.
//#r "System.Data"
//uncomment previous lines to debug in VS
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
var lastScriptFileName = "last-script.txt";
if (!File.Exists(lastScriptFileName))
{
File.WriteAllText(lastScriptFileName, "0");
}
int stamp;
int.TryParse(File.ReadAllText(lastScriptFileName), out stamp);
Console.WriteLine("Stamp is - '{0}'", stamp);
var files = Directory.GetFiles(@"..\..\db\", "*.sql");
var connString = new Regex("set connStr=(.*)").Match(File.ReadAllText(@"..\var.cmd")).Groups[1].Value;
Console.WriteLine("Get connection string from 'var.cmd'");
Console.WriteLine(@"Connection string - {0}", connString);
Console.WriteLine();
using (var cn = new SqlConnection(connString))
{
cn.Open();
foreach (var fullFileName in files.OrderBy(_ => _))
{
var fileName = Path.GetFileName(fullFileName);
var fileVersion = int.Parse(fileName.Substring(0, fileName.IndexOf("_")));
if (fileVersion > stamp)
{
SqlTransaction tran = null;
try
{
tran = cn.BeginTransaction();
//execute sql
Console.WriteLine("Start to execute '{0}' file", fileName);
var cmd = cn.CreateCommand();
cmd.Transaction = tran;
var sql = File.ReadAllText(fullFileName);
cmd.CommandText = sql;
Console.WriteLine("Execute - {0}", sql);
cmd.ExecuteNonQuery();
tran.Commit();
stamp = fileVersion;
}
catch (Exception ex)
{
if (tran != null)
{
tran.Rollback();
}
Console.WriteLine("!!!!!! Exception !!!!!!!! - '{0}'", ex.Message);
break;
}
Console.WriteLine();
}
}
//save file version
File.WriteAllText(lastScriptFileName, stamp.ToString());
Console.WriteLine();
Console.WriteLine(new string('=', 40));
Console.WriteLine("Last succeeded version was - '{0}'", stamp);
}
Console.ReadLine();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment