public FilterHelper(IDictionary<string, string> filters, Dialect.Dialect dialect, SQLFunctionRegistry sqlFunctionRegistry)
		{
			int filterCount = filters.Count;
			filterNames = new string[filterCount];
			filterConditions = new string[filterCount];
			filterCount = 0;
			foreach (KeyValuePair<string, string> entry in filters)
			{
				filterNames[filterCount] = entry.Key;
				filterConditions[filterCount] =
					Template.RenderWhereStringTemplate(entry.Value, FilterImpl.MARKER, dialect, sqlFunctionRegistry);
				filterConditions[filterCount] =
					StringHelper.Replace(filterConditions[filterCount], ":", ":" + filterNames[filterCount] + ".");
				filterCount++;
			}
		}
		public static string RenderWhereStringTemplate(string sqlWhereString, string placeholder, Dialect.Dialect dialect,
		                                               SQLFunctionRegistry functionRegistry)
		{
			//TODO: make this a bit nicer
			string symbols = new StringBuilder()
				.Append("=><!+-*/()',|&`")
				.Append(ParserHelper.Whitespace)
				.Append(dialect.OpenQuote)
				.Append(dialect.CloseQuote)
				.ToString();
			StringTokenizer tokens = new StringTokenizer(sqlWhereString, symbols, true);

			StringBuilder result = new StringBuilder();
			bool quoted = false;
			bool quotedIdentifier = false;
			bool beforeTable = false;
			bool inFromClause = false;
			bool afterFromTable = false;

			IEnumerator tokensEnum = tokens.GetEnumerator();
			bool hasMore = tokensEnum.MoveNext();
			string nextToken = hasMore ? (string) tokensEnum.Current : null;
			while (hasMore)
			{
				string token = nextToken;
				string lcToken = token.ToLower(CultureInfo.InvariantCulture);
				hasMore = tokensEnum.MoveNext();
				nextToken = hasMore ? (string) tokensEnum.Current : null;

				bool isQuoteCharacter = false;

				if (!quotedIdentifier && "'".Equals(token))
				{
					quoted = !quoted;
					isQuoteCharacter = true;
				}

				if (!quoted)
				{
					bool isOpenQuote;
					if ("`".Equals(token))
					{
						isOpenQuote = !quotedIdentifier;
						token = lcToken = isOpenQuote ?
						                  dialect.OpenQuote.ToString() :
						                  dialect.CloseQuote.ToString();
						quotedIdentifier = isOpenQuote;
						isQuoteCharacter = true;
					}
					else if (!quotedIdentifier && (dialect.OpenQuote == token[0]))
					{
						isOpenQuote = true;
						quotedIdentifier = true;
						isQuoteCharacter = true;
					}
					else if (quotedIdentifier && (dialect.CloseQuote == token[0]))
					{
						quotedIdentifier = false;
						isQuoteCharacter = true;
						isOpenQuote = false;
					}
					else
					{
						isOpenQuote = false;
					}

					if (isOpenQuote)
					{
						result.Append(placeholder).Append('.');
					}
				}

				bool quotedOrWhitespace = quoted ||
				                          quotedIdentifier ||
				                          isQuoteCharacter ||
				                          char.IsWhiteSpace(token[0]);

				if (quotedOrWhitespace)
				{
					result.Append(token);
				}
				else if (beforeTable)
				{
					result.Append(token);
					beforeTable = false;
					afterFromTable = true;
				}
				else if (afterFromTable)
				{
					if (!"as".Equals(lcToken))
						afterFromTable = false;
					result.Append(token);
				}
				else if (IsNamedParameter(token))
				{
					result.Append(token);
				}
				else if (
					IsIdentifier(token, dialect) &&
					!IsFunctionOrKeyword(lcToken, nextToken, dialect, functionRegistry)
					)
				{
					result.Append(placeholder)
						.Append('.')
						.Append(token);
				}
				else
				{
					if (BeforeTableKeywords.Contains(lcToken))
					{
						beforeTable = true;
						inFromClause = true;
					}
					else if (inFromClause && ",".Equals(lcToken))
					{
						beforeTable = true;
					}
					result.Append(token);
				}

				if ( //Yuck:
					inFromClause &&
					Keywords.Contains(lcToken) && //"as" is not in Keywords
					!BeforeTableKeywords.Contains(lcToken)
					)
				{
					inFromClause = false;
				}
			}
			return result.ToString();
		}
		public static string RenderWhereStringTemplate(string sqlWhereString, Dialect.Dialect dialect,
		                                               SQLFunctionRegistry functionRegistry)
		{
			return RenderWhereStringTemplate(sqlWhereString, Placeholder, dialect, functionRegistry);
		}
		private static bool IsFunctionOrKeyword(string lcToken, string nextToken, Dialect.Dialect dialect,
		                                        SQLFunctionRegistry functionRegistry)
		{
			return "(".Equals(nextToken) ||
			       Keywords.Contains(lcToken) ||
			       functionRegistry.HasFunction(lcToken) ||
			       // TODO H3: dialect.Keywords.Contains(lcToken) ||
			       FunctionKeywords.Contains(lcToken);
		}
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
		{
			Init();
			log.Info("building session factory");

			properties = new Dictionary<string, string>(cfg.Properties);
			interceptor = cfg.Interceptor;
			this.settings = settings;
			sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
			eventListeners = listeners;
			filters = new Dictionary<string, FilterDefinition>(cfg.FilterDefinitions);
			if (log.IsDebugEnabled)
			{
				log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
			}

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
			}

			try
			{
				if (settings.IsKeywordsImportEnabled)
				{
					SchemaMetadataUpdater.Update(this);
				}
				if (settings.IsAutoQuoteEnabled)
				{
					SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
				}
			}
			catch (NotSupportedException)
			{
				// Ignore if the Dialect does not provide DataBaseSchema 
			}

			#region Caches
			settings.CacheProvider.Start(properties);
			#endregion

			#region Generators
			identifierGenerators = new Dictionary<string, IIdentifierGenerator>();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					IIdentifierGenerator generator =
						model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
						                                           settings.DefaultSchemaName, (RootClass) model);

					identifierGenerators[model.EntityName] = generator;
				}
			}
			#endregion

			#region Persisters

			Dictionary<string, ICacheConcurrencyStrategy> caches = new Dictionary<string, ICacheConcurrencyStrategy>();
			entityPersisters = new Dictionary<string, IEntityPersister>();
			implementorToEntityName = new Dictionary<System.Type, string>();

			Dictionary<string, IClassMetadata> classMeta = new Dictionary<string, IClassMetadata>();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				model.PrepareTemporaryTables(mapping, settings.Dialect);
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache;
				if (!caches.TryGetValue(cacheRegion, out cache))
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				entityPersisters[model.EntityName] = cp;
				classMeta[model.EntityName] = cp.ClassMetadata;

				if (model.HasPocoRepresentation)
				{
					implementorToEntityName[model.MappedClass] = model.EntityName;
				}
			}
			classMetadata = new UnmodifiableDictionary<string, IClassMetadata>(classMeta);

			Dictionary<string, ISet<string>> tmpEntityToCollectionRoleMap = new Dictionary<string, ISet<string>>();
			collectionPersisters = new Dictionary<string, ICollectionPersister>();
			foreach (Mapping.Collection model in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
				{
					allCacheRegions[cache.RegionName] = cache.Cache;
				}
				ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
				collectionPersisters[model.Role] = persister;
				IType indexType = persister.IndexType;
				if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
				{
					string entityName = ((IAssociationType) indexType).GetAssociatedEntityName(this);
					ISet<string> roles;
					if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
					{
						roles = new HashedSet<string>();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
				IType elementType = persister.ElementType;
				if (elementType.IsAssociationType && !elementType.IsAnyType)
				{
					string entityName = ((IAssociationType) elementType).GetAssociatedEntityName(this);
					ISet<string> roles;
					if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
					{
						roles = new HashedSet<string>();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
			}
			Dictionary<string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary<string, ICollectionMetadata>(collectionPersisters.Count);
			foreach (KeyValuePair<string, ICollectionPersister> collectionPersister in collectionPersisters)
			{
				tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
			}
			collectionMetadata = new UnmodifiableDictionary<string, ICollectionMetadata>(tmpcollectionMetadata);
			collectionRolesByEntityParticipant = new UnmodifiableDictionary<string, ISet<string>>(tmpEntityToCollectionRoleMap);
			#endregion

			#region Named Queries
			namedQueries = new Dictionary<string, NamedQueryDefinition>(cfg.NamedQueries);
			namedSqlQueries = new Dictionary<string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Dictionary<string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
			#endregion

			imports = new Dictionary<string, string>(cfg.Imports);

			#region after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in entityPersisters.Values)
			{
				persister.PostInstantiate();
			}
			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}
			#endregion

			#region Serialization info

			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("Could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			#endregion

			log.Debug("Instantiated session factory");

			#region Schema management
			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate(cfg).Execute(false, true);
			}
			if (settings.IsAutoValidateSchema)
			{
				 new SchemaValidator(cfg, settings).Validate();
			}
			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}
			#endregion

			#region Obtaining TransactionManager
			// not ported yet
			#endregion

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = new ThreadSafeDictionary<string, IQueryCache>(new Dictionary<string, IQueryCache>());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}

			#region Checking for named queries
			if (settings.IsNamedQueryStartupCheckingEnabled)
			{
				IDictionary<string, HibernateException> errors = CheckNamedQueries();
				if (errors.Count > 0)
				{
					StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
					foreach (KeyValuePair<string, HibernateException> pair in errors)
					{
						failingQueries.Append('{').Append(pair.Key).Append('}');
						log.Error("Error in named query: " + pair.Key, pair.Value);
					}
					throw new HibernateException(failingQueries.ToString());
				}
			}
			#endregion

			Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

			// EntityNotFoundDelegate
			IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
			if (enfd == null)
			{
				enfd = new DefaultEntityNotFoundDelegate();
			}
			entityNotFoundDelegate = enfd;
		}
