public InMemoryTransactionManager(
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Transaction> logger)
        {
            Check.NotNull(logger, nameof(logger));

            _logger = logger;
        }
Esempio n. 2
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public Migrator(
            [NotNull] IMigrationsAssembly migrationsAssembly,
            [NotNull] IHistoryRepository historyRepository,
            [NotNull] IDatabaseCreator databaseCreator,
            [NotNull] IMigrationsSqlGenerator migrationsSqlGenerator,
            [NotNull] IRawSqlCommandBuilder rawSqlCommandBuilder,
            [NotNull] IMigrationCommandExecutor migrationCommandExecutor,
            [NotNull] IRelationalConnection connection,
            [NotNull] ISqlGenerationHelper sqlGenerationHelper,
            [NotNull] IInterceptingLogger <LoggerCategory.Migrations> logger,
            [NotNull] IDatabaseProvider databaseProvider)
        {
            Check.NotNull(migrationsAssembly, nameof(migrationsAssembly));
            Check.NotNull(historyRepository, nameof(historyRepository));
            Check.NotNull(databaseCreator, nameof(databaseCreator));
            Check.NotNull(migrationsSqlGenerator, nameof(migrationsSqlGenerator));
            Check.NotNull(rawSqlCommandBuilder, nameof(rawSqlCommandBuilder));
            Check.NotNull(migrationCommandExecutor, nameof(migrationCommandExecutor));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(sqlGenerationHelper, nameof(sqlGenerationHelper));
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(databaseProvider, nameof(databaseProvider));

            _migrationsAssembly       = migrationsAssembly;
            _historyRepository        = historyRepository;
            _databaseCreator          = (IRelationalDatabaseCreator)databaseCreator;
            _migrationsSqlGenerator   = migrationsSqlGenerator;
            _rawSqlCommandBuilder     = rawSqlCommandBuilder;
            _migrationCommandExecutor = migrationCommandExecutor;
            _connection          = connection;
            _sqlGenerationHelper = sqlGenerationHelper;
            _logger         = logger;
            _activeProvider = databaseProvider.InvariantName;
        }
Esempio n. 3
0
        private static async Task <TResult> ExecuteSingletonAsyncQuery <TResult>(
            QueryContext queryContext,
            Func <QueryContext, IAsyncEnumerable <TResult> > compiledQuery,
            IInterceptingLogger <LoggerCategory.Query> logger,
            Type contextType)
        {
            try
            {
                var asyncEnumerable = compiledQuery(queryContext);

                using (var asyncEnumerator = asyncEnumerable.GetEnumerator())
                {
                    await asyncEnumerator.MoveNext(queryContext.CancellationToken);

                    return(asyncEnumerator.Current);
                }
            }
            catch (Exception exception)
            {
                logger
                .LogError(
                    CoreEventId.DatabaseError,
                    () => new DatabaseErrorLogState(contextType),
                    exception,
                    e => CoreStrings.LogExceptionDuringQueryIteration(Environment.NewLine, e));

                throw;
            }
        }
Esempio n. 4
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 protected virtual IRelationalCommand BuildCore(
     [NotNull] IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     [NotNull] DiagnosticSource diagnosticSource,
     [NotNull] string commandText,
     [NotNull] IReadOnlyList <IRelationalParameter> parameters)
 => new RelationalCommand(
     logger, diagnosticSource, commandText, parameters);
