Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity">an actual entity object, not a proxy!</param>
        /// <param name="entityMode"></param>
        /// <returns></returns>
        public string ToString(object entity, EntityMode entityMode)
        {
            IClassMetadata cm = _factory.GetClassMetadata(entity.GetType());

            if (cm == null)
            {
                return(entity.GetType().FullName);
            }

            IDictionary <string, string> result = new Dictionary <string, string>();

            if (cm.HasIdentifierProperty)
            {
                result[cm.IdentifierPropertyName] =
                    cm.IdentifierType.ToLoggableString(cm.GetIdentifier(entity, entityMode), _factory);
            }

            IType[]  types  = cm.PropertyTypes;
            string[] names  = cm.PropertyNames;
            object[] values = cm.GetPropertyValues(entity, entityMode);

            for (int i = 0; i < types.Length; i++)
            {
                result[names[i]] = types[i].ToLoggableString(values[i], _factory);
            }

            return(cm.EntityName + CollectionPrinter.ToString(result));
        }
Пример #2
0
 public override string ToString()
 {
     return("InitialScene:" + initialScene + "\nScenes: " + CollectionPrinter.PrintCollection(scenes) + "\nCutscenes: " + CollectionPrinter.PrintCollection(cutscenes) + "\nBooks: " +
            CollectionPrinter.PrintCollection(books) + "\nItems: " + CollectionPrinter.PrintCollection(items) + "\nAtrezzo: " + CollectionPrinter.PrintCollection(atrezzo) + "\n Player:" + player + "\nCharacters: " +
            CollectionPrinter.PrintCollection(characters) + "\nConversations:" + CollectionPrinter.PrintCollection(conversations) + "\nTimers: " + CollectionPrinter.PrintCollection(timers) + "\nFlags: " + CollectionPrinter.PrintCollection(flags) + "\nVars " +
            CollectionPrinter.PrintCollection(vars) + "\nGlobalStates: " + CollectionPrinter.PrintCollection(globalStates) + "\nMacros: " + CollectionPrinter.PrintCollection(macros));
 }
Пример #3
0
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder()
                                .Append("sql: ")
                                .Append(sqlQueryString);

            Printer print = new Printer(factory);

            if (values != null)
            {
                buf
                .Append("; parameters: ")
                .Append(print.ToString(types, values));
            }
            if (namedParameters != null)
            {
                buf
                .Append("; named parameters: ")
                .Append(print.ToString(namedParameters));
            }
            if (filters != null)
            {
                buf.Append("; filters: ").Append(CollectionPrinter.ToString(filters));
            }
            if (firstRow != RowSelection.NoValue)
            {
                buf.Append("; first row: ").Append(firstRow);
            }
            if (maxRows != RowSelection.NoValue)
            {
                buf.Append("; max rows: ").Append(maxRows);
            }

            if (multiQueriesFirstRows != null)
            {
                buf.Append("; multi queries - first rows: ");
                for (int i = 0; i < multiQueriesFirstRows.Length; i++)
                {
                    buf.Append("#").Append(i)
                    .Append("=")
                    .Append(multiQueriesFirstRows[i]);
                }
                buf.Append("; ");
            }

            if (multiQueriesMaxRows != null)
            {
                buf.Append("; multi queries - max rows: ");
                for (int i = 0; i < multiQueriesMaxRows.Length; i++)
                {
                    buf.Append("#").Append(i)
                    .Append("=")
                    .Append(multiQueriesMaxRows[i]);
                }
                buf.Append("; ");
            }


            return(buf.ToString());
        }
Пример #4
0
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder()
                                .Append("sql: ")
                                .Append(sqlQueryString);

            if (values != null)
            {
                buf.Append("; parameters: ");
                for (int i = 0; i < values.Length; i++)
                {
                    buf.Append(values[i])
                    .Append(", ");
                }
            }
            if (namedParameters != null)
            {
                buf.Append("; named parameters: ")
                .Append(CollectionPrinter.ToString(namedParameters));
            }
            if (firstRow != RowSelection.NoValue)
            {
                buf.Append("; first row: ").Append(firstRow);
            }
            if (maxRows != RowSelection.NoValue)
            {
                buf.Append("; max rows: ").Append(maxRows);
            }

            return(buf.ToString());
        }