Example #6
0
		public static string RenderOrderByStringTemplate(string sqlOrderByString, Dialect.Dialect dialect,
		                                                 SQLFunctionRegistry functionRegistry)
		{
			//TODO: make this a bit nicer
			string symbols = new StringBuilder()
				.Append("=><!+-*/()',|&`")
				.Append(ParserHelper.Whitespace)
				.Append(dialect.OpenQuote)
				.Append(dialect.CloseQuote)
				.ToString();
			StringTokenizer tokens = new StringTokenizer(sqlOrderByString, symbols, true);

			StringBuilder result = new StringBuilder();
			bool quoted = false;
			bool quotedIdentifier = false;

			IEnumerator<string> tokensEnum = tokens.GetEnumerator();
			bool hasMore = tokensEnum.MoveNext();
			string nextToken = hasMore ? tokensEnum.Current : null;
			while (hasMore)
			{
				string token = nextToken;
				string lcToken = token.ToLowerInvariant();
				hasMore = tokensEnum.MoveNext();
				nextToken = hasMore ? tokensEnum.Current : null;

				bool isQuoteCharacter = false;

				if (!quotedIdentifier && "'".Equals(token))
				{
					quoted = !quoted;
					isQuoteCharacter = true;
				}

				if (!quoted)
				{
					bool isOpenQuote;
					if ("`".Equals(token))
					{
						isOpenQuote = !quotedIdentifier;
						token = lcToken = isOpenQuote ?
						                  dialect.OpenQuote.ToString() :
						                  dialect.CloseQuote.ToString();
						quotedIdentifier = isOpenQuote;
						isQuoteCharacter = true;
					}
					else if (!quotedIdentifier && (dialect.OpenQuote == token[0]))
					{
						isOpenQuote = true;
						quotedIdentifier = true;
						isQuoteCharacter = true;
					}
					else if (quotedIdentifier && (dialect.CloseQuote == token[0]))
					{
						quotedIdentifier = false;
						isQuoteCharacter = true;
						isOpenQuote = false;
					}
					else
					{
						isOpenQuote = false;
					}

					if (isOpenQuote)
					{
						result.Append(Placeholder).Append('.');
					}
				}

				bool quotedOrWhitespace = quoted ||
				                          quotedIdentifier ||
				                          isQuoteCharacter ||
				                          char.IsWhiteSpace(token[0]);

				if (quotedOrWhitespace)
				{
					result.Append(token);
				}
				else if (
					IsIdentifier(token, dialect) &&
					!IsFunctionOrKeyword(lcToken, nextToken, dialect, functionRegistry)
					)
				{
					result.Append(Placeholder)
						.Append('.')
						.Append(token);
				}
				else
				{
					result.Append(token);
				}
			}
			return result.ToString();
		}
