public Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException; if (sqle != null) { switch (sqle.Number) { case 17: // SQL Server does not exist or access denied. case 4060: // Invalid Database case 18456: // Login Failed return new DatabaseException(sqle.Message, sqle); case 547: // ForeignKey Violation return new ConstraintException(_ParseConstraintName(sqle.Message), sqle); case 1205: // DeadLock Victim return new DatabaseException(sqle.Message, sqle); case 2627: case 2601: // Unique Index/Constriant Violation return new ConstraintException(_ParseConstraintName(sqle.Message), sqle); default: // throw a general DAL Exception return new DatabaseException(sqle.Message, sqle); } } return SQLStateConverter.HandledNonSpecificException( exInfo.SqlException, exInfo.Message, exInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo exInfo) { //var dbException = ADOExceptionHelper.ExtractDbException(exInfo.SqlException); //var textoResource = String.Empty; //// SQLite exception //switch (dbException.ErrorCode) //{ // case 2601://Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls. // textoResource = _resource.GetString("DadoDuplicadoNaoPermitido"); //Repetição não permitida para o campo {0}. // //return new BusinessException(campo, erro);//DadoDuplicadoNaoPermitido // case 233: // textoResource = _resource.GetString("ValorNuloNaoPermitido"); // //return new BusinessException(campo, erro);//DadoDuplicadoNaoPermitido // default: // throw new InvalidOperationException(String.Format("ExtendedError {0} não mapeado", erro)); //} throw new NotImplementedException(); }
public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { DbException sqlException = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException); string message = adoExceptionContextInfo.Message; string sql = adoExceptionContextInfo.Sql; int errorCode = (int)sqlException.GetType().GetProperty("NativeError").GetValue(sqlException, null); if (errorCode >= 1 && errorCode <= 90) { return(new SQLGrammarException(message, sqlException, sql)); } if (integrityViolationCategories.Contains(errorCode)) { string constraintName = extracter.ExtractConstraintName(sqlException); return(new ConstraintViolationException(message, sqlException, sql, constraintName)); } if (connectionCategories.Contains(errorCode)) { return(new ADOConnectionException(message, sqlException, sql)); } if (dataCategories.Contains(errorCode)) { return(new DataException(message, sqlException, sql)); } return(HandledNonSpecificException(sqlException, message, sql)); }
public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { DbException sqlException = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException); string message = adoExceptionContextInfo.Message; string sql = adoExceptionContextInfo.Sql; int errorCode = (int)sqlException.GetType().GetProperty("NativeError").GetValue(sqlException, null); if (errorCode >= 1 && errorCode <= 90) { return new SQLGrammarException(message, sqlException, sql); } if (integrityViolationCategories.Contains(errorCode)) { string constraintName = extracter.ExtractConstraintName(sqlException); return new ConstraintViolationException(message, sqlException, sql, constraintName); } if (connectionCategories.Contains(errorCode)) { return new ADOConnectionException(message, sqlException, sql); } if (dataCategories.Contains(errorCode)) { return new DataException(message, sqlException, sql); } return HandledNonSpecificException(sqlException, message, sql); }
public Exception Convert(AdoExceptionContextInfo contextInfo) { Exception result = null; var sqle = ADOExceptionHelper.ExtractDbException(contextInfo.SqlException) as SqlException; if (sqle != null) { switch (sqle.Number) { case 547: result = new ConstraintViolationException( sqle.Message, sqle, contextInfo.Sql, null); break; case 208: result = new SQLGrammarException( contextInfo.Message, sqle, contextInfo.Sql); break; case 3960: result = new StaleObjectStateException( contextInfo.EntityName, contextInfo.EntityId); break; } } return result ?? SQLStateConverter.HandledNonSpecificException( contextInfo.SqlException, contextInfo.Message, contextInfo.Sql); }
/// <summary> /// Converts the db specific exceptions to something more usable. /// </summary> /// <param name="exInfo">The exception info.</param> /// <returns>Exception thrown</returns> public System.Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException; var finalException = Convert(sqle, exInfo); return finalException; }
public Exception Convert(AdoExceptionContextInfo exInfo) { var dbException = ADOExceptionHelper.ExtractDbException(exInfo.SqlException); var ns = dbException.GetType().Namespace ?? string.Empty; if (ns.ToLowerInvariant().StartsWith("system.data.sqlite")) { // SQLite exception switch (dbException.ErrorCode) { case -2147467259: // Abort due to constraint violation throw new ConcurrencyException(); } } if (ns.ToLowerInvariant().StartsWith("system.data.sqlclient")) { // MS SQL Server switch (dbException.ErrorCode) { case -2146232060: throw new ConcurrencyException(); } } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
/// <summary> /// Converts the specified sqle. /// </summary> /// <param name="sqle">The sqle.</param> /// <param name="exInfo">The ex info.</param> /// <returns>Exception thrown by NHibernate</returns> private System.Exception Convert(SqlException sqle, AdoExceptionContextInfo exInfo) { System.Exception finalException; if (sqle != null) { switch (sqle.Number) { case 17: // SQL Server does not exist or access denied. case 4060: // Invalid Database case 18456: // Login Failed finalException = new DbLoginException(sqle.Message, sqle); break; case 1205: // DeadLock Victim finalException = new DbDeadLockException(sqle.Message, sqle); break; case 2627: case 2601: // Unique Index/Constriant Violation finalException = new DbUniqueConstraintException(sqle.Message, sqle); break; case 547: finalException = new DbForeignKeyException(sqle.Message, sqle); break; case 208: finalException = new SQLGrammarException( exInfo.Message, sqle.InnerException, exInfo.Sql); break; case 3960: // in case of snapshot isolation finalException = new StaleObjectStateException(exInfo.EntityName, exInfo.EntityId); break; default: finalException = SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); break; } } else { finalException = SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); } return finalException; }
public Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException; if ((sqle != null) && (sqle.Number == 3960)) { return new StaleObjectStateException(exInfo.EntityName, exInfo.EntityId); } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo exceptionInfo) { /* * So far I know we don't have something similar to "X/Open-compliant SQLState" in .NET * This mean that each Dialect must have its own ISQLExceptionConverter, overriding BuildSQLExceptionConverter method, * and its own IViolatedConstraintNameExtracter if needed. * The System.Data.Common.DbException, of .NET2.0, don't give us something applicable to all dialects. */ return(HandledNonSpecificException(exceptionInfo.SqlException, exceptionInfo.Message, exceptionInfo.Sql)); }
public Exception Convert(AdoExceptionContextInfo exceptionInfo) { /* * So far I know we don't have something similar to "X/Open-compliant SQLState" in .NET * This mean that each Dialect must have its own ISQLExceptionConverter, overriding BuildSQLExceptionConverter method, * and its own IViolatedConstraintNameExtracter if needed. * The System.Data.Common.DbException, of .NET2.0, don't give us something applicable to all dialects. */ return HandledNonSpecificException(exceptionInfo.SqlException, exceptionInfo.Message, exceptionInfo.Sql); }
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); }
public Exception Convert(AdoExceptionContextInfo exInfo) { SqlException sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException; if(sqle != null) { if (sqle.Number == 547) return new ConstraintViolationException(exInfo.Message, sqle.InnerException, exInfo.Sql, null); if (sqle.Number == 208) return new SQLGrammarException(exInfo.Message, sqle.InnerException, exInfo.Sql); } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
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)); }
public Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as OracleException; if (sqle != null) { if (sqle.Code == 1036) { return new ConstraintViolationException(exInfo.Message, sqle.InnerException, exInfo.Sql, null); } if (sqle.Code == 942) { return new SQLGrammarException(exInfo.Message, sqle.InnerException, exInfo.Sql); } } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { var sqle = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException) as DbException; if (sqle != null) { if (sqle.ErrorCode == 335544466) { return new ConstraintViolationException(adoExceptionContextInfo.Message, sqle.InnerException, adoExceptionContextInfo.Sql, null); } if (sqle.ErrorCode == 335544569) { return new SQLGrammarException(adoExceptionContextInfo.Message, sqle.InnerException, adoExceptionContextInfo.Sql); } } return SQLStateConverter.HandledNonSpecificException(adoExceptionContextInfo.SqlException, adoExceptionContextInfo.Message, adoExceptionContextInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as DbException; if (sqle != null) { string code = (string)sqle.GetType().GetProperty("Code").GetValue(sqle, null); if (code == "23503") { return new ConstraintViolationException(exInfo.Message, sqle.InnerException, exInfo.Sql, null); } if (code == "42P01") { return new SQLGrammarException(exInfo.Message, sqle.InnerException, exInfo.Sql); } } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
/// <summary> /// 转换 /// </summary> /// <param name="adoExceptionContextInfo"></param> /// <returns></returns> public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { var sqle = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException) as SqlException; if (sqle != null) { switch (sqle.Number) { case 547: case 2627: return new ConstraintViolationException(adoExceptionContextInfo.SqlException.Message, null, adoExceptionContextInfo.Sql, null); case 208: return new SQLGrammarException(adoExceptionContextInfo.SqlException.Message, null, adoExceptionContextInfo.Sql); case 3960: return new StaleObjectStateException(adoExceptionContextInfo.EntityName, adoExceptionContextInfo.EntityId); } } return SQLStateConverter.HandledNonSpecificException(adoExceptionContextInfo.SqlException, adoExceptionContextInfo.SqlException.Message, adoExceptionContextInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo exInfo) { var dbException = ADOExceptionHelper.ExtractDbException(exInfo.SqlException); var erro = ErrorDescription(dbException.Message); var campo = SQLiteErrorField(dbException.Message); // SQLite exception switch (dbException.ErrorCode) { case 19: // violação de constraint return WorkOnExtendedError(erro, campo); default: throw new InvalidOperationException(String.Format("Error code {0} não mapeado", dbException.ErrorCode)); //return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, //exInfo.Message, exInfo.Sql); } }
public Exception Convert(AdoExceptionContextInfo exInfo) { var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException; if (sqle != null) { switch (sqle.Number) { case -2: // timeout case -2147217871: // timeout case 11: // network error case 1205: // deadlock return new TransientErrorException("Temporary db error occured. Try again later.", sqle); // case 208: // sql grammar // case 547: // constraint violation // case 3960: // stale object state (does not occur with ReadCommitted isolation level). Should trigger reload on client side default: return new ApplicationException("DB error", sqle); } } return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException, exInfo.Message, exInfo.Sql); }
public virtual object[] GetNaturalIdentifierSnapshot(object id, ISessionImplementor session) { if (!HasNaturalIdentifier) { throw new MappingException("persistent class did not define a natural-id : " + MessageHelper.InfoString(this)); } if (log.IsDebugEnabled) { log.Debug("Getting current natural-id snapshot state for: " + MessageHelper.InfoString(this, id, Factory)); } int[] naturalIdPropertyIndexes = NaturalIdentifierProperties; int naturalIdPropertyCount = naturalIdPropertyIndexes.Length; bool[] naturalIdMarkers = new bool[PropertySpan]; IType[] extractionTypes = new IType[naturalIdPropertyCount]; for (int i = 0; i < naturalIdPropertyCount; i++) { extractionTypes[i] = PropertyTypes[naturalIdPropertyIndexes[i]]; naturalIdMarkers[naturalIdPropertyIndexes[i]] = true; } /////////////////////////////////////////////////////////////////////// // TODO : look at perhaps caching this... SqlSelectBuilder select = new SqlSelectBuilder(Factory); if (Factory.Settings.IsCommentsEnabled) { select.SetComment("get current natural-id state " + EntityName); } select.SetSelectClause(ConcretePropertySelectFragmentSansLeadingComma(RootAlias, naturalIdMarkers)); select.SetFromClause(FromTableFragment(RootAlias) + FromJoinFragment(RootAlias, true, false)); string[] aliasedIdColumns = StringHelper.Qualify(RootAlias, IdentifierColumnNames); SqlString whereClause = new SqlStringBuilder() .Add(StringHelper.Join(new SqlString("=", Parameter.Placeholder, " and "), aliasedIdColumns)) .Add("=").AddParameter() .Add(WhereJoinFragment(RootAlias, true, false)) .ToSqlString(); SqlString sql = select.SetOuterJoins(SqlString.Empty, SqlString.Empty).SetWhereClause(whereClause).ToStatementString(); /////////////////////////////////////////////////////////////////////// object[] snapshot = new object[naturalIdPropertyCount]; using (new SessionIdLoggingContext(session.SessionId)) try { IDbCommand ps = session.Batcher.PrepareCommand(CommandType.Text, sql, IdentifierType.SqlTypes(factory)); IDataReader rs = null; try { IdentifierType.NullSafeSet(ps, id, 0, session); rs = session.Batcher.ExecuteReader(ps); //if there is no resulting row, return null if (!rs.Read()) { return null; } for (int i = 0; i < naturalIdPropertyCount; i++) { snapshot[i] = extractionTypes[i].Hydrate(rs, GetPropertyAliases(string.Empty, naturalIdPropertyIndexes[i]), session, null); if (extractionTypes[i].IsEntityType) { snapshot[i] = extractionTypes[i].ResolveIdentifier(snapshot[i], session, null); } } return snapshot; } finally { session.Batcher.CloseCommand(ps, rs); } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not retrieve snapshot: " + MessageHelper.InfoString(this, id, Factory), Sql = sql.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
/// <summary> /// Perform an SQL DELETE /// </summary> public void Delete(object id, object version, int j, object obj, SqlCommandInfo sql, ISessionImplementor session, object[] loadedState) { if (IsInverseTable(j)) { return; } // NH : Only use version if lock mode is Version bool useVersion = j == 0 && IsVersioned && Versioning.OptimisticLock.Version == entityMetamodel.OptimisticLockMode; //bool callable = IsDeleteCallable(j); IExpectation expectation = Expectations.AppropriateExpectation(deleteResultCheckStyles[j]); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; if (log.IsDebugEnabled) { log.Debug("Deleting entity: " + MessageHelper.InfoString(this, id, Factory)); if (useVersion) { log.Debug("Version: " + version); } } if (IsTableCascadeDeleteEnabled(j)) { if (log.IsDebugEnabled) { log.Debug("delete handled by foreign key constraint: " + GetTableName(j)); } return; //EARLY EXIT! } try { int index = 0; IDbCommand statement; if (useBatch) { statement = session.Batcher.PrepareBatchCommand(sql.CommandType, sql.Text, sql.ParameterTypes); } else { statement = session.Batcher.PrepareCommand(sql.CommandType, sql.Text, sql.ParameterTypes); } try { //index += expectation.Prepare(statement, factory.ConnectionProvider.Driver); // Do the key. The key is immutable so we can use the _current_ object state - not necessarily // the state at the time the delete was issued IdentifierType.NullSafeSet(statement, id, index, session); index += IdentifierColumnSpan; // We should use the _current_ object state (ie. after any updates that occurred during flush) if (useVersion) { VersionType.NullSafeSet(statement, version, index, session); } else if (entityMetamodel.OptimisticLockMode > Versioning.OptimisticLock.Version && loadedState != null) { bool[] versionability = PropertyVersionability; IType[] types = PropertyTypes; for (int i = 0; i < entityMetamodel.PropertySpan; i++) { if (IsPropertyOfTable(i, j) && versionability[i]) { // this property belongs to the table and it is not specifically // excluded from optimistic locking by optimistic-lock="false" bool[] settable = types[i].ToColumnNullness(loadedState[i], Factory); types[i].NullSafeSet(statement, loadedState[i], index, settable, session); index += ArrayHelper.CountTrue(settable); } } } if (useBatch) { session.Batcher.AddToBatch(expectation); } else { Check(session.Batcher.ExecuteNonQuery(statement), id, j, expectation, statement); } } catch (Exception e) { if (useBatch) { session.Batcher.AbortBatch(e); } throw; } finally { if (!useBatch) { session.Batcher.CloseCommand(statement, null); } } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not delete: " + MessageHelper.InfoString(this, id, Factory), Sql = sql.Text.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
private void ProcessGeneratedProperties(object id, object entity, object[] state, ISessionImplementor session, SqlString selectionSQL, ValueInclusion[] includeds) { session.Batcher.ExecuteBatch(); //force immediate execution of the insert using (new SessionIdLoggingContext(session.SessionId)) try { IDbCommand cmd = session.Batcher.PrepareQueryCommand(CommandType.Text, selectionSQL, IdentifierType.SqlTypes(Factory)); IDataReader rs = null; try { IdentifierType.NullSafeSet(cmd, id, 0, session); rs = session.Batcher.ExecuteReader(cmd); if (!rs.Read()) { throw new HibernateException("Unable to locate row for retrieval of generated properties: " + MessageHelper.InfoString(this, id, Factory)); } for (int i = 0; i < PropertySpan; i++) { if (includeds[i] != ValueInclusion.None) { object hydratedState = PropertyTypes[i].Hydrate(rs, GetPropertyAliases(string.Empty, i), session, entity); state[i] = PropertyTypes[i].ResolveIdentifier(hydratedState, session, entity); SetPropertyValue(entity, i, state[i], session.EntityMode); } } } finally { session.Batcher.CloseCommand(cmd, rs); } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "unable to select generated column values", Sql = selectionSQL.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
/// <summary> /// Perform an SQL INSERT. /// </summary> /// <remarks> /// This for is used for all non-root tables as well as the root table /// in cases where the identifier value is known before the insert occurs. /// </remarks> protected void Insert(object id, object[] fields, bool[] notNull, int j, SqlCommandInfo sql, object obj, ISessionImplementor session) { if (IsInverseTable(j)) { return; } //note: it is conceptually possible that a UserType could map null to // a non-null value, so the following is arguable: if (IsNullableTable(j) && IsAllNull(fields, j)) { return; } if (log.IsDebugEnabled) { log.Debug("Inserting entity: " + MessageHelper.InfoString(this, id, Factory)); if (j == 0 && IsVersioned) { log.Debug("Version: " + Versioning.GetVersion(fields, this)); } } IExpectation expectation = Expectations.AppropriateExpectation(insertResultCheckStyles[j]); //bool callable = IsInsertCallable(j); // we can't batch joined inserts, *especially* not if it is an identity insert; // nor can we batch statements where the expectation is based on an output param bool useBatch = j == 0 && expectation.CanBeBatched; try { // Render the SQL query IDbCommand insertCmd = useBatch ? session.Batcher.PrepareBatchCommand(sql.CommandType, sql.Text, sql.ParameterTypes) : session.Batcher.PrepareCommand(sql.CommandType, sql.Text, sql.ParameterTypes); try { int index = 0; //index += expectation.Prepare(insertCmd, factory.ConnectionProvider.Driver); // Write the values of the field onto the prepared statement - we MUST use the // state at the time the insert was issued (cos of foreign key constraints). // Not necessarily the obect's current state Dehydrate(id, fields, null, notNull, propertyColumnInsertable, j, insertCmd, session, index); if (useBatch) { session.Batcher.AddToBatch(expectation); } else { expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(insertCmd), insertCmd); } } catch (Exception e) { if (useBatch) { session.Batcher.AbortBatch(e); } throw; } finally { if (!useBatch) { session.Batcher.CloseCommand(insertCmd, null); } } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not insert: " + MessageHelper.InfoString(this, id), Sql = sql.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
protected bool Update(object id, object[] fields, object[] oldFields, object rowId, bool[] includeProperty, int j, object oldVersion, object obj, SqlCommandInfo sql, ISessionImplementor session) { bool useVersion = j == 0 && IsVersioned; IExpectation expectation = Expectations.AppropriateExpectation(updateResultCheckStyles[j]); //bool callable = IsUpdateCallable(j); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; //note: updates to joined tables can't be batched... if (log.IsDebugEnabled) { log.Debug("Updating entity: " + MessageHelper.InfoString(this, id, Factory)); if (useVersion) { log.Debug("Existing version: " + oldVersion + " -> New Version: " + fields[VersionProperty]); } } try { int index = 0; IDbCommand statement = useBatch ? session.Batcher.PrepareBatchCommand(sql.CommandType, sql.Text, sql.ParameterTypes) : session.Batcher.PrepareCommand(sql.CommandType, sql.Text, sql.ParameterTypes); try { //index += expectation.Prepare(statement, factory.ConnectionProvider.Driver); //Now write the values of fields onto the prepared statement index = Dehydrate(id, fields, rowId, includeProperty, propertyColumnUpdateable, j, statement, session, index); // Write any appropriate versioning conditional parameters if (useVersion && Versioning.OptimisticLock.Version == entityMetamodel.OptimisticLockMode) { if (CheckVersion(includeProperty)) VersionType.NullSafeSet(statement, oldVersion, index, session); } else if (entityMetamodel.OptimisticLockMode > Versioning.OptimisticLock.Version && oldFields != null) { bool[] versionability = PropertyVersionability; bool[] includeOldField = OptimisticLockMode == Versioning.OptimisticLock.All ? PropertyUpdateability : includeProperty; IType[] types = PropertyTypes; for (int i = 0; i < entityMetamodel.PropertySpan; i++) { bool include = includeOldField[i] && IsPropertyOfTable(i, j) && versionability[i]; if (include) { bool[] settable = types[i].ToColumnNullness(oldFields[i], Factory); types[i].NullSafeSet(statement, oldFields[i], index, settable, session); index += ArrayHelper.CountTrue(settable); } } } if (useBatch) { session.Batcher.AddToBatch(expectation); return true; } else { return Check(session.Batcher.ExecuteNonQuery(statement), id, j, expectation, statement); } } catch (StaleStateException e) { if (useBatch) { session.Batcher.AbortBatch(e); } throw new StaleObjectStateException(EntityName, id); } catch (Exception e) { if (useBatch) { session.Batcher.AbortBatch(e); } throw; } finally { if (!useBatch) { session.Batcher.CloseCommand(statement, null); } } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not update: " + MessageHelper.InfoString(this, id, Factory), Sql = sql.Text.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
public object ForceVersionIncrement(object id, object currentVersion, ISessionImplementor session) { if (!IsVersioned) throw new AssertionFailure("cannot force version increment on non-versioned entity"); if (IsVersionPropertyGenerated) { // the difficulty here is exactly what do we update in order to // force the version to be incremented in the db... throw new HibernateException("LockMode.Force is currently not supported for generated version properties"); } object nextVersion = VersionType.Next(currentVersion, session); if (log.IsDebugEnabled) { log.Debug("Forcing version increment [" + MessageHelper.InfoString(this, id, Factory) + "; " + VersionType.ToLoggableString(currentVersion, Factory) + " -> " + VersionType.ToLoggableString(nextVersion, Factory) + "]"); } IExpectation expectation = Expectations.AppropriateExpectation(updateResultCheckStyles[0]); // todo : cache this sql... SqlCommandInfo versionIncrementCommand = GenerateVersionIncrementUpdateString(); try { IDbCommand st = session.Batcher.PrepareCommand(versionIncrementCommand.CommandType, versionIncrementCommand.Text, versionIncrementCommand.ParameterTypes); try { VersionType.NullSafeSet(st, nextVersion, 0, session); IdentifierType.NullSafeSet(st, id, 1, session); VersionType.NullSafeSet(st, currentVersion, 1 + IdentifierColumnSpan, session); Check(session.Batcher.ExecuteNonQuery(st), id, 0, expectation, st); } finally { session.Batcher.CloseCommand(st, null); } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not retrieve version: " + MessageHelper.InfoString(this, id, Factory), Sql = VersionSelectString.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } return nextVersion; }
/// <summary> /// Retrieve the version number /// </summary> public object GetCurrentVersion(object id, ISessionImplementor session) { if (log.IsDebugEnabled) { log.Debug("Getting version: " + MessageHelper.InfoString(this, id, Factory)); } using(new SessionIdLoggingContext(session.SessionId)) try { IDbCommand st = session.Batcher.PrepareQueryCommand(CommandType.Text, VersionSelectString, IdentifierType.SqlTypes(Factory)); IDataReader rs = null; try { IdentifierType.NullSafeSet(st, id, 0, session); rs = session.Batcher.ExecuteReader(st); if (!rs.Read()) { return null; } if (!IsVersioned) { return this; } return VersionType.NullSafeGet(rs, VersionColumnName, session, null); } finally { session.Batcher.CloseCommand(st, rs); } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not retrieve version: " + MessageHelper.InfoString(this, id, Factory), Sql = VersionSelectString.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
private object InitializeLazyPropertiesFromDatastore(string fieldName, object entity, ISessionImplementor session, object id, EntityEntry entry) { if (!HasLazyProperties) throw new AssertionFailure("no lazy properties"); log.Debug("initializing lazy properties from datastore"); using (new SessionIdLoggingContext(session.SessionId)) try { object result = null; IDbCommand ps = null; IDataReader rs = null; try { SqlString lazySelect = SQLLazySelectString; if (lazySelect != null) { // null sql means that the only lazy properties // are shared PK one-to-one associations which are // handled differently in the Type#nullSafeGet code... ps = session.Batcher.PrepareCommand(CommandType.Text, lazySelect, IdentifierType.SqlTypes(Factory)); IdentifierType.NullSafeSet(ps, id, 0, session); rs = session.Batcher.ExecuteReader(ps); rs.Read(); } object[] snapshot = entry.LoadedState; for (int j = 0; j < lazyPropertyNames.Length; j++) { object propValue = lazyPropertyTypes[j].NullSafeGet(rs, lazyPropertyColumnAliases[j], session, entity); if (InitializeLazyProperty(fieldName, entity, session, snapshot, j, propValue)) { result = propValue; } } } finally { session.Batcher.CloseCommand(ps, rs); } log.Debug("done initializing lazy properties"); return result; } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not initialize lazy properties: " + MessageHelper.InfoString(this, id, Factory), Sql = SQLLazySelectString.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
public object[] GetDatabaseSnapshot(object id, ISessionImplementor session) { if (log.IsDebugEnabled) { log.Debug("Getting current persistent state for: " + MessageHelper.InfoString(this, id, Factory)); } using (new SessionIdLoggingContext(session.SessionId)) try { IDbCommand st = session.Batcher.PrepareCommand(CommandType.Text, SQLSnapshotSelectString, IdentifierType.SqlTypes(factory)); IDataReader rs = null; try { IdentifierType.NullSafeSet(st, id, 0, session); rs = session.Batcher.ExecuteReader(st); if (!rs.Read()) { //if there is no resulting row, return null return null; } //otherwise return the "hydrated" state (ie. associations are not resolved) IType[] types = PropertyTypes; object[] values = new object[types.Length]; bool[] includeProperty = PropertyUpdateability; for (int i = 0; i < types.Length; i++) { if (includeProperty[i]) { values[i] = types[i].Hydrate(rs, GetPropertyAliases(string.Empty, i), session, null); //null owner ok?? } } return values; } finally { session.Batcher.CloseCommand(st, rs); } } catch (DbException sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not retrieve snapshot: " + MessageHelper.InfoString(this, id, Factory), Sql = SQLSnapshotSelectString.ToString(), EntityName = EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, exceptionContext); } }
public Exception Convert(AdoExceptionContextInfo exceptionContextInfo) { throw new GenericADOException(exceptionContextInfo.Message, exceptionContextInfo.SqlException, exceptionContextInfo.Sql); }
public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { return new UnitTestException(); }
public void Lock(object id, object version, object obj, ISessionImplementor session) { ISessionFactoryImplementor factory = session.Factory; try { IDbCommand st = session.Batcher.PrepareCommand(CommandType.Text, sql, lockable.IdAndVersionSqlTypes); IDataReader rs = null; try { lockable.IdentifierType.NullSafeSet(st, id, 0, session); if (lockable.IsVersioned) { lockable.VersionType.NullSafeSet(st, version, lockable.IdentifierType.GetColumnSpan(factory), session); } rs = session.Batcher.ExecuteReader(st); try { if (!rs.Read()) { if (factory.Statistics.IsStatisticsEnabled) { factory.StatisticsImplementor.OptimisticFailure(lockable.EntityName); } throw new StaleObjectStateException(lockable.EntityName, id); } } finally { rs.Close(); } } finally { session.Batcher.CloseCommand(st, rs); } } catch (HibernateException) { // Do not call Convert on HibernateExceptions throw; } catch (Exception sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not lock: " + MessageHelper.InfoString(lockable, id, factory), Sql = sql.ToString(), EntityName = lockable.EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, exceptionContext); } }
public Exception Convert(AdoExceptionContextInfo exceptionContextInfo) { throw new GenericADOException(exceptionContextInfo.Message, exceptionContextInfo.SqlException, exceptionContextInfo.Sql); }
public void Lock(object id, object version, object obj, ISessionImplementor session) { if (!lockable.IsVersioned) { throw new HibernateException("write locks via update not supported for non-versioned entities [" + lockable.EntityName + "]"); } // todo : should we additionally check the current isolation mode explicitly? ISessionFactoryImplementor factory = session.Factory; try { IDbCommand st = session.Batcher.PrepareCommand(CommandType.Text, sql, lockable.IdAndVersionSqlTypes); try { lockable.VersionType.NullSafeSet(st, version, 1, session); int offset = 2; lockable.IdentifierType.NullSafeSet(st, id, offset, session); offset += lockable.IdentifierType.GetColumnSpan(factory); if (lockable.IsVersioned) { lockable.VersionType.NullSafeSet(st, version, offset, session); } int affected = session.Batcher.ExecuteNonQuery(st); if (affected < 0) { factory.StatisticsImplementor.OptimisticFailure(lockable.EntityName); throw new StaleObjectStateException(lockable.EntityName, id); } } finally { session.Batcher.CloseCommand(st, null); } } catch (HibernateException) { // Do not call Convert on HibernateExceptions throw; } catch (Exception sqle) { var exceptionContext = new AdoExceptionContextInfo { SqlException = sqle, Message = "could not lock: " + MessageHelper.InfoString(lockable, id, factory), Sql = sql.ToString(), EntityName = lockable.EntityName, EntityId = id }; throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, exceptionContext); } }