wasm-dbms-api 0.9.0

Runtime-agnostic API types and traits for the wasm-dbms DBMS engine.
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
use serde::{Deserialize, Serialize};

use crate::dbms::types::DataTypeKind;
use crate::dbms::value::Value;

/// Constructor for a column's default value.
///
/// Stored as a function pointer rather than a `Value` so [`ColumnDef`] can stay
/// `Copy`. The migration planner calls the constructor whenever it needs to
/// materialise the default for an `AddColumn` op or to fill a fresh row.
pub type DefaultValueFn = fn() -> Value;

/// Defines a column in a database table.
#[derive(Clone, Copy, Debug)]
pub struct ColumnDef {
    /// The name of the column.
    pub name: &'static str,
    /// The data type of the column.
    pub data_type: DataTypeKind,
    /// Indicates if this column is auto-incrementing (applicable for integer types).
    /// Cannot be `nullable`.
    pub auto_increment: bool,
    /// Indicates if this column can contain NULL values.
    pub nullable: bool,
    /// Indicates if this column is part of the primary key.
    pub primary_key: bool,
    /// Indicates if this column has unique values across all records.
    pub unique: bool,
    /// Foreign key definition, if any.
    pub foreign_key: Option<ForeignKeyDef>,
    /// Default value constructor, if any.
    ///
    /// Populated by the `#[default = ...]` attribute on a `#[derive(Table)]`
    /// field. Consumed by the migration planner when adding a non-nullable
    /// column to satisfy the
    /// [`DefaultMissing`](crate::dbms::migration::MigrationError::DefaultMissing)
    /// check.
    pub default: Option<DefaultValueFn>,
    /// Previous names this column was known by, in chronological order.
    ///
    /// Populated by the `#[renamed_from("old1", "old2", ...)]` attribute. The
    /// migration planner walks this list to detect a `RenameColumn` op when a
    /// stored column with one of these names matches the compiled column.
    pub renamed_from: &'static [&'static str],
}

impl PartialEq for ColumnDef {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.data_type == other.data_type
            && self.auto_increment == other.auto_increment
            && self.nullable == other.nullable
            && self.primary_key == other.primary_key
            && self.unique == other.unique
            && self.foreign_key == other.foreign_key
            && self.default.map(|f| f as usize) == other.default.map(|f| f as usize)
            && self.renamed_from == other.renamed_from
    }
}

impl Eq for ColumnDef {}

/// Defines a foreign key relationship for a column.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ForeignKeyDef {
    /// Name of the local column that holds the foreign key (es: "user_id")
    pub local_column: &'static str,
    /// Name of the foreign table (e.g., "users")
    pub foreign_table: &'static str,
    /// Name of the foreign column that the FK points to (e.g., "id")
    pub foreign_column: &'static str,
}

/// Defines an index on one or more columns of a table.
///
/// Contains a static slice of column names that make up the index, in the order they are defined.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IndexDef(pub &'static [&'static str]);

impl IndexDef {
    /// Returns the column names that make up this index.
    pub fn columns(&self) -> &'static [&'static str] {
        self.0
    }
}

/// Serializable data type kind for API boundaries.
///
/// Mirrors [`DataTypeKind`] but uses owned `String` for the `Custom` variant,
/// making it suitable for serialization across API boundaries.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "candid", derive(candid::CandidType))]
pub enum CandidDataTypeKind {
    Blob,
    Boolean,
    Date,
    DateTime,
    Decimal,
    Int8,
    Int16,
    Int32,
    Int64,
    Json,
    Text,
    Uint8,
    Uint16,
    Uint32,
    Uint64,
    Uuid,
    Custom(String),
}

