Пример #1
0
        public async Task <ExecutionDataContext> GetContextAsync(DatabaseConfiguration dbConfig, CancellationToken cancellation)
        {
            _logger.Trace($"Getting a connection for database: '{dbConfig.Name}'");
            if (dbConfig == null)
            {
                throw new ArgumentNullException(nameof(dbConfig));
            }
            if (Pool.ContainsKey(dbConfig.Name))
            {
                return(Pool[dbConfig.Name]);
            }
            var build = new NpgsqlConnectionStringBuilder(dbConfig.ConnectionString)
            {
                Password            = dbConfig.Password,
                IncludeErrorDetails = true
            };
            var connection = new NpgsqlConnection(build.ConnectionString);

            connection.Open();
            var transaction = await connection.BeginTransactionAsync(cancellation);

            var context = new ExecutionDataContext(connection, transaction);

            Pool.Add(dbConfig.Name, context);
            return(context);
        }
Пример #2
0
        public async Task ExecuteAsync(string scriptPath, ExecutionDataContext context, CancellationToken cancellation)
        {
            if (string.IsNullOrWhiteSpace(scriptPath))
            {
                throw new ArgumentNullException(nameof(scriptPath));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            _logger.Trace($"executing script: {scriptPath}");
            var npgsqlConnection = context.Connection as NpgsqlConnection;

            if (npgsqlConnection == null)
            {
                throw new ApplicationException($"Db connection must be npgsql but it is {context.Connection.GetType().FullName}");
            }
            if (npgsqlConnection.State != ConnectionState.Open)
            {
                npgsqlConnection.Open();
            }
            var npgsqlTransaction = context.Transaction as NpgsqlTransaction;

            if (npgsqlTransaction == null)
            {
                throw new ApplicationException($"Db transaction must be npgsql but it is {context.Transaction.GetType().FullName}");
            }

            cancellation.ThrowIfCancellationRequested();
            _logger.Trace($"reading script: {scriptPath}");
            var sqlCommand = await File.ReadAllTextAsync(scriptPath, cancellation);

            await using var command = new NpgsqlCommand(sqlCommand, npgsqlConnection, npgsqlTransaction);
            cancellation.ThrowIfCancellationRequested();
            _logger.Trace($"executing script: {scriptPath}");
            await command.ExecuteNonQueryAsync(cancellation);

            _logger.Trace($"executed script: {scriptPath}");
        }