示例#1
0
		public DatabaseMetadata(DbConnection connection, Dialect.Dialect dialect, bool extras)
		{
			schemaReader = new InformationSchemaReader(connection);
			this.extras = extras;
			InitSequences(connection, dialect);
			sqlExceptionConverter = dialect.BuildSQLExceptionConverter();
		}
示例#2
0
 public static ADOException Convert(ISQLExceptionConverter converter, Exception sqle, string message, SqlString sql,
     object[] parameterValues, IDictionary namedParameters)
 {
     string extendMessage = ExtendMessage(message, sql, parameterValues, namedParameters);
     ADOExceptionReporter.LogExceptions(sqle, extendMessage);
     return new ADOException(extendMessage, sqle, sql);
 }
		/// <summary> 
		/// Converts the given SQLException into Exception hierarchy, as well as performing
		/// appropriate logging. 
		/// </summary>
		/// <param name="converter">The converter to use.</param>
		/// <param name="sqlException">The exception to convert.</param>
		/// <param name="message">An optional error message.</param>
		/// <param name="sql">The SQL executed.</param>
		/// <returns> The converted <see cref="ADOException"/>.</returns>
		public static Exception Convert(ISQLExceptionConverter converter, Exception sqlException, string message,
		                                   SqlString sql)
		{
			return Convert(converter,
			               new AdoExceptionContextInfo
			               	{SqlException = sqlException, Message = message, Sql = sql != null ? sql.ToString() : null});
		}
示例#4
0
        /// <summary>
        /// Converts the given SQLException into Exception hierarchy, as well as performing
        /// appropriate logging.
        /// </summary>
        /// <param name="converter">The converter to use.</param>
        /// <param name="sqlException">The exception to convert.</param>
        /// <param name="message">An optional error message.</param>
        /// <returns> The converted <see cref="ADOException"/>.</returns>
        public static Exception Convert(ISQLExceptionConverter converter, Exception sqlException, string message)
        {
            var sql = TryGetActualSqlQuery(sqlException, SQLNotAvailable);

            return(Convert(converter, new AdoExceptionContextInfo {
                SqlException = sqlException, Message = message, Sql = sql
            }));
        }
		public DatabaseMetadata(DbConnection connection, Dialect.Dialect dialect, bool extras)
		{
			meta = dialect.GetDataBaseSchema(connection);
		    this.dialect = dialect;
		    this.extras = extras;
			InitSequences(connection, dialect);
			sqlExceptionConverter = dialect.BuildSQLExceptionConverter();
		}
 public DatabaseMetadata(DbConnection connection, Dialect.Dialect dialect, bool extras)
 {
     meta         = dialect.GetDataBaseSchema(connection);
     this.dialect = dialect;
     this.extras  = extras;
     InitSequences(connection, dialect);
     sqlExceptionConverter = dialect.BuildSQLExceptionConverter();
 }
		public static Exception Convert(ISQLExceptionConverter converter, Exception sqle, string message, SqlString sql,
		                                   object[] parameterValues, IDictionary<string, TypedValue> namedParameters)
		{
			sql = TryGetActualSqlQuery(sqle, sql);
			string extendMessage = ExtendMessage(message, sql != null ? sql.ToString() : null, parameterValues, namedParameters);
			ADOExceptionReporter.LogExceptions(sqle, extendMessage);
			return Convert(converter, sqle, extendMessage, sql);
		}
示例#8
0
 /// <summary>
 /// Converts the given SQLException into Exception hierarchy, as well as performing
 /// appropriate logging.
 /// </summary>
 /// <param name="converter">The converter to use.</param>
 /// <param name="sqlException">The exception to convert.</param>
 /// <param name="message">An optional error message.</param>
 /// <param name="sql">The SQL executed.</param>
 /// <returns> The converted <see cref="ADOException"/>.</returns>
 public static Exception Convert(ISQLExceptionConverter converter, Exception sqlException, string message,
                                 SqlString sql)
 {
     return(Convert(converter,
                    new AdoExceptionContextInfo
     {
         SqlException = sqlException, Message = message, Sql = sql != null ? sql.ToString() : null
     }));
 }