impl From<DataTypeKind> for CandidDataTypeKind {
    fn from(kind: DataTypeKind) -> Self {
        match kind {
            DataTypeKind::Blob => Self::Blob,
            DataTypeKind::Boolean => Self::Boolean,
            DataTypeKind::Date => Self::Date,
            DataTypeKind::DateTime => Self::DateTime,
            DataTypeKind::Decimal => Self::Decimal,
            DataTypeKind::Int8 => Self::Int8,
            DataTypeKind::Int16 => Self::Int16,
            DataTypeKind::Int32 => Self::Int32,
            DataTypeKind::Int64 => Self::Int64,
            DataTypeKind::Json => Self::Json,
            DataTypeKind::Text => Self::Text,
            DataTypeKind::Uint8 => Self::Uint8,
            DataTypeKind::Uint16 => Self::Uint16,
            DataTypeKind::Uint32 => Self::Uint32,
            DataTypeKind::Uint64 => Self::Uint64,
            DataTypeKind::Uuid => Self::Uuid,
            DataTypeKind::Custom { tag, .. } => Self::Custom(tag.to_string()),
        }
    }
}

/// Serializable column definition for API boundaries.
///
/// This type mirrors [`ColumnDef`] but uses owned `String` fields instead
/// of `&'static str`, making it suitable for serialization across API boundaries.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "candid", derive(candid::CandidType))]
pub struct JoinColumnDef {
    /// The source table name. `Some` for join results, `None` for single-table queries.
    pub table: Option<String>,
    /// The name of the column.
    pub name: String,
    /// The data type of the column.
    pub data_type: CandidDataTypeKind,
    /// Indicates if this column can contain NULL values.
    pub nullable: bool,
    /// Indicates if this column is part of the primary key.
    pub primary_key: bool,
    /// Foreign key definition, if any.
    pub foreign_key: Option<CandidForeignKeyDef>,
}

/// Serializable foreign key definition for API boundaries.
///
/// This type mirrors [`ForeignKeyDef`] but uses owned `String` fields instead
/// of `&'static str`, making it suitable for serialization across API boundaries.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "candid", derive(candid::CandidType))]
pub struct CandidForeignKeyDef {
    /// Name of the local column that holds the foreign key (e.g., "user_id").
    pub local_column: String,
    /// Name of the foreign table (e.g., "users").
    pub foreign_table: String,
    /// Name of the foreign column that the FK points to (e.g., "id").
    pub foreign_column: String,
}

impl From<ColumnDef> for JoinColumnDef {
    fn from(def: ColumnDef) -> Self {
        Self {
            table: None,
            name: def.name.to_string(),
            data_type: CandidDataTypeKind::from(def.data_type),
            nullable: def.nullable,
            primary_key: def.primary_key,
            foreign_key: def.foreign_key.map(CandidForeignKeyDef::from),
        }
    }
}

