Skip to main content

riverqueue_migrate/
schema.rs

1//! PostgreSQL schema names.
2
3use std::fmt;
4
5use thiserror::Error;
6
7/// PostgreSQL's maximum identifier length.
8const POSTGRES_IDENTIFIER_MAX: usize = 63;
9
10/// Longest River notification topic, which a schema name must leave room for.
11const NOTIFICATION_TOPIC_LONGEST: &str = "river_leadership";
12
13/// Maximum schema length after reserving `<schema>.river_leadership` for
14/// notification channels.
15pub const SCHEMA_MAX_LEN: usize = POSTGRES_IDENTIFIER_MAX - NOTIFICATION_TOPIC_LONGEST.len() - 1;
16
17/// The PostgreSQL schema River's tables live in.
18///
19/// [`SchemaName::current`] uses the connection's current schema (normally
20/// `public`, following `search_path`). An explicit schema is quoted wherever
21/// River renders it, so names such as `river-prod` or `MyRiver` work as
22/// written. Pass the same schema to the
23/// migrator and the client.
24///
25/// ```
26/// use riverqueue_migrate::SchemaName;
27///
28/// let schema = SchemaName::new("river")?;
29/// assert_eq!(schema.qualify("river_job"), r#""river"."river_job""#);
30/// # Ok::<(), riverqueue_migrate::SchemaNameError>(())
31/// ```
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct SchemaName(Option<String>);
34
35impl SchemaName {
36    /// Uses PostgreSQL's current schema.
37    #[must_use]
38    pub const fn current() -> Self {
39        Self(None)
40    }
41
42    /// Validates an optional explicit schema.
43    ///
44    /// Any name is accepted and quoted when rendered, including mixed case
45    /// and punctuation such as
46    /// `river-prod`. Names containing NUL are rejected, as are names too long
47    /// to prefix River's notification topics within PostgreSQL's identifier
48    /// limit.
49    ///
50    /// # Errors
51    ///
52    /// Returns an error when the schema is too long or contains NUL.
53    pub fn new(schema: impl Into<String>) -> Result<Self, SchemaNameError> {
54        let schema = schema.into();
55        if schema.is_empty() {
56            return Ok(Self::current());
57        }
58        if schema.len() > SCHEMA_MAX_LEN {
59            return Err(SchemaNameError::TooLong {
60                length: schema.len(),
61                maximum: SCHEMA_MAX_LEN,
62            });
63        }
64        if schema.contains('\0') {
65            return Err(SchemaNameError::Invalid(schema));
66        }
67
68        Ok(Self(Some(schema)))
69    }
70
71    /// Returns the unquoted explicit schema, if configured.
72    #[must_use]
73    pub fn as_deref(&self) -> Option<&str> {
74        self.0.as_deref()
75    }
76
77    /// Qualifies and quotes a database object name in this schema, for use in
78    /// SQL that refers to River's tables.
79    #[must_use]
80    pub fn qualify(&self, object: &str) -> String {
81        match &self.0 {
82            Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(object)),
83            None => quote_identifier(object),
84        }
85    }
86
87    /// Returns the explicit schema quoted as a PostgreSQL identifier, for
88    /// SQL that names the schema itself, or `None` for the connection's
89    /// current schema.
90    #[must_use]
91    pub fn quoted_identifier(&self) -> Option<String> {
92        self.0.as_deref().map(quote_identifier)
93    }
94
95    /// Prefix used by River's canonical PostgreSQL migration templates.
96    #[cfg(feature = "postgres")]
97    pub(crate) fn migration_prefix(&self) -> String {
98        self.quoted_identifier()
99            .map_or_else(String::new, |schema| format!("{schema}."))
100    }
101}
102
103/// Quotes a PostgreSQL identifier, doubling embedded quotes like Go's
104/// `dbutil.SafeIdentifier`.
105fn quote_identifier(identifier: &str) -> String {
106    format!("\"{}\"", identifier.replace('"', "\"\""))
107}
108
109impl Default for SchemaName {
110    fn default() -> Self {
111        Self::current()
112    }
113}
114
115impl fmt::Display for SchemaName {
116    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117        formatter.write_str(self.as_deref().unwrap_or("<current>"))
118    }
119}
120
121/// Invalid River schema name.
122#[derive(Debug, Error)]
123#[non_exhaustive]
124pub enum SchemaNameError {
125    /// Schema contains a NUL character, which PostgreSQL identifiers cannot.
126    #[error("schema name cannot contain NUL: {0:?}")]
127    Invalid(String),
128
129    /// Schema is too long to prefix River's notification topics.
130    #[error("schema length {length} exceeds maximum {maximum}")]
131    TooLong {
132        /// Observed byte length.
133        length: usize,
134        /// Maximum byte length.
135        maximum: usize,
136    },
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn schema_name_validates_and_qualifies() {
145        let schema = SchemaName::new("river_test").unwrap();
146        assert_eq!(schema.qualify("river_job"), "\"river_test\".\"river_job\"");
147
148        // Go quotes any schema with `SafeIdentifier`, so Rust accepts the
149        // same names and escapes embedded quotes.
150        let hyphenated = SchemaName::new("river-prod").unwrap();
151        assert_eq!(
152            hyphenated.qualify("river_job"),
153            "\"river-prod\".\"river_job\""
154        );
155        assert_eq!(
156            SchemaName::new("odd\"name").unwrap().quoted_identifier(),
157            Some("\"odd\"\"name\"".to_owned())
158        );
159        assert_eq!(SchemaName::current().quoted_identifier(), None);
160        assert_eq!(
161            SchemaName::new("odd\"name").unwrap().qualify("river_job"),
162            "\"odd\"\"name\".\"river_job\""
163        );
164        assert!(SchemaName::new("1leading_digit").is_ok());
165        assert!(SchemaName::new("nul\0byte").is_err());
166        assert!(SchemaName::new("a".repeat(SCHEMA_MAX_LEN + 1)).is_err());
167    }
168
169    #[cfg(feature = "postgres")]
170    #[test]
171    fn migration_prefix_qualifies_templates() {
172        assert_eq!(
173            SchemaName::new("MyRiver").unwrap().migration_prefix(),
174            "\"MyRiver\"."
175        );
176        assert_eq!(SchemaName::current().migration_prefix(), "");
177    }
178}