Пример #1
0
        public override string SelectFragment(IJoinable rhs, string rhsAlias, string lhsAlias, string collectionSuffix, bool includeCollectionColumns, EntityLoadInfo entityInfo)
        {
            var buf = new StringBuilder();

            if (includeCollectionColumns)
            {
                buf.Append(SelectFragment(lhsAlias, collectionSuffix)).Append(StringHelper.CommaSpace);
            }

            //6.0 TODO: Remove
#pragma warning disable 618
            if (entityInfo.IncludeLazyProps)
            {
                var selectMode = ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(ElementPersister, "fetch lazy properties");
                if (selectMode != null)
                {
                    return(buf.Append(selectMode.SelectFragment(null, null, lhsAlias, entityInfo.EntitySuffix, null, false, true)).ToString());
                }
            }
#pragma warning restore 618

            if (entityInfo.LazyProperties?.Count > 0)
            {
                var selectMode = ReflectHelper.CastOrThrow <ISupportLazyPropsJoinable>(ElementPersister, "fetch lazy properties");
                if (selectMode != null)
                {
                    return(buf.Append(selectMode.SelectFragment(null, null, lhsAlias, null, false, entityInfo)).ToString());
                }
            }

            var ojl = (IOuterJoinLoadable)ElementPersister;
            return(buf.Append(ojl.SelectFragment(lhsAlias, entityInfo.EntitySuffix)).ToString());            //use suffix for the entity columns
        }
        private TenantConfiguration ValidateTenantConfiguration(ISessionFactoryImplementor factory, ISessionCreationOptions options)
        {
            if (factory.Settings.MultiTenancyStrategy == MultiTenancyStrategy.None)
            {
                return(null);
            }

            var tenantConfiguration = ReflectHelper.CastOrThrow <ISessionCreationOptionsWithMultiTenancy>(options, "multi-tenancy").TenantConfiguration;

            if (string.IsNullOrEmpty(tenantConfiguration?.TenantIdentifier))
            {
                throw new ArgumentException(
                          $"Tenant configuration with `{nameof(TenantConfiguration.TenantIdentifier)}` defined is required for multi-tenancy.",
                          nameof(tenantConfiguration));
            }

            if (_factory.Settings.MultiTenancyConnectionProvider == null)
            {
                throw new ArgumentException(
                          $"`{nameof(IMultiTenancyConnectionProvider)}` is required for multi-tenancy." +
                          $" Provide it via '{Cfg.Environment.MultiTenancyConnectionProvider}` session factory setting." +
                          $" You can use `{nameof(AbstractMultiTenancyConnectionProvider)}` as a base.");
            }

            return(tenantConfiguration);
        }
 //6.0 TODO: Merge into ICollectionPropertiesMapper<TEntity, TElement>
 public static void Type <TEntity, TElement>(
     this ICollectionPropertiesMapper <TEntity, TElement> mapper,
     string collectionType)
 {
     ReflectHelper
     .CastOrThrow <CollectionPropertiesCustomizer <TEntity, TElement> >(mapper, "Type(string)")
     .Type(collectionType);
 }
 /// <summary>
 /// Attempt to retrieve multiple objects from the Cache
 /// </summary>
 /// <param name="cache">The cache concurrency strategy.</param>
 /// <param name="keys">The keys (id) of the objects to get out of the Cache.</param>
 /// <param name="timestamp">A timestamp prior to the transaction start time</param>
 /// <returns>An array of cached objects or <see langword="null" /></returns>
 /// <exception cref="CacheException"></exception>
 public static object[] GetMany(this ICacheConcurrencyStrategy cache, CacheKey[] keys, long timestamp)
 {
     // PreferMultipleGet yields false if !IBatchableCacheConcurrencyStrategy, no GetMany call should be done
     // in such case.
     return(ReflectHelper
            .CastOrThrow <IBatchableCacheConcurrencyStrategy>(cache, "batching")
            .GetMany(keys, timestamp));
 }
        private static void CallFormulas(object mapper, string[] formulas)
        {
            var colsOrForMapper = ReflectHelper.CastOrThrow <IColumnsAndFormulasMapper>(
                mapper,
                "Setting many formula");

            colsOrForMapper.Formulas(formulas);
        }