Example #7
0
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
		{
			Init();
			log.Info("building session factory");

			properties = cfg.Properties;
			interceptor = cfg.Interceptor;
			this.settings = settings;
			sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
			eventListeners = listeners;

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: "
				          + CollectionPrinter.ToString(properties));
			}

			settings.CacheProvider.Start(properties);

			// Generators:
			identifierGenerators = new Hashtable();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					IIdentifierGenerator generator =
						model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
						                                           settings.DefaultSchemaName, (RootClass) model);

					identifierGenerators[model.MappedClass] = generator;
				}
			}


			// Persisters:

			IDictionary caches = new Hashtable();
			classPersisters = new Hashtable();
			classPersistersByName = new Hashtable();
			IDictionary classMeta = new Hashtable();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache = (ICacheConcurrencyStrategy) caches[cacheRegion];
				if (cache == null)
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				classPersisters[model.MappedClass] = cp;

				// Adds the "Namespace.ClassName" (FullClassname) as a lookup to get to the Persiter.
				// Most of the internals of NHibernate use this method to get to the Persister since
				// Model.Name is used in so many places.  It would be nice to fix it up to be Model.TypeName
				// instead of just FullClassname
				classPersistersByName[model.EntityName] = cp;

				// Add in the AssemblyQualifiedName (includes version) as a lookup to get to the Persister.  
				// In HQL the Imports are used to get from the Classname to the Persister.  The
				// Imports provide the ability to jump from the Classname to the AssemblyQualifiedName.
				classPersistersByName[model.MappedClass.AssemblyQualifiedName] = cp;

				classMeta[model.MappedClass] = cp.ClassMetadata;
			}
			classMetadata = new Hashtable(classMeta);
			IDictionary tmpEntityToCollectionRoleMap= new Hashtable();
			collectionPersisters = new Hashtable();
			foreach (Mapping.Collection map in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(map.CacheConcurrencyStrategy, map.CacheRegionName, map.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
					allCacheRegions[cache.RegionName] = cache.Cache;

				collectionPersisters[map.Role] =
					PersisterFactory.CreateCollectionPersister(cfg, map, cache, this).CollectionMetadata;
				ICollectionPersister persister = collectionPersisters[map.Role] as ICollectionPersister;
				IType indexType = persister.IndexType;
				if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
				{
					string entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
					ISet roles = tmpEntityToCollectionRoleMap[entityName] as ISet;
					if (roles == null)
					{
						roles = new HashedSet();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
				IType elementType = persister.ElementType;
				if (elementType.IsAssociationType && !elementType.IsAnyType)
				{
					string entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
					ISet roles = tmpEntityToCollectionRoleMap[entityName] as ISet;
					if (roles == null)
					{
						roles = new HashedSet();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
			}
			collectionMetadata = new Hashtable(collectionPersisters);
			collectionRolesByEntityParticipant = new Hashtable(tmpEntityToCollectionRoleMap);
			//TODO:
			// For databinding:
			//templates = XMLDatabinder.GetOutputStyleSheetTemplates( properties );


			// serialization info
			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			// Named queries:
			// TODO: precompile and cache named queries

			namedQueries = new Dictionary<string, NamedQueryDefinition>(cfg.NamedQueries);
			namedSqlQueries = new Dictionary<string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Dictionary<string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
			filters = new Dictionary<string, FilterDefinition>(cfg.FilterDefinitions);

			imports = new Dictionary<string, string>(cfg.Imports);

			// after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in classPersisters.Values)
			{
				persister.PostInstantiate();
			}

			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}

			log.Debug("Instantiated session factory");

			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			/*
			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate( cfg ).Execute( false, true );
			}
			*/

			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}

			// Obtaining TransactionManager - not ported from H2.1

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory
					.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = Hashtable.Synchronized(new Hashtable());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}

			//checking for named queries
			if (settings.IsNamedQueryStartupCheckingEnabled)
			{
				IDictionary<string, HibernateException> errors = CheckNamedQueries();
				if (errors.Count > 0)
				{
					StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
					foreach (KeyValuePair<string, HibernateException> pair in errors)
					{
						failingQueries.Append('{').Append(pair.Key).Append('}');
						log.Error("Error in named query: " + pair.Key, pair.Value);
					}
					throw new HibernateException(failingQueries.ToString());
				}
			}

			Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

			// EntityNotFoundDelegate
			IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
			if (enfd == null)
			{
				enfd = new DefaultEntityNotFoundDelegate();
			}
			entityNotFoundDelegate = enfd;
		}
Example #8
0
		public string GetTemplate(Dialect.Dialect dialect, SQLFunctionRegistry functionRegistry)
		{
			return GetQuotedName(dialect);
		}
		public void SetUp()
		{
			dialect = new MsSql2000Dialect();
			functionRegistry = new SQLFunctionRegistry(dialect, new Dictionary<string, ISQLFunction>());
		}
 public void SetUp()
 {
     dialect = new SQLiteDialect();
     registry = new SQLFunctionRegistry(dialect, new Dictionary<string, ISQLFunction>());
 }
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings)
		{
			log.Info("building session factory");

			this.properties = cfg.Properties;
			this.interceptor = cfg.Interceptor;
			this.settings = settings;
			this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: "
				          + CollectionPrinter.ToString(properties));
			}

			settings.CacheProvider.Start(properties);

			// Generators:
			identifierGenerators = new Hashtable();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					// TODO H3:
					IIdentifierGenerator generator = model.Identifier.CreateIdentifierGenerator(
						settings.Dialect);
					//					IIdentifierGenerator generator = model.Identifier.CreateIdentifierGenerator(
					//						settings.Dialect,
					//						settings.DefaultCatalogName,
					//						settings.DefaultSchemaName,
					//						(RootClass) model
					//						);
					identifierGenerators[model.MappedClass] = generator;
				}
			}


			// Persisters:

			IDictionary caches = new Hashtable();
			classPersisters = new Hashtable();
			classPersistersByName = new Hashtable();
			IDictionary classMeta = new Hashtable();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache = (ICacheConcurrencyStrategy) caches[cacheRegion];
				if (cache == null)
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				classPersisters[model.MappedClass] = cp;

				// Adds the "Namespace.ClassName" (FullClassname) as a lookup to get to the Persiter.
				// Most of the internals of NHibernate use this method to get to the Persister since
				// Model.Name is used in so many places.  It would be nice to fix it up to be Model.TypeName
				// instead of just FullClassname
				classPersistersByName[model.Name] = cp;

				// Add in the AssemblyQualifiedName (includes version) as a lookup to get to the Persister.  
				// In HQL the Imports are used to get from the Classname to the Persister.  The
				// Imports provide the ability to jump from the Classname to the AssemblyQualifiedName.
				classPersistersByName[model.MappedClass.AssemblyQualifiedName] = cp;

				classMeta[model.MappedClass] = cp.ClassMetadata;
			}
			classMetadata = new Hashtable(classMeta);

			collectionPersisters = new Hashtable();
			foreach (Mapping.Collection map in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(map.CacheConcurrencyStrategy, map.CacheRegionName, map.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
					allCacheRegions[cache.RegionName] = cache.Cache;

				collectionPersisters[map.Role] = PersisterFactory
					.CreateCollectionPersister(map, cache, this)
					.CollectionMetadata;
			}
			collectionMetadata = new Hashtable(collectionPersisters);

			//TODO:
			// For databinding:
			//templates = XMLDatabinder.GetOutputStyleSheetTemplates( properties );


			// serialization info
			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			// Named queries:
			// TODO: precompile and cache named queries

			namedQueries = new Hashtable(cfg.NamedQueries);
			namedSqlQueries = new Hashtable(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Hashtable(cfg.SqlResultSetMappings);
			filters = new Hashtable(cfg.FilterDefinitions);

			imports = new Hashtable(cfg.Imports);

			// after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in classPersisters.Values)
			{
				persister.PostInstantiate();
			}

			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}

			log.Debug("Instantiated session factory");

			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			/*
			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate( cfg ).Execute( false, true );
			}
			*/

			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}

			// Obtaining TransactionManager - not ported from H2.1

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory
					.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = Hashtable.Synchronized(new Hashtable());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}
		}
Example #12
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="dialect"></param>
		/// <param name="functionRegistry"></param>
		/// <returns></returns>
		public string GetTemplate(Dialect.Dialect dialect, SQLFunctionRegistry functionRegistry)
		{
			return Template.RenderWhereStringTemplate(formula, dialect, functionRegistry);
		}