Esempio n. 5
0
 public BadDataCommandBuilderFactory(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     IRelationalTypeMapper typeMapper)
     : base(logger, diagnosticSource, typeMapper)
 {
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="RelationalTransaction" /> class.
        /// </summary>
        /// <param name="connection"> The connection to the database. </param>
        /// <param name="transaction"> The underlying <see cref="DbTransaction" />. </param>
        /// <param name="logger"> The logger to write to. </param>
        /// <param name="diagnosticSource"> The diagnostic source to write to. </param>
        /// <param name="transactionOwned">
        ///     A value indicating whether the transaction is owned by this class (i.e. if it can be disposed when this class is disposed).
        /// </param>
        public RelationalTransaction(
            [NotNull] IRelationalConnection connection,
            [NotNull] DbTransaction transaction,
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Transaction> logger,
            [NotNull] DiagnosticSource diagnosticSource,
            bool transactionOwned)
        {
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(transaction, nameof(transaction));
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(diagnosticSource, nameof(diagnosticSource));

            if (connection.DbConnection != transaction.Connection)
            {
                throw new InvalidOperationException(RelationalStrings.TransactionAssociatedWithDifferentConnection);
            }

            _relationalConnection = connection;

            _dbTransaction    = transaction;
            _logger           = logger;
            _diagnosticSource = diagnosticSource;
            _transactionOwned = transactionOwned;

            _diagnosticSource.WriteTransactionStarted(
                _relationalConnection.DbConnection,
                _relationalConnection.ConnectionId,
                _dbTransaction);
        }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static void LogCommandExecuted(
            [NotNull] this IInterceptingLogger <LoggerCategory.Database.Sql> logger,
            [NotNull] DbCommand command,
            long startTimestamp,
            long currentTimestamp)
        {
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(command, nameof(command));

            if (logger.IsEnabled(LogLevel.Information))
            {
                var logParameterValues
                    = command.Parameters.Count > 0 &&
                      logger.LogSensitiveData;

#pragma warning disable 618
                var logData = new DbCommandLogData(
#pragma warning restore 618
                    command.CommandText.TrimEnd(),
                    command.CommandType,
                    command.CommandTimeout,
                    command.Parameters
                    .Cast <DbParameter>()
                    .Select(
                        p => new DbParameterLogData(
                            p.ParameterName,
                            logParameterValues ? p.Value : "?",
                            logParameterValues,
                            p.Direction,
                            p.DbType,
                            p.IsNullable,
                            p.Size,
                            p.Precision,
                            p.Scale))
                    .ToList(),
                    DeriveTimespan(startTimestamp, currentTimestamp));

                logger.Log(
                    LogLevel.Information,
                    (int)RelationalEventId.ExecutedCommand,
                    logData,
                    null,
                    (state, _) =>
                {
                    var elapsedMilliseconds = DeriveTimespan(startTimestamp, currentTimestamp);

                    return(RelationalStrings.RelationalLoggerExecutedCommand(
                               string.Format(CultureInfo.InvariantCulture, "{0:N0}", elapsedMilliseconds),
                               state.Parameters
                               // Interpolation okay here because value is always a string.
                               .Select(p => $"{p.Name}={p.FormatParameter()}")
                               .Join(),
                               state.CommandType,
                               state.CommandTimeout,
                               Environment.NewLine,
                               state.CommandText));
                });
            }
        }
Esempio n. 8
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 protected virtual IRelationalCommandBuilder CreateCore(
     [NotNull] IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     [NotNull] DiagnosticSource diagnosticSource,
     [NotNull] IRelationalTypeMapper relationalTypeMapper)
 => new RelationalCommandBuilder(
     logger,
     diagnosticSource,
     relationalTypeMapper);
Esempio n. 9
0
 public ExceptionInterceptor(
     IAsyncEnumerable <T> innerAsyncEnumerable, Type contextType, IInterceptingLogger <LoggerCategory.Query> logger, QueryContext queryContext)
 {
     _innerAsyncEnumerable = innerAsyncEnumerable;
     _contextType          = contextType;
     _logger       = logger;
     _queryContext = queryContext;
 }
 public TestRelationalCommand(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     string commandText,
     IReadOnlyList <IRelationalParameter> parameters)
 {
     _realRelationalCommand = new RelationalCommand(logger, diagnosticSource, commandText, parameters);
 }
Esempio n. 11
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public SqlServerScaffoldingModelFactory(
     [NotNull] IInterceptingLogger <LoggerCategory.Scaffolding> logger,
     [NotNull] IRelationalTypeMapper typeMapper,
     [NotNull] IDatabaseModelFactory databaseModelFactory,
     [NotNull] CandidateNamingService candidateNamingService,
     [NotNull] IPluralizer pluralizer)
     : base(logger, typeMapper, databaseModelFactory, candidateNamingService, pluralizer)
 {
 }
 public TestRelationalCommandBuilder(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     IRelationalTypeMapper typeMapper)
 {
     _logger           = logger;
     _diagnosticSource = diagnosticSource;
     ParameterBuilder  = new RelationalParameterBuilder(typeMapper);
 }
Esempio n. 13
0
 public BadDataRelationalCommandBuilder(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     IRelationalTypeMapper typeMapper,
     object[] values)
     : base(logger, diagnosticSource, typeMapper)
 {
     _values = values;
 }
 public TestRelationalCommandBuilderFactory(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     IRelationalTypeMapper typeMapper)
 {
     _logger           = logger;
     _diagnosticSource = diagnosticSource;
     _typeMapper       = typeMapper;
 }
Esempio n. 15
0
 private IRelationalCommand CreateRelationalCommand(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger = null,
     DiagnosticSource diagnosticSource = null,
     string commandText = "Command Text",
     IReadOnlyList <IRelationalParameter> parameters = null)
 => new RelationalCommand(
     logger ?? new FakeInterceptingLogger <LoggerCategory.Database.Sql>(),
     diagnosticSource ?? new DiagnosticListener("Fake"),
     commandText,
     parameters ?? new IRelationalParameter[0]);
Esempio n. 16
0
 public BadDataRelationalCommand(
     IInterceptingLogger <LoggerCategory.Database.Sql> logger,
     DiagnosticSource diagnosticSource,
     string commandText,
     IReadOnlyList <IRelationalParameter> parameters,
     object[] values)
     : base(logger, diagnosticSource, commandText, parameters)
 {
     _values = values;
 }
Esempio n. 17
0
 public FakeScaffoldingModelFactory(
     [NotNull] IInterceptingLogger <LoggerCategory.Scaffolding> logger,
     [NotNull] IPluralizer pluralizer)
     : base(logger,
            new TestTypeMapper(new RelationalTypeMapperDependencies()),
            new FakeDatabaseModelFactory(),
            new CandidateNamingService(),
            pluralizer)
 {
 }
Esempio n. 18
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public ParameterExtractingExpressionVisitor(
     [NotNull] IEvaluatableExpressionFilter evaluatableExpressionFilter,
     [NotNull] QueryContext queryContext,
     [NotNull] IInterceptingLogger <LoggerCategory.Query> logger,
     bool parameterize)
 {
     _evaluatableExpressionFilter = evaluatableExpressionFilter;
     _queryContext = queryContext;
     _logger       = logger;
     _parameterize = parameterize;
 }
        /// <summary>
        ///     <para>
        ///         Creates the service dependencies parameter object for a <see cref="ExecutionStrategyContext" />.
        ///     </para>
        ///     <para>
        ///         Do not call this constructor directly from either provider or application code as it may change
        ///         as new dependencies are added. Instead, use this type in your constructor so that an instance
        ///         will be created and injected automatically by the dependency injection container. To create
        ///         an instance with some dependent services replaced, first resolve the object from the dependency
        ///         injection container, then replace selected services using the 'With...' methods. Do not call
        ///         the constructor at any point in this process.
        ///     </para>
        /// </summary>
        /// <param name="currentDbContext"> Indirection to the current <see cref="DbContext" /> instance. </param>
        /// <param name="options"> The options for the current <see cref="DbContext" /> instance. </param>
        /// <param name="logger"> A logger.</param>
        public ExecutionStrategyContextDependencies(
            [NotNull] ICurrentDbContext currentDbContext,
            [CanBeNull] IDbContextOptions options,
            [CanBeNull] IInterceptingLogger <LoggerCategory.Infrastructure> logger)
        {
            Check.NotNull(currentDbContext, nameof(currentDbContext));

            Options          = options;
            CurrentDbContext = currentDbContext;
            Logger           = logger;
        }
Esempio n. 20
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public RelationalCommandBuilder(
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Sql> logger,
            [NotNull] DiagnosticSource diagnosticSource,
            [NotNull] IRelationalTypeMapper typeMapper)
        {
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(diagnosticSource, nameof(diagnosticSource));
            Check.NotNull(typeMapper, nameof(typeMapper));

            _logger           = logger;
            _diagnosticSource = diagnosticSource;
            ParameterBuilder  = new RelationalParameterBuilder(typeMapper);
        }
Esempio n. 21
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public InMemoryDatabase(
            [NotNull] DatabaseDependencies dependencies,
            [NotNull] IInMemoryStoreSource storeSource,
            [NotNull] IDbContextOptions options,
            [NotNull] IInterceptingLogger <LoggerCategory.Update> updateLogger)
            : base(dependencies)
        {
            Check.NotNull(storeSource, nameof(storeSource));
            Check.NotNull(options, nameof(options));
            Check.NotNull(updateLogger, nameof(updateLogger));

            _store        = storeSource.GetStore(options);
            _updateLogger = updateLogger;
        }
        /// <summary>
        ///     <para>
        ///         Creates the service dependencies parameter object for a <see cref="RelationalConnection" />.
        ///     </para>
        ///     <para>
        ///         Do not call this constructor directly from either provider or application code as it may change
        ///         as new dependencies are added. Instead, use this type in your constructor so that an instance
        ///         will be created and injected automatically by the dependency injection container. To create
        ///         an instance with some dependent services replaced, first resolve the object from the dependency
        ///         injection container, then replace selected services using the 'With...' methods. Do not call
        ///         the constructor at any point in this process.
        ///     </para>
        /// </summary>
        /// <param name="contextOptions"> The options for the current context instance. </param>
        /// <param name="transactionLogger"> The logger to which transaction messages will be written. </param>
        /// <param name="connectionLogger"> The logger to which connection messages will be written. </param>
        /// <param name="diagnosticSource"> The diagnostic source to write to. </param>
        public RelationalConnectionDependencies(
            [NotNull] IDbContextOptions contextOptions,
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Transaction> transactionLogger,
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Connection> connectionLogger,
            [NotNull] DiagnosticSource diagnosticSource)
        {
            Check.NotNull(contextOptions, nameof(contextOptions));
            Check.NotNull(connectionLogger, nameof(connectionLogger));
            Check.NotNull(transactionLogger, nameof(transactionLogger));
            Check.NotNull(diagnosticSource, nameof(diagnosticSource));

            ContextOptions    = contextOptions;
            ConnectionLogger  = connectionLogger;
            TransactionLogger = transactionLogger;
            DiagnosticSource  = diagnosticSource;
        }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public RelationalCommand(
            [NotNull] IInterceptingLogger <LoggerCategory.Database.Sql> logger,
            [NotNull] DiagnosticSource diagnosticSource,
            [NotNull] string commandText,
            [NotNull] IReadOnlyList <IRelationalParameter> parameters)
        {
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(diagnosticSource, nameof(diagnosticSource));
            Check.NotNull(commandText, nameof(commandText));
            Check.NotNull(parameters, nameof(parameters));

            Logger           = logger;
            DiagnosticSource = diagnosticSource;
            CommandText      = commandText;
            Parameters       = parameters;
        }
Esempio n. 24
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static Expression ExtractParameters(
            [NotNull] Expression expression,
            [NotNull] QueryContext queryContext,
            [NotNull] IEvaluatableExpressionFilter evaluatableExpressionFilter,
            [NotNull] IInterceptingLogger <LoggerCategory.Query> logger,
            bool parameterize)
        {
            var visitor
                = new ParameterExtractingExpressionVisitor(
                      evaluatableExpressionFilter,
                      queryContext,
                      logger,
                      parameterize);

            return(visitor.ExtractParameters(expression));
        }
Esempio n. 25
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual int ExecuteTransaction(
            IEnumerable <IUpdateEntry> entries,
            IInterceptingLogger <LoggerCategory.Update> updateLogger)
        {
            var rowsAffected = 0;

            lock (_lock)
            {
                foreach (var entry in entries)
                {
                    var entityType = entry.EntityType;

                    Debug.Assert(!entityType.IsAbstract());

                    IInMemoryTable table;
                    if (!_tables.Value.TryGetValue(entityType, out table))
                    {
                        _tables.Value.Add(entityType, table = _tableFactory.Create(entityType));
                    }

                    switch (entry.EntityState)
                    {
                    case EntityState.Added:
                        table.Create(entry);
                        break;

                    case EntityState.Deleted:
                        table.Delete(entry);
                        break;

                    case EntityState.Modified:
                        table.Update(entry);
                        break;
                    }

                    rowsAffected++;
                }
            }

            updateLogger.LogInformation <object>(
                InMemoryEventId.SavedChanges,
                rowsAffected,
                InMemoryStrings.LogSavedChanges);

            return(rowsAffected);
        }
Esempio n. 26
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public QueryCompilationContextDependencies(
            [NotNull] IModel model,
            [NotNull] IInterceptingLogger <LoggerCategory.Query> logger,
            [NotNull] IEntityQueryModelVisitorFactory entityQueryModelVisitorFactory,
            [NotNull] IRequiresMaterializationExpressionVisitorFactory requiresMaterializationExpressionVisitorFactory,
            [NotNull] ICurrentDbContext currentContext)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(entityQueryModelVisitorFactory, nameof(entityQueryModelVisitorFactory));
            Check.NotNull(requiresMaterializationExpressionVisitorFactory, nameof(requiresMaterializationExpressionVisitorFactory));
            Check.NotNull(currentContext, nameof(currentContext));

            Model  = model;
            Logger = logger;
            EntityQueryModelVisitorFactory = entityQueryModelVisitorFactory;
            RequiresMaterializationExpressionVisitorFactory = requiresMaterializationExpressionVisitorFactory;
            CurrentContext = currentContext;
        }