Пример #6
0
        /// <summary>
        /// Evict an entry from the process-level cache.  This method occurs outside
        /// of any transaction; it performs an immediate "hard" remove, so does not respect
        /// any transaction isolation semantics of the usage strategy.  Use with care.
        /// </summary>
        /// <param name="factory">The session factory.</param>
        /// <param name="roleName">Collection role name.</param>
        /// <param name="id">Collection id</param>
        /// <param name="tenantIdentifier">Tenant identifier</param>
        public static void EvictCollection(this ISessionFactory factory, string roleName, object id, string tenantIdentifier)
        {
            if (tenantIdentifier == null)
            {
                factory.EvictCollection(roleName, id);
            }

            ReflectHelper.CastOrThrow <SessionFactoryImpl>(factory, "multi-tenancy").EvictCollection(roleName, id, tenantIdentifier);
        }
Пример #7
0
        internal string GetSelectFragment(string entitySuffix, string collectionSuffix, OuterJoinableAssociation next)
        {
            switch (SelectMode)
            {
            case SelectMode.Undefined:
            case SelectMode.Fetch:
#pragma warning disable 618
                return(Joinable.SelectFragment(
                           next?.Joinable,
                           next?.RHSAlias,
                           RHSAlias,
                           entitySuffix,
                           collectionSuffix,
                           ShouldFetchCollectionPersister()));

#pragma warning restore 618

            case SelectMode.FetchLazyProperties:
#pragma warning disable 618
                return(ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(Joinable, "fetch lazy properties")
                       .SelectFragment(
                           next?.Joinable,
                           next?.RHSAlias,
                           RHSAlias,
                           entitySuffix,
                           collectionSuffix,
                           ShouldFetchCollectionPersister(),
                           true));

#pragma warning restore 618

            case SelectMode.FetchLazyPropertyGroup:
                return(ReflectHelper.CastOrThrow <ISupportLazyPropsJoinable>(Joinable, "fetch lazy property")
                       .SelectFragment(
                           next?.Joinable,
                           next?.RHSAlias,
                           RHSAlias,
                           collectionSuffix,
                           ShouldFetchCollectionPersister(),
                           new EntityLoadInfo(entitySuffix)
                {
                    LazyProperties = EntityFetchLazyProperties,
                    IncludeLazyProps = SelectMode == SelectMode.FetchLazyProperties,
                }));

            case SelectMode.ChildFetch:
                return(ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(Joinable, "child fetch select mode")
                       .IdentifierSelectFragment(RHSAlias, entitySuffix));

            case SelectMode.JoinOnly:
                return(string.Empty);

            default:
                throw new ArgumentOutOfRangeException(nameof(SelectMode), $"{SelectMode} is unexpected.");
            }
        }
Пример #8
0
        /// <summary>
        /// Evict an entry from the process-level cache.  This method occurs outside
        /// of any transaction; it performs an immediate "hard" remove, so does not respect
        /// any transaction isolation semantics of the usage strategy.  Use with care.
        /// </summary>
        /// <param name="factory">The session factory.</param>
        /// <param name="roleName">Collection role name.</param>
        /// <param name="id">Collection id</param>
        /// <param name="tenantIdentifier">Tenant identifier</param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        public static async Task EvictCollectionAsync(this ISessionFactory factory, string roleName, object id, string tenantIdentifier, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (tenantIdentifier == null)
            {
                await(factory.EvictCollectionAsync(roleName, id, cancellationToken)).ConfigureAwait(false);
            }

            await(ReflectHelper.CastOrThrow <SessionFactoryImpl>(factory, "multi-tenancy").EvictCollectionAsync(roleName, id, tenantIdentifier, cancellationToken)).ConfigureAwait(false);
        }
        private static void CallColumnsAndFormulas(
            object mapper,
            Action <IColumnOrFormulaMapper>[] columnOrFormulaMapper)
        {
            var colsOrForMapper = ReflectHelper.CastOrThrow <IColumnsAndFormulasMapper>(
                mapper,
                nameof(IColumnsAndFormulasMapper.ColumnsAndFormulas));

            colsOrForMapper.ColumnsAndFormulas(columnOrFormulaMapper);
        }
