private void CheckFull()
{
Boolean rename = false;
// connect to db using connection string from parent app
using (SqlConnection cn = new SqlConnection(_cnConfig.ToString()))
{
// at least an empty db needs to pre-exist but a schema is not required
cn.Open();
// check if schema exists - if so there should always be a migration history table
_sql =
@"
SELECT
OBJECT_ID(N'[dbo].[__MigrationHistory]', 'U') AS OldHistory,
OBJECT_ID(N'[dbo].[MigrationHistory]', 'U') AS NewHistory
";
using (SqlCommand cmd = new SqlCommand(_sql, cn))
{
using (SqlDataReader rs = cmd.ExecuteReader())
{
rs.Read();
// note new install if no schema exists
if (rs["OldHistory"].ToString() == "" && rs["NewHistory"].ToString() == "") NewInstall = true;
// note to rename table if __MigrationHistory table exists
if (rs["OldHistory"].ToString() != "") rename = true;
}
}
// Rename __MigrationHistory table to MigrationHistory (prevents entity framework version check)
if (rename)
{
ExecFullNativeSQL(Properties.Resources.RenameMigrationHistory, cn);
}
// if no schema then create entire schema then populate bitmasks
if (NewInstall)
{
// create main schema
_sql = Properties.Resources.CreateEntireSchema;
if (_cnConfig.ProviderName.Equals("System.Data.?SqlClient")) // should never be true - lifted logic as-is from "broken" migration
{ // so exactly matches latest db structure that theoretically should
_sql += Properties.Resources._201306050753190_ProgressiveLoad; // not have the sprocs that ProgressiveLoad introduces.
}
ExecFullNativeSQL(_sql, cn);
// populate bitmasks
EnsureBitmasksPopulated();
}
else
{
// schema exists - build list of already executed migration steps
_sql = "SELECT MigrationId AS MigrationTitle FROM [MigrationHistory] WITH (NOLOCK) ORDER BY MigrationId";
using (SqlCommand cmd = new SqlCommand(_sql, cn))
{
using (SqlDataReader rs = cmd.ExecuteReader())
{
if (rs.HasRows)
{
while (rs.Read())
{
string[] titleParts = rs["MigrationTitle"].ToString().Split('_'); // 0 will be key, 1 will be value (description).
if (!_migrated.ContainsKey(titleParts[0]))
{
_migrated.Add(titleParts[0], titleParts[1]);
}
}
}
}
}
// see if any migration stepa are missing - if so build sql in correct order which should also note step completed in db
_sql = BuildAnyMissingMigrationStepsSQL(_migrated);
// if any steps were missing
if (_sql != "")
{
// execute sql for any missing steps
ExecFullNativeSQL(_sql, cn);
// ensure bitmasks are populated/repopulated
EnsureBitmasksPopulated();
}
}
cn.Close();
}
}