Пример #5
0
 internal string ToString(IEnumerable <KeyValuePair <string, TypedValue> > namedTypedValues)
 {
     return(CollectionPrinter.ToString(
                namedTypedValues.Select(
                    ntv => new KeyValuePair <string, string>(
                        ntv.Key,
                        ntv.Value.Type.ToLoggableString(ntv.Value.Value, _factory)))));
 }
Пример #6
0
        public string ToString(IDictionary <string, TypedValue> namedTypedValues)
        {
            IDictionary <string, string> result = new Dictionary <string, string>(namedTypedValues.Count);

            foreach (KeyValuePair <string, TypedValue> me in namedTypedValues)
            {
                TypedValue tv = me.Value;
                result[me.Key] = tv.Type.ToLoggableString(tv.Value, _factory);
            }

            return(CollectionPrinter.ToString(result));
        }
Пример #7
0
        public string ToString(IDictionary namedTypedValues)
        {
            IDictionary result = new Hashtable(namedTypedValues.Count);

            foreach (DictionaryEntry me in namedTypedValues)
            {
                TypedValue tv = ( TypedValue )me.Value;
                result[me.Key] = tv.Type.ToString(tv.Value, _factory);
            }

            return(CollectionPrinter.ToString(result));
        }
Пример #8
0
        public string ToString(IType[] types, object[] values)
        {
            List <string> list = new List <string>(types.Length);

            for (int i = 0; i < types.Length; i++)
            {
                if (types[i] != null)
                {
                    list.Add(types[i].ToLoggableString(values[i], _factory));
                }
            }
            return(CollectionPrinter.ToString(list));
        }
Пример #9
0
        protected internal virtual string RenderLoggableString(object value, ISessionFactoryImplementor factory)
        {
            IList       list     = new ArrayList();
            IType       elemType = GetElementType(factory);
            IEnumerable iter     = GetElementsIterator(value);

            foreach (object o in iter)
            {
                list.Add(elemType.ToLoggableString(o, factory));
            }

            return(CollectionPrinter.ToString(list));
        }
Пример #10
0
        /// <summary>
        /// Perform parameters validation. Flatten them if needed. Used prior to executing the encapsulated query.
        /// </summary>
        /// <param name="reserveFirstParameter">
        /// If true, the first positional parameter will not be verified since
        /// its needed for e.g. callable statements returning an out parameter.
        /// </param>
        protected internal virtual void VerifyParameters(bool reserveFirstParameter)
        {
            if (parameterMetadata.NamedParameterNames.Count != namedParameters.Count + namedParameterLists.Count)
            {
                var missingParams = new HashSet <string>(parameterMetadata.NamedParameterNames);
                missingParams.ExceptWith(namedParameterLists.Keys);
                missingParams.ExceptWith(namedParameters.Keys);
                throw new QueryException("Not all named parameters have been set: " + CollectionPrinter.ToString(missingParams), QueryString);
            }

            var positionalValueSpan = 0;
            // Values and Types may be overriden to yield refined parameters, check them
            // instead of the fields.
            var values = Values;
            var types  = Types;

            for (var i = 0; i < values.Count; i++)
            {
                var type = types[i];
                if (values[i] == UNSET_PARAMETER || type == UNSET_TYPE)
                {
                    if (reserveFirstParameter && i == 0)
                    {
                        continue;
                    }
                    else
                    {
                        throw new QueryException("Unset positional parameter at position: " + i, QueryString);
                    }
                }
                positionalValueSpan++;
            }

            if (parameterMetadata.OrdinalParameterCount != positionalValueSpan)
            {
                if (reserveFirstParameter && parameterMetadata.OrdinalParameterCount - 1 != positionalValueSpan)
                {
                    throw new QueryException(
                              "Expected positional parameter count: " + (parameterMetadata.OrdinalParameterCount - 1) + ", actual parameters: "
                              + CollectionPrinter.ToString(values), QueryString);
                }
                else if (!reserveFirstParameter)
                {
                    throw new QueryException(
                              "Expected positional parameter count: " + parameterMetadata.OrdinalParameterCount + ", actual parameters: "
                              + CollectionPrinter.ToString(values), QueryString);
                }
            }
        }
