Ejemplo n.º 1
0
        protected override void ProcessRecord()
        {
            var seedersDir       = Configuration.GetMigratioDir(MigrationRootDir, ConfigFile, MigratioDirectory.Seeders);
            var replaceVariables = ReplaceVariables.IsPresent
                ? ReplaceVariables.ToBool()
                : Configuration.Resolve(Configuration?.Config?.ReplaceVariables, false, false);


            var cfg = GetConnectionInfo();

            DatabaseProvider.SetConnectionInfo(cfg);

            if (!DatabaseProvider.SeedingTableExists())
            {
                if (CreateTableIfNotExist.ToBool())
                {
                    DatabaseProvider.CreateSeedersTable();
                    WriteVerbose("Created seeders table");
                }
                else
                {
                    throw new Exception("Seeders table does not exist");
                }
            }

            var scripts = FileManager.GetAllFilesInFolder(seedersDir)
                          .OrderBy(f => f)
                          .ToArray();

            if (scripts.Length == 0)
            {
                WriteWarning("No scripts found");
                WriteObject(new MgResult {
                    Successful = false, Details = "No scripts found"
                });
                return;
            }

            WriteVerbose($"Found a total of {scripts.Length} seeding scripts in the seeders folder");

            var applied = DatabaseProvider.GetAppliedSeeders();

            WriteObject($"Found {applied.Length} applied seeders");
            WriteObject($"Found {scripts.Length} total seeders");

            if (applied.Length == scripts.Length)
            {
                WriteObject("Number of applied seeders are the same as the total, skipping");
                return;
            }


            var stringBuilder = new StringBuilder();

            foreach (var script in scripts)
            {
                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(script);
                if (applied.Any(x => x.SeedId.Contains(fileNameWithoutExtension)))
                {
                    WriteObject($"Seeder {Path.GetFileNameWithoutExtension(script)} is applied, skipping");
                    continue;
                }

                WriteObject($"Seeder {fileNameWithoutExtension} is not applied adding to transaction");

                var scriptContent = _migrationHelper.GetScriptContent(script, replaceVariables ?? false);
                stringBuilder.Append(scriptContent);
                stringBuilder.Append(GetSeederQuery(fileNameWithoutExtension));
            }

            DatabaseProvider.RunTransaction(stringBuilder.ToString());
            WriteObject(new MgResult {
                Successful = true
            });
        }