pg-client 0.3.0

PostgreSQL client configuration and connection management
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! PostgreSQL identifier types.
//!
//! This module provides types for PostgreSQL identifier values (table names, schema names, etc.).
//!
//! **Important:** These types represent identifier *values*, not SQL syntax. They do not parse
//! or produce quoted identifier syntax. For example, a table named `my table` (with a space)
//! is represented as the string `my table`, not as `"my table"`.
//!
//! Validation rules:
//! - Cannot be empty
//! - Maximum length of 63 bytes (NAMEDATALEN - 1)
//! - Cannot contain NUL bytes

use std::borrow::Cow;

use core::fmt::{Display, Formatter};
use core::str::FromStr;

/// Maximum length of a PostgreSQL identifier in bytes.
pub const MAX_LENGTH: usize = 63;

/// Const-compatible validation that returns an optional error.
const fn validate(input: &str) -> Option<ParseError> {
    if input.is_empty() {
        return Some(ParseError::Empty);
    }

    if input.len() > MAX_LENGTH {
        return Some(ParseError::TooLong);
    }

    let bytes = input.as_bytes();
    let mut index = 0;

    while index < bytes.len() {
        if bytes[index] == 0 {
            return Some(ParseError::ContainsNul);
        }
        index += 1;
    }

    None
}

/// A validated PostgreSQL identifier value.
///
/// This represents the actual identifier value, not SQL syntax. Identifiers can contain
/// spaces and special characters (which would require quoting in SQL).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "String")]
struct Identifier(Cow<'static, str>);

impl TryFrom<String> for Identifier {
    type Error = ParseError;

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

impl Identifier {
    /// Creates a new identifier from a static string.
    ///
    /// # Panics
    ///
    /// Panics if the input is empty, exceeds [`MAX_LENGTH`], or contains NUL bytes.
    #[must_use]
    const fn from_static_or_panic(input: &'static str) -> Self {
        match validate(input) {
            Some(error) => panic!("{}", error.message()),
            None => Self(Cow::Borrowed(input)),
        }
    }

    /// Returns the identifier as a string slice.
    #[must_use]
    fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for Identifier {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

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

impl FromStr for Identifier {
    type Err = ParseError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match validate(input) {
            Some(error) => Err(error),
            None => Ok(Self(Cow::Owned(input.to_owned()))),
        }
    }
}

/// Error parsing a PostgreSQL identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError {
    /// Identifier cannot be empty.
    Empty,

    /// Identifier exceeds maximum length.
    TooLong,

    /// Identifier contains a NUL byte.
    ContainsNul,
}

impl ParseError {
    /// Returns the error message.
    #[must_use]
    pub const fn message(&self) -> &'static str {
        match self {
            Self::Empty => "identifier cannot be empty",
            Self::TooLong => "identifier exceeds maximum length",
            Self::ContainsNul => "identifier cannot contain NUL bytes",
        }
    }
}

impl Display for ParseError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "{}", self.message())
    }
}

impl std::error::Error for ParseError {}