Пример #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public override string ToLoggableString(object value, ISessionFactoryImplementor factory)
        {
            if (value == null)
            {
                return("null");
            }
            IDictionary <string, string> result = new Dictionary <string, string>();

            object[] values = GetPropertyValues(value);
            for (int i = 0; i < propertyTypes.Length; i++)
            {
                result[propertyNames[i]] = propertyTypes[i].ToLoggableString(values[i], factory);
            }
            return(StringHelper.Unqualify(Name) + CollectionPrinter.ToString(result));
        }
Пример #12
0
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder()
                                .Append("sql: ")
                                .Append(sqlQueryString);


            if (namedParameters != null)
            {
                buf
                .Append("; named parameters: ")
                .Append(CollectionPrinter.ToString(namedParameters));
            }

            return(buf.ToString());
        }
Пример #13
0
        public override string ToLoggableString(object value, ISessionFactoryImplementor factory)
        {
            if (value == null)
            {
                return("null");
            }
            Array array    = (Array)value;
            int   length   = array.Length;
            IList list     = new ArrayList(length);
            IType elemType = GetElementType(factory);

            for (int i = 0; i < length; i++)
            {
                list.Add(elemType.ToLoggableString(array.GetValue(i), factory));
            }
            return(CollectionPrinter.ToString(list));
        }
