public object GetObjectToSerialize(object obj, Type targetType)
 {
     // Serialize proxies as the base type
     if (obj is INHibernateProxy)
     {
         // Getting the implementation of the proxy forces an initialization of the proxied object (if not yet initialized)
         try
         {
             var newobject = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation();
             obj = newobject;
         }
         catch (Exception)
         {
             // Type test = NHibernateProxyHelper.GetClassWithoutInitializingProxy(obj);
             obj = null;
         }
     }
     // Serialize persistent collections as the collection interface type
     if (obj is IPersistentCollection)
     {
         IPersistentCollection persistentCollection = (IPersistentCollection)obj;
         persistentCollection.ForceInitialization();
         //obj = persistentCollection.Entries(); // This returns the "wrapped" collection
         obj = persistentCollection.Entries(null);     // This returns the "wrapped" collection
     }
     return(obj);
 }
示例#2
0
        private void Audit(IPersistentCollection col, bool recreate)
        {
            var ce       = _sessionImpl.PersistenceContext.GetCollectionEntry(col);
            var entities = col.Entries(ce.CurrentPersister).Cast <object>().ToArray();

            // we don't support non-entity collections... (Jury?)
            if (!ce.CurrentPersister.ElementType.IsEntityType)
            {
                return;
            }

            for (var i = 0; i < entities.Length; i++)
            {
                var entity = entities[i];
                if (recreate || col.NeedsInserting(entity, i, ce.CurrentPersister.ElementType))
                {
                    _audit.Collections.Add(AuditCollection(col, ce, entity, true));
                }
            }

            if (!recreate)
            {
                foreach (var entity in col.GetDeletes(ce.CurrentPersister, true))
                {
                    _audit.Collections.Add(AuditCollection(col, ce, entity, false));
                }
            }
        }
