public void Execute(SqlMigratorParameters parameters) { var root = parameters.RootDirectory; if (root == null) throw new NullReferenceException("parameters.RootDirectory"); if (!root.Exists) throw new FileNotFoundException("parameters.RootDirectory", root.FullName); bool initialized = _sqlExecutor.Initialize(); if (!initialized) throw new Exception("Unable to initialize database version"); _logger.Info("Searching script folders in: {0}", root.FullName); var directories = new List<DirectoryInfo>(root.GetDirectories()); directories.Sort((d1, d2) => string.Compare(d1.FullName, d2.FullName, StringComparison.OrdinalIgnoreCase)); _logger.Info("Found {0} folders.", directories.Count); foreach (var directory in directories) { _logger.Info("Processing folder: {0}", directory.Name); var files = new List<FileInfo>(directory.GetFiles("*.sql", SearchOption.TopDirectoryOnly)); files.Sort((f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.OrdinalIgnoreCase)); var versions = new HashSet<int>(); foreach (var file in files) { var version = GetFileVersion(file); if (versions.Contains(version)) throw new NotSupportedException("Duplicated version: " + version); } int currentVersion = _sqlExecutor.GetCurrentVersion(directory.Name); _logger.Info("Current version: {0}", currentVersion); for (int i = currentVersion; i < files.Count; ++i) { var file = files[i]; _logger.Info("Processing file: {0}", file.Name); var version = GetFileVersion(file); string content = File.ReadAllText(file.FullName); using (var transaction = _sqlExecutor.StartTransaction()) { _sqlExecutor.Apply(file.FullName, content, directory.Name, version); transaction.Commit(); } _logger.Info("File applied successfully"); } currentVersion = _sqlExecutor.GetCurrentVersion(directory.Name); _logger.Info("Current version: {0}", currentVersion); } }
static void Main(string[] args) { try { //"c:\Projects\DatabaseManager\Sql\PostgreSql" //"Server=localhost;Database=DatabaseManager;User Id=admin;Password=admin" bool test = false; bool showHelp = false; if (args == null || args.Length < 2) { showHelp = true; } else if (args.Length > 2) { if (string.Compare(args[2].Trim(), "-test", StringComparison.InvariantCultureIgnoreCase) != 0) { showHelp = true; } else { test = true; } } if (showHelp) { ShowHelp(); } else { var parameters = new SqlMigratorParameters(new DirectoryInfo(args[0])); using (var executor = new PostgreSqlExecutor(args[1])) { var migrator = new SqlMigrator(new ConsoleLogger(), executor); if (test) migrator.Test(parameters); else migrator.Execute(parameters); } } } catch (Exception exc) { System.Console.WriteLine(exc); } if (System.Diagnostics.Debugger.IsAttached) { System.Console.WriteLine("Press enter to exit"); System.Console.ReadLine(); } }
public void Test(SqlMigratorParameters parameters) { using (_sqlExecutor.StartTransaction()) { Execute(parameters); } }