Esempio n. 27
0
        public RelationalScaffoldingModelFactory(
            [NotNull] IInterceptingLogger <LoggerCategory.Scaffolding> logger,
            [NotNull] IRelationalTypeMapper typeMapper,
            [NotNull] IDatabaseModelFactory databaseModelFactory,
            [NotNull] CandidateNamingService candidateNamingService,
            [NotNull] IPluralizer pluralizer)
        {
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(typeMapper, nameof(typeMapper));
            Check.NotNull(databaseModelFactory, nameof(databaseModelFactory));
            Check.NotNull(candidateNamingService, nameof(candidateNamingService));
            Check.NotNull(pluralizer, nameof(pluralizer));

            Logger                 = logger;
            TypeMapper             = typeMapper;
            CandidateNamingService = candidateNamingService;
            _databaseModelFactory  = databaseModelFactory;
            _pluralizer            = pluralizer;
        }
Esempio n. 28
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public QueryCompiler(
            [NotNull] IQueryContextFactory queryContextFactory,
            [NotNull] ICompiledQueryCache compiledQueryCache,
            [NotNull] ICompiledQueryCacheKeyGenerator compiledQueryCacheKeyGenerator,
            [NotNull] IDatabase database,
            [NotNull] IInterceptingLogger <LoggerCategory.Query> logger,
            [NotNull] INodeTypeProviderFactory nodeTypeProviderFactory,
            [NotNull] ICurrentDbContext currentContext)
        {
            Check.NotNull(queryContextFactory, nameof(queryContextFactory));
            Check.NotNull(compiledQueryCache, nameof(compiledQueryCache));
            Check.NotNull(compiledQueryCacheKeyGenerator, nameof(compiledQueryCacheKeyGenerator));
            Check.NotNull(database, nameof(database));
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(currentContext, nameof(currentContext));

            _queryContextFactory            = queryContextFactory;
            _compiledQueryCache             = compiledQueryCache;
            _compiledQueryCacheKeyGenerator = compiledQueryCacheKeyGenerator;
            _database = database;
            _logger   = logger;
            _nodeTypeProviderFactory = nodeTypeProviderFactory;
            _contextType             = currentContext.Context.GetType();
        }
Esempio n. 29
0
 public FakeScaffoldingModelFactory(
     [NotNull] IInterceptingLogger <LoggerCategory.Scaffolding> logger)
     : this(logger, new NullPluralizer())
 {
 }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public EqualsTranslator([NotNull] IInterceptingLogger <LoggerCategory.Query> logger)
        {
            Check.NotNull(logger, nameof(logger));

            _logger = logger;
        }