示例#9
0
        public static Exception Convert(ISQLExceptionConverter converter, Exception sqle, string message, SqlString sql,
                                        object[] parameterValues, IDictionary <string, TypedValue> namedParameters)
        {
            sql = TryGetActualSqlQuery(sqle, sql);
            string extendMessage = ExtendMessage(message, sql != null ? sql.ToString() : null, parameterValues, namedParameters);

            ADOExceptionReporter.LogExceptions(sqle, extendMessage);
            return(Convert(converter, sqle, extendMessage, sql));
        }
示例#10
0
        public ExecutionService(InternalDbContext dbContext)
        {
            this.dbContext = dbContext;
            log            = dbContext.Log;

            if (exceptionConverter == null)
            {
                exceptionConverter = new SqlExceptionConverter();
            }
        }
示例#11
0
 public static Exception Convert(ISqlLog log, ISQLExceptionConverter converter, DbExceptionContextInfo exceptionContextInfo)
 {
     if (exceptionContextInfo == null)
     {
         throw new ArgumentNullException("The argument exceptionContextInfo is null.");
     }
     var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);
     log.Error(exceptionContextInfo.SqlException,
                                        ExtendMessage(exceptionContextInfo.Message, sql));
     return converter.Convert(exceptionContextInfo);
 }
		public static Exception Convert(ISQLExceptionConverter converter, AdoExceptionContextInfo exceptionContextInfo)
		{
			if(exceptionContextInfo == null)
			{
				throw new AssertionFailure("The argument exceptionContextInfo is null.");
			}
			var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);
			ADOExceptionReporter.LogExceptions(exceptionContextInfo.SqlException,
			                                   ExtendMessage(exceptionContextInfo.Message, sql, null, null));
			return converter.Convert(exceptionContextInfo);
		}
示例#13
0
        public static Exception Convert(ILogger log, ISQLExceptionConverter converter, DbExceptionContextInfo exceptionContextInfo)
        {
            //if (exceptionContextInfo == null)
            //{
            //    throw new ArgumentNullException("The argument exceptionContextInfo is null.");
            //}
            var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);

            //log.Log(LogLevel.Error, exceptionContextInfo.SqlException,
            //                                   ExtendMessage(exceptionContextInfo.Message, sql));
            return(converter.Convert(exceptionContextInfo));
        }
示例#14
0
        public static Exception Convert(ISQLExceptionConverter converter, AdoExceptionContextInfo exceptionContextInfo)
        {
            if (exceptionContextInfo == null)
            {
                throw new AssertionFailure("The argument exceptionContextInfo is null.");
            }
            var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);

            ADOExceptionReporter.LogExceptions(exceptionContextInfo.SqlException,
                                               ExtendMessage(exceptionContextInfo.Message, sql, null, null));
            return(converter.Convert(exceptionContextInfo));
        }
示例#15
0
        public static Exception Convert(ISqlLog log, ISQLExceptionConverter converter, DbExceptionContextInfo exceptionContextInfo)
        {
            if (exceptionContextInfo == null)
            {
                throw new ArgumentNullException("The argument exceptionContextInfo is null.");
            }
            var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);

            log.Error(exceptionContextInfo.SqlException,
                      ExtendMessage(exceptionContextInfo.Message, sql));
            return(converter.Convert(exceptionContextInfo));
        }
示例#16
0
        public void BadGrammar()
        {
            if (Dialect is SQLiteDialect)
            {
                Assert.Ignore("Example exception converter not implemented.");
            }

            //ISQLExceptionConverter converter = Dialect.BuildSQLExceptionConverter();
            ISQLExceptionConverter converter = sessions.Settings.SqlExceptionConverter;

            ISession      session    = OpenSession();
            IDbConnection connection = session.Connection;

            // prepare/execute a query against a non-existent table
            IDbCommand ps = null;

            try
            {
                ps             = connection.CreateCommand();
                ps.CommandType = CommandType.Text;
                ps.CommandText = "SELECT user_id, user_name FROM tbl_no_there";
                ps.ExecuteNonQuery();

                Assert.Fail("SQL compilation should have failed");
            }
            catch (Exception sqle)
            {
                Assert.AreEqual(typeof(SQLGrammarException),
                                converter.Convert(new AdoExceptionContextInfo {
                    SqlException = sqle
                }).GetType(),
                                "Bad conversion [" + sqle.Message + "]");
            }
            finally
            {
                if (ps != null)
                {
                    try
                    {
                        ps.Dispose();
                    }
                    catch (Exception)
                    {
                        // ignore...
                    }
                }
            }

            session.Close();
        }
