use-pg-identifier 0.1.0

PostgreSQL identifier primitives for RustUse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;

/// Rendering style for a PostgreSQL identifier segment.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PgIdentifierStyle {
    /// The identifier can render without double quotes.
    #[default]
    Unquoted,
    /// The identifier must render as a double-quoted identifier.
    Quoted,
}

/// A validated PostgreSQL identifier segment.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIdentifier {
    text: String,
    style: PgIdentifierStyle,
}

impl PgIdentifier {
    /// Creates an identifier from either unquoted text or a double-quoted identifier token.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError`] when the value is empty, malformed, or not valid for its style.
    pub fn new(input: impl AsRef<str>) -> Result<Self, PgIdentifierError> {
        let input = input.as_ref();
        let trimmed = input.trim();
        if trimmed.starts_with('"') || trimmed.ends_with('"') {
            return Self::from_quoted_token(trimmed);
        }
        Self::unquoted(trimmed)
    }

    /// Creates an unquoted identifier segment using PostgreSQL-style conservative validation.
    ///
    /// Unquoted identifiers are stored in lowercase because PostgreSQL folds unquoted names.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError`] when the value cannot be rendered safely without quotes.
    pub fn unquoted(input: impl AsRef<str>) -> Result<Self, PgIdentifierError> {
        let trimmed = validate_identifier_segment(input.as_ref(), false)?;
        validate_unquoted_identifier(trimmed)?;
        Ok(Self {
            text: trimmed.to_ascii_lowercase(),
            style: PgIdentifierStyle::Unquoted,
        })
    }

    /// Creates a quoted identifier segment from raw identifier text.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError`] when the value is empty or contains a control character.
    pub fn quoted(input: impl AsRef<str>) -> Result<Self, PgIdentifierError> {
        let text = validate_identifier_segment(input.as_ref(), true)?;
        Ok(Self {
            text: text.to_owned(),
            style: PgIdentifierStyle::Quoted,
        })
    }

    /// Parses a double-quoted SQL identifier token, including doubled embedded quotes.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError`] when the token is not a complete quoted identifier.
    pub fn from_quoted_token(input: &str) -> Result<Self, PgIdentifierError> {
        if !(input.starts_with('"') && input.ends_with('"') && input.len() >= 2) {
            return Err(PgIdentifierError::UnterminatedQuotedIdentifier);
        }

        let inner = &input[1..input.len() - 1];
        let mut text = String::new();
        let mut characters = inner.chars().peekable();
        while let Some(character) = characters.next() {
            if character == '"' {
                if matches!(characters.peek(), Some('"')) {
                    let _ = characters.next();
                    text.push('"');
                } else {
                    return Err(PgIdentifierError::UnescapedQuote);
                }
            } else {
                text.push(character);
            }
        }
        Self::quoted(text)
    }

    /// Returns the raw identifier text without SQL quotes.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Returns the rendering style.
    #[must_use]
    pub const fn style(&self) -> PgIdentifierStyle {
        self.style
    }

    /// Returns `true` when this identifier renders with double quotes.
    #[must_use]
    pub const fn is_quoted(&self) -> bool {
        matches!(self.style, PgIdentifierStyle::Quoted)
    }

    /// Consumes the identifier and returns its raw text.
    #[must_use]
    pub fn into_string(self) -> String {
        self.text
    }
}

impl AsRef<str> for PgIdentifier {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for PgIdentifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.style {
            PgIdentifierStyle::Unquoted => formatter.write_str(self.as_str()),
            PgIdentifierStyle::Quoted => formatter.write_str(&quote_identifier(self.as_str())),
        }
    }
}

impl FromStr for PgIdentifier {
    type Err = PgIdentifierError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::new(input)
    }
}

impl TryFrom<&str> for PgIdentifier {
    type Error = PgIdentifierError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// A dot-qualified PostgreSQL name.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgQualifiedName {
    parts: Vec<PgIdentifier>,
}

impl PgQualifiedName {
    /// Creates a qualified name from one or more identifier parts.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError::EmptyQualifiedName`] when `parts` is empty.
    pub fn new(parts: Vec<PgIdentifier>) -> Result<Self, PgIdentifierError> {
        if parts.is_empty() {
            return Err(PgIdentifierError::EmptyQualifiedName);
        }
        Ok(Self { parts })
    }