Пример #14
0
        /// <summary>
        /// Perform parameter validation.  Used prior to executing the encapsulated query.
        /// </summary>
        /// <param name="reserveFirstParameter">
        /// if true, the first ? will not be verified since
        /// its needed for e.g. callable statements returning a out parameter
        /// </param>
        protected internal virtual void VerifyParameters(bool reserveFirstParameter)
        {
            if (parameterMetadata.NamedParameterNames.Count != namedParameters.Count + namedParameterLists.Count)
            {
                var missingParams = new HashSet <string>(parameterMetadata.NamedParameterNames);
                missingParams.ExceptWith(namedParameterLists.Keys);
                missingParams.ExceptWith(namedParameters.Keys);
                throw new QueryException("Not all named parameters have been set: " + CollectionPrinter.ToString(missingParams), QueryString);
            }

            int positionalValueSpan = 0;

            for (int i = 0; i < values.Count; i++)
            {
                object obj = types[i];
                if (values[i] == UNSET_PARAMETER || obj == UNSET_TYPE)
                {
                    if (reserveFirstParameter && i == 0)
                    {
                        continue;
                    }
                    else
                    {
                        throw new QueryException("Unset positional parameter at position: " + i, QueryString);
                    }
                }
                positionalValueSpan++;
            }

            if (parameterMetadata.OrdinalParameterCount != positionalValueSpan)
            {
                if (reserveFirstParameter && parameterMetadata.OrdinalParameterCount - 1 != positionalValueSpan)
                {
                    throw new QueryException(
                              "Expected positional parameter count: " + (parameterMetadata.OrdinalParameterCount - 1) + ", actual parameters: "
                              + CollectionPrinter.ToString(values), QueryString);
                }
                else if (!reserveFirstParameter)
                {
                    throw new QueryException(
                              "Expected positional parameter count: " + parameterMetadata.OrdinalParameterCount + ", actual parameters: "
                              + CollectionPrinter.ToString(values), QueryString);
                }
            }
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public override string ToLoggableString(object value, ISessionFactoryImplementor factory)
        {
            if (value == null)
            {
                return("null");
            }
            IDictionary <string, string> result = new Dictionary <string, string>();
            EntityMode?entityMode = tuplizerMapping.GuessEntityMode(value);

            if (!entityMode.HasValue)
            {
                throw new InvalidCastException(value.GetType().FullName);
            }
            object[] values = GetPropertyValues(value, entityMode.Value);
            for (int i = 0; i < propertyTypes.Length; i++)
            {
                result[propertyNames[i]] = propertyTypes[i].ToLoggableString(values[i], factory);
            }
            return(StringHelper.Unqualify(Name) + CollectionPrinter.ToString(result));
        }
Пример #16
0
        public override string ToString(object value, ISessionFactoryImplementor factory)
        {
            if (value == null)
            {
                return("null");
            }

            IType elemType = GetElementType(factory);

            if (NHibernateUtil.IsInitialized(value))
            {
                IList       list     = new ArrayList();
                ICollection elements = GetElementsCollection(value);
                foreach (object element in elements)
                {
                    list.Add(elemType.ToString(element, factory));
                }
                return(CollectionPrinter.ToString(list));
            }
            else
            {
                return("uninitialized");
            }
        }
Пример #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity">an actual entity object, not a proxy!</param>
        /// <returns></returns>
        public string ToString(object entity)
        {
            IClassMetadata cm = _factory.GetClassMetadata(entity.GetType());

            if (cm == null)
            {
                return(entity.GetType().FullName);
            }

            IDictionary <string, string> result = new Dictionary <string, string>();

            if (cm.HasIdentifierProperty)
            {
                result[cm.IdentifierPropertyName] =
                    cm.IdentifierType.ToLoggableString(cm.GetIdentifier(entity), _factory);
            }

            IType[]  types  = cm.PropertyTypes;
            string[] names  = cm.PropertyNames;
            object[] values = cm.GetPropertyValues(entity);

            for (int i = 0; i < types.Length; i++)
            {
                var value = values[i];
                if (Equals(LazyPropertyInitializer.UnfetchedProperty, value) || Equals(BackrefPropertyAccessor.Unknown, value))
                {
                    result[names[i]] = value.ToString();
                }
                else
                {
                    result[names[i]] = types[i].ToLoggableString(value, _factory);
                }
            }

            return(cm.EntityName + CollectionPrinter.ToString(result));
        }
Пример #18
0
 public override string ToString()
 {
     return(string.Format("FilterKey[{0}{1}]", _filterName, CollectionPrinter.ToString(_filterParameters)));
 }
Пример #19
0
 public override string ToString(object value, ISessionFactoryImplementor factory)
 {
     return(value == null ? "null" : CollectionPrinter.ToString(( IDictionary )value));
 }
Пример #20
0
 public override string ToString()
 {
     return(string.Format("[{0}={1}]", name, CollectionPrinter.ToString(values)));
 }
Пример #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="settings"></param>
        public SessionFactoryImpl(Configuration cfg, Settings settings)
        {
            log.Info("building session factory");

            this.properties  = cfg.Properties;
            this.interceptor = cfg.Interceptor;
            this.settings    = settings;

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

            // Persisters:

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

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                IClassPersister cp = PersisterFactory.CreateClassPersister(model, this);
                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)
            {
                collectionPersisters[map.Role] = PersisterFactory
                                                 .CreateCollectionPersister(map, this)
                                                 .CollectionMetadata;
            }
            collectionMetadata = new Hashtable(collectionPersisters);

            // after *all* persisters are registered
            foreach (IClassPersister persister in classPersisters.Values)
            {
                // TODO: H2.1 doesn't pass this to PostInstantiate
                persister.PostInstantiate(this);
            }

            //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.Count);
            foreach (DictionaryEntry de in cfg.NamedSQLQueries)
            {
                NamedSQLQuery nsq = ( NamedSQLQuery )de.Value;
                namedSqlQueries[de.Key] = new InternalNamedSQLQuery(nsq.QueryString, nsq.ReturnAliases, nsq.ReturnClasses, nsq.SynchronizedTables);
            }

            imports = new Hashtable(cfg.Imports);

            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

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings.CacheProvider, properties);
                queryCache            = settings.QueryCacheFactory
                                        .GetQueryCache(null, settings.CacheProvider, updateTimestampsCache, properties);
                queryCaches = Hashtable.Synchronized(new Hashtable());
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }
        }
