public void DropDatabase(string dbName) { using (Log.InfoTraceMethodCallFormat("DropDatabase", "Dropping Database [{0}]", dbName)) { _provider.DropDatabase(dbName); } }
public void ResetDatabase() { using (Log.InfoTraceMethodCall("ResetDatabase")) { var connectionString = config.Server.GetConnectionString(Zetbox.API.Helper.ZetboxConnectionStringKey); Assert.That(connectionString.ConnectionString, Is.StringContaining("_test"), "test databases should be marked with '_test' in the connection string"); Log.InfoFormat("Current Directory=[{0}]", Environment.CurrentDirectory); Log.InfoFormat("Using config from [{0}]", config.ConfigFilePath); try { Log.Info("Restoring Database"); var cb = new NpgsqlConnectionStringBuilder(connectionString.ConnectionString); var srcDB = cb.Database.Substring(0, cb.Database.Length - "_test".Length); var destDB = cb.Database; var userCmdString = "--username=sa --no-password"; var dumpFile = tmpService.CreateWithExtension(".zetbox.backup"); try { var exitCode = RunPgUtil("pg_dump", String.Format("--format c {0} --file={1} {2}", userCmdString, dumpFile, srcDB)); if (exitCode != 0) { throw new ApplicationException(String.Format("Failed to dump database (exit={0}), maybe you need to put your password into AppData\\Roaming\\postgresql\\pgpass.conf", exitCode)); } var admin = new NpgsqlConnectionStringBuilder(connectionString.ConnectionString); var dbName = admin.Database; using (Log.InfoTraceMethodCall("DropCreateDatabase", string.Format("Recreating database {0}", dbName))) { admin.Database = "postgres"; // use "default" database to connect, when trying to drop "dbName" schemaManager.Open(admin.ConnectionString); if (schemaManager.CheckDatabaseExists(dbName)) { schemaManager.DropDatabase(dbName); } schemaManager.CreateDatabase(dbName); } exitCode = RunPgUtil("pg_restore", String.Format("--format c {0} --dbname={2} {1}", userCmdString, dumpFile, destDB)); if (exitCode != 0) { throw new ApplicationException(String.Format("Failed to restore database (exit={0})", exitCode)); } schemaManager.RefreshDbStats(); } finally { // cleanup File.Delete(dumpFile); // After recreating the database, all connection pools should be cleard NpgsqlConnection.ClearAllPools(); } } catch (ApplicationException) { throw; } catch (Exception ex) { Log.Error("Error while restoring database", ex); throw; } } }