/// Macro to define identifier-backed newtypes.
macro_rules! define_identifier_type {
    ($(#[$meta:meta])* $name:ident, $test_mod:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
        #[serde(try_from = "String")]
        pub struct $name(Identifier);

        impl TryFrom<String> for $name {
            type Error = ParseError;

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

        impl $name {
            /// Creates a new value from a static string.
            ///
            /// # Panics
            ///
            /// Panics if the input is empty, exceeds [`MAX_LENGTH`], or contains NUL bytes.
            #[must_use]
            pub const fn from_static_or_panic(input: &'static str) -> Self {
                Self(Identifier::from_static_or_panic(input))
            }

            /// Returns the value as a string slice.
            #[must_use]
            pub fn as_str(&self) -> &str {
                self.0.as_str()
            }
        }

        impl Display for $name {
            fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
                write!(formatter, "{}", self.0)
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                self.0.as_ref()
            }
        }

        impl FromStr for $name {
            type Err = ParseError;

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

        #[cfg(test)]
        mod $test_mod {
            use super::*;

            #[test]
            fn parse_valid() {
                let value: $name = "test".parse().unwrap();
                assert_eq!(value.to_string(), "test");
            }

            #[test]
            fn parse_valid_with_space() {
                let value: $name = "test value".parse().unwrap();
                assert_eq!(value.to_string(), "test value");
            }

            #[test]
            fn parse_empty_fails() {
                let result: Result<$name, _> = "".parse();
                assert!(matches!(result, Err(ParseError::Empty)));
            }

            #[test]
            fn parse_contains_nul_fails() {
                let result: Result<$name, _> = "test\0value".parse();
                assert!(matches!(result, Err(ParseError::ContainsNul)));
            }

            #[test]
            fn parse_too_long_fails() {
                let input = "a".repeat(MAX_LENGTH + 1);
                let result: Result<$name, _> = input.parse();
                assert!(matches!(result, Err(ParseError::TooLong)));
            }
        }
    };
}

define_identifier_type!(
    /// A PostgreSQL table name.
    Table,
    table
);

define_identifier_type!(
    /// A PostgreSQL schema name.
    Schema,
    schema
);

impl Schema {
    /// The default `public` schema.
    pub const PUBLIC: Self = Self::from_static_or_panic("public");
}

/// A schema-qualified PostgreSQL table name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct QualifiedTable {
    /// The schema name.
    pub schema: Schema,
    /// The table name.
    pub table: Table,
}

impl Display for QualifiedTable {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "{}.{}", self.schema, self.table)
    }
}

define_identifier_type!(
    /// A PostgreSQL column name.
    Column,
    column
);

define_identifier_type!(
    /// A PostgreSQL index name.
    Index,
    index
);

define_identifier_type!(
    /// A PostgreSQL constraint name.
    ///
    /// Includes PRIMARY KEY, FOREIGN KEY, CHECK, UNIQUE, and EXCLUSION constraints.
    Constraint,
    constraint
);

define_identifier_type!(
    /// A PostgreSQL extension name.
    Extension,
    extension
);

define_identifier_type!(
    /// A PostgreSQL sequence name.
    Sequence,
    sequence
);

define_identifier_type!(
    /// A PostgreSQL function or procedure name.
    Function,
    function
);

define_identifier_type!(
    /// A PostgreSQL trigger name.
    Trigger,
    trigger
);

define_identifier_type!(
    /// A PostgreSQL domain name.
    Domain,
    domain
);

define_identifier_type!(
    /// A PostgreSQL type name.
    ///
    /// Includes custom types, enums, and composite types.
    Type,
    r#type
);

define_identifier_type!(
    /// A PostgreSQL view name.
    View,
    view
);

define_identifier_type!(
    /// A PostgreSQL relation name.
    ///
    /// A relation is either a table or a view. Use this type when an operation
    /// accepts both tables and views (e.g., SELECT queries).
    Relation,
    relation
);

impl From<Table> for Relation {
    fn from(table: Table) -> Self {
        Self(table.0)
    }
}

impl From<View> for Relation {
    fn from(view: View) -> Self {
        Self(view.0)
    }
}

define_identifier_type!(
    /// A PostgreSQL materialized view name.
    MaterializedView,
    materialized_view
);

impl From<MaterializedView> for Relation {
    fn from(materialized_view: MaterializedView) -> Self {
        Self(materialized_view.0)
    }
}

define_identifier_type!(
    /// A PostgreSQL operator name.
    Operator,
    operator
);

define_identifier_type!(
    /// A PostgreSQL aggregate function name.
    Aggregate,
    aggregate
);

define_identifier_type!(
    /// A PostgreSQL collation name.
    Collation,
    collation
);

define_identifier_type!(
    /// A PostgreSQL tablespace name.
    Tablespace,
    tablespace
);

define_identifier_type!(
    /// A PostgreSQL row-level security policy name.
    Policy,
    policy
);

define_identifier_type!(
    /// A PostgreSQL rule name.
    Rule,
    rule
);

