Example #1
0
        public static FluentConfiguration ExposeDbCommand(this FluentConfiguration fluentConfiguration, Action <IDbCommand, global::NHibernate.Cfg.Configuration> action)
        {
            fluentConfiguration.ExposeConfiguration(cfg =>
            {
                DbConnection connection      = null;
                IConnectionProvider provider = null;
                IDbCommand command           = null;

                try
                {
                    provider            = GetConnectionProvider(cfg);
                    connection          = provider.GetConnection();
                    command             = connection.CreateCommand();
                    command.CommandType = CommandType.Text;

                    action(command, cfg);
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }

                    if (connection != null)
                    {
                        provider.CloseConnection(connection);
                        provider.Dispose();
                    }
                }
            });

            return(fluentConfiguration);
        }
        /// <summary>
        /// Execute the specified stored procedure with the given parameters and then converts
        /// the results using the supplied delegate.
        /// </summary>
        /// <typeparam name="T2">The collection type to return.</typeparam>
        /// <param name="converter">The delegate which converts the raw results.</param>
        /// <param name="sp_name">The name of the stored procedure.</param>
        /// <param name="parameters">Parameters for the stored procedure.</param>
        /// <returns></returns>
        public ICollection <T2> ExecuteStoredProcedure <T2>(Converter <IDataReader, T2> converter, string sp_name,
                                                            params Parameter[] parameters)
        {
            IConnectionProvider connectionProvider = ((ISessionFactoryImplementor)SessionFactory).ConnectionProvider;
            IDbConnection       connection         = connectionProvider.GetConnection();

            try
            {
                using (IDbCommand command = connection.CreateCommand())
                {
                    command.CommandText = sp_name;
                    command.CommandType = CommandType.StoredProcedure;

                    RepositoryHelper <T> .CreateDbDataParameters(command, parameters);

                    IDataReader      reader  = command.ExecuteReader();
                    ICollection <T2> results = new List <T2>();

                    while (reader.Read())
                    {
                        results.Add(converter(reader));
                    }

                    reader.Close();

                    return(results);
                }
            }
            finally
            {
                connectionProvider.CloseConnection(connection);
            }
        }
