Exemplo n.º 1
0
        public EntityUpdateException(Exception ex) : base(ex.Message)
        {
            Type type = ex.GetType();

            ValidationCodeResult = new EntityUpdateErrorResult();
            var entityUpdateErrorResult = (EntityUpdateErrorResult)ValidationCodeResult;

            if (type == typeof(PostgresException))
            {
                PostgresException dbEx = ex as PostgresException;
                entityUpdateErrorResult.Data           = dbEx.Data;
                entityUpdateErrorResult.Code           = dbEx.Code;
                entityUpdateErrorResult.ColumnName     = dbEx.ColumnName;
                entityUpdateErrorResult.ConstraintName = dbEx.ConstraintName;
                entityUpdateErrorResult.DataTypeName   = dbEx.DataTypeName;
                entityUpdateErrorResult.Detail         = dbEx.Detail;
                entityUpdateErrorResult.File           = dbEx.File;
                entityUpdateErrorResult.InternalQuery  = dbEx.InternalQuery;
                this.Message     = dbEx.Message;
                this.MessageText = dbEx.MessageText;
                entityUpdateErrorResult.Position   = dbEx.Position;
                entityUpdateErrorResult.Routine    = dbEx.Routine;
                entityUpdateErrorResult.SchemaName = dbEx.SchemaName;
                entityUpdateErrorResult.Severity   = dbEx.Severity;
                entityUpdateErrorResult.SqlState   = dbEx.SqlState;
                entityUpdateErrorResult.TableName  = dbEx.TableName;
                entityUpdateErrorResult.Where      = dbEx.Where;
            }
        }
Exemplo n.º 2
0
        public static bool IsUniqueConstraintViolationException(this PostgresException e, string constraintName)
        {
            const string constraintViolationErrorCode = "23505";

            return(string.Equals(e.SqlState, constraintViolationErrorCode, StringComparison.InvariantCultureIgnoreCase) &&
                   string.Equals(e.ConstraintName, constraintName, StringComparison.InvariantCultureIgnoreCase));
        }
