Пример #1
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);

            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:

            // TODO: Environment.BatchVersionedData
            settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0);
            bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false);
            log.Debug("Wrap result sets: " + EnabledDisabled(wrapResultSets));
            settings.IsWrapResultSetsEnabled = wrapResultSets;
            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);
                }
            }

            EntityMode defaultEntityMode =
                EntityModeHelper.Parse(PropertiesHelper.GetString(Environment.DefaultEntityMode, properties, "poco"));
            log.Info("Default entity-mode: " + defaultEntityMode);
            settings.DefaultEntityMode = defaultEntityMode;

            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

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

            return(settings);
        }
Пример #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="connectionBuilder"></param>
 public CassandraSession(IConnectionBuilder connectionBuilder)
     : this(ConnectionProviderFactory.Get(connectionBuilder), connectionBuilder.ReadConsistency, connectionBuilder.WriteConsistency)
 {
 }
Пример #3
0
        private async Task InitConnectionAndExecuteAsync(Action <string> scriptAction, bool execute, bool justDrop, DbConnection connection, TextWriter exportOutput, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            await(InitializeAsync(cancellationToken)).ConfigureAwait(false);
            TextWriter          fileOutput         = exportOutput;
            IConnectionProvider connectionProvider = null;

            try
            {
                if (fileOutput == null && outputFile != null)
                {
                    fileOutput = new StreamWriter(outputFile);
                }

                if (execute && connection == null)
                {
                    if (_requireTenantConnection)
                    {
                        throw new ArgumentException("When Database multi-tenancy is enabled you need to provide explicit connection. Please use overload with connection parameter.");
                    }

                    var props = new Dictionary <string, string>();
                    foreach (var de in dialect.DefaultProperties)
                    {
                        props[de.Key] = de.Value;
                    }

                    if (configProperties != null)
                    {
                        foreach (var de in configProperties)
                        {
                            props[de.Key] = de.Value;
                        }
                    }

                    connectionProvider = ConnectionProviderFactory.NewConnectionProvider(props);
                    connection         = await(connectionProvider.GetConnectionAsync(cancellationToken)).ConfigureAwait(false);
                }

                await(ExecuteAsync(scriptAction, execute, justDrop, connection, fileOutput, cancellationToken)).ConfigureAwait(false);
            }
            catch (OperationCanceledException) { throw; }
            catch (HibernateException)
            {
                // So that we don't wrap HibernateExceptions in HibernateExceptions
                throw;
            }
            catch (Exception e)
            {
                log.Error(e, e.Message);
                throw new HibernateException(e.Message, e);
            }
            finally
            {
                if (connectionProvider != null)
                {
                    if (connection != null)
                    {
                        connectionProvider.CloseConnection(connection);
                    }

                    connectionProvider.Dispose();
                }
            }
        }
