use-pg-index 0.1.0

PostgreSQL index 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

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

use use_pg_identifier::{PgIdentifier, PgIdentifierError};
use use_pg_table::PgTableRef;

/// PostgreSQL index name primitive.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIndexName(PgIdentifier);

impl PgIndexName {
    /// Creates an index name.
    ///
    /// # Errors
    ///
    /// Returns [`PgIndexError`] when identifier validation fails.
    pub fn new(input: impl AsRef<str>) -> Result<Self, PgIndexError> {
        PgIdentifier::new(input)
            .map(Self)
            .map_err(PgIndexError::Identifier)
    }

    /// Returns the index name text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

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

impl FromStr for PgIndexName {
    type Err = PgIndexError;

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

/// PostgreSQL index access methods.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PgIndexMethod {
    /// B-tree index method.
    #[default]
    Btree,
    /// Hash index method.
    Hash,
    /// GiST index method.
    Gist,
    /// SP-GiST index method.
    Spgist,
    /// GIN index method.
    Gin,
    /// BRIN index method.
    Brin,
}

impl PgIndexMethod {
    /// Returns the stable PostgreSQL method label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Btree => "btree",
            Self::Hash => "hash",
            Self::Gist => "gist",
            Self::Spgist => "spgist",
            Self::Gin => "gin",
            Self::Brin => "brin",
        }
    }
}

impl fmt::Display for PgIndexMethod {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for PgIndexMethod {
    type Err = PgIndexError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "btree" | "b tree" => Ok(Self::Btree),
            "hash" => Ok(Self::Hash),
            "gist" => Ok(Self::Gist),
            "spgist" | "sp gist" => Ok(Self::Spgist),
            "gin" => Ok(Self::Gin),
            "brin" => Ok(Self::Brin),
            _ => Err(PgIndexError::UnknownMethod),
        }
    }
}

/// PostgreSQL index column label.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIndexColumn(PgIdentifier);

impl PgIndexColumn {
    /// Creates an index column label.
    ///
    /// # Errors
    ///
    /// Returns [`PgIndexError`] when identifier validation fails.
    pub fn new(input: impl AsRef<str>) -> Result<Self, PgIndexError> {
        PgIdentifier::new(input)
            .map(Self)
            .map_err(PgIndexError::Identifier)
    }

    /// Returns the column label text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

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

/// PostgreSQL index expression label.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIndexExpression(String);

impl PgIndexExpression {
    /// Creates an expression label without parsing SQL.
    ///
    /// # Errors
    ///
    /// Returns [`PgIndexError`] when the label is empty or contains control characters.
    pub fn new(input: impl AsRef<str>) -> Result<Self, PgIndexError> {
        validate_label(input.as_ref(), PgIndexError::EmptyExpression)
            .map(|value| Self(value.to_owned()))
    }

    /// Returns the expression label.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for PgIndexExpression {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// PostgreSQL index flag metadata.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIndexFlags {
    bits: u8,
}

const UNIQUE_FLAG: u8 = 1 << 0;
const PRIMARY_FLAG: u8 = 1 << 1;
const PARTIAL_FLAG: u8 = 1 << 2;
const EXPRESSION_FLAG: u8 = 1 << 3;
const CONCURRENT_FLAG: u8 = 1 << 4;
const INVALID_FLAG: u8 = 1 << 5;

impl PgIndexFlags {
    /// Sets the unique flag.
    #[must_use]
    pub const fn unique(mut self, value: bool) -> Self {
        self.set_flag(UNIQUE_FLAG, value);
        self
    }

    /// Sets the primary-index flag.
    #[must_use]
    pub const fn primary(mut self, value: bool) -> Self {
        self.set_flag(PRIMARY_FLAG, value);
        self
    }

    /// Sets the partial-index flag.
    #[must_use]
    pub const fn partial(mut self, value: bool) -> Self {
        self.set_flag(PARTIAL_FLAG, value);
        self
    }

    /// Sets the expression-index flag.
    #[must_use]
    pub const fn expression(mut self, value: bool) -> Self {
        self.set_flag(EXPRESSION_FLAG, value);
        self
    }