Example #3
0
        public int ExecuteStatement(string sql)
        {
            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                IDbConnection conn = prov.GetConnection();

                try
                {
                    using (IDbTransaction tran = conn.BeginTransaction())
                        using (IDbCommand comm = conn.CreateCommand())
                        {
                            comm.CommandText = sql;
                            comm.Transaction = tran;
                            comm.CommandType = CommandType.Text;
                            int result = comm.ExecuteNonQuery();
                            tran.Commit();
                            return(result);
                        }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
Example #4
0
 public void Release()
 {
     if (connection != null)
     {
         provider.CloseConnection(connection);
     }
 }
Example #5
0
        public int ExecuteStatement(string sql)
        {
            if (cfg == null)
            {
                cfg = TestConfigurationHelper.GetDefaultConfiguration();
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                var conn = prov.GetConnection();

                try
                {
                    using (var tran = conn.BeginTransaction())
                        using (var comm = conn.CreateCommand())
                        {
                            comm.CommandText = sql;
                            comm.Transaction = tran;
                            comm.CommandType = CommandType.Text;
                            int result = comm.ExecuteNonQuery();
                            tran.Commit();
                            return(result);
                        }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
Example #6
0
        private void InitConnectionAndExecute(Action <string> scriptAction, bool execute, bool justDrop, DbConnection connection, TextWriter exportOutput)
        {
            Initialize();
            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         = connectionProvider.GetConnection();
                }

                Execute(scriptAction, execute, justDrop, connection, fileOutput);
            }
            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)
                {
                    connectionProvider.CloseConnection(connection);
                    connectionProvider.Dispose();
                }
            }
        }
 public void Release()
 {
     if (connection != null)
     {
         connectionProvider.CloseConnection(connection);
     }
     connection = null;
 }
        public async Task ExecuteAsync(Action <string> scriptAction, bool execute, bool justDrop, TextWriter exportOutput, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            await(InitializeAsync(cancellationToken)).ConfigureAwait(false);
            DbConnection        connection         = null;
            TextWriter          fileOutput         = exportOutput;
            IConnectionProvider connectionProvider = null;

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

                if (execute)
                {
                    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 (connection != null)
                {
                    connectionProvider.CloseConnection(connection);
                    connectionProvider.Dispose();
                }
            }
        }
Example #9
0
        public void Execute(Action <string> scriptAction, bool export, bool justDrop)
        {
            Initialize();
            IDbConnection       connection         = null;
            StreamWriter        fileOutput         = null;
            IConnectionProvider connectionProvider = null;

            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;
                }
            }

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

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

                Execute(scriptAction, export, justDrop, connection, fileOutput);
            }
            catch (HibernateException)
            {
                // So that we don't wrap HibernateExceptions in HibernateExceptions
                throw;
            }
            catch (Exception e)
            {
                log.Error(e.Message, e);
                throw new HibernateException(e.Message, e);
            }
            finally
            {
                if (connection != null)
                {
                    connectionProvider.CloseConnection(connection);
                    connectionProvider.Dispose();
                }
            }
        }
        public void BulkSave(IConnectionProvider conn, IEntityCollection entitiesToSave, IEntityDaoFactory daoFactory)
        {
            IEntityCollection newEntities, changedEntities, removedEntities;
            SplitCollectionForInsertUpdateAndDeleteOperations(entitiesToSave, out newEntities, out changedEntities, out removedEntities);

            bool connIsLocal = !conn.IsOpen;
            if (connIsLocal)
                conn.OpenConnection();

            try
            {
                BulkInsert(conn, newEntities, daoFactory);
                BulkUpdate(conn, changedEntities, daoFactory);
                BulkDelete(conn, removedEntities, daoFactory);
            }
            finally
            {
                if (connIsLocal)
                    conn.CloseConnection();
            }
        }
        public object ExecuteStoredProcedure(string sp_name, params Parameter[] parameters)
        {
            IConnectionProvider connectionProvider = ((ISessionFactoryImplementor)SessionFactory).ConnectionProvider;
            IDbConnection       connection         = connectionProvider.GetConnection();

            try
            {
                using (IDbCommand command = connection.CreateCommand())
                {
                    command.CommandText = sp_name;
                    command.CommandType = CommandType.StoredProcedure;

                    RepositoryHelper <T> .CreateDbDataParameters(command, parameters);

                    return(command.ExecuteScalar());
                }
            }
            finally
            {
                connectionProvider.CloseConnection(connection);
            }
        }