Exemplo n.º 3
0
        public void DetailsAreRemoved()
        {
            using (var conn = OpenConnection(ConnectionString + ";SuppressDetailedExceptions=true"))
            {
                // Make sure messages are in English
                conn.ExecuteNonQuery(@"SET lc_messages='en_US.UTF-8'");
                conn.ExecuteNonQuery(@"
                     CREATE OR REPLACE FUNCTION pg_temp.emit_exception() RETURNS VOID AS
                        'BEGIN RAISE EXCEPTION ''testexception'' USING DETAIL = ''testdetail''; END;'
                     LANGUAGE 'plpgsql';
                ");

                PostgresException ex = null !;
                try
                {
                    conn.ExecuteNonQuery("SELECT pg_temp.emit_exception()");
                    Assert.Fail("No exception was thrown");
                }
                catch (PostgresException e)
                {
                    ex = e;
                }

                Assert.That(ex.Detail, Is.EqualTo("Detail suppressed as SuppressDetailInPostgressError is enabled"));

                var data = ex.Data;
                Assert.That(data[nameof(PostgresException.Detail)], Is.EqualTo("Detail suppressed as SuppressDetailInPostgressError is enabled"));

                var exString = ex.ToString();
                Assert.That(exString, Does.Not.Contain("testdetail"));
            }
        }
Exemplo n.º 4
0
        private void ParsePostgresException(Exception ex)
        {
            PostgresException pEx1 = ex as PostgresException;

            if (pEx1 != null)
            {
                m_sSqlState      = pEx1.Code;
                m_sErrorInfo     = pEx1.Message.ToLower();
                m_sDBMSErrorInfo = pEx1.Message.ToLower();
                byte[] buf     = BitConverter.GetBytes(pEx1.HResult);
                byte[] errCode = new byte[2];
                Array.Copy(buf, 0, errCode, 0, 2);
                m_iErrorCode = BitConverter.ToInt16(errCode, 0);
            }
            NpgsqlException pEx = ex as NpgsqlException;

            if (pEx != null)
            {
                m_sErrorInfo     = pEx.Message.ToLower();
                m_sDBMSErrorInfo = pEx.Message.ToLower();
                byte[] buf     = BitConverter.GetBytes(pEx.HResult);
                byte[] errCode = new byte[2];
                Array.Copy(buf, 0, errCode, 0, 2);
                m_iErrorCode = BitConverter.ToInt16(errCode, 0);
            }
        }
 private static SqlStorageException ToSqlStorageException(PostgresException postgresException)
 {
     return(PostgresExceptionRecognizer.TryRecognizeException(postgresException, out var sqlStorageRecognizedException) &&
            sqlStorageRecognizedException != null
                ? sqlStorageRecognizedException
                : new UnknownSqlStorageException(postgresException));
 }
Exemplo n.º 6
0
 public ICollection <CustomerDto> GetCustomers()
 {
     try
     {
         var customer = _dbContext.Customer;
         if (customer != null)
         {
             ICollection <CustomerDto> customerDto = new List <CustomerDto>();
             foreach (var item in customer)
             {
                 customerDto.Add(Mappers.CustomerRepository.MapToDto(item));
             }
             return(customerDto);
         }
     }
     catch (Exception ex)
     {
         if (ex.InnerException.GetType().ToString() == "Npgsql.PostgresException")
         {
             PostgresException postgresException = (PostgresException)ex.InnerException;
             throw new NSIException("Db error: " + postgresException.Detail, Level.Error, ErrorType.DBError);
         }
         else
         {
             throw ex.InnerException;
         }
     }
     return(null);
 }
Exemplo n.º 7
0
 public bool DeleteCustomerById(int customerId)
 {
     try
     {
         var customer = _dbContext.Customer.FirstOrDefault(x => x.CustomerId == customerId);
         if (customer != null)
         {
             customer.IsDeleted = true;
             _dbContext.SaveChanges();
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         if (ex.InnerException.GetType().ToString() == "Npgsql.PostgresException")
         {
             PostgresException postgresException = (PostgresException)ex.InnerException;
             throw new NSIException("Db error: " + postgresException.Detail, Level.Error, ErrorType.DBError);
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
Exemplo n.º 8
0
        public bool EditCustomer(int id, CustomerDto customerDto)
        {
            try
            {
                var customer = _dbContext.Customer.FirstOrDefault(x => x.CustomerId == customerDto.CustomerId);
                if (customer != null)
                {
                    customer.CustomerName     = customerDto.CustomerName ?? customer.CustomerName;
                    customer.IsActive         = customerDto.IsActive ?? customer.IsActive;
                    customer.IsDeleted        = customerDto.IsDeleted ?? customer.IsDeleted;
                    customer.DateModified     = customerDto.DateModified ?? DateTime.Now;
                    customer.PricingPackageId = customerDto.PricingPackageId ?? customer.PricingPackageId;
                    customer.AddressId        = customerDto.AddressId ?? customer.AddressId;
                    _dbContext.SaveChanges();

                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                if (ex.InnerException.GetType().ToString() == "Npgsql.PostgresException")
                {
                    PostgresException postgresException = (PostgresException)ex.InnerException;
                    throw new NSIException("Db error: " + postgresException.Detail, Level.Error, ErrorType.DBError);
                }
                else
                {
                    throw ex.InnerException;
                }
            }
        }
        private ContentResult GetExceptionContent(PostgresException e)
        {
            logger.LogError(e, LoggingService.FormatPostgresExceptionMessage(e, stringData));

            // state 42501 insufficient_privilege, see: https://www.postgresql.org/docs/11/errcodes-appendix.html
            return(e.SqlState == "42501" ? UnauthorizedContent() : BadRequestContent(e));
        }
Exemplo n.º 10
0
        private static bool IsTransientError(PostgresException pgex)
        {
            switch (pgex.SqlState)
            {
            case "40001":     // serialzation_failure
            case "53000":     // insufficient_resources
            case "53100":     // disk_full
            case "53200":     // out_of_memory
            case "53300":     // too_many_connections
            case "53400":     // configuration_limit_exceeded
            case "57P03":     // cannot_connect_now
            case "58000":     // system_error
            case "58030":     // io_error
            case "55P03":     // lock_not_available
            case "55006":     // object_in_use
            case "55000":     // object_not_in_prerequisite_state
            case "08000":     // connection_exception
            case "08003":     // connection_does_not_exist
            case "08006":     // connection_failure
            case "08001":     // sqlclient_unable_to_establish_sqlconnection
            case "08004":     // sqlserver_rejected_establishment_of_sqlconnection
            case "08007":     // transaction_resolution_unknown
                return(true);

            default:
                return(false);
            }
        }
Exemplo n.º 11
0
        public void Serialization()
        {
            var actual = new PostgresException("message text", "high", "high2", "53300", "detail", "hint", 18, 42, "internal query",
                                               "where", "schema", "table", "column", "data type", "constraint", "file", "line", "routine");

            var formatter = new BinaryFormatter();
            var stream    = new MemoryStream();

            formatter.Serialize(stream, actual);
            stream.Seek(0, SeekOrigin.Begin);

            var expected = (PostgresException)formatter.Deserialize(stream);

            Assert.That(expected.Severity, Is.EqualTo(actual.Severity));
            Assert.That(expected.InvariantSeverity, Is.EqualTo(actual.InvariantSeverity));
            Assert.That(expected.SqlState, Is.EqualTo(actual.SqlState));
            Assert.That(expected.MessageText, Is.EqualTo(actual.MessageText));
            Assert.That(expected.Detail, Is.EqualTo(actual.Detail));
            Assert.That(expected.Hint, Is.EqualTo(actual.Hint));
            Assert.That(expected.Position, Is.EqualTo(actual.Position));
            Assert.That(expected.InternalPosition, Is.EqualTo(actual.InternalPosition));
            Assert.That(expected.InternalQuery, Is.EqualTo(actual.InternalQuery));
            Assert.That(expected.Where, Is.EqualTo(actual.Where));
            Assert.That(expected.SchemaName, Is.EqualTo(actual.SchemaName));
            Assert.That(expected.TableName, Is.EqualTo(actual.TableName));
            Assert.That(expected.ColumnName, Is.EqualTo(actual.ColumnName));
            Assert.That(expected.DataTypeName, Is.EqualTo(actual.DataTypeName));
            Assert.That(expected.ConstraintName, Is.EqualTo(actual.ConstraintName));
            Assert.That(expected.File, Is.EqualTo(actual.File));
            Assert.That(expected.Line, Is.EqualTo(actual.Line));
            Assert.That(expected.Routine, Is.EqualTo(actual.Routine));
        }
Exemplo n.º 12
0
        public void SetError(PostgresException exception)
        {
            ErrorCode    = exception.SqlState;
            ErrorMessage = exception.MessageText;

            return;
        }
Exemplo n.º 13
0
        protected override void ThrowSqlException(Type tableType, Exception ex)
        {
            if (!(ex is NpgsqlException))
            {
                throw ex;
            }
            PostgresException nerror = ex as PostgresException;

            if (nerror.SqlState != "23505" || nerror.Detail.Contains(" already exists") == false)
            {
                throw ex;
            }

            StringBuilder output = new StringBuilder();

            string[] captions = null;
            string[] keys     = null;
            try
            {
                string msg = nerror.Detail;


                try
                {
                    var match = Regex.Match(msg, @"Key \((?<c>(\w| |,)+)\)");
                    if (match != null && match.Length > 0)
                    {
                        string indexname = match.Groups["c"].Value;
                        keys = indexname.Split(',');
                        keys = (from m in keys
                                select m.Trim()).ToArray();

                        captions = new string[keys.Length];

                        for (int i = 0; i < keys.Length; i++)
                        {
                            var pinfo = tableType.GetTypeInfo().GetProperty(keys[i]);

                            WayDBColumnAttribute columnAtt = pinfo.GetCustomAttribute(typeof(WayDBColumnAttribute)) as WayDBColumnAttribute;
                            captions[i] = columnAtt.Caption;
                            if (output.Length > 0)
                            {
                                output.Append(',');
                            }

                            output.Append(columnAtt.Caption.IsNullOrEmpty() ? keys[i] : columnAtt.Caption);
                        }
                    }
                }
                catch (Exception ee)
                {
                    throw ex;
                }
            }
            catch
            {
                throw ex;
            }
            throw new RepeatValueException(keys, captions, "此" + output + "已存在");
        }
        public PostgresExceptionInfo(PostgresException exception, Regex detailExpression) : this()
        {
            if (!string.IsNullOrEmpty(exception.TableName))
            {
                TableName = exception.TableName;
            }

            if (!string.IsNullOrEmpty(exception.Detail))
            {
                var match = detailExpression.Match(exception.Detail);

                if (match.Success)
                {
                    string columns        = match.Groups["KeyColumns"].Value;
                    string values         = match.Groups["KeyValues"].Value;
                    string constraintType = match.Groups["ConstraintType"].Value;

                    if (!string.IsNullOrEmpty(columns))
                    {
                        ColumnNames = columns.Replace("\"", "");
                    }

                    if (!string.IsNullOrEmpty(values))
                    {
                        Values = values;
                    }

                    if (!string.IsNullOrEmpty(constraintType))
                    {
                        ConstraintType = GetConstrainType(constraintType);
                    }
                }
            }
        }
Exemplo n.º 15
0
        private string FormatMessage(PostgresException pex, DBTable table, DBItem dbItem)
        {
            var text     = string.IsNullOrEmpty(pex.Detail) ? pex.MessageText : pex.Detail;
            var refTable = string.IsNullOrEmpty(pex.TableName) ? null : DBService.Schems.ParseTable(pex.TableName);
            var builder  = new StringBuilder();

            text = text.Replace("character varying", "Text");
            foreach (var item in text.Split(new char[] { ',', ' ', '"', '(', ')' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (table != null)
                {
                    var column = refTable?.ParseColumnProperty(item) ?? table?.ParseColumnProperty(item);
                    if (column != null)
                    {
                        builder.Append(column.DisplayName);
                        builder.Append(' ');
                        continue;
                    }
                }

                builder.Append(item);
                builder.Append(' ');
            }

            return(builder.ToString());
        }
Exemplo n.º 16
0
        void IVocabularyWindow.DefineLexicalData(dictionary_type lexicalType)
        {
            Word[] selected = SelectedWords().OrderBy(x => x.Id).ToArray();
            if (selected.Length > 1)
            {
                using (ISession session = DataHelper.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        Dictionary d = null;
                        try
                        {
                            for (int i = 0; i < selected.Length; i++)
                            {
                                for (int j = i + 1; j < selected.Length; j++)
                                {
                                    d                = new Dictionary();
                                    d.Left           = selected[i];
                                    d.Right          = selected[j];
                                    d.DictionaryType = lexicalType;
                                    session.SaveOrUpdate(d);
                                }
                            }

                            transaction.Commit();
                        }
                        catch (ADOException e)
                        {
                            transaction.Rollback();
                            Trace.TraceError(ErrorHelper.Message(e));
                            PostgresException ne = e.InnerException as PostgresException;
                            if (ne != null && ne.SqlState == "23505")
                            {
                                string format = string.Empty;
                                switch (lexicalType)
                                {
                                case dictionary_type.synonym:
                                    format = Strings.SynonymsAlreadyExist;
                                    break;

                                case dictionary_type.antonym:
                                    format = Strings.AntnymsAlreadyExist;
                                    break;

                                default:
                                    break;
                                }

                                KryptonMessageBox.Show(this, string.Format(format, d.Left, d.Right), Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                ErrorHelper.ShowDbError(this, e);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
 public InterneuronDBException(PostgresException npgEx, short errorCode = 500, string errorMessage = "", string errorType = "System Error", string errorId = null) : base($"Http.{errorCode} {errorType} {errorMessage}", npgEx)
 {
     this.ErrorId              = errorId ?? Guid.NewGuid().ToString();
     this.ErrorCode            = errorCode;
     this.ErrorMessage         = errorMessage;
     this.ErrorType            = errorType;
     this.ErrorResponseMessage = $"Error fetching data from database. Please check the error log with ID: {this.ErrorId} for more details";
 }
Exemplo n.º 18
0
        /// <summary>
        /// Metod som utifrån ett postgresexception sedan kan skicka ut en sträng med relevant meddelande
        /// </summary>
        /// <param name="ex"></param>
        /// <returns>Sträng med felmeddelande</returns>
        public static string ErrorMessage(PostgresException ex)
        {
            string errorMessage = "";

            //ex.ConstraintName

            //Returnera den sträng du skapat med information
            return(errorMessage);
        }
 // See Issue #985(EFCore)
 private bool RetryOnExistsFailure(PostgresException exception)
 {
     if (exception.SqlState == "3D000")
     {
         ClearPool();
         return(true);
     }
     return(false);
 }
Exemplo n.º 20
0
        public static bool IsPrimaryKeyViolationException(this PostgresException e)
        {
            const string constraintViolationErrorCode = "23505";
            const string primaryKeyNamePrefix         = "pk_";
            const string primaryKeyNameSuffix         = "_pkey";

            return(string.Equals(e.SqlState, constraintViolationErrorCode, StringComparison.InvariantCultureIgnoreCase) &&
                   (e.ConstraintName.StartsWith(primaryKeyNamePrefix, StringComparison.InvariantCultureIgnoreCase) ||
                    e.ConstraintName.EndsWith(primaryKeyNameSuffix, StringComparison.InvariantCultureIgnoreCase)));
        }
Exemplo n.º 21
0
        public static void SendPgError(this WorkspaceConnection ws, PostgresException e)
        {
            var message = new Message(e);

            if (ws.ErrorOffset.HasValue && message.Position != 0)
            {
                message.Position -= ws.ErrorOffset.Value;
            }
            ws.Proxy.SendAsync($"error-{ws.Id}", message).GetAwaiter().GetResult();
        }
Exemplo n.º 22
0
        private SqlExceptionType ProcessServerSideException(PostgresException serverSideException)
        {
            // There is no guaranteed way to detect a operation timeout.
            // We simply check that error message says something about CommandTimeout connection parameter.
            if (serverSideException.Message.ToUpperInvariant().Contains("COMMANDTIMEOUT"))
            {
                return(SqlExceptionType.OperationTimeout);
            }

            if (serverSideException.SqlState.Length != 5)
            {
                return(SqlExceptionType.Unknown);
            }

            var errorCode      = serverSideException.SqlState.ToUpperInvariant();
            var errorCodeClass = errorCode.Substring(0, 2);

            // Error codes have been taken from
            // http://www.postgresql.org/docs/8.4/static/errcodes-appendix.html

            switch (errorCodeClass)
            {
            case "08": // connection_exception
                return(SqlExceptionType.ConnectionError);

            case "42": // syntax_error_or_access_rule_violation
                if (errorCode == "42501")
                {
                    return(SqlExceptionType.Unknown);
                }
                return(SqlExceptionType.SyntaxError);
            }

            switch (errorCode)
            {
            case "23502": // not_null_violation
            case "23514": // check_violation
                return(SqlExceptionType.CheckConstraintViolation);

            case "23001": // restrict_violation
            case "23503": // foreign_key_violation
                return(SqlExceptionType.ReferentialConstraintViolation);

            case "23505": // unique_violation
                return(SqlExceptionType.UniqueConstraintViolation);

            case "40P01": // deadlock_detected
                return(SqlExceptionType.Deadlock);

            case "40001": // serialization_failure
                return(SqlExceptionType.SerializationFailure);
            }

            return(SqlExceptionType.Unknown);
        }
Exemplo n.º 23
0
        public bool IsUniqueViolation()
        {
            PostgresException exception = this.PostgresException;

            if (exception == null)
            {
                return(false);
            }

            return(exception.SqlState == PostgresErrorCodes.UniqueViolation);
        }
Exemplo n.º 24
0
        private static AsyncInjectOutcomePolicy CreateRetryChaosAsync(IPolicies policies)
        {
            var fault = new PostgresException(string.Empty, string.Empty, string.Empty,
                                              ChaosPolicyShared.GetRandomString(RetryablePostGreErrors.Errors.ToList()));

            return(MonkeyPolicy.InjectExceptionAsync(with =>
                                                     with.Fault(fault)
                                                     .InjectionRate((context, token) => ChaosPolicyShared.InjectionRateAsync(context, RetryConstants.RetryCount, RetryAttempts))
                                                     .Enabled(policies.EnableChaos)
                                                     ));
        }
        private void ProcessException(PostgresException ex)
        {
            var constraintName = ex.ConstraintName ?? string.Empty;

            if (_exceptionsOnConstraints != null && _exceptionsOnConstraints.ContainsKey(constraintName))
            {
                var exception = _exceptionsOnConstraints[constraintName];
                throw exception;
            }

            throw ex;
        }
 private static string GetExceptionMessage(PostgresException exception)
 {
     if (exception.SqlState == "23503")
     {
         var isDelete = exception.MessageText.Contains("delete");
         return(isDelete ? "message.SQL23503D" : "message.SQL23503A");
     }
     else
     {
         return($"message.SQL{exception.SqlState}");
     }
 }
Exemplo n.º 27
0
        private static string FormatPostgresExceptionMessage(PostgresException e)
        {
            var sb = new StringBuilder();

            sb.Append($"{NL}PostgreSQL error:{NL}");
            foreach (var entry in e.Data.Cast <DictionaryEntry>().Where(entry => entry.Value != null))
            {
                sb.Append($"{NL}{entry.Key}: {entry.Value}");
            }
            sb.Append($"{NL}{NL}");
            return(sb.ToString());
        }
Exemplo n.º 28
0
        private string GetReadableErrorMessage(PostgresException innerException)
        {
            switch (innerException.SqlState)
            {
            case DbErrorCodes.UNIQUE_VIOLATION:
                return("Unique violation error");

            case DbErrorCodes.FOREIGN_KEY_VIOLATION:
                return("Foreign key violation error");

            default:
                return(null);
            }
        }
Exemplo n.º 29
0
 private static string FormatPostgresExceptionMessage(PostgresException e) => $"{e.Severity}\n" +
 $"Message: {e.Message}\n" +
 $"Detail: {e.Detail}\n" +
 $"Line: {e.Line}\n" +
 $"InternalPosition: {e.InternalPosition}\n" +
 $"Position: {e.Position}\n" +
 $"SqlState: {e.SqlState}\n" +
 $"Statement: {e.Statement}\n" +
 $"ColumnName: {e.ColumnName}\n" +
 $"ConstraintName: {e.ConstraintName}\n" +
 $"TableName: {e.TableName}\n" +
 $"InternalQuery: {e.InternalQuery}\n" +
 $"Where: {e.Where}\n" +
 $"Hint: {e.Hint}\n\n";
Exemplo n.º 30
0
 private ContentResult BadRequestContent(PostgresException e) => new ContentResult
 {
     StatusCode = 400,
     Content    = JsonConvert.SerializeObject(new
     {
         messeage   = e.MessageText,
         details    = e.Detail,
         table      = e.TableName,
         column     = e.ColumnName,
         constraint = e.ConstraintName,
         error      = true
     }),
     ContentType = contentType
 };