    /// Sets the concurrent-build flag.
    #[must_use]
    pub const fn concurrent(mut self, value: bool) -> Self {
        self.set_flag(CONCURRENT_FLAG, value);
        self
    }

    /// Sets the invalid-index flag.
    #[must_use]
    pub const fn invalid(mut self, value: bool) -> Self {
        self.set_flag(INVALID_FLAG, value);
        self
    }

    /// Returns `true` when the unique flag is set.
    #[must_use]
    pub const fn is_unique(self) -> bool {
        self.has_flag(UNIQUE_FLAG)
    }

    /// Returns `true` when the primary-index flag is set.
    #[must_use]
    pub const fn is_primary(self) -> bool {
        self.has_flag(PRIMARY_FLAG)
    }

    /// Returns `true` when the partial-index flag is set.
    #[must_use]
    pub const fn is_partial(self) -> bool {
        self.has_flag(PARTIAL_FLAG)
    }

    /// Returns `true` when the expression-index flag is set.
    #[must_use]
    pub const fn is_expression(self) -> bool {
        self.has_flag(EXPRESSION_FLAG)
    }

    /// Returns `true` when the concurrent-build flag is set.
    #[must_use]
    pub const fn is_concurrent(self) -> bool {
        self.has_flag(CONCURRENT_FLAG)
    }

    /// Returns `true` when the invalid-index flag is set.
    #[must_use]
    pub const fn is_invalid(self) -> bool {
        self.has_flag(INVALID_FLAG)
    }

    const fn set_flag(&mut self, flag: u8, value: bool) {
        if value {
            self.bits |= flag;
        } else {
            self.bits &= !flag;
        }
    }

    const fn has_flag(self, flag: u8) -> bool {
        self.bits & flag != 0
    }
}

/// PostgreSQL index metadata without SQL generation or execution.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PgIndex {
    name: PgIndexName,
    table: Option<PgTableRef>,
    method: PgIndexMethod,
    columns: Vec<PgIndexColumn>,
    expressions: Vec<PgIndexExpression>,
    predicate: Option<String>,
    flags: PgIndexFlags,
}

impl PgIndex {
    /// Creates index metadata from a name.
    #[must_use]
    pub const fn new(name: PgIndexName) -> Self {
        Self {
            name,
            table: None,
            method: PgIndexMethod::Btree,
            columns: Vec::new(),
            expressions: Vec::new(),
            predicate: None,
            flags: PgIndexFlags { bits: 0 },
        }
    }

    /// Sets the table reference.
    #[must_use]
    pub fn with_table(mut self, table: PgTableRef) -> Self {
        self.table = Some(table);
        self
    }

    /// Sets the index method.
    #[must_use]
    pub const fn with_method(mut self, method: PgIndexMethod) -> Self {
        self.method = method;
        self
    }

    /// Sets indexed columns.
    #[must_use]
    pub fn with_columns(mut self, columns: Vec<PgIndexColumn>) -> Self {
        self.columns = columns;
        self
    }

    /// Adds an index expression label and marks the index as expression-backed.
    #[must_use]
    pub fn with_expression(mut self, expression: PgIndexExpression) -> Self {
        self.expressions.push(expression);
        self.flags = self.flags.expression(true);
        self
    }

    /// Sets a partial-index predicate label without parsing SQL.
    ///
    /// # Errors
    ///
    /// Returns [`PgIndexError`] when the label is empty or contains control characters.
    pub fn with_predicate(mut self, predicate: impl AsRef<str>) -> Result<Self, PgIndexError> {
        self.predicate =
            Some(validate_label(predicate.as_ref(), PgIndexError::EmptyPredicate)?.to_owned());
        self.flags = self.flags.partial(true);
        Ok(self)
    }

    /// Sets index flags.
    #[must_use]
    pub const fn with_flags(mut self, flags: PgIndexFlags) -> Self {
        self.flags = flags;
        self
    }

    /// Returns the index name.
    #[must_use]
    pub const fn name(&self) -> &PgIndexName {
        &self.name
    }

    /// Returns the optional table reference.
    #[must_use]
    pub const fn table(&self) -> Option<&PgTableRef> {
        self.table.as_ref()
    }

    /// Returns the index method.
    #[must_use]
    pub const fn method(&self) -> PgIndexMethod {
        self.method
    }

