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    /// Preferences the server does not know, sent with `handling=strict`.
311    ///
312    /// Strict handling is a request to be told rather than have them ignored.
313    #[error("Invalid preferences given with handling=strict")]
314    InvalidPreferences(Vec<String>),
315
316    // ========================================================================
317    // Schema Cache Errors
318    // ========================================================================
319    /// A request arrived before the schema had been read. Transient at
320    /// start-up; persistent means the initial load failed.
321    #[error("Schema cache not loaded")]
322    SchemaCacheNotLoaded,
323
324    /// Reading the schema from PostgreSQL failed. Usually a missing privilege
325    /// on the catalogue rather than a fault in the schema itself.
326    #[error("Schema cache load failed: {0}")]
327    SchemaCacheLoadFailed(String),
328
329    // ========================================================================
330    // Database Errors (500/4xx depending on type)
331    // ========================================================================
332    /// PostgreSQL refused the statement. The SQLSTATE decides the HTTP status,
333    /// so this is not always a 500.
334    #[error("Database error: {0}")]
335    Database(#[from] DatabaseError),
336
337    /// No connection could be obtained: the pool is exhausted, or the database
338    /// is unreachable.
339    #[error("Connection pool error: {0}")]
340    ConnectionPool(String),
341
342    // ========================================================================
343    // Internal Errors (500)
344    // ========================================================================
345    /// A fault in this server. Always a bug; the message is for its log rather
346    /// than for the client to act on.
347    #[error("Internal error: {0}")]
348    Internal(String),
349
350    /// The server was started with a setting it cannot act on.
351    #[error("Configuration error: {0}")]
352    Config(String),
353
354    // ========================================================================
355    // Plan Errors
356    // ========================================================================
357    /// The request parsed and no execution plan could be built from it.
358    #[error("Invalid plan: {0}")]
359    InvalidPlan(String),
360
361    /// An embed that cannot be planned, where no more specific variant fits.
362    #[error("Embedding error: {0}")]
363    EmbeddingError(String),
364}
365
366impl Error {
367    /// Get the HTTP status code for this error, as it is answered to an
368    /// anonymous request.
369    ///
370    /// See [`status_code_as`](Self::status_code_as) for the one status that
371    /// depends on who asked.
372    pub fn status_code(&self) -> StatusCode {
373        self.status_code_as(false)
374    }
375
376    /// Get the HTTP status code for this error, for a request that is or is
377    /// not authenticated.
378    ///
379    /// Only a database error's status can differ: a missing grant (`42501`)
380    /// is 401 to an anonymous request and 403 to an authenticated one. See
381    /// [`DatabaseError::status_code_as`].
382    pub fn status_code_as(&self, authenticated: bool) -> StatusCode {
383        match self {
384            // 400 Bad Request
385            Self::InvalidPath(_)
386            | Self::InvalidQueryParam(_)
387            | Self::InvalidHeader(_)
388            | Self::InvalidBody(_)
389            | Self::MissingParameter(_)
390            | Self::AmbiguousRequest(_)
391            | Self::UnparsableQuery { .. }
392            | Self::UnknownColumn { .. }
393            | Self::NotAnEmbeddedResource(_)
394            | Self::RelatedOrderNotPossible { .. }
395            | Self::InvalidPreferences(_)
396            | Self::PutLimitNotAllowed
397            | Self::PutMatchingPk
398            | Self::MaxAffectedExceeded(_)
399            | Self::InvalidPlan(_)
400            | Self::EmbeddingError(_)
401            | Self::AggregatesNotAllowed
402            | Self::MissingGeometryColumn => StatusCode::BAD_REQUEST,
403
404            // The request names something real, but not which one of it.
405            Self::AmbiguousFunction { .. } | Self::AmbiguousRelationship { .. } => {
406                StatusCode::MULTIPLE_CHOICES
407            }
408
409            // 401 Unauthorized
410            Self::InvalidJwt(_)
411            | Self::NoSuitableJwtKey
412            | Self::JwtClaim(_)
413            | Self::MissingAuth => StatusCode::UNAUTHORIZED,
414
415            // 403 Forbidden
416            Self::InsufficientPermissions(_) => StatusCode::FORBIDDEN,
417
418            // 404 Not Found
419            Self::NotFound(_) | Self::TableNotFound { .. } | Self::FunctionNotFound { .. } => {
420                StatusCode::NOT_FOUND
421            }
422
423            // A relationship or a column the schema does not have is a fault
424            // in the request, not a missing resource: the resource addressed
425            // by the URL exists, and `?select=` asked it for something it
426            // cannot give. The table it names is what a 404 would be about.
427            Self::ColumnNotFound(_) | Self::RelationshipNotFound { .. } => StatusCode::BAD_REQUEST,
428
429            // 405 Method Not Allowed
430            Self::UnsupportedMethod(_) | Self::InvalidRpcMethod(_) | Self::InvalidPutFilters => {
431                StatusCode::METHOD_NOT_ALLOWED
432            }
433
434            // 406 Not Acceptable
435            Self::UnacceptableSchema { .. }
436            | Self::NotSingular { .. }
437            | Self::InvalidMediaType(_) => StatusCode::NOT_ACCEPTABLE,
438
439            Self::InvalidResourcePath => StatusCode::NOT_FOUND,
440
441            // A range the server cannot satisfy, which is what 416 is for --
442            // a negative limit asks for a window that does not exist rather
443            // than for one the server merely declines.
444            Self::InvalidRange(_) => StatusCode::RANGE_NOT_SATISFIABLE,
445
446            // 500 Internal Server Error
447            Self::JwtSecretMissing
448            | Self::RaiseNotUnderstood(_)
449            | Self::InvalidGucHeaders
450            | Self::InvalidGucStatus
451            | Self::SchemaCacheNotLoaded
452            | Self::SchemaCacheLoadFailed(_)
453            | Self::ConnectionPool(_)
454            | Self::Internal(_)
455            | Self::Config(_) => StatusCode::INTERNAL_SERVER_ERROR,
456
457            // Database errors map based on type
458            Self::Database(db_err) => db_err.status_code_as(authenticated),
459        }
460    }
461
462    /// Get the error code for API responses.
463    pub fn code(&self) -> &'static str {
464        match self {
465            Self::InvalidPath(_) => "PGRST100",
466            Self::AggregatesNotAllowed => "PGRST123",
467            // PGRST100 is the parse failure in PostgREST's taxonomy, covering
468            // both the path and the query string; PGRST101 is a function
469            // invoked with a method its volatility does not allow.
470            Self::InvalidQueryParam(_) | Self::UnparsableQuery { .. } => "PGRST100",
471            // Not one of PostgREST's own: a malformed header is a request
472            // that did not parse, which is what PGRST100 covers.
473            Self::InvalidHeader(_) => "PGRST100",
474            Self::InvalidBody(_) => "PGRST102",
475            Self::UnsupportedMethod(_) => "PGRST117",
476            Self::InvalidRpcMethod(_) => "PGRST101",
477            Self::UnacceptableSchema { .. } => "PGRST106",
478            Self::UnknownColumn { .. } => "PGRST204",
479            Self::InvalidRange(_) => "PGRST103",
480            Self::InvalidMediaType(_) => "PGRST107",
481            Self::MissingParameter(_) => "PGRST109",
482            Self::AmbiguousRequest(_) => "PGRST110",
483            Self::AmbiguousFunction { .. } => "PGRST203",
484            Self::AmbiguousRelationship { .. } => "PGRST201",
485
486            Self::InvalidJwt(_) | Self::NoSuitableJwtKey => "PGRST301",
487            Self::JwtSecretMissing => "PGRST300",
488            Self::JwtClaim(_) => "PGRST303",
489            Self::MissingAuth => "PGRST302",
490            Self::InsufficientPermissions(_) => "PGRST203",
491
492            Self::NotFound(_) => "PGRST205",
493            Self::TableNotFound { .. } => "PGRST205",
494            Self::FunctionNotFound { .. } => "PGRST202",
495            Self::MissingGeometryColumn => "22023",
496            Self::ColumnNotFound(_) => "PGRST204",
497            Self::RelationshipNotFound { .. } => "PGRST200",
498            Self::NotAnEmbeddedResource(_) => "PGRST108",
499            Self::NotSingular { .. } => "PGRST116",
500            Self::InvalidResourcePath => "PGRST125",
501            Self::InvalidPutFilters => "PGRST105",
502            Self::PutLimitNotAllowed => "PGRST114",
503            Self::PutMatchingPk => "PGRST115",
504            Self::MaxAffectedExceeded(_) => "PGRST124",
505            Self::RaiseNotUnderstood(_) => "PGRST121",
506            Self::InvalidGucHeaders => "PGRST111",
507            Self::InvalidGucStatus => "PGRST112",
508            Self::RelatedOrderNotPossible { .. } => "PGRST118",
509            Self::InvalidPreferences(_) => "PGRST122",
510
511            Self::SchemaCacheNotLoaded => "PGRST400",
512            Self::SchemaCacheLoadFailed(_) => "PGRST401",
513
514            Self::Database(e) => e.code(),
515            Self::ConnectionPool(_) => "PGRST500",
516
517            Self::Internal(_) => "PGRST900",
518            Self::Config(_) => "PGRST901",
519
520            Self::InvalidPlan(_) => "PGRST600",
521            Self::EmbeddingError(_) => "PGRST601",
522        }
523    }
524
525    /// Convert to JSON error response.
526    pub fn to_json(&self) -> serde_json::Value {
527        serde_json::json!({
528            "code": self.code(),
529            "message": self.to_string(),
530            "details": self.details(),
531            "hint": self.hint(),
532        })
533    }
534
535    /// Get additional details for the error.
536    pub fn details(&self) -> Option<serde_json::Value> {
537        match self {
538            Self::Database(db_err) => db_err.details.clone().map(serde_json::Value::String),
539            // A structured list rather than a sentence: each candidate is
540            // named so the client can pick one and say which.
541            Self::AmbiguousRelationship {
542                origin,
543                target,
544                candidates,
545                ..
546            } => Some(serde_json::Value::Array(
547                candidates
548                    .iter()
549                    .map(|(cardinality, description)| {
550                        serde_json::json!({
551                            "cardinality": cardinality,
552                            "embedding": format!("{} with {}", origin, target),
553                            "relationship": description,
554                        })
555                    })
556                    .collect(),
557            )),
558            Self::RelationshipNotFound {
559                origin,
560                target,
561                hint,
562                schema,
563                ..
564            } => Some(serde_json::Value::String(format!(
565                "Searched for a foreign key relationship between '{}' and '{}'{} in the schema \
566                 '{}', but no matches were found.",
567                origin,
568                target,
569                match hint {
570                    Some(hint) => format!(" using the hint '{}'", hint),
571                    None => String::new(),
572                },
573                schema
574            ))),
575            Self::RelatedOrderNotPossible { origin, relation } => {
576                Some(serde_json::Value::String(format!(
577                    "'{}' and '{}' do not form a many-to-one or one-to-one relationship",
578                    origin, relation
579                )))
580            }
581            Self::InvalidRange(reason) => Some(serde_json::Value::String(reason.clone())),
582            Self::MaxAffectedExceeded(affected) => Some(serde_json::Value::String(format!(
583                "The query affects {} rows",
584                affected
585            ))),
586            Self::NotSingular { rows } => Some(serde_json::Value::String(format!(
587                "The result contains {} rows",
588                rows
589            ))),
590            Self::InvalidPreferences(invalid) => Some(serde_json::Value::String(format!(
591                "Invalid preferences: {}",
592                invalid.join(", ")
593            ))),
594            Self::RaiseNotUnderstood(fault) => Some(serde_json::Value::String(fault.details())),
595            Self::NoSuitableJwtKey => Some(serde_json::Value::String(
596                "No suitable key was found to decode the JWT".into(),
597            )),
598            Self::UnparsableQuery { expected, .. } => {
599                Some(serde_json::Value::String(expected.clone()))
600            }
601            Self::FunctionNotFound {
602                name,
603                params,
604                single_param,
605                ..
606            } => Some(serde_json::Value::String(format!(
607                "Searched for the function {} {}, but no matches were found in the schema cache.",
608                name,
609                match single_param.as_deref() {
610                    // A body that is one value carries no argument names, so
611                    // the only thing that could have matched is the parameter
612                    // that takes it.
613                    Some(other) if other != JSON_PARAM =>
614                        format!("with a single unnamed {} parameter", other),
615                    Some(_) => format!(
616                        "{} or with a single unnamed {} parameter",
617                        describe_params(params),
618                        JSON_PARAM
619                    ),
620                    None => describe_params(params),
621                }
622            ))),
623            _ => None,
624        }
625    }
626
627    /// Get a hint for resolving the error.
628    pub fn hint(&self) -> Option<String> {
629        match self {
630            Self::NotAnEmbeddedResource(name) => Some(format!(
631                "Verify that '{}' is included in the 'select' query parameter.",
632                name
633            )),
634            Self::TableNotFound { suggestion, .. } => suggestion
635                .as_ref()
636                .map(|name| format!("Perhaps you meant the table '{}'", name)),
637            Self::RelationshipNotFound {
638                target, suggestion, ..
639            } => suggestion
640                .as_ref()
641                .map(|name| format!("Perhaps you meant '{}' instead of '{}'.", name, target)),
642            Self::AmbiguousFunction { .. } => Some(
643                "Try renaming the parameters or the function itself in the database so function \
644                 overloading can be resolved"
645                    .into(),
646            ),
647            Self::AmbiguousRelationship {
648                target,
649                disambiguated,
650                ..
651            } => Some(format!(
652                "Try changing '{}' to one of the following: {}. Find the desired relationship in \
653                 the 'details' key.",
654                target,
655                disambiguated
656                    .iter()
657                    .map(|name| format!("'{}'", name))
658                    .collect::<Vec<_>>()
659                    .join(", ")
660            )),
661            Self::RaiseNotUnderstood(fault) => Some(fault.hint().into()),
662            // A body that is one value names no arguments, so there is no
663            // near miss to point at: any function of that name would have
664            // done, and none of them takes this body.
665            Self::FunctionNotFound {
666                candidate,
667                single_param,
668                ..
669            } if !names_only_one_param(single_param.as_deref()) => candidate
670                .as_ref()
671                .map(|c| format!("Perhaps you meant to call the function {}", c)),
672            Self::FunctionNotFound { .. } => None,
673            // The schemas a server exposes are part of its contract, not an
674            // internal detail, so naming them is how the client is told what
675            // to ask for instead.
676            Self::UnacceptableSchema { exposed, .. } => Some(format!(
677                "Only the following schemas are exposed: {}",
678                exposed.join(", ")
679            )),
680            Self::Database(db_err) => db_err.hint.clone(),
681            _ => None,
682        }
683    }
684}
685
686/// How the message spells the type of a single unnamed JSON parameter.
687///
688/// It is the one media type that can also carry named arguments, so it reads
689/// as an alternative rather than as the only thing looked for.
690pub const JSON_PARAM: &str = "json/jsonb";
691
692/// Whether the request could only ever have matched one unnamed parameter.
693///
694/// True for a body that is one value -- text, xml or bytes -- which carries no
695/// argument names at all.
696pub fn names_only_one_param(single_param: Option<&str>) -> bool {
697    matches!(single_param, Some(other) if other != JSON_PARAM)
698}
699
700/// How a function's argument list reads in an error message.
701///
702/// PostgREST words the no-argument case differently rather than printing an
703/// empty list, and the messages are matched verbatim by clients.
704pub fn function_signature(name: &str, params: &[String]) -> String {
705    match params.is_empty() {
706        true => format!("{} without parameters", name),
707        false => format!("{}({})", name, params.join(", ")),
708    }
709}
710
711fn describe_params(params: &[String]) -> String {
712    match params.len() {
713        0 => "without parameters".to_string(),
714        1 => format!("with parameter {}", params[0]),
715        _ => format!("with parameters {}", params.join(", ")),
716    }
717}
718
719/// Database-specific error type.
720#[derive(Error, Debug)]
721#[error("Database error [{code}]: {message}")]
722pub struct DatabaseError {
723    /// The five-character SQLSTATE. This decides the HTTP status, so it is the
724    /// field that matters most.
725    pub code: String,
726    /// PostgreSQL's primary message.
727    pub message: String,
728    /// PostgreSQL's detail field, where it sent one.
729    pub details: Option<String>,
730    /// PostgreSQL's hint field, where it sent one.
731    pub hint: Option<String>,
732    /// The constraint that was violated, for the integrity SQLSTATEs.
733    pub constraint: Option<String>,
734    /// The table the failure concerns, where PostgreSQL identified one.
735    pub table: Option<String>,
736    /// The column the failure concerns, where PostgreSQL identified one.
737    pub column: Option<String>,
738}
739
740/// What was wrong with a `RAISE sqlstate 'PGRST'`.
741#[derive(Clone, Debug)]
742pub enum RaiseFault {
743    /// The MESSAGE was not the JSON object it has to be.
744    Message(String),
745    /// The DETAIL was not the JSON object it has to be.
746    Detail(String),
747    /// There was no DETAIL, and the status has to come from somewhere.
748    NoDetail,
749}
750
751impl RaiseFault {
752    /// What the schema author has to look at.
753    pub fn details(&self) -> String {
754        match self {
755            Self::Message(raw) => format!("Invalid JSON value for MESSAGE: '{}'", raw),
756            Self::Detail(raw) => format!("Invalid JSON value for DETAIL: '{}'", raw),
757            Self::NoDetail => "DETAIL is missing in the RAISE statement".to_string(),
758        }
759    }
760
761    /// What the document should have contained.
762    pub fn hint(&self) -> &'static str {
763        match self {
764            Self::Message(_) => {
765                "MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and \
766                 optional keys: 'details', 'hint'."
767            }
768            _ => {
769                "DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and \
770                 optional key: 'status_text'."
771            }
772        }
773    }
774}
775
776/// A response a database function asked for outright.
777#[derive(Clone, Debug)]
778pub struct RaisedResponse {
779    /// The HTTP status to answer with.
780    pub status: u16,
781    /// The reason phrase, where the schema named one of its own.
782    pub status_text: Option<String>,
783    /// Headers to add to the response.
784    pub headers: Vec<(String, String)>,
785    /// The response body, verbatim.
786    pub body: serde_json::Value,
787    /// Whether the schema wrote the body itself, with a `body` key in DETAIL,
788    /// rather than leaving it to be built from the MESSAGE. Such a response is
789    /// the schema's alone, so a `Content-Type` it raises replaces the default.
790    pub body_supplied: bool,
791}
792
793/// The headers a raise asked for. A value that is not a string is not a
794/// header, as PostgREST reads them.
795fn raised_headers(headers: &serde_json::Map<String, serde_json::Value>) -> Vec<(String, String)> {
796    headers
797        .iter()
798        .filter_map(|(name, value)| Some((name.clone(), value.as_str()?.to_string())))
799        .collect()
800}
801
802impl DatabaseError {
803    /// The response a `RAISE sqlstate 'PGRST'` asked for.
804    ///
805    /// A function can take over the whole response by raising that SQLSTATE:
806    /// the message is the body, and the detail carries the status, an optional
807    /// status text and any headers. It is how a schema returns a 402 with its
808    /// own payload without the API layer knowing anything about billing.
809    ///
810    /// PostgREST rebuilds the body as `{code, message, details, hint}`, which
811    /// is no use to a schema that replaces an API whose errors have another
812    /// shape. So a `body` key in the detail, of any JSON type, is the body
813    /// instead, byte for byte; the message is then only what gets logged, and
814    /// may be free text, and `headers` is optional. PostgREST has no such key
815    /// and ignores it, so no schema written for it is affected.
816    ///
817    /// `None` when this is not that error. `Err` when it is and the schema
818    /// wrote it wrongly, which is a bug in the schema rather than a response
819    /// to half-apply.
820    pub fn raised_response(&self) -> Option<std::result::Result<RaisedResponse, RaiseFault>> {
821        if self.code != "PGRST" {
822            return None;
823        }
824        Some(self.parse_raise())
825    }
826
827    /// Whether the schema chose the status itself, by raising `sqlstate
828    /// 'PGRST'` or a `PT<nnn>` code, rather than leaving it to the table.
829    ///
830    /// Such a status is a request and not a classification, so configuration
831    /// that maps SQLSTATEs to statuses does not apply to it.
832    pub fn status_is_raised(&self) -> bool {
833        self.code == "PGRST" || self.code.starts_with("PT")
834    }
835
836    fn parse_raise(&self) -> std::result::Result<RaisedResponse, RaiseFault> {
837        let object = |raw: &str| -> Option<serde_json::Map<String, serde_json::Value>> {
838            match serde_json::from_str(raw) {
839                Ok(serde_json::Value::Object(map)) => Some(map),
840                _ => None,
841            }
842        };
843
844        // A body of the schema's own makes the rest of the message's rules moot:
845        // nothing is built from it.
846        if let Some(raised) = self.parse_raise_with_body(&object) {
847            return raised;
848        }
849
850        // The message is the body, and a body has to say what went wrong and
851        // under what code -- the two keys a client reads first.
852        let message =
853            object(&self.message).ok_or_else(|| RaiseFault::Message(self.message.clone()))?;
854        if !message.contains_key("code") || !message.contains_key("message") {
855            return Err(RaiseFault::Message(self.message.clone()));
856        }
857
858        let raw_detail = self.details.as_deref().ok_or(RaiseFault::NoDetail)?;
859        let detail =
860            object(raw_detail).ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
861        let status = detail
862            .get("status")
863            .and_then(serde_json::Value::as_u64)
864            .ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
865        let headers = detail
866            .get("headers")
867            .and_then(serde_json::Value::as_object)
868            .ok_or_else(|| RaiseFault::Detail(raw_detail.to_string()))?;
869
870        // Every key the error body has, present whether the schema wrote it or
871        // not: a client reading `details` should not have to tell "no detail"
872        // from "no such key".
873        let key = |name: &str| {
874            message
875                .get(name)
876                .cloned()
877                .unwrap_or(serde_json::Value::Null)
878        };
879
880        Ok(RaisedResponse {
881            status: status as u16,
882            status_text: detail
883                .get("status_text")
884                .and_then(serde_json::Value::as_str)
885                .map(str::to_string),
886            headers: raised_headers(headers),
887            body: serde_json::json!({
888                "code": key("code"),
889                "message": key("message"),
890                "details": key("details"),
891                "hint": key("hint"),
892            }),
893            body_supplied: false,
894        })
895    }
896
897    /// The response of a raise whose DETAIL carries a `body`, or `None` if it
898    /// does not and PostgREST's rules apply. The status is still required, and
899    /// `headers`, if given, must still be an object: a schema that wrote those
900    /// wrongly is told so rather than guessed at.
901    fn parse_raise_with_body(
902        &self,
903        object: &dyn Fn(&str) -> Option<serde_json::Map<String, serde_json::Value>>,
904    ) -> Option<std::result::Result<RaisedResponse, RaiseFault>> {
905        let raw_detail = self.details.as_deref()?;
906        let mut detail = object(raw_detail)?;
907        let body = detail.remove("body")?;
908        let fault = || RaiseFault::Detail(raw_detail.to_string());
909
910        let headers = match detail.get("headers") {
911            None => Some(Vec::new()),
912            Some(serde_json::Value::Object(headers)) => Some(raised_headers(headers)),
913            Some(_) => None,
914        };
915        let status = detail.get("status").and_then(serde_json::Value::as_u64);
916        Some(match (status, headers) {
917            (Some(status), Some(headers)) => Ok(RaisedResponse {
918                status: status as u16,
919                status_text: detail
920                    .get("status_text")
921                    .and_then(serde_json::Value::as_str)
922                    .map(str::to_string),
923                headers,
924                body,
925                body_supplied: true,
926            }),
927            _ => Err(fault()),
928        })
929    }
930
931    /// The HTTP status a PostgreSQL error code maps to.
932    ///
933    /// PostgREST's table (`mapSQLtoHTTP` in `Error.hs`), which is part of its
934    /// contract rather than an implementation detail: a client distinguishes a
935    /// missing function from a bad argument by the status.
936    ///
937    /// The default is 400, not 500: the great majority of SQLSTATEs a request
938    /// can provoke are provoked by the request. Reporting them as server
939    /// errors tells the client to retry something that will never succeed.
940    pub fn status_code(&self) -> StatusCode {
941        self.status_code_as(false)
942    }
943
944    /// The HTTP status for a request that is or is not authenticated.
945    ///
946    /// The same table as [`status_code`](Self::status_code), which has the
947    /// answer for an anonymous request. Only `42501` (insufficient privilege)
948    /// depends on who asked, as it does in PostgREST: 401 for an anonymous
949    /// request, which may simply not have said who it is, and 403 for an
950    /// authenticated one, which has and is still not permitted. "Authenticated"
951    /// means the request runs as a role other than the configured anonymous
952    /// role, see
953    /// [`AppConfig::is_authenticated_role`](crate::AppConfig::is_authenticated_role).
954    pub fn status_code_as(&self, authenticated: bool) -> StatusCode {
955        let code = self.code.as_str();
956        let message = self.message.as_str();
957
958        match self.raised_response() {
959            Some(Ok(raised)) => {
960                if let Ok(status) = StatusCode::from_u16(raised.status) {
961                    return status;
962                }
963            }
964            // A raise the schema wrote wrongly is the schema's fault, and a
965            // fault in the server's own data is a 500.
966            Some(Err(_)) => return StatusCode::INTERNAL_SERVER_ERROR,
967            None => {}
968        }
969
970        // `PT<nnn>` is a status code raised by the schema itself: a function
971        // says `RAISE sqlstate 'PT402'` to answer 402, with the message as the
972        // status text.
973        if let Some(digits) = code.strip_prefix("PT") {
974            if let Ok(status) = digits.parse::<u16>() {
975                if let Ok(status) = StatusCode::from_u16(status) {
976                    return status;
977                }
978            }
979            return StatusCode::INTERNAL_SERVER_ERROR;
980        }
981
982        if self.is_unwritable_view() {
983            return StatusCode::METHOD_NOT_ALLOWED;
984        }
985
986        match code {
987            "23503" | "23505" => StatusCode::CONFLICT,
988            // A write attempted inside the read-only transaction a read
989            // request runs in. The request was not wrong, the method was.
990            "25006" => StatusCode::METHOD_NOT_ALLOWED,
991            // Cardinality violation. `pg-safeupdate` raises it for an
992            // unqualified UPDATE or DELETE, which is the client's doing;
993            // anything else is a function or view misbehaving.
994            "21000" => match message.ends_with("requires a WHERE clause") {
995                true => StatusCode::BAD_REQUEST,
996                false => StatusCode::INTERNAL_SERVER_ERROR,
997            },
998            // Invalid parameter value, which is also how PostgreSQL reports a
999            // `SET ROLE` to a role that does not exist.
1000            "22023" => match message.starts_with("role") && message.ends_with("does not exist") {
1001                true => StatusCode::UNAUTHORIZED,
1002                false => StatusCode::BAD_REQUEST,
1003            },
1004            "53400" => StatusCode::INTERNAL_SERVER_ERROR,
1005            "57P01" => StatusCode::SERVICE_UNAVAILABLE,
1006            "P0001" => StatusCode::BAD_REQUEST,
1007            // `xmlagg` is missing only when the request asked for XML the
1008            // server cannot produce, which is a negotiation failure.
1009            "42883" => match message.starts_with("function xmlagg(") {
1010                true => StatusCode::NOT_ACCEPTABLE,
1011                false => StatusCode::NOT_FOUND,
1012            },
1013            "42P01" => StatusCode::NOT_FOUND,
1014            "42P17" => StatusCode::INTERNAL_SERVER_ERROR,
1015            // Without authentication the client may simply not have said who
1016            // it is, so it is told to; with it, it has and is still not
1017            // permitted, which a 401 would send it away to retry.
1018            "42501" => match authenticated {
1019                true => StatusCode::FORBIDDEN,
1020                false => StatusCode::UNAUTHORIZED,
1021            },
1022            _ => match code.as_bytes() {
1023                [b'0', b'8', ..] => StatusCode::SERVICE_UNAVAILABLE,
1024                [b'0', b'9', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1025                [b'0', b'L', ..] | [b'0', b'P', ..] => StatusCode::FORBIDDEN,
1026                [b'2', b'5', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1027                [b'2', b'8', ..] => StatusCode::FORBIDDEN,
1028                [b'2', b'D', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1029                [b'3', b'8', ..] | [b'3', b'9', ..] | [b'3', b'B', ..] => {
1030                    StatusCode::INTERNAL_SERVER_ERROR
1031                }
1032                [b'4', b'0', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1033                [b'5', b'3', ..] => StatusCode::SERVICE_UNAVAILABLE,
1034                [b'5', b'4', ..] | [b'5', b'5', ..] | [b'5', b'7', ..] | [b'5', b'8', ..] => {
1035                    StatusCode::INTERNAL_SERVER_ERROR
1036                }
1037                [b'F', b'0', ..] | [b'H', b'V', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1038                [b'P', b'0', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1039                [b'X', b'X', ..] => StatusCode::INTERNAL_SERVER_ERROR,
1040                _ => StatusCode::BAD_REQUEST,
1041            },
1042        }
1043    }
1044
1045    /// Whether this is PostgreSQL refusing a write to a view it cannot write
1046    /// through: one that is not automatically updatable and has no `INSTEAD
1047    /// OF` trigger or rule for the operation, or a materialized view.
1048    ///
1049    /// That is a method the resource does not take, whoever asks -- a 405,
1050    /// not the 500 its SQLSTATE (`55000`, object not in prerequisite state)
1051    /// would otherwise be. Read from the message, as `xmlagg` and the missing
1052    /// role are, because the SQLSTATE alone covers unrelated faults too; a
1053    /// server whose `lc_messages` is not English keeps the 500.
1054    pub fn is_unwritable_view(&self) -> bool {
1055        let message = self.message.as_str();
1056        match self.code.as_str() {
1057            "55000" => [
1058                "cannot insert into view ",
1059                "cannot update view ",
1060                "cannot delete from view ",
1061            ]
1062            .iter()
1063            .any(|prefix| message.starts_with(prefix)),
1064            "42809" => message.starts_with("cannot change materialized view "),
1065            _ => false,
1066        }
1067    }
1068
1069    /// Get error code for API response.
1070    pub fn code(&self) -> &'static str {
1071        if self.is_unwritable_view() {
1072            // PostgREST's code for a verb the resource does not support.
1073            return "PGRST117";
1074        }
1075        match self.code.as_str() {
1076            c if c.starts_with("23") => "PGRST503", // Constraint violation
1077            c if c.starts_with("42") => "PGRST504", // SQL error
1078            c if c.starts_with("28") => "PGRST505", // Auth error
1079            _ => "PGRST500",                        // Generic database error
1080        }
1081    }
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086    use super::*;
1087
1088    fn database(code: &str, message: &str) -> DatabaseError {
1089        DatabaseError {
1090            code: code.into(),
1091            message: message.into(),
1092            details: None,
1093            hint: None,
1094            constraint: None,
1095            table: None,
1096            column: None,
1097        }
1098    }
1099
1100    fn raised(message: &str, detail: Option<&str>) -> DatabaseError {
1101        DatabaseError {
1102            details: detail.map(str::to_string),
1103            ..database("PGRST", message)
1104        }
1105    }
1106
1107    /// PostgREST's own shape, which a `body` key does not disturb when it is
1108    /// absent: the body is rebuilt from the message, with every key present.
1109    #[test]
1110    fn a_raise_without_a_body_is_postgrests() {
1111        let raised = raised(
1112            r#"{"code":"123","message":"Payment Required","hint":"Upgrade"}"#,
1113            Some(r#"{"status":402,"headers":{"X-Powered-By":"Nerd Rage","X-N":3}}"#),
1114        )
1115        .raised_response()
1116        .unwrap()
1117        .unwrap();
1118        assert_eq!(raised.status, 402);
1119        assert_eq!(
1120            raised.headers,
1121            [("X-Powered-By".to_string(), "Nerd Rage".to_string())]
1122        );
1123        assert_eq!(
1124            raised.body,
1125            serde_json::json!({
1126                "code": "123", "message": "Payment Required",
1127                "details": null, "hint": "Upgrade",
1128            })
1129        );
1130        assert!(!raised.body_supplied);
1131
1132        // And its faults are as they were: the message is checked first, and
1133        // `headers` is required.
1134        let fault = |message, detail| raised_fault(self::raised(message, detail)).details();
1135        assert_eq!(
1136            fault("not json", Some(r#"{"status":402,"headers":{}}"#)),
1137            "Invalid JSON value for MESSAGE: 'not json'"
1138        );
1139        assert_eq!(
1140            fault(r#"{"code":"1","message":"m"}"#, Some(r#"{"status":402}"#)),
1141            r#"Invalid JSON value for DETAIL: '{"status":402}'"#
1142        );
1143        assert_eq!(
1144            fault(r#"{"code":"1","message":"m"}"#, None),
1145            "DETAIL is missing in the RAISE statement"
1146        );
1147    }
1148
1149    fn raised_fault(error: DatabaseError) -> RaiseFault {
1150        error.raised_response().unwrap().unwrap_err()
1151    }
1152
1153    /// A `body` of any JSON type is the body, as written, and the message
1154    /// need not be JSON at all.
1155    #[test]
1156    fn a_body_in_the_detail_is_the_response_body() {
1157        let body = |detail: &str| {
1158            raised(
1159                "access required for report 7",
1160                Some(&format!(r#"{{"status":403,"body":{detail}}}"#)),
1161            )
1162            .raised_response()
1163            .unwrap()
1164            .unwrap()
1165        };
1166
1167        let object = body(r#"{"detail":{"code":"access_required","can_request":true}}"#);
1168        assert_eq!(object.status, 403);
1169        assert!(object.body_supplied);
1170        assert!(object.headers.is_empty(), "headers are optional");
1171        assert_eq!(
1172            object.body,
1173            serde_json::json!({"detail": {"code": "access_required", "can_request": true}})
1174        );
1175        assert_eq!(
1176            body(r#""plain text""#).body,
1177            serde_json::json!("plain text")
1178        );
1179        assert_eq!(body("[1,2]").body, serde_json::json!([1, 2]));
1180        assert_eq!(body("null").body, serde_json::Value::Null);
1181    }
1182
1183    #[test]
1184    fn a_body_comes_with_headers_and_a_status_text_when_given() {
1185        let raised = raised(
1186            r#"{"code":"x","message":"also valid"}"#,
1187            Some(
1188                r#"{"status":451,"status_text":"Gone Away","headers":{"Content-Type":"text/plain"},"body":"x"}"#,
1189            ),
1190        )
1191        .raised_response()
1192        .unwrap()
1193        .unwrap();
1194        assert_eq!(raised.status, 451);
1195        assert_eq!(raised.status_text.as_deref(), Some("Gone Away"));
1196        assert_eq!(
1197            raised.headers,
1198            [("Content-Type".to_string(), "text/plain".to_string())]
1199        );
1200        assert_eq!(raised.body, serde_json::json!("x"));
1201    }
1202
1203    /// The status is still the schema's to give, and a `headers` that is
1204    /// there has to be an object; a body does not excuse either.
1205    #[test]
1206    fn a_body_still_needs_a_status() {
1207        for detail in [
1208            r#"{"body":{"a":1}}"#,
1209            r#"{"status":"402","body":{"a":1}}"#,
1210            r#"{"status":402,"headers":["a"],"body":{"a":1}}"#,
1211        ] {
1212            let fault = raised_fault(raised("free text", Some(detail)));
1213            assert_eq!(
1214                fault.details(),
1215                format!("Invalid JSON value for DETAIL: '{detail}'")
1216            );
1217        }
1218        // Only an object with a `body` key is a takeover of the body: a
1219        // DETAIL that is not an object is the usual fault.
1220        let fault = raised_fault(raised("free text", Some("[1]")));
1221        assert!(matches!(fault, RaiseFault::Message(_)));
1222    }
1223
1224    /// A view PostgreSQL cannot write through refuses the method for every
1225    /// role, which is a 405; it was answered as the 500 its SQLSTATE says.
1226    #[test]
1227    fn a_write_a_view_cannot_take_is_a_405() {
1228        for (code, message) in [
1229            ("55000", "cannot insert into view \"j\""),
1230            ("55000", "cannot update view \"j\""),
1231            ("55000", "cannot delete from view \"j\""),
1232            ("42809", "cannot change materialized view \"m\""),
1233        ] {
1234            let error = Error::Database(database(code, message));
1235            assert_eq!(
1236                error.status_code(),
1237                StatusCode::METHOD_NOT_ALLOWED,
1238                "{message}"
1239            );
1240            assert_eq!(error.code(), "PGRST117", "{message}");
1241        }
1242        // The same SQLSTATEs about anything else keep their status.
1243        let other = Error::Database(database("55000", "lock is not available"));
1244        assert_eq!(other.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
1245        let other = Error::Database(database("42809", "\"f\" is not a procedure"));
1246        assert_eq!(other.status_code(), StatusCode::BAD_REQUEST);
1247    }
1248
1249    /// A missing grant is 401 to a request that has not said who it is and 403
1250    /// to one that has, as in PostgREST; `status_code` is the anonymous answer.
1251    #[test]
1252    fn a_missing_grant_is_a_401_or_a_403_by_who_asked() {
1253        let error = Error::Database(database("42501", "permission denied for table t"));
1254        assert_eq!(error.status_code_as(false), StatusCode::UNAUTHORIZED);
1255        assert_eq!(error.status_code_as(true), StatusCode::FORBIDDEN);
1256        assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED);
1257
1258        let Error::Database(db) = &error else {
1259            unreachable!()
1260        };
1261        assert_eq!(db.status_code_as(true), StatusCode::FORBIDDEN);
1262        assert_eq!(db.status_code(), db.status_code_as(false));
1263    }
1264
1265    /// Who asked changes nothing else, including a status the schema raised.
1266    #[test]
1267    fn who_asked_decides_only_a_missing_grant() {
1268        for code in ["23505", "42P01", "P0001", "PT402", "28000", "22023"] {
1269            let db = database(code, "x");
1270            assert_eq!(db.status_code_as(true), db.status_code(), "{code}");
1271        }
1272    }
1273
1274    #[test]
1275    fn test_error_status_codes() {
1276        assert_eq!(
1277            Error::InvalidQueryParam("test".into()).status_code(),
1278            StatusCode::BAD_REQUEST
1279        );
1280        assert_eq!(Error::MissingAuth.status_code(), StatusCode::UNAUTHORIZED);
1281        assert_eq!(
1282            Error::TableNotFound {
1283                name: "users".into(),
1284                suggestion: None
1285            }
1286            .status_code(),
1287            StatusCode::NOT_FOUND
1288        );
1289        assert_eq!(
1290            Error::UnsupportedMethod("TRACE".into()).status_code(),
1291            StatusCode::METHOD_NOT_ALLOWED
1292        );
1293    }
1294
1295    #[test]
1296    fn test_error_codes() {
1297        // A malformed query string is a parse failure, PGRST100 -- the same
1298        // code as a malformed path. PGRST101 means something else entirely.
1299        assert_eq!(Error::InvalidQueryParam("test".into()).code(), "PGRST100");
1300        assert_eq!(Error::MissingAuth.code(), "PGRST302");
1301        assert_eq!(
1302            Error::TableNotFound {
1303                name: "users".into(),
1304                suggestion: None
1305            }
1306            .code(),
1307            "PGRST205"
1308        );
1309    }
1310
1311    #[test]
1312    fn test_database_error_status() {
1313        let constraint_error = DatabaseError {
1314            code: "23505".into(), // unique_violation
1315            message: "Duplicate key".into(),
1316            details: None,
1317            hint: None,
1318            constraint: Some("users_pkey".into()),
1319            table: Some("users".into()),
1320            column: None,
1321        };
1322        assert_eq!(constraint_error.status_code(), StatusCode::CONFLICT);
1323    }
1324
1325    #[test]
1326    fn test_error_to_json() {
1327        let error = Error::InvalidQueryParam("bad filter".into());
1328        let json = error.to_json();
1329        assert_eq!(json["code"], "PGRST100");
1330        assert!(json["message"].as_str().unwrap().contains("bad filter"));
1331    }
1332}