Пример #10
0
        //6.0 TODO: Merge into IBasePlainPropertyContainerMapper<> interface
        /// <summary>
        /// Maps a generic <c>IDictionary&lt;string, object&gt;</c> property as a dynamic component.
        /// </summary>
        /// <param name="mapper">The mapper.</param>
        /// <param name="property">The property to map.</param>
        /// <param name="dynamicComponentTemplate">The template for the component. It should either be a (usually
        /// anonymous) type having the same properties than the component, or an
        /// <c>IDictionary&lt;string, System.Type&gt;</c> of property names with their type.</param>
        /// <param name="mapping">The mapping of the component.</param>
        /// <typeparam name="TContainer">The type of the mapped class.</typeparam>
        /// <typeparam name="TComponent">The type of the template.</typeparam>
        public static void Component <TContainer, TComponent>(
            this IBasePlainPropertyContainerMapper <TContainer> mapper,
            Expression <Func <TContainer, IDictionary <string, object> > > property,
            TComponent dynamicComponentTemplate,
            Action <IDynamicComponentMapper <TComponent> > mapping) where TComponent : class
        {
            var customizer = ReflectHelper.CastOrThrow <PropertyContainerCustomizer <TContainer> >(
                mapper, "mapping a generic <string, object> dictionary as a dynamic component");

            customizer.Component(property, dynamicComponentTemplate, mapping);
        }
Пример #11
0
 internal static Task <DbConnection> GetConnectionAsync(this IConnectionProvider connectionProvider, string connectionString, CancellationToken cancellationToken)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <DbConnection>(cancellationToken));
     }
     try
     {
         return(ReflectHelper.CastOrThrow <ConnectionProvider>(connectionProvider, "open connection by connectionString").GetConnectionAsync(connectionString, cancellationToken));
     }
     catch (Exception ex)
     {
         return(Task.FromException <DbConnection>(ex));
     }
 }
Пример #12
0
 /// <summary>
 /// Return the persistent instance of the given entity class with the given identifier, or null
 /// if there is no such persistent instance. (If the instance, or a proxy for the instance, is
 /// already associated with the session, return that instance or proxy.)
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="entityName">The entity name.</param>
 /// <param name="id">The entity identifier.</param>
 /// <param name="lockMode">The lock mode to use for getting the entity.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
 /// <returns>A persistent instance, or <see langword="null" />.</returns>
 public static Task <object> GetAsync(this ISession session, string entityName, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <object>(cancellationToken));
     }
     try
     {
         return
             (ReflectHelper
              .CastOrThrow <SessionImpl>(session, "Get with entityName and lockMode")
              .GetAsync(entityName, id, lockMode, cancellationToken));
     }
     catch (Exception ex)
     {
         return(Task.FromException <object>(ex));
     }
 }
 /// <summary>
 /// Attempt to retrieve multiple objects from the Cache
 /// </summary>
 /// <param name="cache">The cache concurrency strategy.</param>
 /// <param name="keys">The keys (id) of the objects to get out of the Cache.</param>
 /// <param name="timestamp">A timestamp prior to the transaction start time</param>
 /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
 /// <returns>An array of cached objects or <see langword="null" /></returns>
 /// <exception cref="CacheException"></exception>
 public static Task <object[]> GetManyAsync(this ICacheConcurrencyStrategy cache, CacheKey[] keys, long timestamp, CancellationToken cancellationToken)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <object[]>(cancellationToken));
     }
     try
     {
         // PreferMultipleGet yields false if !IBatchableCacheConcurrencyStrategy, no GetMany call should be done
         // in such case.
         return(ReflectHelper
                .CastOrThrow <IBatchableCacheConcurrencyStrategy>(cache, "batching")
                .GetManyAsync(keys, timestamp, cancellationToken));
     }
     catch (System.Exception ex)
     {
         return(Task.FromException <object[]>(ex));
     }
 }