    /// Returns indexed columns.
    #[must_use]
    pub fn columns(&self) -> &[PgIndexColumn] {
        &self.columns
    }

    /// Returns expression labels.
    #[must_use]
    pub fn expressions(&self) -> &[PgIndexExpression] {
        &self.expressions
    }

    /// Returns the optional partial-index predicate label.
    #[must_use]
    pub fn predicate(&self) -> Option<&str> {
        self.predicate.as_deref()
    }

    /// Returns the index flags.
    #[must_use]
    pub const fn flags(&self) -> PgIndexFlags {
        self.flags
    }
}

/// Error returned when PostgreSQL index metadata is invalid.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PgIndexError {
    Empty,
    EmptyExpression,
    EmptyPredicate,
    UnknownMethod,
    ControlCharacter,
    Identifier(PgIdentifierError),
}

impl fmt::Display for PgIndexError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("PostgreSQL index label cannot be empty"),
            Self::EmptyExpression => {
                formatter.write_str("PostgreSQL index expression cannot be empty")
            }
            Self::EmptyPredicate => {
                formatter.write_str("PostgreSQL index predicate cannot be empty")
            }
            Self::UnknownMethod => formatter.write_str("unknown PostgreSQL index method"),
            Self::ControlCharacter => {
                formatter.write_str("PostgreSQL index label cannot contain control characters")
            }
            Self::Identifier(error) => {
                write!(formatter, "invalid PostgreSQL index identifier: {error}")
            }
        }
    }
}

impl Error for PgIndexError {}

fn normalized_label(input: &str) -> Result<String, PgIndexError> {
    let trimmed = validate_label(input, PgIndexError::Empty)?;
    Ok(trimmed
        .replace('_', " ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_ascii_lowercase())
}

fn validate_label(input: &str, empty_error: PgIndexError) -> Result<&str, PgIndexError> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(empty_error);
    }
    if trimmed.chars().any(char::is_control) {
        return Err(PgIndexError::ControlCharacter);
    }
    Ok(trimmed)
}

#[cfg(test)]
mod tests {
    use super::{
        PgIndex, PgIndexColumn, PgIndexError, PgIndexExpression, PgIndexFlags, PgIndexMethod,
        PgIndexName,
    };

    #[test]
    fn parses_and_renders_index_methods() -> Result<(), PgIndexError> {
        assert_eq!("btree".parse::<PgIndexMethod>()?, PgIndexMethod::Btree);
        assert_eq!("sp gist".parse::<PgIndexMethod>()?, PgIndexMethod::Spgist);
        assert_eq!(PgIndexMethod::Brin.to_string(), "brin");
        Ok(())
    }

    #[test]
    fn tracks_index_flags() {
        let flags = PgIndexFlags::default()
            .unique(true)
            .primary(true)
            .concurrent(true)
            .invalid(true);
        assert!(flags.is_unique());
        assert!(flags.is_primary());
        assert!(flags.is_concurrent());
        assert!(flags.is_invalid());
    }

    #[test]
    fn creates_btree_index_metadata() -> Result<(), PgIndexError> {
        let index = PgIndex::new(PgIndexName::new("users_email_idx")?)
            .with_method(PgIndexMethod::Btree)
            .with_columns(vec![PgIndexColumn::new("email")?])
            .with_flags(PgIndexFlags::default().unique(true));

        assert_eq!(index.name().as_str(), "users_email_idx");
        assert_eq!(index.method(), PgIndexMethod::Btree);
        assert_eq!(index.columns().len(), 1);
        assert!(index.flags().is_unique());
        Ok(())
    }

    #[test]
    fn tracks_expression_and_partial_labels() -> Result<(), PgIndexError> {
        let index = PgIndex::new(PgIndexName::new("users_lower_email_idx")?)
            .with_expression(PgIndexExpression::new("lower(email)")?)
            .with_predicate("deleted_at IS NULL")?;
        assert_eq!(index.expressions().len(), 1);
        assert_eq!(index.predicate(), Some("deleted_at IS NULL"));
        assert!(index.flags().is_expression());
        assert!(index.flags().is_partial());
        Ok(())
    }
}