radixdb-core 1.2.25

Canonical value, identity, and shared contracts for RadixDB
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
use std::collections::BTreeMap;
use std::fmt::Write;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const SCHEMA_DESCRIPTOR_VERSION: &str = "radixdb.schema.v1";

#[derive(Debug, thiserror::Error)]
pub enum DescriptorError {
    #[error("unsupported schema descriptor version '{0}'")]
    UnsupportedVersion(String),
    #[error("schema descriptor kind mismatch: expected {expected:?}, got {actual:?}")]
    KindMismatch {
        expected: DescriptorKind,
        actual: DescriptorKind,
    },
    #[error("schema descriptor JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DescriptorKind {
    Table,
    Database,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DescriptorEnvelope<T> {
    pub descriptor: String,
    pub kind: DescriptorKind,
    pub payload: T,
}

impl<T> DescriptorEnvelope<T>
where
    T: Serialize,
{
    pub fn new(kind: DescriptorKind, payload: T) -> Self {
        Self {
            descriptor: SCHEMA_DESCRIPTOR_VERSION.to_string(),
            kind,
            payload,
        }
    }

    pub fn to_json(&self) -> Result<String, DescriptorError> {
        Ok(serde_json::to_string(self)?)
    }

    pub fn to_pretty_json(&self) -> Result<String, DescriptorError> {
        Ok(serde_json::to_string_pretty(self)?)
    }
}

impl<T> DescriptorEnvelope<T>
where
    T: for<'de> Deserialize<'de>,
{
    pub fn from_json(json: &str, expected: DescriptorKind) -> Result<Self, DescriptorError> {
        let envelope: Self = serde_json::from_str(json)?;
        if envelope.descriptor != SCHEMA_DESCRIPTOR_VERSION {
            return Err(DescriptorError::UnsupportedVersion(envelope.descriptor));
        }
        if envelope.kind != expected {
            return Err(DescriptorError::KindMismatch {
                expected,
                actual: envelope.kind,
            });
        }
        Ok(envelope)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatabaseDescriptor {
    pub schema_generation: u64,
    pub fingerprint: String,
    pub tables: Vec<TableDescriptor>,
    pub views: Vec<ViewDescriptor>,
    /// Durable SQL procedures visible to the descriptor caller.
    ///
    /// The field is additive to `radixdb.schema.v1`: old descriptors omit it
    /// and retain their original fingerprint, while current producers include
    /// it whenever at least one procedure exists.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub procedures: Vec<ProcedureDescriptor>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TableDescriptor {
    pub catalog_id: String,
    pub name: String,
    pub schema_generation: u64,
    pub fingerprint: String,
    pub created_at: String,
    pub updated_at: String,
    pub columns: Vec<ColumnDescriptor>,
    pub constraints: Vec<ConstraintDescriptor>,
    pub indexes: Vec<IndexDescriptor>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ColumnDescriptor {
    pub ordinal: u32,
    pub name: String,
    pub data_type: DataTypeDescriptor,
    pub nullable: bool,
    pub auto_increment: bool,
    pub default_expression: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DataTypeDescriptor {
    Null,
    Integer,
    Float,
    DoublePrecision,
    Text {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_chars: Option<u32>,
    },
    Boolean,
    /// UTC instant (`TIMESTAMP WITH TIME ZONE`).
    Timestamp,
    /// Civil date and time (`TIMESTAMP WITHOUT TIME ZONE`).
    CivilTimestamp,
    /// Civil time of day (`TIME WITHOUT TIME ZONE`).
    Time,
    Date,
    Json,
    Uuid,
    Bytes,
    Decimal {
        precision: Option<u8>,
        scale: Option<u8>,
    },
    Vector {
        dimensions: u16,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConstraintDescriptor {
    pub id: u64,
    pub name: String,
    #[serde(flatten)]
    pub definition: ConstraintDefinition,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "constraint_type", rename_all = "snake_case")]
pub enum ConstraintDefinition {
    PrimaryKey {
        columns: Vec<String>,
    },
    Unique {
        columns: Vec<String>,
        owned_index: String,
    },
    ForeignKey {
        columns: Vec<String>,
        referenced_table: String,
        referenced_columns: Vec<String>,
        on_delete: ForeignKeyActionDescriptor,
        on_update: ForeignKeyActionDescriptor,
    },
    Check {
        column: Option<String>,
        expression: String,
        ordinal: u32,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForeignKeyActionDescriptor {
    Restrict,
    Cascade,
    SetNull,
    NoAction,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexDescriptor {
    pub name: String,
    pub method: String,
    pub columns: Vec<String>,
    pub unique: bool,
    pub predicate: Option<String>,
    pub options: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewDescriptor {
    pub name: String,
    pub query: String,
    pub dependencies: Vec<String>,
    pub result_columns: Vec<ResultColumnDescriptor>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResultColumnDescriptor {
    pub name: String,
    pub data_type: DataTypeDescriptor,
    pub nullable: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcedureDescriptor {
    pub catalog_id: String,
    pub name: String,
    pub definition_revision: u64,
    pub fingerprint: String,
    pub source_sha256: String,
    pub language: String,
    pub language_version: u16,
    pub compiler_abi: u32,
    pub runtime_abi: u32,
    pub security: RoutineSecurityDescriptor,
    pub volatility: RoutineVolatilityDescriptor,
    pub arguments: Vec<RoutineArgumentDescriptor>,
    pub result: RoutineResultDescriptor,
    pub resource_policy: RoutineResourcePolicyDescriptor,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoutineArgumentDescriptor {
    pub ordinal: u32,
    pub name: String,
    pub mode: RoutineArgumentModeDescriptor,
    pub sql_type: String,
    /// `None` denotes a catalog-defined extension type. Its stable SQL name is
    /// still carried in `sql_type`; application generators may reject it until
    /// an explicit codec binding is configured.
    pub data_type: Option<DataTypeDescriptor>,
    pub nullable: bool,
    pub default_expression: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutineArgumentModeDescriptor {
    In,
    Out,
    InOut,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RoutineResultDescriptor {
    Void,
    Scalar {
        sql_type: String,
        data_type: Option<DataTypeDescriptor>,
        nullable: bool,
    },
    Table {
        columns: Vec<RoutineResultColumnDescriptor>,
    },
    Trigger,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoutineResultColumnDescriptor {
    pub ordinal: u32,
    pub name: String,
    pub sql_type: String,
    pub data_type: Option<DataTypeDescriptor>,
    pub nullable: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutineSecurityDescriptor {
    Invoker,
    Definer,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutineVolatilityDescriptor {
    Immutable,
    Stable,
    Volatile,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoutineResourcePolicyDescriptor {
    pub instructions: u64,
    pub heap_bytes: u64,
    pub frames: u32,
    pub sql_statements: u64,
    pub rows: u64,
    pub result_bytes: u64,
    pub deadline_ms: u64,
}

impl TableDescriptor {
    pub fn to_json(&self) -> Result<String, DescriptorError> {
        DescriptorEnvelope::new(DescriptorKind::Table, self.clone()).to_json()
    }

    pub fn from_json(json: &str) -> Result<Self, DescriptorError> {
        Ok(DescriptorEnvelope::<Self>::from_json(json, DescriptorKind::Table)?.payload)
    }

    pub fn form_descriptor(&self) -> crate::TableFormDescriptor {
        crate::TableFormDescriptor::from_table(self)
    }

    /// Compute the schema fingerprint with the fingerprint field itself blank.
    pub fn computed_fingerprint(&self) -> Result<String, DescriptorError> {
        let mut canonical = self.clone();
        canonical.fingerprint.clear();
        canonical_fingerprint(&canonical)
    }

    pub fn refresh_fingerprint(&mut self) -> Result<(), DescriptorError> {
        self.fingerprint = self.computed_fingerprint()?;
        Ok(())
    }
}

impl DatabaseDescriptor {
    pub fn to_json(&self) -> Result<String, DescriptorError> {
        DescriptorEnvelope::new(DescriptorKind::Database, self.clone()).to_json()
    }

    pub fn from_json(json: &str) -> Result<Self, DescriptorError> {
        Ok(DescriptorEnvelope::<Self>::from_json(json, DescriptorKind::Database)?.payload)
    }

    /// Compute the database fingerprint from its ordered, already-fingerprinted
    /// table/view catalog while excluding the fingerprint field itself.
    pub fn computed_fingerprint(&self) -> Result<String, DescriptorError> {
        let mut canonical = self.clone();
        canonical.fingerprint.clear();
        canonical_fingerprint(&canonical)
    }

    pub fn refresh_fingerprint(&mut self) -> Result<(), DescriptorError> {
        self.fingerprint = self.computed_fingerprint()?;
        Ok(())
    }
}

impl ProcedureDescriptor {
    /// Compute the procedure contract fingerprint with the fingerprint field
    /// itself blank. Source text is represented only by `source_sha256`.
    pub fn computed_fingerprint(&self) -> Result<String, DescriptorError> {
        let mut canonical = self.clone();
        canonical.fingerprint.clear();
        canonical_fingerprint(&canonical)
    }

    pub fn refresh_fingerprint(&mut self) -> Result<(), DescriptorError> {
        self.fingerprint = self.computed_fingerprint()?;
        Ok(())
    }
}

pub fn canonical_fingerprint<T: Serialize>(value: &T) -> Result<String, DescriptorError> {
    let encoded = serde_json::to_vec(value)?;
    let digest = Sha256::digest(encoded);
    let mut fingerprint = String::with_capacity(digest.len() * 2);
    for byte in digest {
        write!(&mut fingerprint, "{byte:02x}").expect("writing to String cannot fail");
    }
    Ok(fingerprint)
}

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

    #[test]
    fn descriptor_envelope_round_trip_is_versioned_and_canonical() {
        let descriptor = TableDescriptor {
            catalog_id: "018f2b34-7a10-7cc2-8f3a-9d4b5c6d7e01".to_string(),
            name: "people".to_string(),
            schema_generation: 7,
            fingerprint: "abc".to_string(),
            created_at: "2026-08-21T00:00:00Z".to_string(),
            updated_at: "2026-08-21T00:00:00Z".to_string(),
            columns: Vec::new(),
            constraints: Vec::new(),
            indexes: Vec::new(),
            extensions: BTreeMap::new(),
        };
        let envelope = DescriptorEnvelope::new(DescriptorKind::Table, descriptor.clone());
        let json = envelope.to_json().unwrap();
        assert_eq!(envelope.to_json().unwrap(), json);
        let decoded =
            DescriptorEnvelope::<TableDescriptor>::from_json(&json, DescriptorKind::Table).unwrap();
        assert_eq!(decoded.payload, descriptor);
        assert_eq!(
            TableDescriptor::from_json(&descriptor.to_json().unwrap()).unwrap(),
            descriptor
        );
        assert!(
            DescriptorEnvelope::<TableDescriptor>::from_json(&json, DescriptorKind::Database)
                .is_err()
        );
    }

    #[test]
    fn text_descriptor_preserves_old_unbounded_json_and_bounded_identity() {
        let unbounded = DataTypeDescriptor::Text { max_chars: None };
        assert_eq!(
            serde_json::to_string(&unbounded).unwrap(),
            r#"{"type":"text"}"#
        );
        assert_eq!(
            serde_json::from_str::<DataTypeDescriptor>(r#"{"type":"text"}"#).unwrap(),
            unbounded
        );

        let bounded = DataTypeDescriptor::Text {
            max_chars: Some(255),
        };
        assert_eq!(
            serde_json::to_string(&bounded).unwrap(),
            r#"{"type":"text","max_chars":255}"#
        );
        assert_ne!(
            canonical_fingerprint(&unbounded).unwrap(),
            canonical_fingerprint(&bounded).unwrap()
        );
    }

    #[test]
    fn double_precision_has_a_distinct_stable_descriptor_identity() {
        let double = DataTypeDescriptor::DoublePrecision;
        assert_eq!(
            serde_json::to_string(&double).unwrap(),
            r#"{"type":"double_precision"}"#
        );
        assert_ne!(
            canonical_fingerprint(&DataTypeDescriptor::Float).unwrap(),
            canonical_fingerprint(&double).unwrap()
        );
    }
}