/// <summary> /// Initializes a new instance of the <see cref="MerchelloMigrationContext"/> class. /// </summary> /// <param name="databaseProvider"> /// The database provider. /// </param> /// <param name="database"> /// The database. /// </param> /// <param name="logger"> /// The logger. /// </param> public MerchelloMigrationContext(DatabaseProviders databaseProvider, Database database, ILogger logger) { Expressions = new Collection<IMigrationExpression>(); CurrentDatabaseProvider = databaseProvider; Database = database; Logger = logger; }
public AlterColumnExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { Column = new ColumnDefinition() { ModificationType = ModificationType.Alter }; }
public CreateColumnExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { Column = new ColumnDefinition { ModificationType = ModificationType.Create }; }
public static string Construct(DatabaseProviders provider, string server, string user, string password) { var connectionstring = String.Empty; switch (provider) { case DatabaseProviders.MSSQLServer: var mssqlConnStringBuilder = new SqlConnectionStringBuilder(); mssqlConnStringBuilder.DataSource = server; mssqlConnStringBuilder.UserID = user; mssqlConnStringBuilder.Password = password; mssqlConnStringBuilder.MultipleActiveResultSets = true; mssqlConnStringBuilder.InitialCatalog = "ERService"; mssqlConnStringBuilder.ApplicationName = AppDomain.CurrentDomain.FriendlyName; connectionstring = mssqlConnStringBuilder.ToString(); break; case DatabaseProviders.MSSQLServerLocalDb: var path = AppDomain.CurrentDomain.BaseDirectory; connectionstring = $@"Data Source=(LocalDb)\MSSQLLocalDB;Integrated Security=SSPI;AttachDBFilename={path}localdb.mdf"; break; case DatabaseProviders.MySQLServer: var mysqlConnStringBuilder = new MySqlConnectionStringBuilder(); mysqlConnStringBuilder.Server = server; mysqlConnStringBuilder.UserID = user; mysqlConnStringBuilder.Password = password; mysqlConnStringBuilder.Database = "ERService"; connectionstring = mysqlConnStringBuilder.ToString(); break; } return(connectionstring); }
public void CheckServerDb(DatabaseProviders dbProvider) { Route4MeDbContext _route4meDbContext; Route4MeDbManager r4mdbManager; var curPath = Directory.GetCurrentDirectory(); var configBuilder = new ConfigurationBuilder() .SetBasePath(curPath) .AddJsonFile("appsettings.json", optional: true); var config = configBuilder.Build(); Route4MeDbManager.DatabaseProvider = dbProvider; r4mdbManager = new Route4MeDbManager(config); _route4meDbContext = r4mdbManager.Route4MeContext; try { if (!_route4meDbContext.Database.CanConnect()) { Skip = "Cannot find " + dbProvider + " server"; //return; } if (!(_route4meDbContext.Database.GetService <IDatabaseCreator>() as RelationalDatabaseCreator).Exists()) { Skip = "Route4MeDB not exists in the " + dbProvider + " server."; return; } } catch (Exception) { Skip = "Cannot run the tests for " + dbProvider + " server."; } }
public MigrationContext(DatabaseProviders databaseProvider, Database database, ILogger logger) { Expressions = new Collection <IMigrationExpression>(); CurrentDatabaseProvider = databaseProvider; Database = database; Logger = logger; }
public AbpDbConnectionsOptions Configure(IConfiguration configuration) { var dbConnectionConfigurations = configuration.GetSection("DbConnections") .Get <Dictionary <string, DbConnectionConfiguration> >(); foreach (var dbConnectionConfigurationKv in dbConnectionConfigurations) { DbConnections.Configure(dbConnectionConfigurationKv.Key, c => { c.DatabaseProvider = dbConnectionConfigurationKv.Value.DatabaseProvider; c.ConnectionString = dbConnectionConfigurationKv.Value.ConnectionString; }); } var databaseProviders = configuration.GetSection("DatabaseProviders")? .Get <List <DatabaseProvider> >(); if (databaseProviders != null) { foreach (var databaseProvider in databaseProviders) { DatabaseProviders.AddIfNotContains(databaseProvider); } } return(this); }
/// <summary> /// Private method to install the umbraco database schema in an empty database /// </summary> /// <param name="database"></param> /// <param name="databaseProvider"></param> /// <param name="dataDirectory"></param> private static void CreateDatabaseSchema(Database database, DatabaseProviders databaseProvider, string dataDirectory) { Console.WriteLine("Please note that installing the umbraco database schema requires an empty database configured in config."); Console.WriteLine("The 'umbracoConfigurationStatus' under appSettings should be left blank."); Console.WriteLine("If you are using Sql Ce an empty Umbraco.sdf file should exist in the DataDictionary."); Console.WriteLine("Press y to continue"); var input = Console.ReadLine(); if (string.IsNullOrEmpty(input) == false && input.ToLowerInvariant().Equals("y")) { try { if (databaseProvider == DatabaseProviders.SqlServerCE) { var dbPath = Path.Combine(dataDirectory, "Umbraco.sdf"); if (File.Exists(dbPath) == false) { var engine = new SqlCeEngine(@"Data Source=|DataDirectory|\Umbraco.sdf;Flush Interval=1;"); engine.CreateDatabase(); } } database.CreateDatabaseSchema(false); Console.WriteLine("The database schema has been installed"); Console.WriteLine("Note: This is just an example, so no backoffice user has been created."); } catch (Exception e) { Console.WriteLine("An error occured while trying to install the database schema"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } }
private string GetConnectionString(out DatabaseProviders provider) { provider = DatabaseProviders.Unknown; var _web_config_file = Path.Combine(Environment.GetEnvironmentVariable("MaestroPanelPath", EnvironmentVariableTarget.Machine), "Web", "www", "Web.config"); if (!File.Exists(_web_config_file)) { throw new Exception("1. Web.config not found " + _web_config_file); } var web_config = System.Configuration.ConfigurationManager. OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = _web_config_file }, ConfigurationUserLevel.None); if (web_config == null) { throw new Exception("2. Web.config file cannot be read."); } if (web_config.ConnectionStrings.ConnectionStrings["MaestroConnection"].ProviderName == "System.Data.SqlClient") { provider = DatabaseProviders.MSSQL; } if (web_config.ConnectionStrings.ConnectionStrings["MaestroConnection"].ProviderName == "System.Data.SQLite") { provider = DatabaseProviders.SQLITE; } return(web_config.ConnectionStrings.ConnectionStrings["MaestroConnection"].ConnectionString); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config")); //DatabaseProviders.RegisterProvider<NpgsqlProviderAttribute>(); DatabaseProviders.RegisterProvider <MSSQLProviderAttribute>(); }
/// <summary> /// Executes the migrations against the database. /// </summary> /// <param name="database">The PetaPoco Database, which the migrations will be run against</param> /// <param name="databaseProvider"></param> /// <param name="isUpgrade">Boolean indicating whether this is an upgrade or downgrade</param> /// <returns><c>True</c> if migrations were applied, otherwise <c>False</c></returns> public bool Execute(Database database, DatabaseProviders databaseProvider, bool isUpgrade = true) { LogHelper.Info <MigrationRunner>("Initializing database migrations"); var foundMigrations = MigrationResolver.Current.Migrations; var migrations = isUpgrade ? OrderedUpgradeMigrations(foundMigrations).ToList() : OrderedDowngradeMigrations(foundMigrations).ToList(); if (Migrating.IsRaisedEventCancelled(new MigrationEventArgs(migrations, _configuredVersion, _targetVersion, true), this)) { return(false); } //Loop through migrations to generate sql var context = new MigrationContext(databaseProvider, database); foreach (MigrationBase migration in migrations) { if (isUpgrade) { migration.GetUpExpressions(context); LogHelper.Info <MigrationRunner>(string.Format("Added UPGRADE migration '{0}' to context", migration.GetType().Name)); } else { migration.GetDownExpressions(context); LogHelper.Info <MigrationRunner>(string.Format("Added DOWNGRADE migration '{0}' to context", migration.GetType().Name)); } } //Transactional execution of the sql that was generated from the found migrations using (Transaction transaction = database.GetTransaction()) { int i = 1; foreach (var expression in context.Expressions) { var sql = expression.Process(database); if (string.IsNullOrEmpty(sql)) { i++; continue; } LogHelper.Info <MigrationRunner>("Executing sql statement " + i + ": " + sql); database.Execute(sql); i++; } transaction.Complete(); } Migrated.RaiseEvent(new MigrationEventArgs(migrations, context, _configuredVersion, _targetVersion, false), this); return(true); }
/// <summary> /// Executes the migrations against the database. /// </summary> /// <param name="database">The PetaPoco Database, which the migrations will be run against</param> /// <param name="databaseProvider"></param> /// <param name="isUpgrade">Boolean indicating whether this is an upgrade or downgrade</param> /// <returns><c>True</c> if migrations were applied, otherwise <c>False</c></returns> public bool Execute(Database database, DatabaseProviders databaseProvider, bool isUpgrade = true) { LogHelper.Info<MigrationRunner>("Initializing database migrations"); var foundMigrations = MigrationResolver.Current.Migrations; var migrations = isUpgrade ? OrderedUpgradeMigrations(foundMigrations).ToList() : OrderedDowngradeMigrations(foundMigrations).ToList(); if (Migrating.IsRaisedEventCancelled(new MigrationEventArgs(migrations, _configuredVersion, _targetVersion, true), this)) return false; //Loop through migrations to generate sql var context = new MigrationContext(databaseProvider, database); foreach (MigrationBase migration in migrations) { if (isUpgrade) { migration.GetUpExpressions(context); LogHelper.Info<MigrationRunner>(string.Format("Added UPGRADE migration '{0}' to context", migration.GetType().Name)); } else { migration.GetDownExpressions(context); LogHelper.Info<MigrationRunner>(string.Format("Added DOWNGRADE migration '{0}' to context", migration.GetType().Name)); } } //Transactional execution of the sql that was generated from the found migrations using (Transaction transaction = database.GetTransaction()) { int i = 1; foreach (var expression in context.Expressions) { var sql = expression.Process(database); if (string.IsNullOrEmpty(sql)) { i++; continue; } LogHelper.Info<MigrationRunner>("Executing sql statement " + i + ": " + sql); database.Execute(sql); i++; } transaction.Complete(); } Migrated.RaiseEvent(new MigrationEventArgs(migrations, context, _configuredVersion, _targetVersion, false), this); return true; }
private static void LoadDatabaseSets() { var databaseSets = ConfigurationSection.DatabaseSets; if (databaseSets == null) { throw new DalException("Missing DatabaseSets."); } //一个DataBaseSet可以配置多个 例如主从 或者 分片 DatabaseSets = new Dictionary <String, DatabaseSetWrapper>(); foreach (DatabaseSetElement databaseSet in databaseSets) { if (!DatabaseProviders.ContainsKey(databaseSet.Provider)) { throw new DalException("DatabaseProvider doesn't match."); } IDatabaseProvider provider = DatabaseProviders[databaseSet.Provider]; //build set wrapper 同一个DataBaseSet的Provider必须一致 var databaseSetWrapper = new DatabaseSetWrapper { Name = databaseSet.Name, EnableReadWriteSpliding = false,//默认关闭读写分离 ProviderType = DatabaseProviderTypeFactory.GetProviderType(provider.ProviderType), }; foreach (DatabaseElement database in databaseSet.Databases) { databaseSetWrapper.DatabaseWrappers.Add(new DatabaseWrapper { Name = database.Name, ConnectionString = database.ConnectionString, DatabaseType = database.DatabaseType, DatabaseProvider = provider, Database = new Database(databaseSet.Name, database.Name, database.ConnectionString, provider) { DatabaseRWType = database.DatabaseType }, }); if (database.DatabaseType == DatabaseType.Slave && !databaseSetWrapper.EnableReadWriteSpliding) { databaseSetWrapper.EnableReadWriteSpliding = true; } } DatabaseSets.Add(databaseSet.Name, databaseSetWrapper); } }
public void GetDbContext(DatabaseProviders dbProvider) { Route4MeDbManager.DatabaseProvider = dbProvider; var curPath = Directory.GetCurrentDirectory(); var configBuilder = new ConfigurationBuilder() .SetBasePath(curPath) .AddJsonFile("appsettings.json", optional: true); var config = configBuilder.Build(); r4mdbManager = new Route4MeDbManager(config); _route4meDbContext = r4mdbManager.Route4MeContext; }
private DatabaseProviders PleskDatabaseProvider(string databaseProviderName) { DatabaseProviders provider = DatabaseProviders.Unknown; switch (databaseProviderName) { case "MySQL": provider = DatabaseProviders.MYSQL; break; case "MsSQL": provider = DatabaseProviders.MSSQL; break; } return(provider); }
public MaestroPanelDiscover() { currentProvider = DatabaseProviders.Unknown; if (isInstalled()) { currentConnectionString = GetConnectionString(out currentProvider); if (currentConnectionString.EndsWith(";")) { currentConnectionString = currentConnectionString.Remove(currentConnectionString.Length - 1, 1); } connectionStringKeys = currentConnectionString.Split(';') .Select(t => t.Split(new char[] { '=' }, 2)) .ToDictionary(t => t[0].Trim(), t => t[1].Trim(), StringComparer.InvariantCultureIgnoreCase); } }
/// <summary> /// Executes the migrations against the database. /// </summary> /// <param name="database">The PetaPoco Database, which the migrations will be run against</param> /// <param name="databaseProvider"></param> /// <param name="isUpgrade">Boolean indicating whether this is an upgrade or downgrade</param> /// <returns><c>True</c> if migrations were applied, otherwise <c>False</c></returns> public virtual bool Execute(Database database, DatabaseProviders databaseProvider, bool isUpgrade = true) { _logger.Info <MigrationRunner>("Initializing database migrations"); var foundMigrations = FindMigrations(); //filter all non-schema migrations var migrations = isUpgrade ? OrderedUpgradeMigrations(foundMigrations).ToList() : OrderedDowngradeMigrations(foundMigrations).ToList(); if (Migrating.IsRaisedEventCancelled(new MigrationEventArgs(migrations, _currentVersion, _targetVersion, _productName, true), this)) { _logger.Warn <MigrationRunner>("Migration was cancelled by an event"); return(false); } //Loop through migrations to generate sql var migrationContext = InitializeMigrations(migrations, database, databaseProvider, isUpgrade); try { ExecuteMigrations(migrationContext, database); } catch (Exception ex) { //if this fails then the transaction will be rolled back, BUT if we are using MySql this is not the case, //since it does not support schema changes in a transaction, see: http://dev.mysql.com/doc/refman/5.0/en/implicit-commit.html //so in that case we have to downgrade if (databaseProvider == DatabaseProviders.MySql) { throw new DataLossException( "An error occurred running a schema migration but the changes could not be rolled back. Error: " + ex.Message + ". In some cases, it may be required that the database be restored to it's original state before running this upgrade process again.", ex); } //continue throwing the exception throw; } Migrated.RaiseEvent(new MigrationEventArgs(migrations, migrationContext, _currentVersion, _targetVersion, _productName, false), this); return(true); }
public static bool IsConnectionAvailable(string connString, DatabaseProviders provider) { DbProviderFactory factory; switch (provider) { case DatabaseProviders.SqlServer: case DatabaseProviders.SqlAzure: factory = DbProviderFactories.GetFactory(Constants.DatabaseProviders.SqlServer); break; case DatabaseProviders.SqlServerCE: factory = DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0"); break; case DatabaseProviders.MySql: factory = DbProviderFactories.GetFactory(Constants.DatabaseProviders.MySql); break; case DatabaseProviders.PostgreSQL: case DatabaseProviders.Oracle: case DatabaseProviders.SQLite: default: throw new NotSupportedException("The provider " + provider + " is not supported"); } var conn = factory.CreateConnection(); if (conn == null) { throw new InvalidOperationException("Could not create a connection for provider " + provider); } conn.ConnectionString = connString; using (var connection = conn) { return(connection.IsAvailable()); } }
/// <summary> /// Configures the database connection. /// </summary> /// <param name="configuration">Application configuration properties.</param> /// <param name="services">Collection of service descriptors.</param> public static void ConfigureDatabase(IConfiguration configuration, IServiceCollection services) { //read which database provider to use DatabaseProviders provider = configuration.GetValue <DatabaseProviders>("DatabaseProvider"); switch (provider) { case DatabaseProviders.MySQL: configureMySQL(configuration, services); break; case DatabaseProviders.SQLServer: configureSQLServer(configuration, services); break; case DatabaseProviders.SQLite: configureSQLite(configuration, services); break; default: case DatabaseProviders.InMemory: configureInMemory(configuration, services); break; } services.AddScoped <ProductRepository, EFProductRepository>(); services.AddScoped <ProductCategoryRepository, EFProductCategoryRepository>(); services.AddScoped <MaterialRepository, EFMaterialRepository>(); services.AddScoped <CommercialCatalogueRepository, EFCommercialCatalogueRepository>(); services.AddScoped <CustomizedProductSerialNumberRepository, EFCustomizedProductSerialNumberRepository>(); services.AddScoped <CustomizedProductRepository, EFCustomizedProductRepository>(); services.AddScoped <CustomizedProductCollectionRepository, EFCustomizedProductCollectionRepository>(); services.AddScoped <CommercialCatalogueRepository, EFCommercialCatalogueRepository>(); services.AddScoped <FinishPriceTableRepository, EFFinishPriceTableRepository>(); services.AddScoped <MaterialPriceTableRepository, EFMaterialPriceTableRepository>(); }
public DeleteColumnExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { ColumnNames = new List<string>(); }
public RenameColumnExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
public MigrationContext(DatabaseProviders databaseProvider, Database database) { Expressions = new Collection<IMigrationExpression>(); CurrentDatabaseProvider = databaseProvider; Database = database; }
public DeleteTableExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
/// <summary> /// Initializes the Merchell Migrations. /// </summary> /// <param name="migrations"> /// The migrations. /// </param> /// <param name="database"> /// The database. /// </param> /// <param name="databaseProvider"> /// The database provider. /// </param> /// <param name="isUpgrade"> /// The is upgrade. /// </param> /// <returns> /// The <see cref="MerchelloMigrationContext"/>. /// </returns> internal MerchelloMigrationContext InitializeMigrations(List<IMigration> migrations, Database database, DatabaseProviders databaseProvider, bool isUpgrade = true) { //Loop through migrations to generate sql var context = new MerchelloMigrationContext(databaseProvider, database, _logger); foreach (var migration in migrations) { var baseMigration = migration as MerchelloMigrationBase; if (baseMigration != null) { if (isUpgrade) { baseMigration.GetUpExpressions(context); _logger.Info<CoreMigrationManager>(string.Format("Added UPGRADE migration '{0}' to context", baseMigration.GetType().Name)); } else { baseMigration.GetDownExpressions(context); _logger.Info<CoreMigrationManager>(string.Format("Added DOWNGRADE migration '{0}' to context", baseMigration.GetType().Name)); } } else { //this is just a normal migration so we can only call Up/Down if (isUpgrade) { migration.Up(); _logger.Info<MigrationRunner>(string.Format("Added UPGRADE migration '{0}' to context", migration.GetType().Name)); } else { migration.Down(); _logger.Info<MigrationRunner>(string.Format("Added DOWNGRADE migration '{0}' to context", migration.GetType().Name)); } } } return context; }
public UpdateDataExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
public CreateTableExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { Columns = new List<ColumnDefinition>(); }
public DeleteForeignKeyExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { ForeignKey = new ForeignKeyDefinition(); }
public InsertDataExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
protected MigrationExpressionBase(DatabaseProviders current, DatabaseProviders[] databaseProviders) { SupportedDatabaseProviders = databaseProviders; CurrentDatabaseProvider = current; }
public ExecuteCodeStatementExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
public DeleteConstraintExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders, ConstraintType type) : base(current, databaseProviders) { Constraint = new ConstraintDefinition(type); }
public DeleteDefaultConstraintExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { }
public CreateIndexExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders) { Index = new IndexDefinition(); }