    /// Parses a conservative dot-qualified name.
    ///
    /// This is not a full SQL parser. It splits on dots and parses each segment as a PostgreSQL identifier.
    ///
    /// # Errors
    ///
    /// Returns [`PgIdentifierError`] when any segment is invalid.
    pub fn parse(input: &str) -> Result<Self, PgIdentifierError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(PgIdentifierError::EmptyQualifiedName);
        }
        let parts = trimmed
            .split('.')
            .map(PgIdentifier::new)
            .collect::<Result<Vec<_>, _>>()?;
        Self::new(parts)
    }

    /// Creates a two-part schema-qualified object name.
    #[must_use]
    pub fn schema_object(schema: PgIdentifier, object: PgIdentifier) -> Self {
        Self {
            parts: vec![schema, object],
        }
    }

    /// Returns the identifier parts.
    #[must_use]
    pub fn parts(&self) -> &[PgIdentifier] {
        &self.parts
    }

    /// Returns the last identifier part.
    #[must_use]
    pub fn leaf(&self) -> &PgIdentifier {
        &self.parts[self.parts.len() - 1]
    }
}

impl fmt::Display for PgQualifiedName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = self.parts.iter();
        if let Some(first) = parts.next() {
            write!(formatter, "{first}")?;
        }
        for part in parts {
            write!(formatter, ".{part}")?;
        }
        Ok(())
    }
}

impl FromStr for PgQualifiedName {
    type Err = PgIdentifierError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::parse(input)
    }
}

impl TryFrom<&str> for PgQualifiedName {
    type Error = PgIdentifierError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

/// Error returned when PostgreSQL identifier text is rejected.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PgIdentifierError {
    /// The supplied value was empty.
    Empty,
    /// A conservative unquoted identifier segment cannot contain `.`.
    ContainsDot,
    /// A qualified name requires at least one segment.
    EmptyQualifiedName,
    /// The supplied value started with an invalid character.
    InvalidStart {
        /// The rejected character.
        character: char,
    },
    /// The supplied value contained an invalid unquoted character.
    InvalidCharacter {
        /// Byte index of the rejected character.
        index: usize,
        /// The rejected character.
        character: char,
    },
    /// The supplied value contained a control character.
    ControlCharacter {
        /// Byte index of the rejected character.
        index: usize,
        /// The rejected character.
        character: char,
    },
    /// The supplied value was a reserved PostgreSQL keyword-like label.
    ReservedKeyword,
    /// A quoted identifier token was missing its closing quote.
    UnterminatedQuotedIdentifier,
    /// A quoted identifier token contained a single embedded quote instead of a doubled quote.
    UnescapedQuote,
}

impl fmt::Display for PgIdentifierError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("PostgreSQL identifier cannot be empty"),
            Self::ContainsDot => {
                formatter.write_str("PostgreSQL unquoted identifier segment cannot contain a dot")
            },
            Self::EmptyQualifiedName => {
                formatter.write_str("PostgreSQL qualified name cannot be empty")
            },
            Self::InvalidStart { character } => write!(
                formatter,
                "PostgreSQL unquoted identifier cannot start with {character:?}"
            ),
            Self::InvalidCharacter { index, character } => write!(
                formatter,
                "PostgreSQL unquoted identifier contains invalid character {character:?} at byte index {index}"
            ),
            Self::ControlCharacter { index, character } => write!(
                formatter,
                "PostgreSQL identifier contains control character {character:?} at byte index {index}"
            ),
            Self::ReservedKeyword => formatter.write_str(
                "PostgreSQL reserved keyword-like labels should be represented as quoted identifiers",
            ),
            Self::UnterminatedQuotedIdentifier => {
                formatter.write_str("PostgreSQL quoted identifier is not terminated")
            },
            Self::UnescapedQuote => formatter.write_str(
                "PostgreSQL quoted identifier contains an embedded quote that is not doubled",
            ),
        }
    }
}

impl Error for PgIdentifierError {}

/// Returns `true` when `input` is conservatively valid as an unquoted PostgreSQL identifier.
#[must_use]
pub fn is_valid_unquoted_identifier(input: &str) -> bool {
    validate_identifier_segment(input, false)
        .and_then(validate_unquoted_identifier)
        .is_ok()
}

/// Returns `true` when an identifier should be double-quoted for conservative PostgreSQL rendering.
#[must_use]
pub fn needs_quoting(input: &str) -> bool {
    !is_valid_unquoted_identifier(input)
}

/// Quotes an identifier with PostgreSQL double quotes, doubling embedded double quotes.
#[must_use]
pub fn quote_identifier(input: &str) -> String {
    let mut quoted = String::with_capacity(input.len() + 2);
    quoted.push('"');
    for character in input.chars() {
        if character == '"' {
            quoted.push('"');
        }
        quoted.push(character);
    }
    quoted.push('"');
    quoted
}