define_identifier_type!(
    /// A PostgreSQL publication name (for logical replication).
    Publication,
    publication
);

define_identifier_type!(
    /// A PostgreSQL subscription name (for logical replication).
    Subscription,
    subscription
);

define_identifier_type!(
    /// A PostgreSQL foreign server name.
    ForeignServer,
    foreign_server
);

define_identifier_type!(
    /// A PostgreSQL foreign data wrapper name.
    ForeignDataWrapper,
    foreign_data_wrapper
);

define_identifier_type!(
    /// A PostgreSQL foreign table name.
    ForeignTable,
    foreign_table
);

define_identifier_type!(
    /// A PostgreSQL event trigger name.
    EventTrigger,
    event_trigger
);

define_identifier_type!(
    /// A PostgreSQL procedural language name.
    Language,
    language
);

define_identifier_type!(
    /// A PostgreSQL text search configuration name.
    TextSearchConfiguration,
    text_search_configuration
);

define_identifier_type!(
    /// A PostgreSQL text search dictionary name.
    TextSearchDictionary,
    text_search_dictionary
);

define_identifier_type!(
    /// A PostgreSQL encoding conversion name.
    Conversion,
    conversion
);

define_identifier_type!(
    /// A PostgreSQL operator class name.
    OperatorClass,
    operator_class
);

define_identifier_type!(
    /// A PostgreSQL operator family name.
    OperatorFamily,
    operator_family
);

define_identifier_type!(
    /// A PostgreSQL access method name.
    AccessMethod,
    access_method
);

define_identifier_type!(
    /// A PostgreSQL extended statistics object name.
    StatisticsObject,
    statistics_object
);

define_identifier_type!(
    /// A PostgreSQL database name.
    Database,
    database
);

impl Database {
    /// The default `postgres` database.
    pub const POSTGRES: Self = Self::from_static_or_panic("postgres");
}

define_identifier_type!(
    /// A PostgreSQL role name.
    ///
    /// Roles with the `LOGIN` attribute are typically called users.
    Role,
    role
);

impl Role {
    /// The default `postgres` superuser role.
    pub const POSTGRES: Self = Self::from_static_or_panic("postgres");
}

/// A PostgreSQL user (alias for [`Role`]).
///
/// A user is a role with the `LOGIN` attribute.
pub type User = Role;

#[cfg(test)]
mod tests {
    use super::*;

    mod identifier {
        use super::*;

        #[test]
        fn parse_valid_simple() {
            let identifier: Identifier = "users".parse().unwrap();
            assert_eq!(identifier.to_string(), "users");
        }

        #[test]
        fn parse_valid_with_space() {
            let identifier: Identifier = "my table".parse().unwrap();
            assert_eq!(identifier.to_string(), "my table");
        }

        #[test]
        fn parse_valid_with_special_chars() {
            let identifier: Identifier = "my-table.name".parse().unwrap();
            assert_eq!(identifier.to_string(), "my-table.name");
        }

        #[test]
        fn parse_valid_starting_with_digit() {
            let identifier: Identifier = "1table".parse().unwrap();
            assert_eq!(identifier.to_string(), "1table");
        }

        #[test]
        fn parse_valid_max_length() {
            let input = "a".repeat(MAX_LENGTH);
            let identifier: Identifier = input.parse().unwrap();
            assert_eq!(identifier.to_string(), input);
        }

        #[test]
        fn parse_empty_fails() {
            let result: Result<Identifier, _> = "".parse();
            assert_eq!(result, Err(ParseError::Empty));
        }

        #[test]
        fn parse_too_long_fails() {
            let input = "a".repeat(MAX_LENGTH + 1);
            let result: Result<Identifier, _> = input.parse();
            assert_eq!(result, Err(ParseError::TooLong));
        }

        #[test]
        fn parse_contains_nul_fails() {
            let result: Result<Identifier, _> = "my\0table".parse();
            assert_eq!(result, Err(ParseError::ContainsNul));
        }
    }
}