nodedb-types 0.6.0

Portable type definitions shared between NodeDB Origin and NodeDB-Lite
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
// SPDX-License-Identifier: Apache-2.0

//! [`std::fmt::Display`] and [`std::str::FromStr`] for [`ColumnType`], plus
//! [`ColumnTypeParseError`].

use std::fmt;
use std::str::FromStr;

use super::column_type::ColumnType;
use super::decimal_typmod::{DecimalTypmod, DecimalTypmodError};
use crate::error::sqlstate;

/// Every declared spelling that resolves to [`ColumnType::Int64`].
///
/// nodedb stores every integer as a full `i64`, so all of these collapse to
/// one storage variant. The declared width travels separately as an
/// [`IntWidth`](super::IntWidth), which narrows the advertised wire OID and
/// bounds writes. [`IntWidth::from_declared_type`](super::IntWidth::from_declared_type)
/// must recognize every spelling listed here — a spelling it does not know
/// advertises OID 20 (`bigint`) whatever the author declared.
pub const DECLARED_INT_KEYWORDS: [&str; 8] = [
    "BIGINT", "INT64", "INTEGER", "INT", "INT4", "INT8", "SMALLINT", "INT2",
];

/// Every declared spelling that resolves to [`ColumnType::Float64`].
///
/// The float counterpart of [`DECLARED_INT_KEYWORDS`]: nodedb stores every
/// float as a full `f64`, and
/// [`FloatWidth::from_declared_type`](super::FloatWidth::from_declared_type)
/// carries the declared width that narrows the advertised wire OID. It must
/// recognize every spelling listed here.
pub const DECLARED_FLOAT_KEYWORDS: [&str; 8] = [
    "FLOAT64",
    "DOUBLE",
    "DOUBLE PRECISION",
    "FLOAT8",
    "REAL",
    "FLOAT4",
    "FLOAT32",
    "FLOAT",
];

/// Error from parsing a column type string.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ColumnTypeParseError {
    #[error("unknown column type: '{0}'")]
    Unknown(String),
    #[error("'DATETIME' is not a valid type — use 'TIMESTAMP' instead")]
    UseTimestamp,
    #[error("invalid VECTOR dimension: '{0}' (must be a positive integer)")]
    InvalidVectorDim(String),
    #[error("invalid VARCHAR length: '{0}' (must be a positive integer)")]
    InvalidCharLength(String),
    #[error(
        "invalid DECIMAL/NUMERIC params: '{0}' (expected DECIMAL(precision) or DECIMAL(precision, scale))"
    )]
    InvalidDecimalParams(String),
    /// A well-formed `DECIMAL(p,s)` whose precision or scale is out of range.
    #[error("{0}")]
    InvalidDecimalTypmod(#[from] DecimalTypmodError),
}

impl ColumnTypeParseError {
    /// The SQLSTATE a DDL statement refuses this declared type with.
    ///
    /// An out-of-range typmod is `22023` (invalid_parameter_value), as
    /// PostgreSQL reports it. Every other refusal is `42601` (syntax_error).
    pub fn sqlstate(&self) -> &'static str {
        match self {
            Self::InvalidDecimalTypmod(_) => sqlstate::INVALID_PARAMETER_VALUE,
            Self::Unknown(_)
            | Self::UseTimestamp
            | Self::InvalidVectorDim(_)
            | Self::InvalidCharLength(_)
            | Self::InvalidDecimalParams(_) => sqlstate::SYNTAX_ERROR,
        }
    }
}

impl fmt::Display for ColumnType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Int64 => f.write_str("BIGINT"),
            Self::Float64 => f.write_str("FLOAT64"),
            Self::String => f.write_str("TEXT"),
            Self::Bool => f.write_str("BOOL"),
            Self::Bytes => f.write_str("BYTES"),
            Self::Timestamp => f.write_str("TIMESTAMP"),
            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
            Self::SystemTimestamp => f.write_str("SYSTEM_TIMESTAMP"),
            Self::Decimal(Some(typmod)) => {
                write!(f, "DECIMAL({},{})", typmod.precision(), typmod.scale())
            }
            Self::Decimal(None) => f.write_str("DECIMAL"),
            Self::Geometry => f.write_str("GEOMETRY"),
            Self::Vector(dim) => write!(f, "VECTOR({dim})"),
            Self::SparseVector => f.write_str("SPARSEVECTOR"),
            Self::Uuid => f.write_str("UUID"),
            Self::Json => f.write_str("JSON"),
            Self::Ulid => f.write_str("ULID"),
            Self::Duration => f.write_str("DURATION"),
            Self::Array => f.write_str("ARRAY"),
            Self::Set => f.write_str("SET"),
            Self::Regex => f.write_str("REGEX"),
            Self::Range => f.write_str("RANGE"),
            Self::Record => f.write_str("RECORD"),
        }
    }
}