/// Normalizes an identifier label for simple display-oriented comparisons.
#[must_use]
pub fn normalize_identifier(input: &str) -> String {
    let trimmed = input.trim();
    if is_valid_unquoted_identifier(trimmed) {
        trimmed.to_ascii_lowercase()
    } else {
        quote_identifier(trimmed)
    }
}

fn validate_identifier_segment(input: &str, allow_dot: bool) -> Result<&str, PgIdentifierError> {
    if input.is_empty() {
        return Err(PgIdentifierError::Empty);
    }
    if !allow_dot && input.contains('.') {
        return Err(PgIdentifierError::ContainsDot);
    }
    if let Some((index, character)) = input
        .char_indices()
        .find(|(_, character)| character.is_control())
    {
        return Err(PgIdentifierError::ControlCharacter { index, character });
    }
    Ok(input)
}

fn validate_unquoted_identifier(input: &str) -> Result<(), PgIdentifierError> {
    let mut characters = input.char_indices();
    let Some((_, first)) = characters.next() else {
        return Err(PgIdentifierError::Empty);
    };
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return Err(PgIdentifierError::InvalidStart { character: first });
    }
    for (index, character) in characters {
        if !(character == '_' || character.is_ascii_alphanumeric()) {
            return Err(PgIdentifierError::InvalidCharacter { index, character });
        }
    }
    if is_reserved_keyword_like(input) {
        return Err(PgIdentifierError::ReservedKeyword);
    }
    Ok(())
}

fn is_reserved_keyword_like(input: &str) -> bool {
    matches!(
        input.to_ascii_uppercase().as_str(),
        "ALL"
            | "ALTER"
            | "AND"
            | "AS"
            | "CHECK"
            | "CREATE"
            | "DELETE"
            | "DROP"
            | "FALSE"
            | "FOREIGN"
            | "FROM"
            | "GROUP"
            | "INDEX"
            | "INSERT"
            | "KEY"
            | "LIMIT"
            | "NOT"
            | "NULL"
            | "OR"
            | "ORDER"
            | "PRIMARY"
            | "RETURNING"
            | "SELECT"
            | "TABLE"
            | "TRUE"
            | "UNIQUE"
            | "UPDATE"
            | "USER"
            | "WHERE"
    )
}

#[cfg(test)]
mod tests {
    use super::{
        PgIdentifier, PgIdentifierError, PgIdentifierStyle, PgQualifiedName,
        is_valid_unquoted_identifier, needs_quoting, normalize_identifier, quote_identifier,
    };

    #[test]
    fn validates_unquoted_identifiers() -> Result<(), PgIdentifierError> {
        let identifier = PgIdentifier::new(" Users_1 ")?;
        assert_eq!(identifier.as_str(), "users_1");
        assert_eq!(identifier.style(), PgIdentifierStyle::Unquoted);
        assert!(is_valid_unquoted_identifier("users_1"));
        assert!(!is_valid_unquoted_identifier("1users"));
        assert!(matches!(
            PgIdentifier::new("public.users"),
            Err(PgIdentifierError::ContainsDot)
        ));
        Ok(())
    }

    #[test]
    fn supports_quoted_identifiers() -> Result<(), PgIdentifierError> {
        let identifier = PgIdentifier::quoted("User Name")?;
        assert!(identifier.is_quoted());
        assert_eq!(identifier.to_string(), "\"User Name\"");

        let parsed = PgIdentifier::new("\"user\"\"name\"")?;
        assert_eq!(parsed.as_str(), "user\"name");
        assert_eq!(parsed.to_string(), "\"user\"\"name\"");
        Ok(())
    }

    #[test]
    fn quotes_reserved_or_complex_labels() {
        assert!(needs_quoting("select"));
        assert_eq!(quote_identifier("user\"name"), "\"user\"\"name\"");
        assert_eq!(normalize_identifier("Users"), "users");
        assert_eq!(normalize_identifier("order items"), "\"order items\"");
    }

    #[test]
    fn parses_qualified_names() -> Result<(), PgIdentifierError> {
        let qualified = PgQualifiedName::parse("public.users")?;
        assert_eq!(qualified.parts().len(), 2);
        assert_eq!(qualified.leaf().as_str(), "users");
        assert_eq!(qualified.to_string(), "public.users");
        assert!(PgQualifiedName::parse("public.").is_err());
        Ok(())
    }
}