Example #12
0
        public void AttemptToDeleteImmutableObjectShouldThrow()
        {
            using (ISession session = OpenSession())
            {
                Assert.Throws <HibernateException>(() =>
                {
                    using (ITransaction trans = session.BeginTransaction())
                    {
                        var entity = session.Get <DomainClass>(1);
                        session.Delete(entity);

                        trans.Commit();                                 // This used to throw...
                    }
                });
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                var conn = prov.GetConnection();

                try
                {
                    using (var comm = conn.CreateCommand())
                    {
                        comm.CommandText = "SELECT Id FROM DomainClass WHERE Id=1 AND Label='TEST record'";
                        object result = comm.ExecuteScalar();

                        Assert.That(result != null, "Immutable object has been deleted!");
                    }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
Example #13
0
        public void AllowDeletionOfImmutableObject()
        {
            using (ISession session = OpenSession())
            {
                Assert.DoesNotThrow(() =>
                {
                    using (ITransaction trans = session.BeginTransaction())
                    {
                        var entity = session.Get <DomainClass>(1);
                        session.Delete(entity);

                        trans.Commit();
                    }
                });
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                var conn = prov.GetConnection();

                try
                {
                    using (var comm = conn.CreateCommand())
                    {
                        comm.CommandText = "SELECT Id FROM DomainClass WHERE Id=1 AND Label='TEST record'";
                        object result = comm.ExecuteScalar();

                        Assert.That(result == null, "Immutable object has not been deleted!");
                    }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
Example #14
0
        public async Task AllowDeletionOfImmutableObjectAsync()
        {
            using (ISession session = OpenSession())
            {
                Assert.DoesNotThrowAsync(async() =>
                {
                    using (ITransaction trans = session.BeginTransaction())
                    {
                        var entity = await(session.GetAsync <DomainClass>(1));
                        await(session.DeleteAsync(entity));

                        await(trans.CommitAsync());
                    }
                });
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                var conn = await(prov.GetConnectionAsync(CancellationToken.None));

                try
                {
                    using (var comm = conn.CreateCommand())
                    {
                        comm.CommandText = "SELECT Id FROM DomainClass WHERE Id=1 AND Label='TEST record'";
                        object result = await(comm.ExecuteScalarAsync());

                        Assert.That(result == null, "Immutable object has not been deleted!");
                    }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
        private static int CountWithLeafFilter(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, SearchCondition leafFilter, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: final level reached (tree depth is measured).
            int totalCount = 0;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                endAtLevel = GetEndLevel(conn, rootEntity, recursiveRelation, endAtLevel);
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement countAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, leafFilter, level, LevelQuerySelectList.Count);
                    DataTable results = countAtLevel.Execute(conn);
                    totalCount += Convert.ToInt32(results.Rows[0][0], CultureInfo.InvariantCulture);

                    reachedEndLevel = (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalCount;
        }
        private static int UpdateAll(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, UpdateList setExpressions, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: rowsAffected == 0
            int totalRowsAffected = 0;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.BeginTransaction();

                // We need to perform COUNT at least once to determine whether rowsAffacted returned by UPDATE can be trusted.
                RowsAffectedCredibility trustRowsAffected = RowsAffectedCredibility.NotDetermined;
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    // Dependening on DBMS configuration, update statements may automatically return the number of rows affected.
                    int rowsAffectedReturnedByEngine = UpdateAtLevel(conn, rootEntity, recursiveRelation, setExpressions, level);

                    // We need to perform manual counting for as long as rows affected cannot be trusted.
                    int? manualNodeCount = CountNodesAtLevelIfRowsAffectedCannotBeTrusted(conn, rootEntity, trustRowsAffected, recursiveRelation, level);                    
                    
                    // Evaluation which determines whether rows affected may be trusted takes place only once, ie. if not yet determined.
                    bool evaluateRowsAffectedCredibility = (trustRowsAffected == RowsAffectedCredibility.NotDetermined) && (manualNodeCount.HasValue);
                    if (evaluateRowsAffectedCredibility)
                    {
                        bool engineCountMatchesManualCount = (rowsAffectedReturnedByEngine == manualNodeCount.Value);
                        trustRowsAffected = (engineCountMatchesManualCount) ? RowsAffectedCredibility.Trusted : RowsAffectedCredibility.Untrusted;
                    }

                    // Manual node count is null if we have determined that rows affected value returned by engine is credible.
                    int rowsUpdatedInCurrentLevel = manualNodeCount ?? rowsAffectedReturnedByEngine;
                    totalRowsAffected += rowsUpdatedInCurrentLevel;
                    
                    // Inspect stop condition before level variable is increased.
                    reachedEndLevel = IsEndLevelReached(endAtLevel, level, rowsUpdatedInCurrentLevel);

                    // Next level.
                    level++;
                } while (!reachedEndLevel);

                if (isLocalConn)
                    conn.CommitTransaction();
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalRowsAffected;
        }
        private static int UpdateWithLeafFilter(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, UpdateList setExpressions, SearchCondition leafFilter, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: final level reached (tree depth is measured).
            // It's possible that at some intermediate levels no records satisfy the specified criteria.
            // Nevertheless, the algorithm must proceed to the next level where it might find matching records.
            // This behavior simulates the behavior of recursive CTEs.
            int totalRowsAffected = 0;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.BeginTransaction();

                endAtLevel = GetEndLevel(conn, rootEntity, recursiveRelation, endAtLevel);
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    UpdateStatement updateAtLevel = CreateUpdateLevelStatement(rootEntity, recursiveRelation, setExpressions, leafFilter, level);
                    totalRowsAffected += updateAtLevel.Execute(conn);

                    reachedEndLevel = (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);

                if (isLocalConn)
                    conn.CommitTransaction();
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalRowsAffected;
        }
        private static int DetermineTreeDepthInternal(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation)
        {
            EnsureRecursiveRelation(recursiveRelation);
            int depth = 0;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                bool reachedEndLevel = false;
                do
                {
                    SelectStatement countAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, null, depth, LevelQuerySelectList.Count);
                    DataTable results = countAtLevel.Execute(conn);
                    int nodeCount = Convert.ToInt32(results.Rows[0][0], CultureInfo.InvariantCulture);
                    if (nodeCount > 0)
                        depth++;
                    else
                        reachedEndLevel = true;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return depth;
        }
        private static DataTable SelectAll(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: select returns nothing.
            DataTable mergedData = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement fetchLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, null, level, LevelQuerySelectList.AllColumns);
                    DataTable levelData = fetchLevel.Execute(conn);
                    if (levelData.Rows.Count > 0)
                        AppendData(levelData, ref mergedData);

                    reachedEndLevel = (levelData.Rows.Count == 0) || (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return mergedData;
        }
        /// <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);
                    }
                }
            }
        }
        private static object MaxOfAll(IConnectionProvider conn, IEntity rootEntity, IDbColumn column, DbRelation recursiveRelation, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: count returns zero.
            object maximum = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    object levelMax;
                    int nodeCount;
                    FetchMaxFromColumnAndCountAllNodesAtLevel(conn, rootEntity, recursiveRelation, level, column.ColumnName, out levelMax, out nodeCount);

                    maximum = MaxOfNullableValues(maximum as IComparable, levelMax as IComparable);
                    reachedEndLevel = (nodeCount == 0) || (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            if (maximum == null)
                maximum = DBNull.Value;

            return maximum;
        }
        private static object SumAll(IConnectionProvider conn, IEntity rootEntity, IDbColumn column, DbRelation recursiveRelation, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: count returns zero.
            object totalSum = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement sumAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, null, level, LevelQuerySelectList.Default);
                    sumAtLevel.SelectList.Clear();
                    IDbColumn summedColumn = sumAtLevel.FromTable.Columns.GetByColumnName(column.ColumnName);
                    sumAtLevel.SelectList.Add(AggregateFunctionFactory.Sum(summedColumn, false, "levelSum"));
                    sumAtLevel.SelectList.Add(AggregateFunctionFactory.Count("nodeCount"));
                    DataTable results = sumAtLevel.Execute(conn);
                    object levelSum = results.Rows[0]["levelSum"];
                    int nodeCount = Convert.ToInt32(results.Rows[0]["nodeCount"], CultureInfo.InvariantCulture);

                    totalSum = SumNullableValues(column, totalSum, levelSum);
                    reachedEndLevel = (nodeCount == 0) || (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalSum;
        }
        private static int CountAll(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: count returns zero.
            int totalCount = 0;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement countAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, null, level, LevelQuerySelectList.Count);
                    DataTable results = countAtLevel.Execute(conn);
                    int nodeCount = Convert.ToInt32(results.Rows[0][0], CultureInfo.InvariantCulture);

                    totalCount += nodeCount;
                    reachedEndLevel = (nodeCount == 0) || (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalCount;
        }
Example #24
0
        private static object InsertAndSelectAutoNumber(IConnectionProvider conn, string command, DbParameterCollection parameters, int cmdTimeout = 30)
        {
            bool isLocalConn = !conn.IsOpen;
            if (isLocalConn)
                conn.OpenConnection();

            try
            {
                DbUtil.ExecuteNonQuery(conn, command, parameters, CommandType.Text, cmdTimeout);
                // ROWID is always a 64bit integer.
                DataTable data = DbUtil.ExecuteQuery(conn, "SELECT last_insert_rowid()", new DbParameterCollection(), CommandType.Text, null, cmdTimeout);
                int lastId = Convert.ToInt32(data.Rows[0][0], CultureInfo.InvariantCulture);
                return lastId;
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }
        }
Example #25
0
 private static void CloseConnectionIfLocal(IConnectionProvider conn, bool connIsOpennedLocally)
 {
     // Close connection if it was openned in this method.
     if (connIsOpennedLocally)
         conn.CloseConnection();
 }
        public void BulkDelete(IConnectionProvider conn, IEntityCollection removedEntities, IEntityDaoFactory daoFactory)
        {
            if (removedEntities.Count == 0)
                return;

            bool connIsLocal = !conn.IsOpen;
            if (connIsLocal)
                conn.OpenConnection();

            try
            {
                foreach (IEntity entity in removedEntities)
                    GetDao(conn, entity, daoFactory).DeleteOne();
            }
            finally
            {
                if (connIsLocal)
                    conn.CloseConnection();
            }
        }
        private static object SumWithLeafFilter(IConnectionProvider conn, IEntity rootEntity, IDbColumn column, DbRelation recursiveRelation, SearchCondition leafFilter, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: final level reached (tree depth is measured).
            object totalSum = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                endAtLevel = GetEndLevel(conn, rootEntity, recursiveRelation, endAtLevel);
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement sumAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, leafFilter, level, LevelQuerySelectList.Default);
                    sumAtLevel.SelectList.Clear();
                    IDbColumn summedColumn = sumAtLevel.FromTable.Columns.GetByColumnName(column.ColumnName);
                    sumAtLevel.SelectList.Add(AggregateFunctionFactory.Sum(summedColumn, false, "levelSum"));
                    DataTable results = sumAtLevel.Execute(conn);
                    object levelSum = results.Rows[0]["levelSum"];

                    totalSum = SumNullableValues(column, totalSum, levelSum);
                    reachedEndLevel = (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return totalSum;
        }
 public void CloseConnection(DbConnection conn)
 {
     _connectionProvider.CloseConnection(conn);
 }
        private static object MaxWithLeafFilter(IConnectionProvider conn, IEntity rootEntity, IDbColumn column, DbRelation recursiveRelation, SearchCondition leafFilter, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: final level reached (tree depth is measured).
            object maximum = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                endAtLevel = GetEndLevel(conn, rootEntity, recursiveRelation, endAtLevel);
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement maxAtLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, leafFilter, level, LevelQuerySelectList.Default);
                    maxAtLevel.SelectList.Clear();
                    IDbColumn comparedColumn = maxAtLevel.FromTable.Columns.GetByColumnName(column.ColumnName);
                    maxAtLevel.SelectList.Add(AggregateFunctionFactory.Max(comparedColumn, "levelMax"));
                    DataTable results = maxAtLevel.Execute(conn);
                    object levelMax = results.Rows[0]["levelMax"];

                    maximum = MaxOfNullableValues(maximum as IComparable, levelMax as IComparable);
                    reachedEndLevel = (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            if (maximum == null)
                maximum = DBNull.Value;

            return maximum;
        }
        private static DataTable SelectWithLeafFilter(IConnectionProvider conn, IEntity rootEntity, DbRelation recursiveRelation, SearchCondition leafFilter, int beginAtLevel, int endAtLevel)
        {
            // Stop condition: final level reached (tree depth is measured).
            // It's possible that at some intermediate levels no records satisfy the specified criteria.
            // Nevertheless, the algorithm must proceed to the next level where it might find matching records.
            // This behavior simulates the behavior of recursive CTEs.
            DataTable mergedData = null;
            bool isLocalConn = !conn.IsOpen;
            try
            {
                if (isLocalConn)
                    conn.OpenConnection();

                endAtLevel = GetEndLevel(conn, rootEntity, recursiveRelation, endAtLevel);
                bool reachedEndLevel = false;
                int level = beginAtLevel;
                do
                {
                    SelectStatement fetchLevel = CreateSelectFromLevelQuery(rootEntity, recursiveRelation, leafFilter, level, LevelQuerySelectList.AllColumns);
                    DataTable levelData = fetchLevel.Execute(conn);
                    if (levelData.Rows.Count > 0)
                        AppendData(levelData, ref mergedData);

                    reachedEndLevel = (level >= endAtLevel);
                    level++;
                } while (!reachedEndLevel);
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }

            return mergedData;
        }
        private static object InsertAndSelectAutoNumber(IConnectionProvider conn, string command, DbParameterCollection parameters, int cmdTimeout = 30)
        {
            // "SELECT @@IDENTITY" must be executed using the same connection context as INSERT statement.
            // Otherwise SQL CE returns NULL.
            bool isLocalConn = !conn.IsOpen;
            if (isLocalConn)
                conn.OpenConnection();

            try
            {
                DbUtil.ExecuteNonQuery(conn, command, parameters, CommandType.Text, cmdTimeout);
                DataTable data = DbUtil.ExecuteQuery(conn, "SELECT @@IDENTITY", new DbParameterCollection(), CommandType.Text, null, cmdTimeout);
                int lastId = Convert.ToInt32(data.Rows[0][0], CultureInfo.InvariantCulture);
                return lastId;
            }
            finally
            {
                if (isLocalConn)
                    conn.CloseConnection();
            }
        }
 public void CloseConnection(DbConnection conn)
 {
     _base.CloseConnection(conn);
 }