示例#3
0
        public async Task InsertRowsAsync(IPersistentCollection collection, object id, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (!isInverse && RowInsertEnabled)
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("Inserting rows of collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session));
                }

                try
                {
                    // insert all the new entries
                    await(collection.PreInsertAsync(this, cancellationToken)).ConfigureAwait(false);
                    IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
                    //bool callable = InsertCallable;
                    bool useBatch = expectation.CanBeBatched;
                    int  i        = 0;
                    int  count    = 0;

                    IEnumerable entries = collection.Entries(this);
                    foreach (object entry in entries)
                    {
                        if (await(collection.NeedsInsertingAsync(entry, i, elementType, cancellationToken)).ConfigureAwait(false))
                        {
                            object entryId;
                            if (!IsIdentifierAssignedByInsert)
                            {
                                // NH Different implementation: write once
                                entryId = await(PerformInsertAsync(id, collection, expectation, entry, i, useBatch, false, session, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                entryId = await(PerformInsertAsync(id, collection, entry, i, session, cancellationToken)).ConfigureAwait(false);
                            }
                            collection.AfterRowInsert(this, entry, i, entryId);
                            count++;
                        }
                        i++;
                    }

                    if (log.IsDebugEnabled())
                    {
                        log.Debug("done inserting rows: {0} inserted", count);
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle,
                                                     "could not insert collection rows: " + MessageHelper.CollectionInfoString(this, collection, id, session));
                }
            }
        }
示例#4
0
        private void Audit(IPersistentCollection col)
        {
            var ce       = _sessionImpl.PersistenceContext.GetCollectionEntry(col);
            var entities = col.Entries(ce.CurrentPersister).Cast <object>().ToArray();

            for (var i = 0; i < entities.Length; i++)
            {
                var entity = entities[i];
                if (col.NeedsInserting(entity, i, ce.CurrentPersister.ElementType))
                {
                    _audit.Collections.Add(AuditCollection(col, entity, true));
                }
            }

            foreach (var entity in col.GetDeletes(ce.CurrentPersister, true))
            {
                _audit.Collections.Add(AuditCollection(col, entity, false));
            }
        }
        public object GetObjectToSerialize(object obj, Type targetType)
        {
            // Serialize proxies as the base type
            if (obj is INHibernateProxy)
            {
                // Getting the implementation of the proxy forces an initialization of the proxied object (if not yet initialized)
                //obj = (obj as INHibernateProxy).HibernateLazyInitializer.GetImplementation();
                try
                {
                    obj = (obj as INHibernateProxy).HibernateLazyInitializer.GetImplementation();
                }
                catch
                {
                    try
                    {
                        obj = Activator.CreateInstance(targetType);
                    }
                    catch
                    {
                        obj = null;
                    }
                }
            }

            // Serialize persistent collections as the collection interface type
            if (obj is IPersistentCollection)
            {
                IPersistentCollection persistentCollection = (IPersistentCollection)obj;
                //persistentCollection.ForceInitialization();
                obj = persistentCollection.Entries(null);//.Entries(); // This returns the "wrapped" collection
                if (obj == null)
                {
                    if (targetType.IsGenericType)
                    {
                        var genericArgs = targetType.GetGenericArguments().First();
                        var genericList = typeof(List <>).MakeGenericType(genericArgs);
                        obj = Activator.CreateInstance(genericList);
                    }
                }
            }

            return(obj);
        }
示例#6
0
        public async Task RecreateAsync(IPersistentCollection collection, object id, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (!isInverse && RowInsertEnabled)
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("Inserting collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session));
                }

                try
                {
                    IExpectation expectation = null;
                    bool         useBatch    = false;
                    int          i           = 0;
                    int          count       = 0;

                    // create all the new entries
                    foreach (var entry in collection.Entries(this))
                    {
                        // Init, if we're on the first element.
                        if (count == 0)
                        {
                            expectation = Expectations.AppropriateExpectation(insertCheckStyle);
                            await(collection.PreInsertAsync(this, cancellationToken)).ConfigureAwait(false);
                            //bool callable = InsertCallable;
                            useBatch = expectation.CanBeBatched;
                        }

                        if (collection.EntryExists(entry, i))
                        {
                            object entryId;
                            if (!IsIdentifierAssignedByInsert)
                            {
                                // NH Different implementation: write once
                                entryId = await(PerformInsertAsync(id, collection, expectation, entry, i, useBatch, false, session, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                entryId = await(PerformInsertAsync(id, collection, entry, i, session, cancellationToken)).ConfigureAwait(false);
                            }
                            collection.AfterRowInsert(this, entry, i, entryId);
                            count++;
                        }
                        i++;
                    }

                    if (log.IsDebugEnabled())
                    {
                        if (count > 0)
                        {
                            log.Debug("done inserting collection: {0} rows inserted", count);
                        }
                        else
                        {
                            log.Debug("collection was empty");
                        }
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle,
                                                     "could not insert collection: " + MessageHelper.CollectionInfoString(this, collection, id, session));
                }
            }
        }
		protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
		{
			// we finish all the "removes" first to take care of possible unique 
			// constraints and so that we can take better advantage of batching
			try
			{
				const int offset = 0;
				int count = 0;

				if (RowDeleteEnabled)
				{
					IExpectation deleteExpectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
					bool useBatch = deleteExpectation.CanBeBatched;
					SqlCommandInfo sql = SqlDeleteRowString;
					IDbCommand st = null;
					// update removed rows fks to null
					try
					{
						int i = 0;
						IEnumerable entries = collection.Entries(this);

						foreach (object entry in entries)
						{
							if (collection.NeedsUpdating(entry, i, ElementType))
							{
								// will still be issued when it used to be null
								if (useBatch)
								{
									st = session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, sql.Text,
																			 SqlDeleteRowString.ParameterTypes);
								}
								else
								{
									st = session.Batcher.PrepareCommand(SqlDeleteRowString.CommandType, sql.Text,
																		SqlDeleteRowString.ParameterTypes);
								}

								int loc = WriteKey(st, id, offset, session);
								WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), loc, session);
								if (useBatch)
								{
									session.Batcher.AddToBatch(deleteExpectation);
								}
								else
								{
									deleteExpectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
								}
								count++;
							}
							i++;
						}
					}
					catch (Exception e)
					{
						if (useBatch)
						{
							session.Batcher.AbortBatch(e);
						}
						throw;
					}
					finally
					{
						if (!useBatch && st != null)
						{
							session.Batcher.CloseCommand(st, null);
						}
					}
				}

				if (RowInsertEnabled)
				{
					IExpectation insertExpectation = Expectations.AppropriateExpectation(InsertCheckStyle);
					//bool callable = InsertCallable;
					bool useBatch = insertExpectation.CanBeBatched;
					SqlCommandInfo sql = SqlInsertRowString;
					IDbCommand st = null;

					// now update all changed or added rows fks
					try
					{
						int i = 0;
						IEnumerable entries = collection.Entries(this);
						foreach (object entry in entries)
						{
							if (collection.NeedsUpdating(entry, i, ElementType))
							{
								if (useBatch)
								{
									st = session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, sql.Text,
																			 SqlInsertRowString.ParameterTypes);
								}
								else
								{
									st = session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, sql.Text,
																		SqlInsertRowString.ParameterTypes);
								}

								//offset += insertExpectation.Prepare(st, Factory.ConnectionProvider.Driver);
								int loc = WriteKey(st, id, offset, session);
								if (HasIndex && !indexContainsFormula)
								{
									loc = WriteIndexToWhere(st, collection.GetIndex(entry, i, this), loc, session);
								}
								WriteElementToWhere(st, collection.GetElement(entry), loc, session);
								if (useBatch)
								{
									session.Batcher.AddToBatch(insertExpectation);
								}
								else
								{
									insertExpectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
								}
								count++;
							}
							i++;
						}
					}
					catch (Exception e)
					{
						if (useBatch)
						{
							session.Batcher.AbortBatch(e);
						}
						throw;
					}
					finally
					{
						if (!useBatch && st != null)
						{
							session.Batcher.CloseCommand(st, null);
						}
					}
				}
				return count;
			}
			catch (DbException sqle)
			{
				throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle, "could not update collection rows: " + MessageHelper.CollectionInfoString(this, collection, id, session));
			}
		}
		public void InsertRows(IPersistentCollection collection, object id, ISessionImplementor session)
		{
			if (!isInverse && RowInsertEnabled)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("Inserting rows of collection: " + MessageHelper.InfoString(this, id, Factory));
				}

				try
				{
					// insert all the new entries
					collection.PreInsert(this);
					IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
					//bool callable = InsertCallable;
					bool useBatch = expectation.CanBeBatched;
					int i = 0;
					int count = 0;

					IEnumerable entries = collection.Entries(this);
					foreach (object entry in entries)
					{
						if (collection.NeedsInserting(entry, i, elementType))
						{
							object entryId;
							if (!IsIdentifierAssignedByInsert)
							{
								// NH Different implementation: write once
								entryId = PerformInsert(id, collection, expectation, entry, i, useBatch, false, session);
							}
							else
							{
								entryId = PerformInsert(id, collection, entry, i, session);
							}
							collection.AfterRowInsert(this, entry, i, entryId);
							count++;
						}
						i++;
					}

					if (log.IsDebugEnabled)
					{
						log.Debug(string.Format("done inserting rows: {0} inserted", count));
					}
				}
				catch (DbException sqle)
				{
					throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle,
					                                 "could not insert collection rows: " + MessageHelper.InfoString(this, id));
				}
			}
		}
		public void Recreate(IPersistentCollection collection, object id, ISessionImplementor session)
		{
			if (!isInverse && RowInsertEnabled)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("Inserting collection: " + MessageHelper.InfoString(this, id));
				}

				try
				{
					// create all the new entries
					IEnumerator entries = collection.Entries(this).GetEnumerator();
					if (entries.MoveNext())
					{
						entries.Reset();
						IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
						collection.PreInsert(this);
						//bool callable = InsertCallable;
						bool useBatch = expectation.CanBeBatched;
						int i = 0;
						int count = 0;

						while (entries.MoveNext())
						{
							object entry = entries.Current;
							if (collection.EntryExists(entry, i))
							{
								object entryId;
								if (!IsIdentifierAssignedByInsert)
								{
									// NH Different implementation: write once
									entryId = PerformInsert(id, collection, expectation, entry, i, useBatch, false, session);
								}
								else
								{
									entryId = PerformInsert(id, collection, entry, i, session);
								}
								collection.AfterRowInsert(this, entry, i, entryId);
								count++;
							}
							i++;
						}

						if (log.IsDebugEnabled)
						{
							log.Debug(string.Format("done inserting collection: {0} rows inserted", count));
						}
					}
					else
					{
						if (log.IsDebugEnabled)
						{
							log.Debug("collection was empty");
						}
					}
				}
				catch (DbException sqle)
				{
					throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle,
					                                 "could not insert collection: " + MessageHelper.InfoString(this, id));
				}
			}
		}
        protected override async Task <int> DoUpdateRowsAsync(object id, IPersistentCollection collection, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            // we finish all the "removes" first to take care of possible unique
            // constraints and so that we can take better advantage of batching
            try
            {
                const int offset = 0;
                int       count  = 0;

                if (RowDeleteEnabled)
                {
                    IExpectation   deleteExpectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
                    bool           useBatch          = deleteExpectation.CanBeBatched;
                    SqlCommandInfo sql = SqlDeleteRowString;
                    // update removed rows fks to null
                    int         i       = 0;
                    IEnumerable entries = collection.Entries(this);

                    foreach (object entry in entries)
                    {
                        if (await(collection.NeedsUpdatingAsync(entry, i, ElementType, cancellationToken)).ConfigureAwait(false))
                        {
                            DbCommand st;
                            // will still be issued when it used to be null
                            if (useBatch)
                            {
                                st = await(session.Batcher.PrepareBatchCommandAsync(SqlDeleteRowString.CommandType, sql.Text,
                                                                                    SqlDeleteRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                st = await(session.Batcher.PrepareCommandAsync(SqlDeleteRowString.CommandType, sql.Text,
                                                                               SqlDeleteRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                            }

                            try
                            {
                                int loc = await(WriteKeyAsync(st, id, offset, session, cancellationToken)).ConfigureAwait(false);
                                // No columnNullness handling: the element is the entity key and should not contain null
                                // values.
                                await(WriteElementToWhereAsync(st, collection.GetSnapshotElement(entry, i), null, loc, session, cancellationToken)).ConfigureAwait(false);
                                if (useBatch)
                                {
                                    await(session.Batcher.AddToBatchAsync(deleteExpectation, cancellationToken)).ConfigureAwait(false);
                                }
                                else
                                {
                                    deleteExpectation.VerifyOutcomeNonBatched(await(session.Batcher.ExecuteNonQueryAsync(st, cancellationToken)).ConfigureAwait(false), st);
                                }
                            }
                            catch (OperationCanceledException) { throw; }
                            catch (Exception e)
                            {
                                if (useBatch)
                                {
                                    session.Batcher.AbortBatch(e);
                                }
                                throw;
                            }
                            finally
                            {
                                if (!useBatch && st != null)
                                {
                                    session.Batcher.CloseCommand(st, null);
                                }
                            }
                            count++;
                        }
                        i++;
                    }
                }

                if (RowInsertEnabled)
                {
                    IExpectation insertExpectation = Expectations.AppropriateExpectation(InsertCheckStyle);
                    //bool callable = InsertCallable;
                    bool           useBatch = insertExpectation.CanBeBatched;
                    SqlCommandInfo sql      = SqlInsertRowString;

                    // now update all changed or added rows fks
                    int         i       = 0;
                    IEnumerable entries = collection.Entries(this);
                    foreach (object entry in entries)
                    {
                        if (await(collection.NeedsUpdatingAsync(entry, i, ElementType, cancellationToken)).ConfigureAwait(false))
                        {
                            DbCommand st;
                            if (useBatch)
                            {
                                st = await(session.Batcher.PrepareBatchCommandAsync(SqlInsertRowString.CommandType, sql.Text,
                                                                                    SqlInsertRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                st = await(session.Batcher.PrepareCommandAsync(SqlInsertRowString.CommandType, sql.Text,
                                                                               SqlInsertRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                            }

                            try
                            {
                                //offset += insertExpectation.Prepare(st, Factory.ConnectionProvider.Driver);
                                int loc = await(WriteKeyAsync(st, id, offset, session, cancellationToken)).ConfigureAwait(false);
                                if (HasIndex && !indexContainsFormula)
                                {
                                    loc = await(WriteIndexToWhereAsync(st, collection.GetIndex(entry, i, this), loc, session, cancellationToken)).ConfigureAwait(false);
                                }
                                // No columnNullness handling: the element is the entity key and should not contain null
                                // values.
                                await(WriteElementToWhereAsync(st, collection.GetElement(entry), null, loc, session, cancellationToken)).ConfigureAwait(false);
                                if (useBatch)
                                {
                                    await(session.Batcher.AddToBatchAsync(insertExpectation, cancellationToken)).ConfigureAwait(false);
                                }
                                else
                                {
                                    insertExpectation.VerifyOutcomeNonBatched(await(session.Batcher.ExecuteNonQueryAsync(st, cancellationToken)).ConfigureAwait(false), st);
                                }
                            }
                            catch (OperationCanceledException) { throw; }
                            catch (Exception e)
                            {
                                if (useBatch)
                                {
                                    session.Batcher.AbortBatch(e);
                                }
                                throw;
                            }
                            finally
                            {
                                if (!useBatch && st != null)
                                {
                                    session.Batcher.CloseCommand(st, null);
                                }
                            }
                            count++;
                        }
                        i++;
                    }
                }
                return(count);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle, "could not update collection rows: " + MessageHelper.CollectionInfoString(this, collection, id, session));
            }
        }
        public void InsertRows(IPersistentCollection collection, object id, ISessionImplementor session)
        {
            if (!isInverse && RowInsertEnabled)
            {
                if (log.IsDebugEnabled)
                    log.Debug("Inserting rows of collection: " + MessageHelper.InfoString(this, id, Factory));

                try
                {
                    // insert all the new entries
                    collection.PreInsert(this);
                    IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
                    //bool callable = InsertCallable;
                    bool useBatch = expectation.CanBeBatched;
                    int i = 0;
                    int count = 0;

                    IEnumerable entries = collection.Entries(this);
                    foreach (object entry in entries)
                    {
                        int offset = 0;
                        if (collection.NeedsInserting(entry, i, elementType))
                        {
                            IDbCommand st = useBatch
                                                ? session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
                                                                                      SqlInsertRowString.ParameterTypes)
                                                : session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
                                                                                 SqlInsertRowString.ParameterTypes);
                            try
                            {
                                //offset += expectation.Prepare(st, factory.ConnectionProvider.Driver);
                                offset = WriteKey(st, id, offset, session);
                                if (hasIdentifier && !isPostInsertIdentifier)
                                {
                                    offset = WriteIdentifier(st, collection.GetIdentifier(entry, i), offset, session);
                                }
                                if (hasIndex)
                                {
                                    offset = WriteIndex(st, collection.GetIndex(entry, i), offset, session);
                                }
                                WriteElement(st, collection.GetElement(entry), offset, session);
                                if (useBatch)
                                {
                                    session.Batcher.AddToBatch(expectation);
                                }
                                else
                                {
                                    expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                }
                                collection.AfterRowInsert(this, entry, i);
                                count++;
                            }
                            catch (Exception e)
                            {
                                if (useBatch)
                                {
                                    session.Batcher.AbortBatch(e);
                                }
                                throw;
                            }
                            finally
                            {
                                if (!useBatch)
                                {
                                    session.Batcher.CloseCommand(st, null);
                                }
                            }
                        }
                        i++;
                    }

                    if (log.IsDebugEnabled)
                    {
                        log.Debug(string.Format("done inserting rows: {0} inserted", count));
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle, "could not insert collection rows: " + MessageHelper.InfoString(this, id));
                }
            }
        }
		public void Recreate(IPersistentCollection collection, object id, ISessionImplementor session)
		{
			if (!isInverse)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("Inserting collection: " + MessageHelper.InfoString(this, id));
				}

				try
				{
					// create all the new entries
					IEnumerable entries = collection.Entries();
					IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
					bool useBatch = expectation.CanBeBatched;

					int i = 0;
					int count = 0;
					collection.PreInsert(this);

					IDbCommand st = null;
					foreach (object entry in entries)
					{
						if (collection.EntryExists(entry, i))
						{
							try
							{
								int offset = 0;
								if (useBatch)
								{
									if (st == null)
									{
										st = session.Batcher.PrepareBatchCommand(
											SqlInsertRowString.CommandType,
											SqlInsertRowString.Text,
											SqlInsertRowString.ParameterTypes);
									}
								}
								else
								{
									st = session.Batcher.PrepareCommand(
										SqlInsertRowString.CommandType,
										SqlInsertRowString.Text,
										SqlInsertRowString.ParameterTypes);
								}
								//offset += expectation.Prepare(st, factory.ConnectionProvider.Driver);
								int loc = WriteKey(st, id, offset, session);
								if (hasIdentifier)
								{
									loc = WriteIdentifier(st, collection.GetIdentifier(entry, i), loc, session);
								}
								if (hasIndex /*&&! !indexIsFormula */)
								{
									loc = WriteIndex(st, collection.GetIndex(entry, i), loc, session);
								}
								loc = WriteElement(st, collection.GetElement(entry), loc, session);
								if (useBatch)
								{
									session.Batcher.AddToBatch(expectation);
								}
								else
								{
									expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
								}
								collection.AfterRowInsert(this, entry, i);
								count++;
							}
							catch (Exception e)
							{
								if (useBatch)
								{
									session.Batcher.AbortBatch(e);
								}
								throw;
							}
							finally
							{
								if (!useBatch)
								{
									session.Batcher.CloseCommand(st, null);
								}
							}
						}
						i++;
					}

					if (log.IsDebugEnabled)
					{
						log.Debug(string.Format("done inserting collection: {0} rows inserted", count));
					}

					if (count == 0 && log.IsDebugEnabled)
					{
						log.Debug("collection was empty");
					}
				}
				catch (HibernateException)
				{
					// Do not call Convert on HibernateExceptions
					throw;
				}
				catch (Exception sqle)
				{
					throw Convert(sqle, "could not insert collection: " + MessageHelper.InfoString(this, id));
				}
			}
		}
		protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
		{
			if (ArrayHelper.IsAllFalse(elementColumnIsSettable)) return 0;

			try
			{
				IDbCommand st = null;
				IExpectation expectation = Expectations.AppropriateExpectation(UpdateCheckStyle);
				//bool callable = UpdateCallable;
				bool useBatch = expectation.CanBeBatched;
				IEnumerable entries = collection.Entries(this);
				int i = 0;
				int count = 0;
				foreach (object entry in entries)
				{
					if (collection.NeedsUpdating(entry, i, ElementType))
					{
						int offset = 0;
						if (useBatch)
						{
							if (st == null)
							{
								st =
									session.Batcher.PrepareBatchCommand(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
									                                    SqlUpdateRowString.ParameterTypes);
							}
						}
						else
						{
							st =
								session.Batcher.PrepareCommand(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
								                               SqlUpdateRowString.ParameterTypes);
						}

						try
						{
							//offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);

							int loc = WriteElement(st, collection.GetElement(entry), offset, session);
							if (hasIdentifier)
							{
								WriteIdentifier(st, collection.GetIdentifier(entry, i), loc, session);
							}
							else
							{
								loc = WriteKey(st, id, loc, session);
								if (HasIndex && !indexContainsFormula)
								{
									WriteIndexToWhere(st, collection.GetIndex(entry, i, this), loc, session);
								}
								else
								{
									WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), loc, session);
								}
							}

							if (useBatch)
							{
								session.Batcher.AddToBatch(expectation);
							}
							else
							{
								expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
							}
						}
						catch (Exception e)
						{
							if (useBatch)
							{
								session.Batcher.AbortBatch(e);
							}
							throw;
						}
						finally
						{
							if (!useBatch)
							{
								session.Batcher.CloseCommand(st, null);
							}
						}
						count++;
					}
					i++;
				}
				return count;
			}
			catch (DbException sqle)
			{
				throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle,
				                                 "could not update collection rows: " + MessageHelper.InfoString(this, id),
				                                 SqlUpdateRowString.Text);
			}
		}
        public void Recreate(IPersistentCollection collection, object id, ISessionImplementor session)
        {
            if (!isInverse && RowInsertEnabled)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Inserting collection: " + MessageHelper.InfoString(this, id));
                }

                try
                {
                    // create all the new entries
                    IEnumerator entries = collection.Entries(this).GetEnumerator();
                    if (entries.MoveNext())
                    {
                        entries.Reset();
                        collection.PreInsert(this);
                        int i = 0;
                        int count = 0;

                        while (entries.MoveNext())
                        {
                            object entry = entries.Current;
                            if (collection.EntryExists(entry, i))
                            {
                                int offset = 0;
                                IDbCommand st;
                                IExpectation expectation = Expectations.AppropriateExpectation(insertCheckStyle);
                                //bool callable = InsertCallable;

                                bool useBatch = expectation.CanBeBatched;
                                if (useBatch)
                                {
                                    st =
                                        session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
                                                                            SqlInsertRowString.ParameterTypes);
                                }
                                else
                                {
                                    st =
                                        session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
                                                                       SqlInsertRowString.ParameterTypes);
                                }
                                try
                                {
                                    //offset += expectation.Prepare(st, factory.ConnectionProvider.Driver);
                                    int loc = WriteKey(st, id, offset, session);
                                    if (hasIdentifier && !isPostInsertIdentifier)
                                        loc = WriteIdentifier(st, collection.GetIdentifier(entry, i), loc, session);

                                    if (hasIndex)
                                        loc = WriteIndex(st, collection.GetIndex(entry, i), loc, session);

                                    WriteElement(st, collection.GetElement(entry), loc, session);
                                    if (useBatch)
                                    {
                                        session.Batcher.AddToBatch(expectation);
                                    }
                                    else
                                    {
                                        expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                    }
                                    collection.AfterRowInsert(this, entry, i);
                                    count++;
                                }
                                catch (Exception e)
                                {
                                    if (useBatch)
                                    {
                                        session.Batcher.AbortBatch(e);
                                    }
                                    throw;
                                }
                                finally
                                {
                                    if (!useBatch)
                                    {
                                        session.Batcher.CloseCommand(st, null);
                                    }
                                }
                            }
                            i++;
                        }

                        if (log.IsDebugEnabled)
                        {
                            log.Debug(string.Format("done inserting collection: {0} rows inserted", count));
                        }
                    }
                    else
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("collection was empty");
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle,
                                                     "could not insert collection: " + MessageHelper.InfoString(this, id));
                }
            }
        }
        protected override async Task <int> DoUpdateRowsAsync(object id, IPersistentCollection collection, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (ArrayHelper.IsAllFalse(elementColumnIsSettable))
            {
                return(0);
            }

            try
            {
                DbCommand    st          = null;
                IExpectation expectation = Expectations.AppropriateExpectation(UpdateCheckStyle);
                //bool callable = UpdateCallable;
                bool        useBatch = expectation.CanBeBatched;
                IEnumerable entries  = collection.Entries(this);
                int         i        = 0;
                int         count    = 0;
                foreach (object entry in entries)
                {
                    if (await(collection.NeedsUpdatingAsync(entry, i, ElementType, cancellationToken)).ConfigureAwait(false))
                    {
                        int offset = 0;
                        if (useBatch)
                        {
                            if (st == null)
                            {
                                st =
                                    await(session.Batcher.PrepareBatchCommandAsync(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
                                                                                   SqlUpdateRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            st =
                                await(session.Batcher.PrepareCommandAsync(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
                                                                          SqlUpdateRowString.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                        }

                        try
                        {
                            //offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);

                            int loc = await(WriteElementAsync(st, collection.GetElement(entry), offset, session, cancellationToken)).ConfigureAwait(false);
                            if (hasIdentifier)
                            {
                                await(WriteIdentifierAsync(st, collection.GetIdentifier(entry, i), loc, session, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                loc = await(WriteKeyAsync(st, id, loc, session, cancellationToken)).ConfigureAwait(false);
                                if (HasIndex && !indexContainsFormula)
                                {
                                    await(WriteIndexToWhereAsync(st, collection.GetIndex(entry, i, this), loc, session, cancellationToken)).ConfigureAwait(false);
                                }
                                else
                                {
                                    await(WriteElementToWhereAsync(st, collection.GetSnapshotElement(entry, i), loc, session, cancellationToken)).ConfigureAwait(false);
                                }
                            }

                            if (useBatch)
                            {
                                await(session.Batcher.AddToBatchAsync(expectation, cancellationToken)).ConfigureAwait(false);
                            }
                            else
                            {
                                expectation.VerifyOutcomeNonBatched(await(session.Batcher.ExecuteNonQueryAsync(st, cancellationToken)).ConfigureAwait(false), st);
                            }
                        }

                        catch (OperationCanceledException) { throw; }
                        catch (Exception e)
                        {
                            if (useBatch)
                            {
                                session.Batcher.AbortBatch(e);
                            }
                            throw;
                        }
                        finally
                        {
                            if (!useBatch)
                            {
                                session.Batcher.CloseCommand(st, null);
                            }
                        }
                        count++;
                    }
                    i++;
                }
                return(count);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle,
                                                 "could not update collection rows: " + MessageHelper.CollectionInfoString(this, collection, id, session),
                                                 SqlUpdateRowString.Text);
            }
        }
        protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
        {
            if (ArrayHelper.IsAllFalse(elementColumnIsSettable))
            {
                return(0);
            }

            try
            {
                DbCommand    st          = null;
                IExpectation expectation = Expectations.AppropriateExpectation(UpdateCheckStyle);
                //bool callable = UpdateCallable;
                bool        useBatch = expectation.CanBeBatched;
                IEnumerable entries  = collection.Entries(this);
                int         i        = 0;
                int         count    = 0;
                foreach (object entry in entries)
                {
                    if (collection.NeedsUpdating(entry, i, ElementType))
                    {
                        int offset = 0;
                        if (useBatch)
                        {
                            if (st == null)
                            {
                                st =
                                    session.Batcher.PrepareBatchCommand(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
                                                                        SqlUpdateRowString.ParameterTypes);
                            }
                        }
                        else
                        {
                            st =
                                session.Batcher.PrepareCommand(SqlUpdateRowString.CommandType, SqlUpdateRowString.Text,
                                                               SqlUpdateRowString.ParameterTypes);
                        }

                        try
                        {
                            //offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);

                            int loc = WriteElement(st, collection.GetElement(entry), offset, session);
                            if (hasIdentifier)
                            {
                                WriteIdentifier(st, collection.GetIdentifier(entry, i), loc, session);
                            }
                            else
                            {
                                loc = WriteKey(st, id, loc, session);
                                if (HasIndex && !indexContainsFormula)
                                {
                                    WriteIndexToWhere(st, collection.GetIndex(entry, i, this), loc, session);
                                }
                                else
                                {
                                    // No nullness handled on update: updates does not occurs with sets or bags, and
                                    // indexed collections allowing formula (maps) force their element columns to
                                    // not-nullable.
                                    WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), null, loc, session);
                                }
                            }

                            if (useBatch)
                            {
                                session.Batcher.AddToBatch(expectation);
                            }
                            else
                            {
                                expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                            }
                        }
                        catch (Exception e)
                        {
                            if (useBatch)
                            {
                                session.Batcher.AbortBatch(e);
                            }
                            throw;
                        }
                        finally
                        {
                            if (!useBatch)
                            {
                                session.Batcher.CloseCommand(st, null);
                            }
                        }
                        count++;
                    }
                    i++;
                }
                return(count);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle,
                                                 "could not update collection rows: " + MessageHelper.CollectionInfoString(this, collection, id, session),
                                                 SqlUpdateRowString.Text);
            }
        }
示例#17
0
        protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
        {
            // we finish all the "removes" first to take care of possible unique
            // constraints and so that we can take better advantage of batching

            try
            {
                int count = 0;
                if (RowDeleteEnabled)
                {
                    bool       useBatch = true;
                    IDbCommand st       = null;
                    // update removed rows fks to null
                    try
                    {
                        int          i           = 0;
                        IEnumerable  entries     = collection.Entries(this);
                        int          offset      = 0;
                        IExpectation expectation = Expectations.None;

                        foreach (object entry in entries)
                        {
                            if (collection.NeedsUpdating(entry, i, ElementType))
                            {
                                // will still be issued when it used to be null
                                if (st == null)
                                {
                                    SqlCommandInfo sql = SqlDeleteRowString;
                                    if (DeleteCallable)
                                    {
                                        expectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
                                        useBatch    = expectation.CanBeBatched;
                                        st          = useBatch
                                                                                        ? session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                                                              SqlDeleteRowString.ParameterTypes)
                                                                                        : session.Batcher.PrepareCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                                                         SqlDeleteRowString.ParameterTypes);
                                        //offset += expectation.prepare(st);
                                    }
                                    else
                                    {
                                        st =
                                            session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                SqlDeleteRowString.ParameterTypes);
                                    }
                                }

                                int loc = WriteKey(st, id, offset, session);
                                WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), loc, session);
                                if (useBatch)
                                {
                                    session.Batcher.AddToBatch(expectation);
                                }
                                else
                                {
                                    expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                }
                                count++;
                            }
                            i++;
                        }
                    }
                    catch (Exception e)
                    {
                        if (useBatch)
                        {
                            session.Batcher.AbortBatch(e);
                        }
                        throw;
                    }
                    finally
                    {
                        if (!useBatch && st != null)
                        {
                            session.Batcher.CloseCommand(st, null);
                        }
                    }
                }

                if (RowInsertEnabled)
                {
                    IExpectation expectation = Expectations.AppropriateExpectation(InsertCheckStyle);
                    //bool callable = InsertCallable;
                    bool           useBatch = expectation.CanBeBatched;
                    SqlCommandInfo sql      = SqlInsertRowString;
                    IDbCommand     st       = null;

                    // now update all changed or added rows fks
                    try
                    {
                        int         i       = 0;
                        IEnumerable entries = collection.Entries(this);
                        foreach (object entry in entries)
                        {
                            int offset = 0;
                            if (collection.NeedsUpdating(entry, i, ElementType))
                            {
                                if (useBatch)
                                {
                                    if (st == null)
                                    {
                                        st =
                                            session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, sql.Text,
                                                                                SqlInsertRowString.ParameterTypes);
                                    }
                                }
                                else
                                {
                                    st =
                                        session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, sql.Text, SqlInsertRowString.ParameterTypes);
                                }

                                //offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);
                                int loc = WriteKey(st, id, offset, session);
                                if (HasIndex && !indexContainsFormula)
                                {
                                    loc = WriteIndexToWhere(st, collection.GetIndex(entry, i, this), loc, session);
                                }
                                WriteElementToWhere(st, collection.GetElement(entry), loc, session);
                                if (useBatch)
                                {
                                    session.Batcher.AddToBatch(expectation);
                                }
                                else
                                {
                                    expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                }
                                count++;
                            }
                            i++;
                        }
                    }
                    catch (Exception e)
                    {
                        if (useBatch)
                        {
                            session.Batcher.AbortBatch(e);
                        }
                        throw;
                    }
                    finally
                    {
                        if (st != null)
                        {
                            session.Batcher.CloseCommand(st, null);
                        }
                    }
                }
                return(count);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle,
                                                 "could not update collection rows: " + MessageHelper.InfoString(this, id));
            }
        }
		protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
		{
			// we finish all the "removes" first to take care of possible unique 
			// constraints and so that we can take better advantage of batching

			IDbCommand st = null;
			IEnumerable entries;
			int i;
			try
			{
				// update removed rows fks to null
				IExpectation expectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
				bool useBatch = expectation.CanBeBatched;
				int count = 0;
				try
				{
					i = 0;
					entries = collection.Entries();
					int offset = 0;
					foreach (object entry in entries)
					{
						if (collection.NeedsUpdating(entry, i, ElementType)) // will still be issued when it used to be null
						{
							if (useBatch)
							{
								if (st == null)
								{
									st =
										session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, SqlDeleteRowString.Text,
										                                    SqlDeleteRowString.ParameterTypes);
								}
							}
							else
							{
								st = session.Batcher.PrepareCommand(
									SqlDeleteRowString.CommandType,
									SqlDeleteRowString.Text,
									SqlDeleteRowString.ParameterTypes);
							}
							//offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);
							int loc = WriteKey(st, id, offset, session);
							WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), loc, session);
							if (useBatch)
							{
								session.Batcher.AddToBatch(expectation);
							}
							else
							{
								expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
							}
							count++;
						}
						i++;
					}
				}
				catch (Exception e)
				{
					if (useBatch)
					{
						session.Batcher.AbortBatch(e);
					}
					throw;
				}
				finally
				{
					if (!useBatch && st != null)
					{
						session.Batcher.CloseCommand(st, null);
					}
				}

				// now update all changed or added rows fks
				count = 0;
				st = null;

				try
				{
					expectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
					useBatch = expectation.CanBeBatched;
					i = 0;
					entries = collection.Entries();
					foreach (object entry in entries)
					{
						int offset = 0;
						if (collection.NeedsUpdating(entry, i, ElementType)) // will still be issued when it used to be null
						{
							if (useBatch)
							{
								if (st == null)
								{
									st =
										session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
										                                    SqlInsertRowString.ParameterTypes);
								}
							}
							else
							{
								st = session.Batcher.PrepareCommand(
									SqlInsertRowString.CommandType,
									SqlInsertRowString.Text,
									SqlInsertRowString.ParameterTypes);
							}

							//offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);
							int loc = WriteKey(st, id, offset, session);
							if (HasIndex /* TODO H3: && !indexContainsFormula*/)
							{
								loc = WriteIndexToWhere(st, collection.GetIndex(entry, i), loc, session);
							}
							WriteElementToWhere(st, collection.GetElement(entry), loc, session);
							if (useBatch)
							{
								session.Batcher.AddToBatch(expectation);
							}
							else
							{
								expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
							}
							count++;
						}
						i++;
					}
				}
				catch (Exception e)
				{
					if (useBatch)
					{
						session.Batcher.AbortBatch(e);
					}
					throw;
				}
				finally
				{
					if (st != null)
					{
						session.Batcher.CloseCommand(st, null);
					}
				}
				return count;
			}
			catch (HibernateException)
			{
				// Do not call Convert on HibernateExceptions
				throw;
			}
			catch (Exception sqle)
			{
				throw Convert(sqle, "could not update collection rows: " + MessageHelper.InfoString(this, id));
			}
		}