示例#17
0
        public static Exception Convert(ISqlLog log, ISQLExceptionConverter converter,DbExceptionContextInfo exceptionContextInfo,
                                           object[] parameterValues, NamedParameter[] namedParameters)
        {
            var sql = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);
            string extendMessage = ExtendMessage(
                exceptionContextInfo.Message,
                sql != null ? sql.ToString() : null,
                exceptionContextInfo.Entity,
                parameterValues,
                namedParameters);
            log.Error(exceptionContextInfo.SqlException, extendMessage);

            return converter.Convert(exceptionContextInfo);
        }
示例#18
0
        public static Exception Convert(ISqlLog log, ISQLExceptionConverter converter, DbExceptionContextInfo exceptionContextInfo,
                                        object[] parameterValues, NamedParameter[] namedParameters)
        {
            var    sql           = TryGetActualSqlQuery(exceptionContextInfo.SqlException, exceptionContextInfo.Sql);
            string extendMessage = ExtendMessage(
                exceptionContextInfo.Message,
                sql != null ? sql.ToString() : null,
                exceptionContextInfo.Entity,
                parameterValues,
                namedParameters);

            log.Error(exceptionContextInfo.SqlException, extendMessage);

            return(converter.Convert(exceptionContextInfo));
        }
		/// <summary> 
		/// Converts the given SQLException into Exception hierarchy, as well as performing
		/// appropriate logging. 
		/// </summary>
		/// <param name="converter">The converter to use.</param>
		/// <param name="sqlException">The exception to convert.</param>
		/// <param name="message">An optional error message.</param>
		/// <returns> The converted <see cref="ADOException"/>.</returns>
		public static Exception Convert(ISQLExceptionConverter converter, Exception sqlException, string message)
		{
			var sql = TryGetActualSqlQuery(sqlException, SQLNotAvailable);
			return Convert(converter, new AdoExceptionContextInfo {SqlException = sqlException, Message = message, Sql = sql});
		}
		public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg,
		                                   ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			if (factory.Settings.IsStructuredCacheEntriesEnabled)
			{
				cacheEntryStructure = collection.IsMap
				                      	? (ICacheEntryStructure) new StructuredMapCacheEntry()
				                      	: (ICacheEntryStructure) new StructuredCollectionCacheEntry();
			}
			else
			{
				cacheEntryStructure = new UnstructuredCacheEntry();
			}

			dialect = factory.Dialect;
			sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			entityName = collection.OwnerEntityName;
			ownerPersister = factory.GetEntityPersister(entityName);
			queryLoaderName = collection.LoaderName;
			nodeName = collection.NodeName;
			isMutable = collection.IsMutable;

			Table table = collection.CollectionTable;
			fetchMode = collection.Element.FetchMode;
			elementType = collection.Element.Type;
			isPrimitiveArray = collection.IsPrimitiveArray;
			isArray = collection.IsArray;
			subselectLoadable = collection.IsSubselectLoadable;
			qualifiedTableName = table.GetQualifiedName(dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);

			int spacesSize = 1 + collection.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			int ispa = 0;
			spaces[ispa++] = qualifiedTableName;
			foreach (string s in collection.SynchronizedTables)
			{
				spaces[ispa++] = s;
			}

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder
			                           	? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect,
			                           	                                       factory.SQLFunctionRegistry)
			                           	: null;
			sqlWhereString = !string.IsNullOrEmpty(collection.Where) ? '(' + collection.Where + ')' : null;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere
			                         	? Template.RenderWhereStringTemplate(sqlWhereString, dialect, factory.SQLFunctionRegistry)
			                         	: null;
			hasOrphanDelete = collection.HasOrphanDelete;
			int batch = collection.BatchSize;
			if (batch == -1)
			{
				batch = factory.Settings.DefaultBatchFetchSize;
			}
			batchSize = batch;

			isVersioned = collection.IsOptimisticLocked;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			keyColumnAliases = new string[keySpan];
			int k = 0;
			foreach (Column col in collection.Key.ColumnIterator)
			{
				keyColumnNames[k] = col.GetQuotedName(dialect);
				keyColumnAliases[k] = col.GetAlias(dialect);
				k++;
			}
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication(distinctColumns, collection.Key.ColumnIterator);

			#region Element

			IValue element = collection.Element;
			if (!collection.IsOneToMany)
			{
				CheckColumnDuplication(distinctColumns, element.ColumnIterator);
			}

			string elemNode = collection.ElementNodeName;
			if (elementType.IsEntityType)
			{
				string _entityName = ((EntityType) elementType).GetAssociatedEntityName();
				elementPersister = factory.GetEntityPersister(_entityName);
				if (elemNode == null)
				{
					elemNode = cfg.GetClassMapping(_entityName).NodeName;
				}
				// NativeSQL: collect element column and auto-aliases
			}
			else
			{
				elementPersister = null;
			}
			elementNodeName = elemNode;

			int elementSpan = element.ColumnSpan;
			elementColumnAliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			elementFormulaTemplates = new string[elementSpan];
			elementFormulas = new string[elementSpan];
			elementColumnIsSettable = new bool[elementSpan];
			elementColumnIsInPrimaryKey = new bool[elementSpan];
			bool isPureFormula = true;
			bool hasNotNullableColumns = false;
			int j = 0;
			foreach (ISelectable selectable in element.ColumnIterator)
			{
				elementColumnAliases[j] = selectable.GetAlias(dialect);
				if (selectable.IsFormula)
				{
					Formula form = (Formula) selectable;
					elementFormulaTemplates[j] = form.GetTemplate(dialect, factory.SQLFunctionRegistry);
					elementFormulas[j] = form.FormulaString;
				}
				else
				{
					Column col = (Column) selectable;
					elementColumnNames[j] = col.GetQuotedName(dialect);
					elementColumnIsSettable[j] = true;
					elementColumnIsInPrimaryKey[j] = !col.IsNullable;
					if (!col.IsNullable)
					{
						hasNotNullableColumns = true;
					}

					isPureFormula = false;
				}
				j++;
			}
			elementIsPureFormula = isPureFormula;

			//workaround, for backward compatibility of sets with no
			//not-null columns, assume all columns are used in the
			//row locator SQL
			if (!hasNotNullableColumns)
			{
				ArrayHelper.Fill(elementColumnIsInPrimaryKey, true);
			}

			#endregion

			#region INDEX AND ROW SELECT

			hasIndex = collection.IsIndexed;
			if (hasIndex)
			{
				// NativeSQL: collect index column and auto-aliases
				IndexedCollection indexedCollection = (IndexedCollection) collection;
				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];
				indexFormulaTemplates = new string[indexSpan];
				indexFormulas = new string[indexSpan];
				indexColumnIsSettable = new bool[indexSpan];
				indexColumnAliases = new string[indexSpan];
				bool hasFormula = false;
				int i = 0;
				foreach (ISelectable selectable in indexedCollection.Index.ColumnIterator)
				{
					indexColumnAliases[i] = selectable.GetAlias(dialect);
					if (selectable.IsFormula)
					{
						Formula indexForm = (Formula) selectable;
						indexFormulaTemplates[i] = indexForm.GetTemplate(dialect, factory.SQLFunctionRegistry);
						indexFormulas[i] = indexForm.FormulaString;
						hasFormula = true;
					}
					else
					{
						Column indexCol = (Column) selectable;
						indexColumnNames[i] = indexCol.GetQuotedName(dialect);
						indexColumnIsSettable[i] = true;
					}
					i++;
				}
				indexContainsFormula = hasFormula;
				baseIndex = indexedCollection.IsList ? ((List) indexedCollection).BaseIndex : 0;

				indexNodeName = indexedCollection.IndexNodeName;
				CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnIterator);
			}
			else
			{
				indexContainsFormula = false;
				indexColumnIsSettable = null;
				indexFormulaTemplates = null;
				indexFormulas = null;
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
				baseIndex = 0;
				indexNodeName = null;
			}

			hasIdentifier = collection.IsIdentified;
			if (hasIdentifier)
			{
				if (collection.IsOneToMany)
				{
					throw new MappingException("one-to-many collections with identifiers are not supported.");
				}
				IdentifierCollection idColl = (IdentifierCollection) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach (Column column in idColl.Identifier.ColumnIterator)
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName(dialect);
				identifierColumnAlias = col.GetAlias(dialect);
				identifierGenerator =
					idColl.Identifier.CreateIdentifierGenerator(factory.Dialect, factory.Settings.DefaultCatalogName,
					                                            factory.Settings.DefaultSchemaName, null);
				// NH see : identityDelegate declaration
				IPostInsertIdentifierGenerator pig = (identifierGenerator as IPostInsertIdentifierGenerator);
				if (pig != null)
				{
					identityDelegate = pig.GetInsertGeneratedIdentifierDelegate(this, Factory, UseGetGeneratedKeys());
				}
				else
				{
					identityDelegate = null;
				}

				CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnIterator);
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				identifierGenerator = null;
				identityDelegate = null;
			}

			#endregion

			#region GENERATE THE SQL

			// NH Different behavior : for the Insert SQL we are managing isPostInsertIdentifier (not supported in H3.2.5) 
			if (collection.CustomSQLInsert == null)
			{
				if (!IsIdentifierAssignedByInsert)
				{
					sqlInsertRowString = GenerateInsertRowString();
				}
				else
				{
					sqlInsertRowString = GenerateIdentityInsertRowString();
				}
				insertCallable = false;
				insertCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				SqlType[] parmsTypes = GenerateInsertRowString().ParameterTypes;
				sqlInsertRowString = new SqlCommandInfo(collection.CustomSQLInsert, parmsTypes);
				insertCallable = collection.IsCustomInsertCallable;
				insertCheckStyle = collection.CustomSQLInsertCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLInsert, insertCallable);
			}

			sqlUpdateRowString = GenerateUpdateRowString();
			if (collection.CustomSQLUpdate == null)
			{
				updateCallable = false;
				updateCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlUpdateRowString = new SqlCommandInfo(collection.CustomSQLUpdate, sqlUpdateRowString.ParameterTypes);
				updateCallable = collection.IsCustomUpdateCallable;
				updateCheckStyle = collection.CustomSQLUpdateCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLUpdate, updateCallable);
			}

			sqlDeleteRowString = GenerateDeleteRowString();
			if (collection.CustomSQLDelete == null)
			{
				deleteCallable = false;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteRowString = new SqlCommandInfo(collection.CustomSQLDelete, sqlDeleteRowString.ParameterTypes);
				deleteCallable = collection.IsCustomDeleteCallable;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			sqlDeleteString = GenerateDeleteString();
			if (collection.CustomSQLDeleteAll == null)
			{
				deleteAllCallable = false;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteString = new SqlCommandInfo(collection.CustomSQLDeleteAll, sqlDeleteString.ParameterTypes);
				deleteAllCallable = collection.IsCustomDeleteAllCallable;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

		    isCollectionIntegerIndex = collection.IsIndexed && !collection.IsMap;
			sqlDetectRowByIndexString = GenerateDetectRowByIndexString();
			sqlDetectRowByElementString = GenerateDetectRowByElementString();
			sqlSelectRowByIndexString = GenerateSelectRowByIndexString();

			LogStaticSQL();

			#endregion

			isLazy = collection.IsLazy;
			isExtraLazy = collection.ExtraLazy;
			isInverse = collection.IsInverse;

			if (collection.IsArray)
			{
				elementClass = ((Array) collection).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			if (elementType.IsComponentType)
			{
				elementPropertyMapping =
					new CompositeElementPropertyMapping(elementColumnNames, elementFormulaTemplates,
					                                    (IAbstractComponentType) elementType, factory);
			}
			else if (!elementType.IsEntityType)
			{
				elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
			}
			else
			{
				elementPropertyMapping = elementPersister as IPropertyMapping;
				if (elementPropertyMapping == null)
				{
					elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
				}
			}

			// Handle any filters applied to this collection
			filterHelper = new FilterHelper(collection.FilterMap, dialect, factory.SQLFunctionRegistry);

			// Handle any filters applied to this collection for many-to-many
			manyToManyFilterHelper = new FilterHelper(collection.ManyToManyFilterMap, dialect, factory.SQLFunctionRegistry);
			manyToManyWhereString = !string.IsNullOrEmpty(collection.ManyToManyWhere)
			                        	? "( " + collection.ManyToManyWhere + " )"
			                        	: null;
			manyToManyWhereTemplate = manyToManyWhereString == null
			                          	? null
			                          	: Template.RenderWhereStringTemplate(manyToManyWhereString, factory.Dialect,
			                          	                                     factory.SQLFunctionRegistry);
			manyToManyOrderByString = collection.ManyToManyOrdering;
			manyToManyOrderByTemplate = manyToManyOrderByString == null
			                            	? null
			                            	: Template.RenderOrderByStringTemplate(manyToManyOrderByString, factory.Dialect,
			                            	                                       factory.SQLFunctionRegistry);
			InitCollectionPropertyMap();
		}
示例#21
0
        public void IntegrityViolation()
        {
            //ISQLExceptionConverter converter = Dialect.BuildSQLExceptionConverter();
            ISQLExceptionConverter converter = sessions.Settings.SqlExceptionConverter;

            ISession session = OpenSession();

            session.BeginTransaction();
            IDbConnection connection = session.Connection;

            // Attempt to insert some bad values into the T_MEMBERSHIP table that should
            // result in a constraint violation
            IDbCommand ps = null;

            try
            {
                ps             = connection.CreateCommand();
                ps.CommandType = CommandType.Text;
                ps.CommandText = "INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (@p1, @p2)";
                IDbDataParameter pr = ps.CreateParameter();
                pr.ParameterName = "p1";
                pr.DbType        = DbType.Int64;
                pr.Value         = 52134241L;         // Non-existent user_id
                ps.Parameters.Add(pr);

                pr = ps.CreateParameter();
                pr.ParameterName = "p2";
                pr.DbType        = DbType.Int64;
                pr.Value         = 5342L;         // Non-existent group_id
                ps.Parameters.Add(pr);

                session.Transaction.Enlist(ps);
                ps.ExecuteNonQuery();

                Assert.Fail("INSERT should have failed");
            }
            catch (Exception sqle)
            {
                ADOExceptionReporter.LogExceptions(sqle, "Just output!!!!");
                Exception adoException = converter.Convert(new AdoExceptionContextInfo {
                    SqlException = sqle
                });
                Assert.AreEqual(typeof(ConstraintViolationException), adoException.GetType(),
                                "Bad conversion [" + sqle.Message + "]");
                ConstraintViolationException ex = (ConstraintViolationException)adoException;
                Console.WriteLine("Violated constraint name: " + ex.ConstraintName);
            }
            finally
            {
                if (ps != null)
                {
                    try
                    {
                        ps.Dispose();
                    }
                    catch (Exception)
                    {
                        // ignore...
                    }
                }
            }

            session.Transaction.Rollback();
            session.Close();
        }
示例#22
0
 /// <summary> 
 /// Converts the given SQLException into NHibernate's ADOException hierarchy, as well as performing
 /// appropriate logging. 
 /// </summary>
 /// <param name="converter">The converter to use.</param>
 /// <param name="sqlException">The exception to convert.</param>
 /// <param name="message">An optional error message.</param>
 /// <returns> The converted <see cref="ADOException"/>.</returns>
 public static ADOException Convert(ISQLExceptionConverter converter, Exception sqlException, string message)
 {
     return Convert(converter, sqlException, message, new SqlString(SQLNotAvailable));
 }
示例#23
0
 /// <summary> 
 /// Converts the given SQLException into NHibernate's ADOException hierarchy, as well as performing
 /// appropriate logging. 
 /// </summary>
 /// <param name="converter">The converter to use.</param>
 /// <param name="sqlException">The exception to convert.</param>
 /// <param name="message">An optional error message.</param>
 /// <param name="sql">The SQL executed.</param>
 /// <returns> The converted <see cref="ADOException"/>.</returns>
 public static ADOException Convert(ISQLExceptionConverter converter, Exception sqlException, string message, SqlString sql)
 {
     ADOExceptionReporter.LogExceptions(sqlException, ExtendMessage(message, sql, null, null));
     return converter.Convert(sqlException, message, sql);
 }