impl FromStr for ColumnType {
    type Err = ColumnTypeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let upper = s.trim().to_uppercase();

        // NUMERIC / DECIMAL, bare or with a `(p)` / `(p,s)` typmod. A longer
        // word such as `NUMERIC_MONEY` is not this keyword and falls through
        // to the unknown-type arm.
        if let Some(rest) = upper
            .strip_prefix("NUMERIC")
            .or_else(|| upper.strip_prefix("DECIMAL"))
        {
            let rest = rest.trim();
            if rest.is_empty() {
                return Ok(Self::Decimal(None));
            }
            if rest.starts_with('(') {
                return parse_decimal_typmod(rest).map(|typmod| Self::Decimal(Some(typmod)));
            }
        }

        // VECTOR(N) special case.
        if upper.starts_with("VECTOR") {
            let inner = upper
                .trim_start_matches("VECTOR")
                .trim()
                .trim_start_matches('(')
                .trim_end_matches(')')
                .trim();
            if inner.is_empty() {
                return Err(ColumnTypeParseError::InvalidVectorDim("empty".into()));
            }
            let dim: u32 = inner
                .parse()
                .map_err(|_| ColumnTypeParseError::InvalidVectorDim(inner.into()))?;
            if dim == 0 {
                return Err(ColumnTypeParseError::InvalidVectorDim("0".into()));
            }
            return Ok(Self::Vector(dim));
        }

        // VARCHAR(n) special case. A declared character length is a wire
        // contract, not a storage property — nodedb stores every string
        // unbounded — so `VARCHAR(255)` resolves to the answer bare `VARCHAR`
        // gives. The length still parses, so a malformed one errors here
        // instead of resolving to a type the author did not write.
        if let Some(rest) = upper.strip_prefix("VARCHAR")
            && let Some(inner) = rest.strip_prefix('(').and_then(|r| r.strip_suffix(')'))
        {
            let length: u32 = inner
                .trim()
                .parse()
                .map_err(|_| ColumnTypeParseError::InvalidCharLength(inner.trim().to_string()))?;
            if length == 0 {
                return Err(ColumnTypeParseError::InvalidCharLength("0".into()));
            }
            return Ok(Self::String);
        }

        match upper.as_str() {
            // Every PostgreSQL wire-width integer keyword collapses to the
            // one `Int64` storage variant; `DECLARED_INT_KEYWORDS` lists them
            // and carries the width contract.
            keyword if DECLARED_INT_KEYWORDS.contains(&keyword) => Ok(Self::Int64),
            // The float counterpart, listed by `DECLARED_FLOAT_KEYWORDS`.
            keyword if DECLARED_FLOAT_KEYWORDS.contains(&keyword) => Ok(Self::Float64),
            "TEXT" | "STRING" | "VARCHAR" => Ok(Self::String),
            "BOOL" | "BOOLEAN" => Ok(Self::Bool),
            "BYTES" | "BYTEA" | "BLOB" => Ok(Self::Bytes),
            "TIMESTAMP" | "TIMESTAMP WITHOUT TIME ZONE" => Ok(Self::Timestamp),
            "TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" => Ok(Self::Timestamptz),
            "SYSTEM_TIMESTAMP" | "SYSTEMTIMESTAMP" => Ok(Self::SystemTimestamp),
            "GEOMETRY" => Ok(Self::Geometry),
            // Dimensionless: an exact keyword with no `(N)`. Placed as an exact
            // match rather than a `starts_with` guard because "SPARSEVECTOR"
            // does not prefix-collide with the `starts_with("VECTOR")` branch
            // above ("SPARSEVECTOR" starts with "SPARSE", not "VECTOR").
            "SPARSEVECTOR" => Ok(Self::SparseVector),
            "UUID" => Ok(Self::Uuid),
            "JSON" | "JSONB" => Ok(Self::Json),
            "ULID" => Ok(Self::Ulid),
            "DURATION" => Ok(Self::Duration),
            "ARRAY" => Ok(Self::Array),
            "SET" => Ok(Self::Set),
            "REGEX" => Ok(Self::Regex),
            "RANGE" => Ok(Self::Range),
            "RECORD" => Ok(Self::Record),
            "DATETIME" => Err(ColumnTypeParseError::UseTimestamp),
            other => Err(ColumnTypeParseError::Unknown(other.to_string())),
        }
    }
}

