/// <summary>
        ///		Copia masiva de un <see cref="IDataReader"/> sobre una tabla
        /// </summary>
        public long Process(IDbProvider provider, IDataReader reader, string table, Dictionary <string, string> mappings, int recordsPerBlock, TimeSpan?timeout = null)
        {
            long records = 0, blockRecords = 0;
            Dictionary <string, string> mappingsConverted = Convert(reader, mappings);
            string sql = GetInsertCommand(table, mappingsConverted);

            // Abre una transacción
            provider.BeginTransaction();
            // Lee los registros e inserta
            while (reader.Read())
            {
                // Ejecuta el comando de inserción
                provider.Execute(sql, GetParameters(reader, mappingsConverted), CommandType.Text, timeout);
                // Cierra la transacción
                blockRecords++;
                if (blockRecords % recordsPerBlock == 0)
                {
                    // Confirma la transacción y abre una nueva
                    provider.Commit();
                    provider.BeginTransaction();
                    // Reinicia el número de registros del bloque
                    blockRecords = 0;
                }
                // Incrementa el número de registros
                records++;
            }
            // Cierra la transacción
            if (blockRecords != 0)
            {
                provider.Commit();
            }
            // Devuelve el número de registros copiados
            return(records);
        }
        /// <summary>
        /// Executes pre-migration scripts.
        /// </summary>
        /// <returns>True if pre-migrations were executed, otherwise - false.</returns>
        /// <exception cref="MigrationException"></exception>
        private async Task <bool> ExecutePreMigrationScriptsAsync(CancellationToken token = default)
        {
            var desiredMigrations = _preMigrations
                                    .OrderBy(x => x.Version)
                                    .ToArray();

            if (desiredMigrations.Length == 0)
            {
                return(false);
            }

            foreach (var migration in desiredMigrations)
            {
                token.ThrowIfCancellationRequested();

                DbTransaction?transaction = null;

                await _dbProvider.CloseConnectionAsync();

                await _dbProvider.OpenConnectionAsync(token);

                try
                {
                    _logger?.LogInformation(
                        $"Executing pre-migration script {migration.Version} (\"{migration.Comment}\") for database \"{_dbProvider.DbName}\"...");

                    if (migration.IsTransactionRequired)
                    {
                        transaction = _dbProvider.BeginTransaction();
                    }
                    else
                    {
                        _logger?.LogWarning($"Transaction is disabled for pre-migration {migration.Version}");
                    }

                    await migration.UpgradeAsync(transaction, token);

                    transaction?.Commit();

                    _logger?.LogInformation(
                        $"Executing pre-migration script {migration.Version} for database \"{_dbProvider.DbName}\" completed.");
                }
                catch (Exception e)
                {
                    throw new MigrationException(
                              MigrationError.MigratingError,
                              $"Error while executing pre-migration to {migration.Version} for database \"{_dbProvider.DbName}\": {e.Message}",
                              e);
                }
                finally
                {
                    transaction?.Dispose();
                }
            }
            return(true);
        }
Beispiel #3
0
 private static void ProcessDbProvider(ParameterUtil sup, ProcessFunDelegate fun, DbType dbType, bool inTransaction)
 {
     using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(GetDbType(dbType)))
     {
         try
         {
             dbProvider.Open(GetDbConnection(dbType));
             if (inTransaction)
             {
                 dbProvider.BeginTransaction();
             }
             fun(dbProvider);
             AddLog(dbProvider, sup);
             if (inTransaction)
             {
                 dbProvider.CommitTransaction();
             }
         }
         catch (Exception ex)
         {
             if (inTransaction)
             {
                 dbProvider.RollbackTransaction();
             }
             CiExceptionManager.LogException(dbProvider, sup.UserInfo, ex);
             throw;
         }
         finally
         {
             dbProvider.Close();
         }
     }
 }
        /// <summary>
        ///		Copia masiva de un <see cref="IDataReader"/> sobre una tabla de forma asíncrona
        /// </summary>
        public async Task <long> ProcessAsync(IDbProvider provider, IDataReader reader, string table, Dictionary <string, string> mappings, int recordsPerBlock,
                                              TimeSpan timeout, CancellationToken cancellationToken)
        {
            long records = 0, blockRecords = 0;
            Dictionary <string, string> mappingsConverted = Convert(reader, mappings);
            string sql = GetInsertCommand(table, mappingsConverted);

            // Abre una transacción
            provider.BeginTransaction();
            // Lee los registros e inserta
            if (!cancellationToken.IsCancellationRequested)
            {
                while (await(reader as DbDataReader).ReadAsync(cancellationToken))
                {
                    // Ejecuta el comando de inserción
                    await provider.ExecuteAsync(sql, GetParameters(reader, mappingsConverted), CommandType.Text, timeout, cancellationToken);

                    // Cierra la transacción
                    blockRecords++;
                    if (blockRecords % recordsPerBlock == 0)
                    {
                        // Confirma la transacción y abre una nueva
                        provider.Commit();
                        provider.BeginTransaction();
                        // Reinicia el número de registros del bloque
                        blockRecords = 0;
                    }
                    // Incrementa el número de registros
                    records++;
                }
            }
            // Cancela o confirma la transacción si es necesario
            if (cancellationToken.IsCancellationRequested)
            {
                provider.RollBack();
            }
            else if (blockRecords != 0)
            {
                provider.Commit();
            }
            // Devuelve el número de registros copiados
            return(records);
        }