Пример #22
0
        protected void VerifyParameters()
        {
            if (actualNamedParameters.Count != namedParameters.Count + namedParameterLists.Count)
            {
                Set missingParams = new ListSet(actualNamedParameters);
                missingParams.RemoveAll(namedParameterLists.Keys);
                missingParams.RemoveAll(namedParameters.Keys);
                throw new QueryException("Not all named parameters have been set: " + CollectionPrinter.ToString(missingParams), QueryString);
            }

            if (positionalParameterCount != values.Count)
            {
                throw new QueryException(string.Format("Not all positional parameters have been set. Expected {0}, set {1}", positionalParameterCount, values.Count),
                                         QueryString);
            }

            for (int i = 0; i < values.Count; i++)
            {
                if (values[i] == UNSET_PARAMETER || types[i] == UNSET_TYPE)
                {
                    throw new QueryException(string.Format("Not all positional parameters have been set. Found unset parameter at position {0}", i),
                                             QueryString);
                }
            }
        }
Пример #23
0
        public Settings BuildSettings(IDictionary <string, string> properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                Dictionary <string, string> temp = new Dictionary <string, string>();

                foreach (KeyValuePair <string, string> de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (KeyValuePair <string, string> de in properties)
                {
                    temp[de.Key] = de.Value;
                }
                properties = temp;
            }
            catch (HibernateException he)
            {
                log.Warn("No dialect set - using GenericDialect: " + he.Message);
                dialect = new GenericDialect();
            }
            settings.Dialect = dialect;

            settings.LinqToHqlGeneratorsRegistry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties);

            #region SQL Exception converter

            ISQLExceptionConverter sqlExceptionConverter;
            try
            {
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildSQLExceptionConverter(dialect, properties);
            }
            catch (HibernateException)
            {
                log.Warn("Error building SQLExceptionConverter; using minimal converter");
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildMinimalSQLExceptionConverter();
            }
            settings.SqlExceptionConverter = sqlExceptionConverter;

            #endregion

            bool comments = PropertiesHelper.GetBoolean(Environment.UseSqlComments, properties);
            log.Info("Generate SQL with comments: " + EnabledDisabled(comments));
            settings.IsCommentsEnabled = comments;

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);
            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: " + maxFetchDepth);
            }

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = CreateTransactionFactory(properties);
            // TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.GetTransactionManagerLookup( properties );

            // Not ported: useGetGeneratedKeys, useScrollableResultSets

            bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false);
            log.Info("Optimize cache for minimal puts: " + useMinimalPuts);

            string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto");
            log.Info("Connection release mode: " + releaseModeName);
            ConnectionReleaseMode releaseMode;
            if ("auto".Equals(releaseModeName))
            {
                releaseMode = ConnectionReleaseMode.AfterTransaction;                 //transactionFactory.DefaultReleaseMode;
            }
            else
            {
                releaseMode = ConnectionReleaseModeParser.Convert(releaseModeName);
            }
            settings.ConnectionReleaseMode = releaseMode;

            string defaultSchema  = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);
            string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
            if (defaultSchema != null)
            {
                log.Info("Default schema: " + defaultSchema);
            }
            if (defaultCatalog != null)
            {
                log.Info("Default catalog: " + defaultCatalog);
            }
            settings.DefaultSchemaName  = defaultSchema;
            settings.DefaultCatalogName = defaultCatalog;

            int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1);
            log.Info("Default batch fetch size: " + batchFetchSize);
            settings.DefaultBatchFetchSize = batchFetchSize;

            //Statistics and logging:

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);
            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }
            bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties);

            bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties);
            log.Info("Statistics: " + EnabledDisabled(useStatistics));
            settings.IsStatisticsEnabled = useStatistics;

            bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties);
            log.Info("Deleted entity synthetic identifier rollback: " + EnabledDisabled(useIdentifierRollback));
            settings.IsIdentifierRollbackEnabled = useIdentifierRollback;

            // queries:

            settings.QueryTranslatorFactory = CreateQueryTranslatorFactory(properties);

            settings.LinqQueryProviderType = CreateLinqQueryProviderType(properties);

            IDictionary <string, string> querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions,
                                                                                            " ,=;:\n\t\r\f", properties);
            if (log.IsInfoEnabled)
            {
                log.Info("Query language substitutions: " + CollectionPrinter.ToString((IDictionary)querySubstitutions));
            }

            #region Hbm2DDL
            string autoSchemaExport = PropertiesHelper.GetString(Environment.Hbm2ddlAuto, properties, null);
            if (SchemaAutoAction.Update == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            else if (SchemaAutoAction.Create == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            else if (SchemaAutoAction.Recreate == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }
            else if (SchemaAutoAction.Validate == autoSchemaExport)
            {
                settings.IsAutoValidateSchema = true;
            }

            string autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, properties, "not-defined");
            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.None)
            {
                settings.IsKeywordsImportEnabled = false;
                settings.IsAutoQuoteEnabled      = false;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.Keywords)
            {
                settings.IsKeywordsImportEnabled = true;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = true;
            }
            else if (autoKeyWordsImport == "not-defined")
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = false;
            }

            #endregion

            bool useSecondLevelCache = PropertiesHelper.GetBoolean(Environment.UseSecondLevelCache, properties, true);
            bool useQueryCache       = PropertiesHelper.GetBoolean(Environment.UseQueryCache, properties);

            if (useSecondLevelCache || useQueryCache)
            {
                // The cache provider is needed when we either have second-level cache enabled
                // or query cache enabled.  Note that useSecondLevelCache is enabled by default
                settings.CacheProvider = CreateCacheProvider(properties);
            }
            else
            {
                settings.CacheProvider = new NoCacheProvider();
            }

            string cacheRegionPrefix = PropertiesHelper.GetString(Environment.CacheRegionPrefix, properties, null);
            if (string.IsNullOrEmpty(cacheRegionPrefix))
            {
                cacheRegionPrefix = null;
            }
            if (cacheRegionPrefix != null)
            {
                log.Info("Cache region prefix: " + cacheRegionPrefix);
            }


            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties,
                                                                               typeof(StandardQueryCacheFactory).FullName);
                log.Info("query cache factory: " + queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory =
                        (IQueryCacheFactory)
                        Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(queryCacheFactoryClassName));
                }
                catch (Exception cnfe)
                {
                    throw new HibernateException("could not instantiate IQueryCacheFactory: " + queryCacheFactoryClassName, cnfe);
                }
            }

            string sessionFactoryName = PropertiesHelper.GetString(Environment.SessionFactoryName, properties, null);

            //ADO.NET and connection settings:

            settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0);
            bool orderInserts = PropertiesHelper.GetBoolean(Environment.OrderInserts, properties, (settings.AdoBatchSize > 0));
            log.Info("Order SQL inserts for batching: " + EnabledDisabled(orderInserts));
            settings.IsOrderInsertsEnabled = orderInserts;

            bool orderUpdates = PropertiesHelper.GetBoolean(Environment.OrderUpdates, properties, false);
            log.Info("Order SQL updates for batching: " + EnabledDisabled(orderUpdates));
            settings.IsOrderUpdatesEnabled = orderUpdates;

            bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false);
            log.Debug("Wrap result sets: " + EnabledDisabled(wrapResultSets));
            settings.IsWrapResultSetsEnabled = wrapResultSets;

            bool batchVersionedData = PropertiesHelper.GetBoolean(Environment.BatchVersionedData, properties, false);
            log.Debug("Batch versioned data: " + EnabledDisabled(batchVersionedData));
            settings.IsBatchVersionedDataEnabled = batchVersionedData;

            settings.BatcherFactory = CreateBatcherFactory(properties, settings.AdoBatchSize, connectionProvider);

            string         isolationString = PropertiesHelper.GetString(Environment.Isolation, properties, String.Empty);
            IsolationLevel isolation       = IsolationLevel.Unspecified;
            if (isolationString.Length > 0)
            {
                try
                {
                    isolation = (IsolationLevel)Enum.Parse(typeof(IsolationLevel), isolationString);
                    log.Info("Using Isolation Level: " + isolation);
                }
                catch (ArgumentException ae)
                {
                    log.Error("error configuring IsolationLevel " + isolationString, ae);
                    throw new HibernateException(
                              "The isolation level of " + isolationString + " is not a valid IsolationLevel.  Please "
                              + "use one of the Member Names from the IsolationLevel.", ae);
                }
            }

            //NH-3619
            FlushMode defaultFlushMode = (FlushMode)Enum.Parse(typeof(FlushMode), PropertiesHelper.GetString(Environment.DefaultFlushMode, properties, FlushMode.Auto.ToString()), false);
            log.Info("Default flush mode: " + defaultFlushMode);
            settings.DefaultFlushMode = defaultFlushMode;