impl ColumnType {
    /// Resolve a declared DDL type string to a column type.
    ///
    /// This is the single answer to "which [`ColumnType`] does this declared
    /// string denote", shared by both planes. The catalog records the raw DDL
    /// text that followed the column name, so an entry reads `INT DEFAULT 5`
    /// or `DECIMAL(10, 2) NOT NULL`, not `INT`. This resolves the leading type
    /// token, so a trailing modifier never changes the answer.
    ///
    /// `None` means the token names no known type. A caller that needs a
    /// fallback picks its own — this reports the absence rather than guessing.
    ///
    /// A multi-word spelling resolves from its first word: `DOUBLE PRECISION`
    /// is [`ColumnType::Float64`], and `TIMESTAMP WITH TIME ZONE` reaching
    /// here as catalog text resolves to [`ColumnType::Timestamp`]. Pass such a
    /// spelling to [`str::parse`] instead to resolve it whole.
    pub fn from_declared_type(declared: &str) -> Option<Self> {
        Self::parse_declared_type(declared).ok()
    }

    /// [`ColumnType::from_declared_type`] with the parse error kept.
    ///
    /// A DDL gate uses this to refuse a declared type it cannot hold, such as
    /// `DECIMAL(1001,0)`, instead of reading it as an unknown type.
    pub fn parse_declared_type(declared: &str) -> Result<Self, ColumnTypeParseError> {
        bare_declared_token(declared).parse()
    }
}

/// The typmod of `DECIMAL(p)` or `DECIMAL(p,s)`, from the `(p)` or `(p,s)`
/// text after the keyword. A bare `(p)` has scale 0.
///
/// Text that is not one or two integers in parentheses is malformed. Integers
/// out of range are an [`ColumnTypeParseError::InvalidDecimalTypmod`].
fn parse_decimal_typmod(params: &str) -> Result<DecimalTypmod, ColumnTypeParseError> {
    let malformed = || ColumnTypeParseError::InvalidDecimalParams(params.to_string());
    let inner = params
        .strip_prefix('(')
        .and_then(|p| p.strip_suffix(')'))
        .ok_or_else(malformed)?;
    let (precision_text, scale_text) = match inner.split_once(',') {
        Some((precision, scale)) => (precision, scale),
        None => (inner, "0"),
    };
    let precision: i64 = precision_text.trim().parse().map_err(|_| malformed())?;
    let scale: i64 = scale_text.trim().parse().map_err(|_| malformed())?;
    Ok(DecimalTypmod::new(precision, scale)?)
}

/// The leading type token of a declared DDL type string.
///
/// The cut is the first whitespace outside parentheses, so a parameter list
/// keeps its internal spaces and `DECIMAL(10, 2) NOT NULL` yields
/// `DECIMAL(10, 2)`. A trailing comma left by a column-list split is dropped.
fn bare_declared_token(declared: &str) -> &str {
    let trimmed = declared.trim_start();
    let mut depth = 0usize;
    let mut end = trimmed.len();
    for (index, ch) in trimmed.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            _ if depth == 0 && ch.is_whitespace() => {
                end = index;
                break;
            }
            _ => {}
        }
    }
    trimmed.get(..end).unwrap_or(trimmed).trim_end_matches(',')
}

#[cfg(test)]
mod tests {
    use super::super::{FloatWidth, IntWidth};
    use super::*;

    /// Every spelling the parser resolves to `Int64` must also resolve to a
    /// declared [`IntWidth`]. A spelling one side knows and the other does not
    /// advertises the wrong `RowDescription` OID for the column.
    ///
    /// The list is the one the parser itself matches on, so adding a spelling
    /// there extends this test rather than leaving it behind.
    #[test]
    fn every_declared_int_keyword_resolves_to_int64_and_a_width() {
        for keyword in DECLARED_INT_KEYWORDS {
            assert_eq!(
                keyword.parse::<ColumnType>(),
                Ok(ColumnType::Int64),
                "{keyword} must resolve to Int64"
            );
            assert!(
                IntWidth::from_declared_type(keyword).is_some(),
                "{keyword} must resolve to a declared IntWidth"
            );
        }
    }

    /// The float counterpart of
    /// [`every_declared_int_keyword_resolves_to_int64_and_a_width`].
    #[test]
    fn every_declared_float_keyword_resolves_to_float64_and_a_width() {
        for keyword in DECLARED_FLOAT_KEYWORDS {
            assert_eq!(
                keyword.parse::<ColumnType>(),
                Ok(ColumnType::Float64),
                "{keyword} must resolve to Float64"
            );
            assert!(
                FloatWidth::from_declared_type(keyword).is_some(),
                "{keyword} must resolve to a declared FloatWidth"
            );
        }
    }