Пример #4
0
        public void UpgradeSchema()
        {
            var export = new SchemaUpdate(Configuration);

            export.Execute(Debug, true);

            //nhibernate не проверяет типы данных и размерность, делаем еще проход для проверки типов данных
            using (var connectionProvider = ConnectionProviderFactory.NewConnectionProvider(Configuration.Properties))
                using (var connection = (DbConnection)connectionProvider.GetConnection()) {
                    var cmd            = connection.CreateCommand();
                    var defaultCatalog = PropertiesHelper.GetString(NHibernate.Cfg.Environment.DefaultCatalog, Configuration.Properties, null);
                    var defaultSchema  = PropertiesHelper.GetString(NHibernate.Cfg.Environment.DefaultSchema, Configuration.Properties, null);
                    var dialect        = Dialect.GetDialect(Configuration.Properties);
                    var tables         = Tables().Where(t => t.IsPhysicalTable && Configuration.IncludeAction(t.SchemaActions, SchemaAction.Update));
                    var meta           = new DatabaseMetadata(connection, dialect);
                    var mapping        = (IMapping)Configuration.GetType().GetField("mapping", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(Configuration);
                    var schema         = new DevartMySqlSchema(connection);
                    foreach (var table in tables)
                    {
                        var tableMeta = meta.GetTableMetadata(table.Name,
                                                              table.Schema ?? defaultSchema,
                                                              table.Catalog ?? defaultCatalog,
                                                              table.IsQuoted);
                        if (tableMeta == null)
                        {
                            continue;
                        }

                        var alters = new List <string>();
                        var root   = new StringBuilder("alter table ")
                                     .Append(table.GetQualifiedName(dialect, defaultCatalog, defaultSchema))
                                     .Append(" MODIFY ");
                        foreach (var column in table.ColumnIterator)
                        {
                            var columnInfo = tableMeta.GetColumnMetadata(column.Name);
                            if (columnInfo == null)
                            {
                                continue;
                            }

                            var diff = !CompareType(columnInfo, dialect, column, mapping);
                            if (diff)
                            {
                                var sql = new StringBuilder()
                                          .Append(root)
                                          .Append(column.GetQuotedName(dialect))
                                          .Append(" ")
                                          .Append(column.GetSqlType(dialect, mapping));
                                if (!string.IsNullOrEmpty(column.DefaultValue))
                                {
                                    sql.Append(" default ").Append(column.DefaultValue);

                                    if (column.IsNullable)
                                    {
                                        sql.Append(dialect.NullColumnString);
                                    }
                                    else
                                    {
                                        sql.Append(" not null");
                                    }
                                }

                                var useUniqueConstraint = column.Unique && dialect.SupportsUnique &&
                                                          (!column.IsNullable || dialect.SupportsNotNullUnique);
                                if (useUniqueConstraint)
                                {
                                    sql.Append(" unique");
                                }

                                if (column.HasCheckConstraint && dialect.SupportsColumnCheck)
                                {
                                    sql.Append(" check(").Append(column.CheckConstraint).Append(") ");
                                }

                                var columnComment = column.Comment;
                                if (columnComment != null)
                                {
                                    sql.Append(dialect.GetColumnComment(columnComment));
                                }
                                alters.Add(sql.ToString());
                            }
                        }

                        if (table.UniqueKeyIterator.Any())
                        {
                            var indexes = schema.GetIndexInfo(tableMeta.Catalog, null, tableMeta.Name).AsEnumerable()
                                          .Select(x => new DevartMySQLIndexMetadata(x))
                                          .Where(x => x.IsUnique)
                                          .ToArray();


                            foreach (var uniqueKey in table.UniqueKeyIterator)
                            {
                                if (!indexes.Any(x => x.Name.Match(uniqueKey.Name)))
                                {
                                    var sql = uniqueKey.SqlConstraintString(dialect, uniqueKey.Name, defaultCatalog, defaultSchema);
                                    alters.Add($"alter table {table.Name} {sql};");
                                }
                            }
                        }

                        // #56897 привязали элементы, чтоб сохранить настройки конструктора, удалили теги без элементов
                        if (table.Name.Match("PriceTags"))
                        {
                            alters.Add("update PriceTagItems set PriceTagId = (select Id from PriceTags where TagType = 0 order by Id limit 1) where ifnull(PriceTagId, 0) = 0;");
                            alters.Add("delete t from PriceTags t left join PriceTagItems i on i.PriceTagId = t.Id where i.PriceTagId is null;");
                        }

                        // #51646 Проблемы обновления АF.NET
                        if (table.Name.Match("WaybillLines") && tableMeta.GetIndexMetadata("SerialProductIdProducerId") == null)
                        {
                            alters.Add("alter table WaybillLines add index SerialProductIdProducerId (SerialNumber, ProductId, ProducerId);");
                        }

                        if (table.Name.Match("Offers"))
                        {
                            if (tableMeta.GetIndexMetadata("ProductSynonym") == null)
                            {
                                alters.Add("alter table Offers add fulltext (ProductSynonym);");
                            }
                            //из-за ошибки в 0.15.0, были созданы дублирующие индексы чистим их
                            var indexes = schema.GetIndexInfo(tableMeta.Catalog, null, tableMeta.Name).AsEnumerable()
                                          .Select(x => new DevartMySQLIndexMetadata(x))
                                          .Where(x => Regex.IsMatch(x.Name, @"ProductSynonym_\d+", RegexOptions.IgnoreCase))
                                          .ToArray();
                            foreach (var index in indexes)
                            {
                                alters.Add(String.Format("alter table {0} drop index {1};", tableMeta.Name, index.Name));
                            }
                        }

                        if (table.Name.Match("Orders"))
                        {
                            alters.Add("update Orders o left join Prices p on o.PriceId = p.PriceId set SavePriceDate = ifnull(p.PriceDate, o.CreatedOn);");
                        }

                        if (alters.Count > 0)
                        {
                            foreach (var alter in alters)
                            {
                                try {
                                    if (Log.IsDebugEnabled)
                                    {
                                        Log.Debug(alter);
                                    }
                                    cmd.CommandText = alter;
                                    cmd.ExecuteNonQuery();
                                }
                                catch (Exception e) {
                                    Log.Warn("Ошибка при обновлении схемы", e);
                                }
                            }
                        }
                    }    //foreach
                }        //using
        }
Пример #5
0
        /// <summary>
        /// Executes the Export of the Schema.
        /// </summary>
        /// <param name="script"><c>true</c> if the ddl should be outputted in the Console.</param>
        /// <param name="export"><c>true</c> if the ddl should be executed against the Database.</param>
        /// <param name="justDrop"><c>true</c> if only the ddl to drop the Database objects should be executed.</param>
        /// <param name="format"><c>true</c> if the ddl should be nicely formatted instead of one statement per line.</param>
        /// <remarks>
        /// This method allows for both the drop and create ddl script to be executed.
        /// </remarks>
        public void Execute(bool script, bool export, bool justDrop, bool format)
        {
            IDbConnection       connection         = null;
            StreamWriter        fileOutput         = null;
            IConnectionProvider connectionProvider = null;
            IDbCommand          statement          = null;

            IDictionary props = new Hashtable();

            foreach (DictionaryEntry de in dialect.DefaultProperties)
            {
                props[de.Key] = de.Value;
            }

            if (connectionProperties != null)
            {
                foreach (DictionaryEntry de in connectionProperties)
                {
                    props[de.Key] = de.Value;
                }
            }

            try
            {
                if (outputFile != null)
                {
                    fileOutput = new StreamWriter(outputFile);
                }

                if (export)
                {
                    connectionProvider = ConnectionProviderFactory.NewConnectionProvider(props);
                    connection         = connectionProvider.GetConnection();
                    statement          = connection.CreateCommand();
                }

                for (int i = 0; i < dropSQL.Length; i++)
                {
                    try
                    {
                        string formatted;
                        if (format)
                        {
                            formatted = Format(dropSQL[i]);
                        }
                        else
                        {
                            formatted = dropSQL[i];
                        }

                        if (delimiter != null)
                        {
                            formatted += delimiter;
                        }
                        if (script)
                        {
                            Console.WriteLine(formatted);
                        }
                        if (outputFile != null)
                        {
                            fileOutput.WriteLine(formatted);
                        }
                        if (export)
                        {
                            statement.CommandText = dropSQL[i];
                            statement.CommandType = CommandType.Text;
                            statement.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        if (!script)
                        {
                            Console.WriteLine(dropSQL[i]);
                        }
                        Console.WriteLine("Unsuccessful: " + e.Message);
                    }
                }

                if (!justDrop)
                {
                    for (int j = 0; j < createSQL.Length; j++)
                    {
                        try
                        {
                            string formatted;
                            if (format)
                            {
                                formatted = Format(createSQL[j]);
                            }
                            else
                            {
                                formatted = createSQL[j];
                            }
                            if (delimiter != null)
                            {
                                formatted += delimiter;
                            }
                            if (script)
                            {
                                Console.WriteLine(formatted);
                            }
                            if (outputFile != null)
                            {
                                fileOutput.WriteLine(formatted);
                            }
                            if (export)
                            {
                                statement.CommandText = createSQL[j];
                                statement.CommandType = CommandType.Text;
                                statement.ExecuteNonQuery();
                            }
                        }
                        catch (Exception e)
                        {
                            if (!script)
                            {
                                Console.WriteLine(createSQL[j]);
                            }
                            Console.WriteLine("Unsuccessful: " + e.Message);

                            // Fail on create script errors
                            throw;
                        }
                    }
                }
            }
            catch (HibernateException)
            {
                // So that we don't wrap HibernateExceptions in HibernateExceptions
                throw;
            }
            catch (Exception e)
            {
                Console.Write(e.StackTrace);
                throw new HibernateException(e.Message, e);
            }
            finally
            {
                try
                {
                    if (statement != null)
                    {
                        statement.Dispose();
                    }
                    if (connection != null)
                    {
                        connectionProvider.CloseConnection(connection);
                        connectionProvider.Dispose();
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Could not close connection: " + e.Message);
                }
                if (fileOutput != null)
                {
                    try
                    {
                        fileOutput.Close();
                    }
                    catch (Exception ioe)
                    {
                        Console.Error.WriteLine("Error closing output file " + outputFile + ": " + ioe.Message);
                    }
                }
            }
        }
Пример #6
0
 public void Initialize(ConnectionProviderFactory factory)
 {
     ;
 }
 public CassandraSession(ConsistencyLevel read, ConsistencyLevel write)
     : this(ConnectionProviderFactory.Get(CassandraContext.CurrentConnectionBuilder), read, write)
 {
 }
Пример #8
0
 public async Task PrepareAsync(CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     connectionProvider = ConnectionProviderFactory.NewConnectionProvider(cfgProperties);
     connection         = await(connectionProvider.GetConnectionAsync(cancellationToken)).ConfigureAwait(false);
 }
Пример #9
0
 protected AbstractService()
 {
     Factory = new ConnectionProviderFactory(ApplicationConfigurationHelper.GetOracleConnectionString());
     Ninject = new StandardKernel();
     Ninject.Bind <ConnectionProvider>().ToMethod(context => Factory.Get());
 }
 public void Initialize(ConnectionProviderFactory factory)
 {
     MonoConnectionProviderFactory.RegisterProvider(factory, TlsProvider);
 }
Пример #11
0
 static ConnectionTestHelper()
 {
     Factory = DependencyInjector.Get <ConnectionProviderFactory> ();
 }
Пример #12
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(he, "No dialect set - using GenericDialect: {0}", he.Message);
                dialect = new GenericDialect();
            }
            settings.Dialect = dialect;

            settings.LinqToHqlGeneratorsRegistry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties);
            // 6.0 TODO: default to false instead of true, and adjust documentation in xsd, xml comment on Environment
            // and Setting properties, and doc\reference.
            settings.LinqToHqlLegacyPreEvaluation = PropertiesHelper.GetBoolean(
                Environment.LinqToHqlLegacyPreEvaluation,
                properties,
                true);
            settings.LinqToHqlFallbackOnPreEvaluation = PropertiesHelper.GetBoolean(
                Environment.LinqToHqlFallbackOnPreEvaluation,
                properties);

            #region SQL Exception converter

            ISQLExceptionConverter sqlExceptionConverter;
            try
            {
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildSQLExceptionConverter(dialect, properties);
            }
            catch (HibernateException he)
            {
                log.Warn(he, "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: {0}", EnabledDisabled(comments));
            settings.IsCommentsEnabled = comments;

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);
            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: {0}", 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: {0}", useMinimalPuts);

            string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto");
            log.Info("Connection release mode: {0}", 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: {0}", defaultSchema);
            }
            if (defaultCatalog != null)
            {
                log.Info("Default catalog: {0}", defaultCatalog);
            }
            settings.DefaultSchemaName  = defaultSchema;
            settings.DefaultCatalogName = defaultCatalog;

            int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1);
            log.Info("Default batch fetch size: {0}", 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: {0}", EnabledDisabled(useStatistics));
            settings.IsStatisticsEnabled = useStatistics;

            bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties);
            log.Info("Deleted entity synthetic identifier rollback: {0}", 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: {0}", 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");
            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;
            }

            settings.ThrowOnSchemaUpdate = PropertiesHelper.GetBoolean(Environment.Hbm2ddlThrowOnUpdate, properties, false);

            #endregion

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

            if (useSecondLevelCache || useQueryCache)
            {
                settings.CacheReadWriteLockFactory = GetReadWriteLockFactory(PropertiesHelper.GetString(Environment.CacheReadWriteLockFactory, properties, null));
                // 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: {0}", cacheRegionPrefix);
            }

            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties,
                                                                               typeof(StandardQueryCacheFactory).FullName);
                log.Info("query cache factory: {0}", queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory =
                        (IQueryCacheFactory)
                        Environment.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: {0}", EnabledDisabled(orderInserts));
            settings.IsOrderInsertsEnabled = orderInserts;

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

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

            bool batchVersionedData = PropertiesHelper.GetBoolean(Environment.BatchVersionedData, properties, false);
            log.Debug("Batch versioned data: {0}", 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: {0}", isolation);
                }
                catch (ArgumentException ae)
                {
                    log.Error(ae, "error configuring IsolationLevel {0}", isolationString);
                    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: {0}", 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 : {0}", EnabledDisabled(namedQueryChecking));
            settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking;

            bool queryThrowNeverCached = PropertiesHelper.GetBoolean(Environment.QueryThrowNeverCached, properties, true);
            log.Info("Never cached entities/collections query cache throws exception : {0}", EnabledDisabled(queryThrowNeverCached));
            settings.QueryThrowNeverCached = queryThrowNeverCached;

            // 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.AutoJoinTransaction       = PropertiesHelper.GetBoolean(Environment.AutoJoinTransaction, properties, true);
            settings.MaximumFetchDepth         = maxFetchDepth;
            settings.IsQueryCacheEnabled       = useQueryCache;
            settings.IsSecondLevelCacheEnabled = useSecondLevelCache;
            settings.CacheRegionPrefix         = cacheRegionPrefix;
            settings.IsMinimalPutsEnabled      = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData

            settings.QueryModelRewriterFactory = CreateQueryModelRewriterFactory(properties);
            settings.PreTransformerRegistrar   = CreatePreTransformerRegistrar(properties);

            // Avoid dependency on re-linq assembly when PreTransformerRegistrar is null
            if (settings.PreTransformerRegistrar != null)
            {
                settings.LinqPreTransformer = NhRelinqQueryParser.CreatePreTransformer(settings.PreTransformerRegistrar);
            }

            //QueryPlanCache:
            settings.QueryPlanCacheParameterMetadataMaxSize = PropertiesHelper.GetInt32(Environment.QueryPlanCacheParameterMetadataMaxSize, properties, QueryPlanCache.DefaultParameterMetadataMaxCount);
            settings.QueryPlanCacheMaxSize = PropertiesHelper.GetInt32(Environment.QueryPlanCacheMaxSize, properties, QueryPlanCache.DefaultQueryPlanMaxCount);

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

            bool trackSessionId = PropertiesHelper.GetBoolean(Environment.TrackSessionId, properties, true);
            log.Debug("Track session id: " + EnabledDisabled(trackSessionId));
            settings.TrackSessionId = trackSessionId;

            var multiTenancyStrategy = PropertiesHelper.GetEnum(Environment.MultiTenancy, properties, MultiTenancyStrategy.None);
            settings.MultiTenancyStrategy = multiTenancyStrategy;
            if (multiTenancyStrategy != MultiTenancyStrategy.None)
            {
                log.Debug("multi-tenancy strategy : " + multiTenancyStrategy);
                settings.MultiTenancyConnectionProvider = CreateMultiTenancyConnectionProvider(properties);
            }

            return(settings);
        }
Пример #13
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);
        }
Пример #14
0
        protected override bool AppliesTo(Dialect.Dialect dialect)
        {
            var cp = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties);

            return(!cp.Driver.SupportsMultipleQueries);
        }
 public void Prepare()
 {
     connectionProvider = ConnectionProviderFactory.NewConnectionProvider(cfgProperties);
     connection         = connectionProvider.GetConnection();
 }
		public OpenSslConnectionProvider (ConnectionProviderFactory factory)
			: base (factory, ConnectionProviderType.OpenSsl,
				ConnectionProviderFlags.SupportsTls12 | ConnectionProviderFlags.SupportsAeadCiphers | ConnectionProviderFlags.SupportsEcDheCiphers)
		{
		}
Пример #17
0
 public OpenSslConnectionProvider(ConnectionProviderFactory factory)
     : base(factory, ConnectionProviderType.OpenSsl,
            ConnectionProviderFlags.SupportsTls12 | ConnectionProviderFlags.SupportsAeadCiphers | ConnectionProviderFlags.SupportsEcDheCiphers)
 {
 }