impl From<ForeignKeyDef> for CandidForeignKeyDef {
    fn from(def: ForeignKeyDef) -> Self {
        Self {
            local_column: def.local_column.to_string(),
            foreign_table: def.foreign_table.to_string(),
            foreign_column: def.foreign_column.to_string(),
        }
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use crate::dbms::types::DataTypeKind;

    #[test]
    fn test_should_create_column_def() {
        let column = ColumnDef {
            name: "id",
            data_type: DataTypeKind::Uint32,
            auto_increment: false,
            nullable: false,
            primary_key: true,
            unique: false,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };

        assert_eq!(column.name, "id");
        assert_eq!(column.data_type, DataTypeKind::Uint32);
        assert!(!column.auto_increment);
        assert!(!column.nullable);
        assert!(column.primary_key);
        assert!(!column.unique);
        assert!(column.foreign_key.is_none());
    }

    #[test]
    fn test_should_create_column_def_with_foreign_key() {
        let fk = ForeignKeyDef {
            local_column: "user_id",
            foreign_table: "users",
            foreign_column: "id",
        };

        let column = ColumnDef {
            name: "user_id",
            data_type: DataTypeKind::Uint32,
            auto_increment: false,
            nullable: false,
            primary_key: false,
            unique: false,
            foreign_key: Some(fk),
            default: None,
            renamed_from: &[],
        };

        assert_eq!(column.name, "user_id");
        assert!(column.foreign_key.is_some());
        let fk_def = column.foreign_key.unwrap();
        assert_eq!(fk_def.local_column, "user_id");
        assert_eq!(fk_def.foreign_table, "users");
        assert_eq!(fk_def.foreign_column, "id");
    }

    #[test]
    #[allow(clippy::clone_on_copy)]
    fn test_should_clone_column_def() {
        let column = ColumnDef {
            name: "email",
            data_type: DataTypeKind::Text,
            auto_increment: false,
            nullable: true,
            primary_key: false,
            unique: true,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };

        let cloned = column.clone();
        assert_eq!(column, cloned);
    }

    #[test]
    fn test_should_compare_column_defs() {
        let column1 = ColumnDef {
            name: "id",
            data_type: DataTypeKind::Uint32,
            auto_increment: false,
            nullable: false,
            primary_key: true,
            unique: false,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };

        let column2 = ColumnDef {
            name: "id",
            data_type: DataTypeKind::Uint32,
            auto_increment: false,
            nullable: false,
            primary_key: true,
            unique: false,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };

        let column3 = ColumnDef {
            name: "name",
            data_type: DataTypeKind::Text,
            auto_increment: false,
            nullable: true,
            primary_key: false,
            unique: true,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };

        assert_eq!(column1, column2);
        assert_ne!(column1, column3);
    }

    #[test]
    fn test_should_create_foreign_key_def() {
        let fk = ForeignKeyDef {
            local_column: "post_id",
            foreign_table: "posts",
            foreign_column: "id",
        };

        assert_eq!(fk.local_column, "post_id");
        assert_eq!(fk.foreign_table, "posts");
        assert_eq!(fk.foreign_column, "id");
    }

    #[test]
    #[allow(clippy::clone_on_copy)]
    fn test_should_clone_foreign_key_def() {
        let fk = ForeignKeyDef {
            local_column: "author_id",
            foreign_table: "authors",
            foreign_column: "id",
        };

        let cloned = fk.clone();
        assert_eq!(fk, cloned);
    }

    #[test]
    fn test_should_compare_foreign_key_defs() {
        let fk1 = ForeignKeyDef {
            local_column: "user_id",
            foreign_table: "users",
            foreign_column: "id",
        };

        let fk2 = ForeignKeyDef {
            local_column: "user_id",
            foreign_table: "users",
            foreign_column: "id",
        };

        let fk3 = ForeignKeyDef {
            local_column: "category_id",
            foreign_table: "categories",
            foreign_column: "id",
        };

        assert_eq!(fk1, fk2);
        assert_ne!(fk1, fk3);
    }

    #[test]
    fn test_should_create_candid_column_def_with_table() {
        let col = JoinColumnDef {
            table: Some("users".to_string()),
            name: "id".to_string(),
            data_type: CandidDataTypeKind::Uint32,
            nullable: false,
            primary_key: true,
            foreign_key: None,
        };
        assert_eq!(col.table, Some("users".to_string()));
    }

    #[test]
    fn test_should_convert_column_def_to_candid_with_none_table() {
        let col = ColumnDef {
            name: "id",
            data_type: DataTypeKind::Uint32,
            auto_increment: false,
            nullable: false,
            primary_key: true,
            unique: false,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };
        let candid_col = JoinColumnDef::from(col);
        assert_eq!(candid_col.table, None);
        assert_eq!(candid_col.name, "id");
    }

    #[test]
    fn test_should_convert_custom_data_type_kind_to_candid() {
        use crate::dbms::table::WireSize;
        let kind = DataTypeKind::Custom {
            tag: "role",
            wire_size: WireSize::Fixed(1),
        };
        let candid_kind = CandidDataTypeKind::from(kind);
        assert_eq!(candid_kind, CandidDataTypeKind::Custom("role".to_string()));
    }

    #[test]
    fn test_should_convert_builtin_data_type_kind_to_candid() {
        let kind = DataTypeKind::Text;
        let candid_kind = CandidDataTypeKind::from(kind);
        assert_eq!(candid_kind, CandidDataTypeKind::Text);
    }

    #[test]
    fn test_should_create_candid_column_def_with_custom_type() {
        use crate::dbms::table::WireSize;
        let col = ColumnDef {
            name: "role",
            data_type: DataTypeKind::Custom {
                tag: "role",
                wire_size: WireSize::Fixed(1),
            },
            auto_increment: false,
            nullable: false,
            primary_key: false,
            unique: false,
            foreign_key: None,
            default: None,
            renamed_from: &[],
        };
        let candid_col = JoinColumnDef::from(col);
        assert_eq!(
            candid_col.data_type,
            CandidDataTypeKind::Custom("role".to_string())
        );
    }
}