Skip to main content

postrust_core/
error.rs

1//! Error types for Postrust.
2//!
3//! Provides comprehensive error handling with HTTP status code mapping.
4
5use http::StatusCode;
6use thiserror::Error;
7
8/// Result type for Postrust operations.
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Main error type for Postrust.
12#[derive(Error, Debug)]
13pub enum Error {
14    // ========================================================================
15    // Request Parsing Errors (4xx)
16    // ========================================================================
17    /// The request path does not name a resource this API serves.
18    #[error("Invalid path: {0}")]
19    InvalidPath(String),
20
21    /// An aggregate was requested while `db-aggregates-enabled` is off.
22    ///
23    /// Off is the default, matching PostgREST: an unrestricted aggregate over
24    /// a large table is an easy way to make a server do far more work than the
25    /// request looks like it asks for.
26    #[error("Use of aggregate functions is not allowed")]
27    AggregatesNotAllowed,
28
29    /// A query parameter this API does not accept, or one whose value is not
30    /// valid for it.
31    #[error("Invalid query parameter: {0}")]
32    InvalidQueryParam(String),
33
34    /// A fragment of the query string the grammar could not read.
35    ///
36    /// Reported the way a parser reports: what was being read, the text as the
37    /// client wrote it, where reading stopped, and what would have been
38    /// accepted there. All four are the client's own input or the API's own
39    /// grammar, so none of it is a disclosure -- and without them the client
40    /// is told only that something in a URL it wrote is wrong.
41    #[error("\"failed to parse {kind} ({text})\" (line 1, column {column})")]
42    UnparsableQuery {
43        /// What was being read: `filter`, `logic tree`, `order`.
44        kind: &'static str,
45        /// The fragment, as it was written.
46        text: String,
47        /// Where reading stopped, counting from one.
48        column: usize,
49        /// What was found there and what would have been accepted.
50        expected: String,
51    },
52
53    /// A request header whose value this server cannot read. Names the header
54    /// only; the value may carry credentials.
55    #[error("Invalid header: {0}")]
56    InvalidHeader(&'static str),
57
58    /// The body did not parse, or does not fit the resource it was sent to.
59    #[error("{0}")]
60    InvalidBody(String),
61
62    /// An HTTP method this API does not implement for any resource.
63    #[error("Unsupported HTTP method: {0}")]
64    UnsupportedMethod(String),
65
66    /// A method a function cannot be called with.
67    ///
68    /// A function is invoked with GET, HEAD or POST. The others are refused
69    /// with a message that says so rather than one about the method in
70    /// general, since the method is fine elsewhere in the API.
71    #[error("Cannot use the {0} method on RPC")]
72    InvalidRpcMethod(String),
73
74    /// A profile header named a schema the server does not expose.
75    ///
76    /// Carries the schemas that *are* exposed, because the client needs them
77    /// to correct the request and they are part of the API's own contract.
78    #[error("Invalid schema: {requested}")]
79    UnacceptableSchema {
80        /// The schema the profile header named.
81        requested: String,
82        /// The schemas that are exposed, so the client can correct itself.
83        exposed: Vec<String>,
84    },
85
86    /// A column the request named that the relation does not have.
87    #[error("Could not find the '{column}' column of '{relation}' in the schema cache")]
88    UnknownColumn {
89        /// The column the request named.
90        column: String,
91        /// The relation it was looked for on.
92        relation: String,
93    },
94
95    /// A `Range` header or `limit`/`offset` pair that cannot be satisfied.
96    #[error("Requested range not satisfiable")]
97    InvalidRange(String),
98
99    /// Content negotiation found nothing both sides accept.
100    #[error("None of these media types are available: {0}")]
101    InvalidMediaType(String),
102
103    /// A function argument the signature requires and the call omitted.
104    #[error("Missing required parameter: {0}")]
105    MissingParameter(String),
106
107    /// The request admits more than one reading and the server will not guess.
108    #[error("Ambiguous request: {0}")]
109    AmbiguousRequest(String),
110
111    /// Several signatures of a function fit the arguments equally well.
112    #[error("Could not choose the best candidate function between: {}", .candidates.join(", "))]
113    AmbiguousFunction {
114        /// The signatures that fit, as the client would have to distinguish
115        /// them.
116        candidates: Vec<String>,
117    },
118
119    /// Several relationships connect the two resources and none was named.
120    #[error("Could not embed because more than one relationship was found for '{origin}' and '{target}'")]
121    AmbiguousRelationship {
122        /// The resource being embedded from.
123        origin: String,
124        /// The resource being embedded.
125        target: String,
126        /// Each candidate as `(cardinality, description)`.
127        candidates: Vec<(String, String)>,
128        /// How the client would name each candidate: `big_projects!jobs`.
129        disambiguated: Vec<String>,
130    },
131
132    // ========================================================================
133    // Authentication/Authorization Errors (401/403)
134    // ========================================================================
135    /// The token could not be decoded or its signature did not verify.
136    ///
137    /// Distinct from a claims error: nothing about the token was readable, so
138    /// there is nothing to say about what it claimed.
139    #[error("{0}")]
140    InvalidJwt(String),
141
142    /// No key this server holds could decode the token.
143    ///
144    /// Its own code would be indistinguishable from any other decode failure,
145    /// so what separates it is the detail: the client is being told to look at
146    /// which key signed the token, not at the token's contents.
147    #[error("No suitable key or wrong key type")]
148    NoSuitableJwtKey,
149
150    /// The server is configured to read tokens and has nothing to read them
151    /// with. A fault in the deployment, not in the request.
152    #[error("Server lacks JWT secret")]
153    JwtSecretMissing,
154
155    /// The token decoded, but a claim was missing, malformed or unsatisfied.
156    #[error("{0}")]
157    JwtClaim(String),
158
159    /// Nothing said who is asking, and no anonymous role is configured to be.
160    #[error("Anonymous access is disabled")]
161    MissingAuth,
162
163    /// The caller is known and the role it resolved to may not do this.
164    #[error("Insufficient permissions: {0}")]
165    InsufficientPermissions(String),
166
167    // ========================================================================
168    // Resource Errors (404)
169    // ========================================================================
170    /// Nothing at this path, where no more specific variant applies.
171    #[error("Resource not found: {0}")]
172    NotFound(String),
173
174    /// No table, view or foreign table of this name in the exposed schema.
175    #[error("Table not found: {name}")]
176    TableNotFound {
177        /// The name the request asked for, schema-qualified.
178        name: String,
179        /// A table of a very similar name, where the schema has one.
180        suggestion: Option<String>,
181    },
182
183    /// No function of that name accepts the arguments supplied.
184    ///
185    /// Carries what was looked for so the client can see why nothing matched:
186    /// the name, the argument names it was called with, and the signature of
187    /// an overload that does exist, where one does.
188    #[error("Could not find the function {name}")]
189    FunctionNotFound {
190        /// The function's qualified name, without arguments.
191        name: String,
192        /// The argument names it was called with.
193        params: Vec<String>,
194        /// A signature that does exist, where one does.
195        candidate: Option<String>,
196        /// The type of a single unnamed parameter that would also have
197        /// matched, spelled as the message spells it.
198        ///
199        /// Over `POST` the whole body can be one argument, and which type it
200        /// could be is decided by the body's media type: `json/jsonb` for a
201        /// JSON body, `text`, `xml` or `bytea` for the others. Naming it says
202        /// what else was looked for besides the arguments themselves.
203        single_param: Option<String>,
204    },
205
206    /// A `RAISE sqlstate 'PGRST'` the schema wrote wrongly.
207    ///
208    /// The message and the detail are both JSON documents with required keys,
209    /// and a function that gets one wrong has not asked for a response -- it
210    /// has a bug. Reporting it as the 500 it is says so; applying half of what
211    /// it asked for would not.
212    #[error("Could not parse JSON in the \"RAISE SQLSTATE 'PGRST'\" error")]
213    RaiseNotUnderstood(RaiseFault),
214
215    /// `Accept: application/geo+json` on rows that carry no geometry.
216    ///
217    /// PostGIS raises this from `ST_AsGeoJSON` on a record with no geometry
218    /// column, and it is a database error rather than one of PostgREST's own
219    /// -- so it keeps the SQLSTATE it came with.
220    #[error("geometry column is missing")]
221    MissingGeometryColumn,
222
223    /// A column named in the request that the relation does not have. Prefer
224    /// [`Error::UnknownColumn`], which also says which relation was searched.
225    #[error("Column not found: {0}")]
226    ColumnNotFound(String),
227
228    /// Nothing connects the two resources, so the embed cannot be planned.
229    #[error("Could not find a relationship between '{origin}' and '{target}' in the schema cache")]
230    RelationshipNotFound {
231        /// The table the embedding started from.
232        origin: String,
233        /// The resource the request asked to embed.
234        target: String,
235        /// The `!hint` that was meant to identify it, if any.
236        hint: Option<String>,
237        /// The schema that was searched.
238        schema: String,
239        /// A relationship of a very similar name, where there is one.
240        suggestion: Option<String>,
241    },
242
243    /// A filter or order names something the request never embedded.
244    ///
245    /// `?non_existent.name=like.*x*` is not a column with a dot in it, and
246    /// answering it as though the prefix were meaningless would silently
247    /// return the unfiltered table.
248    #[error("'{0}' is not an embedded resource in this request")]
249    NotAnEmbeddedResource(String),
250
251    /// Ordering by a column of a resource that yields many rows per parent.
252    ///
253    /// There is no single value to order on: the parent has a list.
254    #[error("A related order on '{relation}' is not possible")]
255    RelatedOrderNotPossible {
256        /// The table the request started from.
257        origin: String,
258        /// The embedded resource the order named.
259        relation: String,
260    },
261
262    /// A single object was asked for and the result is not one.
263    ///
264    /// `Accept: application/vnd.pgrst.object+json` says the client will accept
265    /// exactly one row; anything else is a negotiation failure rather than a
266    /// missing resource, which is why it is 406 and not 404.
267    #[error("Cannot coerce the result to a single JSON object")]
268    NotSingular {
269        /// How many rows the query actually returned.
270        rows: usize,
271    },
272
273    /// A path with more segments than any resource has.
274    #[error("Invalid path specified in request URL")]
275    InvalidResourcePath,
276
277    /// A `PUT` whose filters do not name exactly one row by its key.
278    ///
279    /// `PUT` writes the row the URL names, so the URL has to name exactly one:
280    /// every primary key column, with `eq`, and nothing else.
281    #[error("Filters must include all and only primary key columns with 'eq' operators")]
282    InvalidPutFilters,
283
284    /// A `PUT` carrying a page.
285    #[error("limit/offset querystring parameters are not allowed for PUT")]
286    PutLimitNotAllowed,
287
288    /// A `PUT` whose body names a different row from its URL.
289    #[error("Payload values do not match URL in primary key column(s)")]
290    PutMatchingPk,
291
292    /// A function set `response.headers` to something that is not headers.
293    #[error(
294        "response.headers guc must be a JSON array composed of objects with a single key and a \
295         string value"
296    )]
297    InvalidGucHeaders,
298
299    /// A function set `response.status` to something that is not a status.
300    #[error("response.status guc must be a valid status code")]
301    InvalidGucStatus,
302
303    /// A mutation touched more rows than `Prefer: max-affected` allowed.
304    ///
305    /// The preference is a guard against a filter that turned out to match
306    /// more than the client meant; nothing is committed when it trips.
307    #[error("Query result exceeds max-affected preference constraint")]
308    MaxAffectedExceeded(i64),
309
310    /// `max-affected` with `handling=strict` on a function that returns one
311    /// value rather than a set: there are no rows to count.
312    #[error(
313        "Function must return SETOF or TABLE when max-affected preference is used with handling=strict"
314    )]
315    MaxAffectedRpcViolation,
316
317    /// Preferences the server does not know, sent with `handling=strict`.
318    ///
319    /// Strict handling is a request to be told rather than have them ignored.
320    #[error("Invalid preferences given with handling=strict")]
321    InvalidPreferences(Vec<String>),
322
323    // ========================================================================
324    // Schema Cache Errors
325    // ========================================================================
326    /// A request arrived before the schema had been read. Transient at
327    /// start-up; persistent means the initial load failed.
328    #[error("Schema cache not loaded")]
329    SchemaCacheNotLoaded,
330
331    /// Reading the schema from PostgreSQL failed. Usually a missing privilege
332    /// on the catalogue rather than a fault in the schema itself.
333    #[error("Schema cache load failed: {0}")]
334    SchemaCacheLoadFailed(String),
335
336    // ========================================================================
337    // Database Errors (500/4xx depending on type)
338    // ========================================================================
339    /// PostgreSQL refused the statement. The SQLSTATE decides the HTTP status,
340    /// so this is not always a 500.
341    #[error("Database error: {0}")]
342    Database(#[from] DatabaseError),
343
344    /// No connection could be obtained: the pool is exhausted, or the database
345    /// is unreachable.
346    #[error("Connection pool error: {0}")]
347    ConnectionPool(String),
348
349    // ========================================================================
350    // Internal Errors (500)
351    // ========================================================================
352    /// A fault in this server. Always a bug; the message is for its log rather
353    /// than for the client to act on.
354    #[error("Internal error: {0}")]
355    Internal(String),
356
357    /// The server was started with a setting it cannot act on.
358    #[error("Configuration error: {0}")]
359    Config(String),
360
361    // ========================================================================
362    // Plan Errors
363    // ========================================================================
364    /// The request parsed and no execution plan could be built from it.
365    #[error("Invalid plan: {0}")]
366    InvalidPlan(String),
367
368    /// An embed that cannot be planned, where no more specific variant fits.
369    #[error("Embedding error: {0}")]
370    EmbeddingError(String),
371}
372
373impl Error {
374    /// Get the HTTP status code for this error, as it is answered to an
375    /// anonymous request.
376    ///
377    /// See [`status_code_as`](Self::status_code_as) for the one status that
378    /// depends on who asked.
379    pub fn status_code(&self) -> StatusCode {
380        self.status_code_as(false)
381    }
382
383    /// Get the HTTP status code for this error, for a request that is or is
384    /// not authenticated.
385    ///
386    /// Only a database error's status can differ: a missing grant (`42501`)
387    /// is 401 to an anonymous request and 403 to an authenticated one. See
388    /// [`DatabaseError::status_code_as`].
389    pub fn status_code_as(&self, authenticated: bool) -> StatusCode {
390        match self {
391            // 400 Bad Request
392            Self::InvalidPath(_)
393            | Self::InvalidQueryParam(_)
394            | Self::InvalidHeader(_)
395            | Self::InvalidBody(_)
396            | Self::MissingParameter(_)
397            | Self::AmbiguousRequest(_)
398            | Self::UnparsableQuery { .. }
399            | Self::UnknownColumn { .. }
400            | Self::NotAnEmbeddedResource(_)
401            | Self::RelatedOrderNotPossible { .. }
402            | Self::InvalidPreferences(_)
403            | Self::PutLimitNotAllowed
404            | Self::PutMatchingPk
405            | Self::MaxAffectedExceeded(_)
406            | Self::MaxAffectedRpcViolation
407            | Self::InvalidPlan(_)
408            | Self::EmbeddingError(_)
409            | Self::AggregatesNotAllowed
410            | Self::MissingGeometryColumn => StatusCode::BAD_REQUEST,
411
412            // The request names something real, but not which one of it.
413            Self::AmbiguousFunction { .. } | Self::AmbiguousRelationship { .. } => {
414                StatusCode::MULTIPLE_CHOICES
415            }
416
417            // 401 Unauthorized
418            Self::InvalidJwt(_)
419            | Self::NoSuitableJwtKey
420            | Self::JwtClaim(_)
421            | Self::MissingAuth => StatusCode::UNAUTHORIZED,
422
423            // 403 Forbidden
424            Self::InsufficientPermissions(_) => StatusCode::FORBIDDEN,
425
426            // 404 Not Found
427            Self::NotFound(_) | Self::TableNotFound { .. } | Self::FunctionNotFound { .. } => {
428                StatusCode::NOT_FOUND
429            }
430
431            // A relationship or a column the schema does not have is a fault
432            // in the request, not a missing resource: the resource addressed
433            // by the URL exists, and `?select=` asked it for something it
434            // cannot give. The table it names is what a 404 would be about.
435            Self::ColumnNotFound(_) | Self::RelationshipNotFound { .. } => StatusCode::BAD_REQUEST,
436
437            // 405 Method Not Allowed
438            Self::UnsupportedMethod(_) | Self::InvalidRpcMethod(_) | Self::InvalidPutFilters => {
439                StatusCode::METHOD_NOT_ALLOWED
440            }
441
442            // 406 Not Acceptable
443            Self::UnacceptableSchema { .. }
444            | Self::NotSingular { .. }
445            | Self::InvalidMediaType(_) => StatusCode::NOT_ACCEPTABLE,
446
447            Self::InvalidResourcePath => StatusCode::NOT_FOUND,
448
449            // A range the server cannot satisfy, which is what 416 is for --
450            // a negative limit asks for a window that does not exist rather
451            // than for one the server merely declines.
452            Self::InvalidRange(_) => StatusCode::RANGE_NOT_SATISFIABLE,
453
454            // 500 Internal Server Error
455            Self::JwtSecretMissing
456            | Self::RaiseNotUnderstood(_)
457            | Self::InvalidGucHeaders
458            | Self::InvalidGucStatus
459            | Self::SchemaCacheNotLoaded
460            | Self::SchemaCacheLoadFailed(_)
461            | Self::ConnectionPool(_)
462            | Self::Internal(_)
463            | Self::Config(_) => StatusCode::INTERNAL_SERVER_ERROR,
464
465            // Database errors map based on type
466            Self::Database(db_err) => db_err.status_code_as(authenticated),
467        }
468    }
469
470    /// Get the error code for API responses.
471    pub fn code(&self) -> &'static str {
472        match self {
473            Self::InvalidPath(_) => "PGRST100",
474            Self::AggregatesNotAllowed => "PGRST123",
475            // PGRST100 is the parse failure in PostgREST's taxonomy, covering
476            // both the path and the query string; PGRST101 is a function
477            // invoked with a method its volatility does not allow.
478            Self::InvalidQueryParam(_) | Self::UnparsableQuery { .. } => "PGRST100",
479            // Not one of PostgREST's own: a malformed header is a request
480            // that did not parse, which is what PGRST100 covers.
481            Self::InvalidHeader(_) => "PGRST100",
482            Self::InvalidBody(_) => "PGRST102",
483            Self::UnsupportedMethod(_) => "PGRST117",
484            Self::InvalidRpcMethod(_) => "PGRST101",
485            Self::UnacceptableSchema { .. } => "PGRST106",
486            Self::UnknownColumn { .. } => "PGRST204",
487            Self::InvalidRange(_) => "PGRST103",
488            Self::InvalidMediaType(_) => "PGRST107",
489            Self::MissingParameter(_) => "PGRST109",
490            Self::AmbiguousRequest(_) => "PGRST110",
491            Self::AmbiguousFunction { .. } => "PGRST203",
492            Self::AmbiguousRelationship { .. } => "PGRST201",
493
494            Self::InvalidJwt(_) | Self::NoSuitableJwtKey => "PGRST301",
495            Self::JwtSecretMissing => "PGRST300",
496            Self::JwtClaim(_) => "PGRST303",
497            Self::MissingAuth => "PGRST302",
498            Self::InsufficientPermissions(_) => "PGRST203",
499
500            Self::NotFound(_) => "PGRST205",
501            Self::TableNotFound { .. } => "PGRST205",
502            Self::FunctionNotFound { .. } => "PGRST202",
503            Self::MissingGeometryColumn => "22023",
504            Self::ColumnNotFound(_) => "PGRST204",
505            Self::RelationshipNotFound { .. } => "PGRST200",
506            Self::NotAnEmbeddedResource(_) => "PGRST108",
507            Self::NotSingular { .. } => "PGRST116",
508            Self::InvalidResourcePath => "PGRST125",
509            Self::InvalidPutFilters => "PGRST105",
510            Self::PutLimitNotAllowed => "PGRST114",
511            Self::PutMatchingPk => "PGRST115",
512            Self::MaxAffectedExceeded(_) => "PGRST124",
513            Self::MaxAffectedRpcViolation => "PGRST128",
514            Self::RaiseNotUnderstood(_) => "PGRST121",
515            Self::InvalidGucHeaders => "PGRST111",
516            Self::InvalidGucStatus => "PGRST112",
517            Self::RelatedOrderNotPossible { .. } => "PGRST118",
518            Self::InvalidPreferences(_) => "PGRST122",
519
520            Self::SchemaCacheNotLoaded => "PGRST400",
521            Self::SchemaCacheLoadFailed(_) => "PGRST401",
522
523            Self::Database(e) => e.code(),
524            Self::ConnectionPool(_) => "PGRST500",
525
526            Self::Internal(_) => "PGRST900",
527            Self::Config(_) => "PGRST901",
528
529            Self::InvalidPlan(_) => "PGRST600",
530            Self::EmbeddingError(_) => "PGRST601",
531        }
532    }
533
534    /// Convert to JSON error response.
535    pub fn to_json(&self) -> serde_json::Value {
536        serde_json::json!({
537            "code": self.code(),
538            "message": self.to_string(),
539            "details": self.details(),
540            "hint": self.hint(),
541        })
542    }
543
544    /// Get additional details for the error.
545    pub fn details(&self) -> Option<serde_json::Value> {
546        match self {
547            Self::Database(db_err) => db_err.details.clone().map(serde_json::Value::String),
548            // A structured list rather than a sentence: each candidate is
549            // named so the client can pick one and say which.
550            Self::AmbiguousRelationship {
551                origin,
552                target,
553                candidates,
554                ..
555            } => Some(serde_json::Value::Array(
556                candidates
557                    .iter()
558                    .map(|(cardinality, description)| {
559                        serde_json::json!({
560                            "cardinality": cardinality,
561                            "embedding": format!("{} with {}", origin, target),
562                            "relationship": description,
563                        })
564                    })
565                    .collect(),
566            )),
567            Self::RelationshipNotFound {
568                origin,
569                target,
570                hint,
571                schema,
572                ..
573            } => Some(serde_json::Value::String(format!(
574                "Searched for a foreign key relationship between '{}' and '{}'{} in the schema \
575                 '{}', but no matches were found.",
576                origin,
577                target,
578                match hint {
579                    Some(hint) => format!(" using the hint '{}'", hint),
580                    None => String::new(),
581                },
582                schema
583            ))),
584            Self::RelatedOrderNotPossible { origin, relation } => {
585                Some(serde_json::Value::String(format!(
586                    "'{}' and '{}' do not form a many-to-one or one-to-one relationship",
587                    origin, relation
588                )))
589            }
590            Self::InvalidRange(reason) => Some(serde_json::Value::String(reason.clone())),
591            Self::MaxAffectedExceeded(affected) => Some(serde_json::Value::String(format!(
592                "The query affects {} rows",
593                affected
594            ))),
595            Self::NotSingular { rows } => Some(serde_json::Value::String(format!(
596                "The result contains {} rows",
597                rows
598            ))),
599            Self::InvalidPreferences(invalid) => Some(serde_json::Value::String(format!(
600                "Invalid preferences: {}",
601                invalid.join(", ")
602            ))),
603            Self::RaiseNotUnderstood(fault) => Some(serde_json::Value::String(fault.details())),
604            Self::NoSuitableJwtKey => Some(serde_json::Value::String(
605                "No suitable key was found to decode the JWT".into(),
606            )),
607            Self::UnparsableQuery { expected, .. } => {
608                Some(serde_json::Value::String(expected.clone()))
609            }
610            Self::FunctionNotFound {
611                name,
612                params,
613                single_param,
614                ..
615            } => Some(serde_json::Value::String(format!(
616                "Searched for the function {} {}, but no matches were found in the schema cache.",
617                name,
618                match single_param.as_deref() {
619                    // A body that is one value carries no argument names, so
620                    // the only thing that could have matched is the parameter
621                    // that takes it.
622                    Some(other) if other != JSON_PARAM =>
623                        format!("with a single unnamed {} parameter", other),
624                    Some(_) => format!(
625                        "{} or with a single unnamed {} parameter",
626                        describe_params(params),
627                        JSON_PARAM
628                    ),
629                    None => describe_params(params),
630                }
631            ))),
632            _ => None,
633        }
634    }
635
636    /// Get a hint for resolving the error.
637    pub fn hint(&self) -> Option<String> {
638        match self {
639            Self::NotAnEmbeddedResource(name) => Some(format!(
640                "Verify that '{}' is included in the 'select' query parameter.",
641                name
642            )),
643            Self::TableNotFound { suggestion, .. } => suggestion
644                .as_ref()
645                .map(|name| format!("Perhaps you meant the table '{}'", name)),
646            Self::RelationshipNotFound {
647                target, suggestion, ..
648            } => suggestion
649                .as_ref()
650                .map(|name| format!("Perhaps you meant '{}' instead of '{}'.", name, target)),
651            Self::AmbiguousFunction { .. } => Some(
652                "Try renaming the parameters or the function itself in the database so function \
653                 overloading can be resolved"
654                    .into(),
655            ),
656            Self::AmbiguousRelationship {
657                target,
658                disambiguated,
659                ..
660            } => Some(format!(
661                "Try changing '{}' to one of the following: {}. Find the desired relationship in \
662                 the 'details' key.",
663                target,
664                disambiguated
665                    .iter()
666                    .map(|name| format!("'{}'", name))
667                    .collect::<Vec<_>>()
668                    .join(", ")
669            )),
670            Self::RaiseNotUnderstood(fault) => Some(fault.hint().into()),
671            // A body that is one value names no arguments, so there is no
672            // near miss to point at: any function of that name would have
673            // done, and none of them takes this body.
674            Self::FunctionNotFound {
675                candidate,
676                single_param,
677                ..
678            } if !names_only_one_param(single_param.as_deref()) => candidate
679                .as_ref()
680                .map(|c| format!("Perhaps you meant to call the function {}", c)),
681            Self::FunctionNotFound { .. } => None,
682            // The schemas a server exposes are part of its contract, not an
683            // internal detail, so naming them is how the client is told what
684            // to ask for instead.
685            Self::UnacceptableSchema { exposed, .. } => Some(format!(
686                "Only the following schemas are exposed: {}",
687                exposed.join(", ")
688            )),
689            Self::Database(db_err) => db_err.hint.clone(),
690            _ => None,
691        }
692    }
693}
694
695/// How the message spells the type of a single unnamed JSON parameter.
696///
697/// It is the one media type that can also carry named arguments, so it reads
698/// as an alternative rather than as the only thing looked for.
699pub const JSON_PARAM: &str = "json/jsonb";
700
701/// Whether the request could only ever have matched one unnamed parameter.
702///
703/// True for a body that is one value -- text, xml or bytes -- which carries no
704/// argument names at all.
705pub fn names_only_one_param(single_param: Option<&str>) -> bool {
706    matches!(single_param, Some(other) if other != JSON_PARAM)
707}
708
709/// How a function's argument list reads in an error message.
710///
711/// PostgREST words the no-argument case differently rather than printing an
712/// empty list, and the messages are matched verbatim by clients.
713pub fn function_signature(name: &str, params: &[String]) -> String {
714    match params.is_empty() {
715        true => format!("{} without parameters", name),
716        false => format!("{}({})", name, params.join(", ")),
717    }
718}
719
720fn describe_params(params: &[String]) -> String {
721    match params.len() {
722        0 => "without parameters".to_string(),
723        1 => format!("with parameter {}", params[0]),
724        _ => format!("with parameters {}", params.join(", ")),
725    }
726}
727
728/// Database-specific error type.
729#[derive(Error, Debug)]
730#[error("Database error [{code}]: {message}")]
731pub struct DatabaseError {
732    /// The five-character SQLSTATE. This decides the HTTP status, so it is the
733    /// field that matters most.
734    pub code: String,
735    /// PostgreSQL's primary message.
736    pub message: String,
737    /// PostgreSQL's detail field, where it sent one.
738    pub details: Option<String>,
739    /// PostgreSQL's hint field, where it sent one.
740    pub hint: Option<String>,
741    /// The constraint that was violated, for the integrity SQLSTATEs.
742    pub constraint: Option<String>,
743    /// The table the failure concerns, where PostgreSQL identified one.
744    pub table: Option<String>,
745    /// The column the failure concerns, where PostgreSQL identified one.
746    pub column: Option<String>,
747}
748
749/// What was wrong with a `RAISE sqlstate 'PGRST'`.
750#[derive(Clone, Debug)]
751pub enum RaiseFault {
752    /// The MESSAGE was not the JSON object it has to be.
753    Message(String),
754    /// The DETAIL was not the JSON object it has to be.
755    Detail(String),
756    /// There was no DETAIL, and the status has to come from somewhere.
757    NoDetail,
758}
759
760impl RaiseFault {
761    /// What the schema author has to look at.
762    pub fn details(&self) -> String {
763        match self {
764            Self::Message(raw) => format!("Invalid JSON value for MESSAGE: '{}'", raw),
765            Self::Detail(raw) => format!("Invalid JSON value for DETAIL: '{}'", raw),
766            Self::NoDetail => "DETAIL is missing in the RAISE statement".to_string(),
767        }
768    }
769
770    /// What the document should have contained.
771    pub fn hint(&self) -> &'static str {
772        match self {
773            Self::Message(_) => {
774                "MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and \
775                 optional keys: 'details', 'hint'."
776            }
777            _ => {
778                "DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and \
779                 optional key: 'status_text'."
780            }
781        }
782    }
783}
784
785/// A response a database function asked for outright.
786#[derive(Clone, Debug)]
787pub struct RaisedResponse {
788    /// The HTTP status to answer with.
789    pub status: u16,
790    /// The reason phrase, where the schema named one of its own.
791    pub status_text: Option<String>,
792    /// Headers to add to the response.
793    pub headers: Vec<(String, String)>,
794    /// The response body, verbatim.
795    pub body: serde_json::Value,
796    /// Whether the schema wrote the body itself, with a `body` key in DETAIL,
797    /// rather than leaving it to be built from the MESSAGE. Such a response is
798    /// the schema's alone, so a `Content-Type` it raises replaces the default.
799    pub body_supplied: bool,
800}
801
802/// The headers a raise asked for. A value that is not a string is not a
803/// header, as PostgREST reads them.
804fn raised_headers(headers: &serde_json::Map<String, serde_json::Value>) -> Vec<(String, String)> {
805    headers
806        .iter()
807        .filter_map(|(name, value)| Some((name.clone(), value.as_str()?.to_string())))
808        .collect()
809}
810
811impl DatabaseError {
812    /// The response a `RAISE sqlstate 'PGRST'` asked for.
813    ///
814    /// A function can take over the whole response by raising that SQLSTATE:
815    /// the message is the body, and the detail carries the status, an optional
816    /// status text and any headers. It is how a schema returns a 402 with its
817    /// own payload without the API layer knowing anything about billing.
818    ///
819    /// PostgREST rebuilds the body as `{code, message, details, hint}`, which
820    /// is no use to a schema that replaces an API whose errors have another
821    /// shape. So a `body` key in the detail, of any JSON type, is the body
822    /// instead, byte for byte; the message is then only what gets logged, and
823    /// may be free text, and `headers` is optional. PostgREST has no such key
824    /// and ignores it, so no schema written for it is affected.
825    ///
826    /// `None` when this is not that error. `Err` when it is and the schema
827    /// wrote it wrongly, which is a bug in the schema rather than a response
828    /// to half-apply.
829    pub fn raised_response(&self) -> Option<std::result::Result<RaisedResponse, RaiseFault>> {
830        if self.code != "PGRST" {
831            return None;
832        }
833        Some(self.parse_raise())
834    }
835
836    /// Whether the schema chose the status itself, by raising `sqlstate
837    /// 'PGRST'` or a `PT<nnn>` code, rather than leaving it to the table.
838    ///
839    /// Such a status is a request and not a classification, so configuration
840    /// that maps SQLSTATEs to statuses does not apply to it.
841    pub fn status_is_raised(&self) -> bool {
842        self.code == "PGRST" || self.code.starts_with("PT")
843    }
844
845    fn parse_raise(&self) -> std::result::Result<RaisedResponse, RaiseFault> {
846        let object = |raw: &str| -> Option<serde_json::Map<String, serde_json::Value>> {
847            match serde_json::from_str(raw) {
848                Ok(serde_json::Value::Object(map)) => Some(map),
849                _ => None,
850            }
851        };
852
853        // A body of the schema's own makes the rest of the message's rules moot:
854        // nothing is built from it.
855        if let Some(raised) = self.parse_raise_with_body(&object) {
856            return raised;
857        }
858
859        // The message is the body, and a body has to say what went wrong and
860        // under what code -- the two keys a client reads first.
861        let message =
862            object(&self.message).ok_or_else(|| RaiseFault::Message(self.message.clone()))?;
863        if !message.contains_key("code") || !message.contains_key("message") {
864            return Err(RaiseFault::Message(self.message.clone()));
865        }
866
867        let raw_detail = self.details.as_deref().ok_or(RaiseFault::NoDetail)?;
868        let detail =
869            object(raw_detail).ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
870        let status = detail
871            .get("status")
872            .and_then(serde_json::Value::as_u64)
873            .ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
874        let headers = detail
875            .get("headers")
876            .and_then(serde_json::Value::as_object)
877            .ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
878
879        // Every key the error body has, present whether the schema wrote it or
880        // not: a client reading `details` should not have to tell "no detail"
881        // from "no such key".
882        let key = |name: &str| {
883            message
884                .get(name)
885                .cloned()
886                .unwrap_or(serde_json::Value::Null)
887        };
888
889        Ok(RaisedResponse {
890            status: status as u16,
891            status_text: detail
892                .get("status_text")
893                .and_then(serde_json::Value::as_str)
894                .map(str::to_string),
895            headers: raised_headers(headers),
896            body: serde_json::json!({
897                "code": key("code"),
898                "message": key("message"),
899                "details": key("details"),
900                "hint": key("hint"),
901            }),
902            body_supplied: false,
903        })
904    }
905
906    /// The response of a raise whose DETAIL carries a `body`, or `None` if it
907    /// does not and PostgREST's rules apply. The status is still required, and
908    /// `headers`, if given, must still be an object: a schema that wrote those
909    /// wrongly is told so rather than guessed at.
910    fn parse_raise_with_body(
911        &self,
912        object: &dyn Fn(&str) -> Option<serde_json::Map<String, serde_json::Value>>,
913    ) -> Option<std::result::Result<RaisedResponse, RaiseFault>> {
914        let raw_detail = self.details.as_deref()?;
915        let mut detail = object(raw_detail)?;
916        let body = detail.remove("body")?;
917        let fault = || RaiseFault::Detail(raw_detail.to_string());
918
919        let headers = match detail.get("headers") {
920            None => Some(Vec::new()),
921            Some(serde_json::Value::Object(headers)) => Some(raised_headers(headers)),
922            Some(_) => None,
923        };
924        let status = detail.get("status").and_then(serde_json::Value::as_u64);
925        Some(match (status, headers) {
926            (Some(status), Some(headers)) => Ok(RaisedResponse {
927                status: status as u16,
928                status_text: detail
929                    .get("status_text")
930                    .and_then(serde_json::Value::as_str)
931                    .map(str::to_string),
932                headers,
933                body,
934                body_supplied: true,
935            }),
936            _ => Err(fault()),
937        })
938    }
939
940    /// The HTTP status a PostgreSQL error code maps to.
941    ///
942    /// PostgREST's table (`mapSQLtoHTTP` in `Error.hs`), which is part of its
943    /// contract rather than an implementation detail: a client distinguishes a
944    /// missing function from a bad argument by the status.
945    ///
946    /// The default is 400, not 500: the great majority of SQLSTATEs a request
947    /// can provoke are provoked by the request. Reporting them as server
948    /// errors tells the client to retry something that will never succeed.
949    pub fn status_code(&self) -> StatusCode {
950        self.status_code_as(false)
951    }
952
953    /// The HTTP status for a request that is or is not authenticated.
954    ///
955    /// The same table as [`status_code`](Self::status_code), which has the
956    /// answer for an anonymous request. Only `42501` (insufficient privilege)
957    /// depends on who asked, as it does in PostgREST: 401 for an anonymous
958    /// request, which may simply not have said who it is, and 403 for an
959    /// authenticated one, which has and is still not permitted. "Authenticated"
960    /// means the request runs as a role other than the configured anonymous
961    /// role, see
962    /// [`AppConfig::is_authenticated_role`](crate::AppConfig::is_authenticated_role).
963    pub fn status_code_as(&self, authenticated: bool) -> StatusCode {
964        let code = self.code.as_str();
965        let message = self.message.as_str();
966
967        match self.raised_response() {
968            Some(Ok(raised)) => {
969                if let Ok(status) = StatusCode::from_u16(raised.status) {
970                    return status;
971                }
972            }
973            // A raise the schema wrote wrongly is the schema's fault, and a
974            // fault in the server's own data is a 500.
975            Some(Err(_)) => return StatusCode::INTERNAL_SERVER_ERROR,
976            None => {}
977        }
978
979        // `PT<nnn>` is a status code raised by the schema itself: a function
980        // says `RAISE sqlstate 'PT402'` to answer 402, with the message as the
981        // status text.
982        if let Some(digits) = code.strip_prefix("PT") {
983            if let Ok(status) = digits.parse::<u16>() {
984                if let Ok(status) = StatusCode::from_u16(status) {
985                    return status;
986                }
987            }
988            return StatusCode::INTERNAL_SERVER_ERROR;
989        }
990
991        if self.is_unwritable_view() {
992            return StatusCode::METHOD_NOT_ALLOWED;
993        }
994
995        match code {
996            "23503" | "23505" => StatusCode::CONFLICT,
997            // A write attempted inside the read-only transaction a read
998            // request runs in. The request was not wrong, the method was.
999            "25006" => StatusCode::METHOD_NOT_ALLOWED,
1000            // Cardinality violation. `pg-safeupdate` raises it for an
1001            // unqualified UPDATE or DELETE, which is the client's doing;
1002            // anything else is a function or view misbehaving.
1003            "21000" => match message.ends_with("requires a WHERE clause") {
1004                true => StatusCode::BAD_REQUEST,
1005                false => StatusCode::INTERNAL_SERVER_ERROR,
1006            },
1007            // Invalid parameter value, which is also how PostgreSQL reports a
1008            // `SET ROLE` to a role that does not exist.
1009            "22023" => match message.starts_with("role") && message.ends_with("does not exist") {
1010                true => StatusCode::UNAUTHORIZED,
1011                false => StatusCode::BAD_REQUEST,
1012            },
1013            "53400" => StatusCode::INTERNAL_SERVER_ERROR,
1014            "57P01" => StatusCode::SERVICE_UNAVAILABLE,
1015            "P0001" => StatusCode::BAD_REQUEST,
1016            // `xmlagg` is missing only when the request asked for XML the
1017            // server cannot produce, which is a negotiation failure.
1018            "42883" => match message.starts_with("function xmlagg(") {
1019                true => StatusCode::NOT_ACCEPTABLE,
1020                false => StatusCode::NOT_FOUND,
1021            },
1022            "42P01" => StatusCode::NOT_FOUND,
1023            "42P17" => StatusCode::INTERNAL_SERVER_ERROR,
1024            // Without authentication the client may simply not have said who
1025            // it is, so it is told to; with it, it has and is still not
1026            // permitted, which a 401 would send it away to retry.
1027            "42501" => match authenticated {
1028                true => StatusCode::FORBIDDEN,
1029                false => StatusCode::UNAUTHORIZED,
1030            },
1031            _ => match code.as_bytes() {
1032                [b'0', b'8', ..] => StatusCode::SERVICE_UNAVAILABLE,
1033                [b'0', b'9', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1034                [b'0', b'L', ..] | [b'0', b'P', ..] => StatusCode::FORBIDDEN,
1035                [b'2', b'5', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1036                [b'2', b'8', ..] => StatusCode::FORBIDDEN,
1037                [b'2', b'D', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1038                [b'3', b'8', ..] | [b'3', b'9', ..] | [b'3', b'B', ..] => {
1039                    StatusCode::INTERNAL_SERVER_ERROR
1040                }
1041                [b'4', b'0', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1042                [b'5', b'3', ..] => StatusCode::SERVICE_UNAVAILABLE,
1043                [b'5', b'4', ..] | [b'5', b'5', ..] | [b'5', b'7', ..] | [b'5', b'8', ..] => {
1044                    StatusCode::INTERNAL_SERVER_ERROR
1045                }
1046                [b'F', b'0', ..] | [b'H', b'V', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1047                [b'P', b'0', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1048                [b'X', b'X', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1049                _ => StatusCode::BAD_REQUEST,
1050            },
1051        }
1052    }
1053
1054    /// Whether this is PostgreSQL refusing a write to a view it cannot write
1055    /// through: one that is not automatically updatable and has no `INSTEAD
1056    /// OF` trigger or rule for the operation, or a materialized view.
1057    ///
1058    /// That is a method the resource does not take, whoever asks -- a 405,
1059    /// not the 500 its SQLSTATE (`55000`, object not in prerequisite state)
1060    /// would otherwise be. Read from the message, as `xmlagg` and the missing
1061    /// role are, because the SQLSTATE alone covers unrelated faults too; a
1062    /// server whose `lc_messages` is not English keeps the 500.
1063    pub fn is_unwritable_view(&self) -> bool {
1064        let message = self.message.as_str();
1065        match self.code.as_str() {
1066            "55000" => [
1067                "cannot insert into view ",
1068                "cannot update view ",
1069                "cannot delete from view ",
1070            ]
1071            .iter()
1072            .any(|prefix| message.starts_with(prefix)),
1073            "42809" => message.starts_with("cannot change materialized view "),
1074            _ => false,
1075        }
1076    }
1077
1078    /// Get error code for API response.
1079    pub fn code(&self) -> &'static str {
1080        if self.is_unwritable_view() {
1081            // PostgREST's code for a verb the resource does not support.
1082            return "PGRST117";
1083        }
1084        match self.code.as_str() {
1085            c if c.starts_with("23") => "PGRST503", // Constraint violation
1086            c if c.starts_with("42") => "PGRST504", // SQL error
1087            c if c.starts_with("28") => "PGRST505", // Auth error
1088            _ => "PGRST500",                        // Generic database error
1089        }
1090    }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096
1097    fn database(code: &str, message: &str) -> DatabaseError {
1098        DatabaseError {
1099            code: code.into(),
1100            message: message.into(),
1101            details: None,
1102            hint: None,
1103            constraint: None,
1104            table: None,
1105            column: None,
1106        }
1107    }
1108
1109    fn raised(message: &str, detail: Option<&str>) -> DatabaseError {
1110        DatabaseError {
1111            details: detail.map(str::to_string),
1112            ..database("PGRST", message)
1113        }
1114    }
1115
1116    /// PostgREST's own shape, which a `body` key does not disturb when it is
1117    /// absent: the body is rebuilt from the message, with every key present.
1118    #[test]
1119    fn a_raise_without_a_body_is_postgrests() {
1120        let raised = raised(
1121            r#"{"code":"123","message":"Payment Required","hint":"Upgrade"}"#,
1122            Some(r#"{"status":402,"headers":{"X-Powered-By":"Nerd Rage","X-N":3}}"#),
1123        )
1124        .raised_response()
1125        .unwrap()
1126        .unwrap();
1127        assert_eq!(raised.status, 402);
1128        assert_eq!(
1129            raised.headers,
1130            [("X-Powered-By".to_string(), "Nerd Rage".to_string())]
1131        );
1132        assert_eq!(
1133            raised.body,
1134            serde_json::json!({
1135                "code": "123", "message": "Payment Required",
1136                "details": null, "hint": "Upgrade",
1137            })
1138        );
1139        assert!(!raised.body_supplied);
1140
1141        // And its faults are as they were: the message is checked first, and
1142        // `headers` is required.
1143        let fault = |message, detail| raised_fault(self::raised(message, detail)).details();
1144        assert_eq!(
1145            fault("not json", Some(r#"{"status":402,"headers":{}}"#)),
1146            "Invalid JSON value for MESSAGE: 'not json'"
1147        );
1148        assert_eq!(
1149            fault(r#"{"code":"1","message":"m"}"#, Some(r#"{"status":402}"#)),
1150            r#"Invalid JSON value for DETAIL: '{"status":402}'"#
1151        );
1152        assert_eq!(
1153            fault(r#"{"code":"1","message":"m"}"#, None),
1154            "DETAIL is missing in the RAISE statement"
1155        );
1156    }
1157
1158    fn raised_fault(error: DatabaseError) -> RaiseFault {
1159        error.raised_response().unwrap().unwrap_err()
1160    }
1161
1162    /// A `body` of any JSON type is the body, as written, and the message
1163    /// need not be JSON at all.
1164    #[test]
1165    fn a_body_in_the_detail_is_the_response_body() {
1166        let body = |detail: &str| {
1167            raised(
1168                "access required for report 7",
1169                Some(&format!(r#"{{"status":403,"body":{detail}}}"#)),
1170            )
1171            .raised_response()
1172            .unwrap()
1173            .unwrap()
1174        };
1175
1176        let object = body(r#"{"detail":{"code":"access_required","can_request":true}}"#);
1177        assert_eq!(object.status, 403);
1178        assert!(object.body_supplied);
1179        assert!(object.headers.is_empty(), "headers are optional");
1180        assert_eq!(
1181            object.body,
1182            serde_json::json!({"detail": {"code": "access_required", "can_request": true}})
1183        );
1184        assert_eq!(
1185            body(r#""plain text""#).body,
1186            serde_json::json!("plain text")
1187        );
1188        assert_eq!(body("[1,2]").body, serde_json::json!([1, 2]));
1189        assert_eq!(body("null").body, serde_json::Value::Null);
1190    }
1191
1192    #[test]
1193    fn a_body_comes_with_headers_and_a_status_text_when_given() {
1194        let raised = raised(
1195            r#"{"code":"x","message":"also valid"}"#,
1196            Some(
1197                r#"{"status":451,"status_text":"Gone Away","headers":{"Content-Type":"text/plain"},"body":"x"}"#,
1198            ),
1199        )
1200        .raised_response()
1201        .unwrap()
1202        .unwrap();
1203        assert_eq!(raised.status, 451);
1204        assert_eq!(raised.status_text.as_deref(), Some("Gone Away"));
1205        assert_eq!(
1206            raised.headers,
1207            [("Content-Type".to_string(), "text/plain".to_string())]
1208        );
1209        assert_eq!(raised.body, serde_json::json!("x"));
1210    }
1211
1212    /// The status is still the schema's to give, and a `headers` that is
1213    /// there has to be an object; a body does not excuse either.
1214    #[test]
1215    fn a_body_still_needs_a_status() {
1216        for detail in [
1217            r#"{"body":{"a":1}}"#,
1218            r#"{"status":"402","body":{"a":1}}"#,
1219            r#"{"status":402,"headers":["a"],"body":{"a":1}}"#,
1220        ] {
1221            let fault = raised_fault(raised("free text", Some(detail)));
1222            assert_eq!(
1223                fault.details(),
1224                format!("Invalid JSON value for DETAIL: '{detail}'")
1225            );
1226        }
1227        // Only an object with a `body` key is a takeover of the body: a
1228        // DETAIL that is not an object is the usual fault.
1229        let fault = raised_fault(raised("free text", Some("[1]")));
1230        assert!(matches!(fault, RaiseFault::Message(_)));
1231    }
1232
1233    /// A view PostgreSQL cannot write through refuses the method for every
1234    /// role, which is a 405; it was answered as the 500 its SQLSTATE says.
1235    #[test]
1236    fn a_write_a_view_cannot_take_is_a_405() {
1237        for (code, message) in [
1238            ("55000", "cannot insert into view \"j\""),
1239            ("55000", "cannot update view \"j\""),
1240            ("55000", "cannot delete from view \"j\""),
1241            ("42809", "cannot change materialized view \"m\""),
1242        ] {
1243            let error = Error::Database(database(code, message));
1244            assert_eq!(
1245                error.status_code(),
1246                StatusCode::METHOD_NOT_ALLOWED,
1247                "{message}"
1248            );
1249            assert_eq!(error.code(), "PGRST117", "{message}");
1250        }
1251        // The same SQLSTATEs about anything else keep their status.
1252        let other = Error::Database(database("55000", "lock is not available"));
1253        assert_eq!(other.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
1254        let other = Error::Database(database("42809", "\"f\" is not a procedure"));
1255        assert_eq!(other.status_code(), StatusCode::BAD_REQUEST);
1256    }
1257
1258    /// A missing grant is 401 to a request that has not said who it is and 403
1259    /// to one that has, as in PostgREST; `status_code` is the anonymous answer.
1260    #[test]
1261    fn a_missing_grant_is_a_401_or_a_403_by_who_asked() {
1262        let error = Error::Database(database("42501", "permission denied for table t"));
1263        assert_eq!(error.status_code_as(false), StatusCode::UNAUTHORIZED);
1264        assert_eq!(error.status_code_as(true), StatusCode::FORBIDDEN);
1265        assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED);
1266
1267        let Error::Database(db) = &error else {
1268            unreachable!()
1269        };
1270        assert_eq!(db.status_code_as(true), StatusCode::FORBIDDEN);
1271        assert_eq!(db.status_code(), db.status_code_as(false));
1272    }
1273
1274    /// Who asked changes nothing else, including a status the schema raised.
1275    #[test]
1276    fn who_asked_decides_only_a_missing_grant() {
1277        for code in ["23505", "42P01", "P0001", "PT402", "28000", "22023"] {
1278            let db = database(code, "x");
1279            assert_eq!(db.status_code_as(true), db.status_code(), "{code}");
1280        }
1281    }
1282
1283    #[test]
1284    fn test_error_status_codes() {
1285        assert_eq!(
1286            Error::InvalidQueryParam("test".into()).status_code(),
1287            StatusCode::BAD_REQUEST
1288        );
1289        assert_eq!(Error::MissingAuth.status_code(), StatusCode::UNAUTHORIZED);
1290        assert_eq!(
1291            Error::TableNotFound {
1292                name: "users".into(),
1293                suggestion: None
1294            }
1295            .status_code(),
1296            StatusCode::NOT_FOUND
1297        );
1298        assert_eq!(
1299            Error::UnsupportedMethod("TRACE".into()).status_code(),
1300            StatusCode::METHOD_NOT_ALLOWED
1301        );
1302    }
1303
1304    #[test]
1305    fn test_error_codes() {
1306        // A malformed query string is a parse failure, PGRST100 -- the same
1307        // code as a malformed path. PGRST101 means something else entirely.
1308        assert_eq!(Error::InvalidQueryParam("test".into()).code(), "PGRST100");
1309        assert_eq!(Error::MissingAuth.code(), "PGRST302");
1310        assert_eq!(
1311            Error::TableNotFound {
1312                name: "users".into(),
1313                suggestion: None
1314            }
1315            .code(),
1316            "PGRST205"
1317        );
1318    }
1319
1320    #[test]
1321    fn test_database_error_status() {
1322        let constraint_error = DatabaseError {
1323            code: "23505".into(), // unique_violation
1324            message: "Duplicate key".into(),
1325            details: None,
1326            hint: None,
1327            constraint: Some("users_pkey".into()),
1328            table: Some("users".into()),
1329            column: None,
1330        };
1331        assert_eq!(constraint_error.status_code(), StatusCode::CONFLICT);
1332    }
1333
1334    #[test]
1335    fn test_error_to_json() {
1336        let error = Error::InvalidQueryParam("bad filter".into());
1337        let json = error.to_json();
1338        assert_eq!(json["code"], "PGRST100");
1339        assert!(json["message"].as_str().unwrap().contains("bad filter"));
1340    }
1341}