Пример #14
0
        public override string SelectFragment(IJoinable rhs, string rhsAlias, string lhsAlias, string entitySuffix, string collectionSuffix, bool includeCollectionColumns, bool fetchLazyProperties)
        {
            var buf = new StringBuilder();

            if (includeCollectionColumns)
            {
                buf.Append(SelectFragment(lhsAlias, collectionSuffix)).Append(StringHelper.CommaSpace);
            }

            if (fetchLazyProperties)
            {
                var selectMode = ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(ElementPersister, "fetch lazy properties");
                if (selectMode != null)
                {
                    return(buf.Append(selectMode.SelectFragment(null, null, lhsAlias, entitySuffix, null, false, fetchLazyProperties)).ToString());
                }
            }

            var ojl = (IOuterJoinLoadable)ElementPersister;

            return(buf.Append(ojl.SelectFragment(lhsAlias, entitySuffix)).ToString());            //use suffix for the entity columns
        }
Пример #15
0
        protected static string GetSelectFragment(OuterJoinableAssociation join, string entitySuffix, string collectionSuffix, OuterJoinableAssociation next = null)
        {
            switch (join.SelectMode)
            {
            case SelectMode.Undefined:
            case SelectMode.Fetch:
#pragma warning disable 618
                return(join.Joinable.SelectFragment(
                           next?.Joinable,
                           next?.RHSAlias,
                           join.RHSAlias,
                           entitySuffix,
                           collectionSuffix,
                           join.ShouldFetchCollectionPersister()));

#pragma warning restore 618

            case SelectMode.FetchLazyProperties:
                return(ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(join.Joinable, "fetch lazy propertie")
                       .SelectFragment(
                           next?.Joinable,
                           next?.RHSAlias,
                           join.RHSAlias,
                           entitySuffix,
                           collectionSuffix,
                           join.ShouldFetchCollectionPersister(),
                           true));

            case SelectMode.ChildFetch:
                return(ReflectHelper.CastOrThrow <ISupportSelectModeJoinable>(join.Joinable, "child fetch select mode").IdentifierSelectFragment(join.RHSAlias, entitySuffix));

            case SelectMode.JoinOnly:
                return(string.Empty);

            default:
                throw new ArgumentOutOfRangeException(nameof(join.SelectMode), $"{join.SelectMode} is unexpected.");
            }
        }
Пример #16
0
        /// <summary>
        /// Adds an entity type for auto-flush synchronization and second level cache invalidation.
        /// </summary>
        /// <param name="sqlQuery">The query.</param>
        /// <param name="entityType">The entity type.</param>
        /// <returns>The query.</returns>
        public static ISQLQuery AddSynchronizedEntityClass(this ISQLQuery sqlQuery, System.Type entityType)
        {
            var ssq = ReflectHelper.CastOrThrow <ISynchronizableSQLQuery>(sqlQuery, "synchronizable query");

            return(ssq.AddSynchronizedEntityClass(entityType));
        }
 private static T CastOrThrow <T>(object obj) where T : class
 {
     return(ReflectHelper.CastOrThrow <T>(obj, "SelectMode"));
 }
Пример #18
0
 /// <summary>
 /// Creates a <see cref="IQueryBatch"/> for the session. Batch extension methods are available in the
 /// <c>NHibernate.Multi</c> namespace.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <returns>A query batch.</returns>
 public static IQueryBatch CreateQueryBatch(this ISession session)
 {
     return(ReflectHelper.CastOrThrow <AbstractSessionImpl>(session, "query batch").CreateQueryBatch());
 }
Пример #19
0
        /// <summary>
        /// Returns the synchronized query spaces added to the query.
        /// </summary>
        /// <param name="sqlQuery">The query.</param>
        /// <returns>The synchronized query spaces.</returns>
        public static IReadOnlyCollection <string> GetSynchronizedQuerySpaces(this ISQLQuery sqlQuery)
        {
            var ssq = ReflectHelper.CastOrThrow <ISynchronizableSQLQuery>(sqlQuery, "synchronizable query");

            return(ssq.GetSynchronizedQuerySpaces());
        }
Пример #20
0
        /// <summary>
        /// Maps many formulas.
        /// </summary>
        /// <param name="mapper">The mapper.</param>
        /// <param name="formulas">The formulas to map.</param>
        public static void Formulas(this IOneToOneMapper mapper, params string[] formulas)
        {
            var o2oMapper = ReflectHelper.CastOrThrow <OneToOneMapper>(mapper, "Setting many formula");

            o2oMapper.Formulas(formulas);
        }