Beispiel #5
0
        public void SaveChanges()
        {
            SqlTransaction transactionResult = _ormProvider.BeginTransaction();

            try
            {
                _ormProvider.CommitTransaction(transactionResult);
            }
            catch (Exception)
            {
                _ormProvider.RollbackTransaction(transactionResult);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Upgrade database to new version
        /// </summary>
        /// <returns></returns>
        /// <exception cref="MigrationException"></exception>
        private async Task ExecutePreMigrationScriptsAsync()
        {
            var desiredMigrations = _preMigrations
                                    .OrderBy(x => x.Version)
                                    .ToList();

            if (desiredMigrations.Count == 0)
            {
                return;
            }

            foreach (var migration in desiredMigrations)
            {
                await _dbProvider.CloseConnectionAsync();

                await _dbProvider.OpenConnectionAsync();

                using (var transaction = _dbProvider.BeginTransaction())
                {
                    try
                    {
                        _logger?.LogInformation(
                            $"Executing pre migration script {migration.Version} ({migration.Comment}) for DB {_dbProvider.DbName}...");
                        await migration.UpgradeAsync(transaction);

                        transaction.Commit();

                        _logger?.LogInformation(
                            $"Executing pre migration script {migration.Version} for DB {_dbProvider.DbName}) completed.");
                    }
                    catch (Exception e)
                    {
                        _logger?.LogError(e,
                                          $"Error while executing pre migration to {migration.Version}: {e.Message}");
                        throw;
                    }
                }
            }
        }
        private void Apply(ChangeScript changeScript)
        {
            Exception exception = null;

            using (var transaction = _provider.BeginTransaction())
            {
                try
                {
                    _provider.ApplyChangeScript(changeScript);

                    _logger.LogInformation($"Database script #{changeScript.Number} of version {changeScript.Version} has been applied.");

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            }

            var changeLogRecord = new ChangeLogRecord(changeScript, exception);

            using (var transaction = _provider.BeginTransaction())
            {
                _provider.DeleteChangeLogRecord(changeLogRecord);
                _provider.InsertChangeLogRecord(changeLogRecord);

                transaction.Commit();
            }

            if (!changeLogRecord.IsSuccessful)
            {
                _provider.Disconnect();

                throw changeLogRecord.Exception;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="ids">主键数组</param>
        /// <returns>影响行数</returns>
        public int BatchDelete(UserInfo userInfo, string[] ids)
        {
            int returnValue = 0;

            using (IDbProvider rdiDbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    rdiDbProvider.Open(RDIFrameworkDbConection);
                    LogManager.Instance.Add(rdiDbProvider, userInfo, this.serviceName, "批量删除数据", MethodBase.GetCurrentMethod());

                    using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(BusinessDbType))
                    {
                        try
                        {
                            dbProvider.Open(BusinessDbConnection);
                            // 开始事务
                            dbProvider.BeginTransaction();
                            LinkManManager manager = new LinkManManager(dbProvider, userInfo);
                            returnValue = manager.Delete(ids);
                            // 提交事务
                            dbProvider.CommitTransaction();
                        }
                        catch (Exception ex)
                        {
                            // 回滚事务
                            dbProvider.RollbackTransaction();
                            CiExceptionManager.LogException(rdiDbProvider, userInfo, ex);
                            throw ex;
                        }
                        finally
                        {
                            dbProvider.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(rdiDbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    rdiDbProvider.Close();
                }
            }

            return(returnValue);
        }
 //事务测试
 private void toolStripButton2_Click(object sender, EventArgs e)
 {
     dbProvider.Open();
     dbProvider.BeginTransaction();
     try
     {
         string sql    = "insert into test1(Id,Col1,Col2,Col3) values('" + BusinessLogic.NewGuid() + "','abcd',2,'kk')";
         int    value1 = dbProvider.ExecuteNonQuery(sql);
         //sql = "insert into test2(Id,Col1,Col2) values('" + BusinessLogic.NewGuid() + "','4','kk')";
         sql = "insert into test2(Id,Col2) values('" + BusinessLogic.NewGuid() + "','kk')";
         int value2 = dbProvider.ExecuteNonQuery(sql); //插入失败,则第一条语句也失败。
         dbProvider.CommitTransaction();
     }
     catch (Exception ex)
     {
         dbProvider.RollbackTransaction();
         MessageBoxHelper.ShowErrorMsg(ex.Message);
     }
     finally
     {
         dbProvider.Close();
     }
 }
Beispiel #10
0
 /// <summary>
 /// Begins a new transaction
 /// </summary>
 public ITransaction BeginTransaction()
 {
     return(provider.BeginTransaction());
 }
Beispiel #11
0
        /// <summary>
        /// 开始事务

        /// </summary>
        public void BeginTransaction()
        {
            provider.BeginTransaction();
        }
Beispiel #12
0
 public override Task BeginTransaction() => Provider.BeginTransaction();