    #[test]
    fn declared_type_ignores_trailing_modifiers() {
        assert_eq!(
            ColumnType::from_declared_type("INT DEFAULT 5"),
            Some(ColumnType::Int64)
        );
        assert_eq!(
            ColumnType::from_declared_type("TEXT NOT NULL PRIMARY KEY"),
            Some(ColumnType::String)
        );
        assert_eq!(
            ColumnType::from_declared_type("timestamp time_key"),
            Some(ColumnType::Timestamp)
        );
        assert_eq!(
            ColumnType::from_declared_type("BIGINT,"),
            Some(ColumnType::Int64)
        );
    }

    /// A parameter list keeps its internal spaces: cutting at the first
    /// whitespace would leave `DECIMAL(10,` and lose the type.
    #[test]
    fn declared_type_keeps_a_spaced_parameter_list() {
        assert_eq!(
            ColumnType::from_declared_type("DECIMAL(10, 2) NOT NULL"),
            Some(ColumnType::Decimal(Some(
                DecimalTypmod::new(10, 2).expect("valid typmod")
            )))
        );
        assert_eq!(
            ColumnType::from_declared_type("VECTOR(768)"),
            Some(ColumnType::Vector(768))
        );
    }

    /// An out-of-range typmod keeps its typed error through the declared-type
    /// parse, and refuses as `22023`. A malformed one refuses as `42601`.
    #[test]
    fn declared_decimal_typmod_errors_are_typed() {
        let err = ColumnType::parse_declared_type("DECIMAL(1001,0) NOT NULL")
            .expect_err("precision 1001 is refused");
        assert_eq!(
            err,
            ColumnTypeParseError::InvalidDecimalTypmod(DecimalTypmodError::PrecisionOutOfRange {
                precision: 1001
            })
        );
        assert_eq!(err.sqlstate(), "22023");
        assert_eq!(ColumnType::from_declared_type("DECIMAL(1001,0)"), None);

        let err = ColumnType::parse_declared_type("NUMERIC(x)").expect_err("malformed");
        assert_eq!(err.sqlstate(), "42601");
        assert_eq!(
            ColumnType::parse_declared_type("NUMERIC DEFAULT 1"),
            Ok(ColumnType::Decimal(None))
        );
    }

    /// The two zone spellings resolve whole, so a parser that reads the full
    /// string reads the zone the author wrote.
    #[test]
    fn both_timestamp_zone_spellings_resolve_whole() {
        assert_eq!(
            "TIMESTAMP WITH TIME ZONE".parse::<ColumnType>(),
            Ok(ColumnType::Timestamptz)
        );
        assert_eq!(
            "timestamp without time zone".parse::<ColumnType>(),
            Ok(ColumnType::Timestamp)
        );
    }

    /// A declared character length resolves to `String` and a malformed one
    /// errors rather than resolving to an unwritten type.
    #[test]
    fn varchar_length_resolves_to_string() {
        assert_eq!("VARCHAR(255)".parse::<ColumnType>(), Ok(ColumnType::String));
        assert_eq!("varchar(1)".parse::<ColumnType>(), Ok(ColumnType::String));
        assert_eq!(
            ColumnType::from_declared_type("VARCHAR(8) NOT NULL"),
            Some(ColumnType::String)
        );
        assert_eq!(
            "VARCHAR(0)".parse::<ColumnType>(),
            Err(ColumnTypeParseError::InvalidCharLength("0".into()))
        );
        assert_eq!(
            "VARCHAR(abc)".parse::<ColumnType>(),
            Err(ColumnTypeParseError::InvalidCharLength("ABC".into()))
        );
    }

    #[test]
    fn declared_type_reports_an_unknown_token_as_none() {
        assert_eq!(ColumnType::from_declared_type("SOMETHING_ELSE"), None);
        assert_eq!(ColumnType::from_declared_type(""), None);
        assert_eq!(ColumnType::from_declared_type("   "), None);
    }

    /// `Timestamp` and `Timestamptz` are instants; `SystemTimestamp` is
    /// engine-assigned and is not.
    #[test]
    fn only_timestamp_types_are_instants() {
        assert!(ColumnType::Timestamp.is_instant());
        assert!(ColumnType::Timestamptz.is_instant());
        assert!(!ColumnType::SystemTimestamp.is_instant());
        assert!(!ColumnType::Int64.is_instant());
        assert!(!ColumnType::String.is_instant());
    }
}