Пример #21
0
        public static void Fetch(this IOneToOneMapper mapper, FetchKind fetchMode)
        {
            var o2oMapper = ReflectHelper.CastOrThrow <OneToOneMapper>(mapper, "Setting fetch");

            o2oMapper.Fetch(fetchMode);
        }
Пример #22
0
 //6.0 TODO: Expose as ConnectionString property
 public static string GetConnectionString(this IConnectionProvider connectionProvider)
 {
     return(ReflectHelper.CastOrThrow <ConnectionProvider>(connectionProvider, "retrieve connectionString").ConnectionString);
 }
Пример #23
0
 //6.0 TODO: Expose as ISessionImplementor.FutureBatch and replace method usages with property
 internal static IQueryBatch GetFutureBatch(this ISessionImplementor session)
 {
     return(ReflectHelper.CastOrThrow <AbstractSessionImpl>(session, "future batch").FutureBatch);
 }
Пример #24
0
        /// <summary>
        /// Adds an entity name for auto-flush synchronization and second level cache invalidation.
        /// </summary>
        /// <param name="sqlQuery">The query.</param>
        /// <param name="entityName">The entity name.</param>
        /// <returns>The query.</returns>
        public static ISQLQuery AddSynchronizedEntityName(this ISQLQuery sqlQuery, string entityName)
        {
            var ssq = ReflectHelper.CastOrThrow <ISynchronizableSQLQuery>(sqlQuery, "synchronizable query");

            return(ssq.AddSynchronizedEntityName(entityName));
        }
 public static void QueryCacheFactory <TFactory>(this ICacheConfigurationProperties config) where TFactory : IQueryCacheFactory
 {
     ReflectHelper
     .CastOrThrow <CacheConfigurationProperties>(config, "Setting the query cache factory with Loquacious")
     .QueryCacheFactory <TFactory>();
 }
Пример #26
0
 public static void SqlDeleteAll(this ICollectionSqlsMapper mapper, string sql, SqlCheck sqlCheck)
 {
     ReflectHelper
     .CastOrThrow <ICollectionSqlsWithCheckMapper>(mapper, "SqlDeleteAll with sqlCheck")
     .SqlDeleteAll(sql, sqlCheck);
 }
 //TODO 6.0: Merge into IStatelessSessionBuilder
 /// <summary>
 /// Associates stateless session with given tenantConfig when multi-tenancy is enabled.
 /// See <seealso cref="NHibernate.Cfg.Environment.MultiTenancy"/>
 /// </summary>
 public static IStatelessSessionBuilder Tenant(this IStatelessSessionBuilder builder, TenantConfiguration tenantConfig)
 {
     ReflectHelper.CastOrThrow <ISessionCreationOptionsWithMultiTenancy>(builder, "multi tenancy").TenantConfiguration = tenantConfig;
     return(builder);
 }
Пример #28
0
 /// <summary>
 /// Given a query alias and an identifying suffix, render the property select fragment.
 /// </summary>
 //6.0 TODO: Merge into IQueryable
 public static string PropertySelectFragment(this IQueryable query, string alias, string suffix, ICollection <string> fetchProperties)
 {
     return(ReflectHelper.CastOrThrow <AbstractEntityPersister>(query, "individual lazy property fetches")
            .PropertySelectFragment(alias, suffix, fetchProperties));
 }
Пример #29
0
 internal static DbConnection GetConnection(this IConnectionProvider connectionProvider, string connectionString)
 {
     return(ReflectHelper.CastOrThrow <ConnectionProvider>(connectionProvider, "open connection by connectionString").GetConnection(connectionString));
 }
Пример #30
0
 //6.0 TODO: Merge to IUnionSubclassAttributesMapper
 public static void Extends(this IUnionSubclassAttributesMapper mapper, string entityOrClassName)
 {
     ReflectHelper.CastOrThrow <UnionSubclassMapper>(mapper, "Extends(entityOrClassName)").Extends(entityOrClassName);
 }