#pragma warning disable CS0618 // Type or member is obsolete
            var defaultEntityMode = PropertiesHelper.GetString(Environment.DefaultEntityMode, properties, null);
            if (!string.IsNullOrEmpty(defaultEntityMode))
            {
                log.Warn("Default entity-mode setting is deprecated.");
            }
#pragma warning restore CS0618 // Type or member is obsolete

            bool namedQueryChecking = PropertiesHelper.GetBoolean(Environment.QueryStartupChecking, properties, true);
            log.Info("Named query checking : " + EnabledDisabled(namedQueryChecking));
            settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking;

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            settings.SqlStatementLogger = new SqlStatementLogger(showSql, formatSql);

            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName        = sessionFactoryName;
            settings.MaximumFetchDepth         = maxFetchDepth;
            settings.IsQueryCacheEnabled       = useQueryCache;
            settings.IsSecondLevelCacheEnabled = useSecondLevelCache;
            settings.CacheRegionPrefix         = cacheRegionPrefix;
            settings.IsMinimalPutsEnabled      = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData

            settings.QueryModelRewriterFactory = CreateQueryModelRewriterFactory(properties);

            // NHibernate-specific:
            settings.IsolationLevel = isolation;

            return(settings);
        }
Пример #24
0
        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 HashSet <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 HashSet <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;
        }
Пример #25
0
        public static Settings BuildSettings(IDictionary properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect = null;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                IDictionary temp = new Hashtable();

                foreach (DictionaryEntry de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (DictionaryEntry de in properties)
                {
                    temp[de.Key] = de.Value;
                }
                properties = temp;
            }
            catch (HibernateException he)
            {
                log.Warn("No dialect set - using GenericDialect: " + he.Message);
                dialect = new GenericDialect();
            }

            // TODO: SQLExceptionConverter

            // TODO: should this be enabled?
//			int statementFetchSize = PropertiesHelper.GetInt32( Environment.StatementFetchSize, properties, -1 );
//			if( statementFetchSize != -1 )
//			{
//				log.Info( "JDBC result set fetch size: " + statementFetchSize );
//			}

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);

            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: " + maxFetchDepth);
            }

            //deprecated:
            bool useOuterJoin = PropertiesHelper.GetBoolean(Environment.UseOuterJoin, properties, true);

            log.Info("use outer join fetching: " + useOuterJoin);

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = new TransactionFactory();             // = TransactionFactoryFactory.BuildTransactionFactory(properties);
            // TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.GetTransactionManagerLookup( properties );

            // Not ported: useGetGeneratedKeys, useScrollableResultSets

            bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false);

            log.Info("Optimize cache for minimal puts: " + useMinimalPuts);

            string defaultSchema = properties[Environment.DefaultSchema] as string;

            if (defaultSchema != null)
            {
                log.Info("Default schema set to: " + defaultSchema);
            }

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);

            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }

            // queries:

            IDictionary querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions, " ,=;:\n\t\r\f", properties);

            if (log.IsInfoEnabled)
            {
                log.Info("Query language substitutions: " + CollectionPrinter.ToString(querySubstitutions));
            }

            string autoSchemaExport = properties[Environment.Hbm2ddlAuto] as string;

            if ("update" == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            if ("create" == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            if ("create-drop" == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }

            string cacheClassName = PropertiesHelper.GetString(Environment.CacheProvider, properties, "NHibernate.Cache.HashtableCacheProvider");

            log.Info("cache provider: " + cacheClassName);
            try
            {
                settings.CacheProvider = ( ICacheProvider )Activator.CreateInstance(ReflectHelper.ClassForName(cacheClassName));
            }
            catch (Exception e)
            {
                throw new HibernateException("could not instantiate CacheProvider: " + cacheClassName, e);
            }

            bool useQueryCache = PropertiesHelper.GetBoolean(Environment.UseQueryCache, properties);

            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties, "NHibernate.Cache.StandardQueryCacheFactory");
                log.Info("query cache factory: " + queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory = (IQueryCacheFactory)Activator.CreateInstance(
                        ReflectHelper.ClassForName(queryCacheFactoryClassName));
                }
                catch (Exception cnfe)
                {
                    throw new HibernateException("could not instantiate IQueryCacheFactory: " + queryCacheFactoryClassName, cnfe);
                }
            }

            string sessionFactoryName = ( string )properties[Environment.SessionFactoryName];

            // TODO: Environment.BatchVersionedData
            // TODO: wrapResultSets/DataReaders

            string         isolationString = PropertiesHelper.GetString(Environment.Isolation, properties, String.Empty);
            IsolationLevel isolation       = IsolationLevel.Unspecified;

            if (isolationString.Length > 0)
            {
                try
                {
                    isolation = ( IsolationLevel )Enum.Parse(typeof(IsolationLevel), isolationString);
                    log.Info("Using Isolation Level: " + isolation.ToString());
                }
                catch (ArgumentException ae)
                {
                    log.Error("error configuring IsolationLevel " + isolationString, ae);
                    throw new HibernateException(
                              "The isolation level of " + isolationString + " is not a valid IsolationLevel.  Please " +
                              "use one of the Member Names from the IsolationLevel.", ae);
                }
            }

            bool prepareSql = PropertiesHelper.GetBoolean(Environment.PrepareSql, properties, false);

            int cmdTimeout = PropertiesHelper.GetInt32(Environment.CommandTimeout, properties, 0);

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            // Not ported - settings.BatchSize = batchSize;
            settings.DefaultSchemaName  = defaultSchema;
            settings.IsShowSqlEnabled   = showSql;
            settings.Dialect            = dialect;
            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName      = sessionFactoryName;
            settings.IsOuterJoinFetchEnabled = useOuterJoin;
            settings.MaximumFetchDepth       = maxFetchDepth;
            settings.IsQueryCacheEnabled     = useQueryCache;
            settings.IsMinimalPutsEnabled    = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData
            // TODO: SQLExceptionConverter
            // TODO: WrapResultSetsEnabled

            // NHibernate-specific:
            settings.IsolationLevel = isolation;
            settings.PrepareSql     = prepareSql;
            settings.CommandTimeout = cmdTimeout;

            return(settings);
        }