toasty-core 0.2.0

Core types, schema representations, and driver interface for Toasty
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use crate::{schema::db, stmt};

/// Describes what a database driver supports.
///
/// The query planner reads these flags to decide which [`Operation`](super::Operation)
/// variants to generate. For example, a SQL driver sets `sql: true` and
/// receives `QuerySql` operations, while DynamoDB sets `sql: false` and
/// receives key-value operations like `GetByKey` and `QueryPk`.
///
/// Pre-built configurations are available as associated constants:
/// [`SQLITE`](Self::SQLITE), [`POSTGRESQL`](Self::POSTGRESQL),
/// [`MYSQL`](Self::MYSQL), and [`DYNAMODB`](Self::DYNAMODB).
///
/// # Examples
///
/// ```
/// use toasty_core::driver::Capability;
///
/// let cap = &Capability::SQLITE;
/// assert!(cap.sql);
/// assert!(cap.returning_from_mutation);
/// assert!(!cap.select_for_update);
/// ```
#[derive(Debug)]
pub struct Capability {
    /// When `true`, the database uses a SQL-based query language and the
    /// planner will emit [`QuerySql`](super::operation::QuerySql) operations.
    pub sql: bool,

    /// Column storage types supported by the database.
    pub storage_types: StorageTypes,

    /// Schema mutation capabilities supported by the datbase.
    pub schema_mutations: SchemaMutations,

    /// SQL: supports update statements in CTE queries.
    pub cte_with_update: bool,

    /// SQL: Supports row-level locking. If false, then the driver is expected
    /// to serializable transaction-level isolation.
    pub select_for_update: bool,

    /// SQL: Mysql doesn't support returning clauses from insert / update queries
    pub returning_from_mutation: bool,

    /// DynamoDB does not support != predicates on the primary key.
    pub primary_key_ne_predicate: bool,

    /// Whether the database has an auto increment modifier for integer columns.
    pub auto_increment: bool,

    /// Whether the database supports `VARCHAR(n)` column types natively.
    ///
    /// Must be consistent with [`StorageTypes::varchar`]: when `true`,
    /// `varchar` must be `Some`; when `false`, `varchar` must be `None`.
    /// Use [`Capability::validate`] to check this invariant.
    pub native_varchar: bool,

    /// Whether the database has native support for Timestamp types.
    pub native_timestamp: bool,

    /// Whether the database has native support for Date types.
    pub native_date: bool,

    /// Whether the database has native support for Time types.
    pub native_time: bool,

    /// Whether the database has native support for DateTime types.
    pub native_datetime: bool,

    /// Whether the database has native support for Decimal types.
    pub native_decimal: bool,

    /// Whether BigDecimal driver support is implemented.
    /// TODO: Remove this flag when PostgreSQL BigDecimal support is implemented.
    /// Currently only MySQL has implemented BigDecimal driver support.
    pub bigdecimal_implemented: bool,

    /// Whether the database's decimal type supports arbitrary precision.
    /// When false, the decimal type requires fixed precision and scale to be specified upfront.
    /// - PostgreSQL: true (NUMERIC supports arbitrary precision)
    /// - MySQL: false (DECIMAL requires fixed precision/scale)
    /// - SQLite/DynamoDB: false (no native decimal support, stored as TEXT)
    pub decimal_arbitrary_precision: bool,

    /// Whether OR is supported in index key conditions (e.g. DynamoDB KeyConditionExpression).
    /// DynamoDB: false. All other backends: true (SQL backends never use index key conditions).
    pub index_or_predicate: bool,

    /// Whether to test connection pool behavior.
    /// TODO: We only need this for the `connection_per_clone.rs` test, come up with a better way.
    pub test_connection_pool: bool,
}

/// Maps application-level types to the concrete database column types used for
/// storage.
///
/// Each database has different native type support. For example, PostgreSQL has
/// a native `UUID` type while SQLite stores UUIDs as `BLOB`. This struct
/// captures those mappings so the schema layer can generate correct DDL and the
/// driver can encode/decode values appropriately.
///
/// Pre-built configurations: [`SQLITE`](Self::SQLITE),
/// [`POSTGRESQL`](Self::POSTGRESQL), [`MYSQL`](Self::MYSQL),
/// [`DYNAMODB`](Self::DYNAMODB).
///
/// # Examples
///
/// ```
/// use toasty_core::driver::StorageTypes;
///
/// let st = &StorageTypes::POSTGRESQL;
/// // PostgreSQL stores UUIDs natively
/// assert!(matches!(st.default_uuid_type, toasty_core::schema::db::Type::Uuid));
/// ```
#[derive(Debug)]
pub struct StorageTypes {
    /// The default storage type for a string.
    pub default_string_type: db::Type,

    /// When `Some` the database supports varchar types with the specified upper
    /// limit.
    pub varchar: Option<u64>,

    /// The default storage type for a UUID.
    pub default_uuid_type: db::Type,

    /// The default storage type for Bytes (Vec<u8>).
    pub default_bytes_type: db::Type,

    /// The default storage type for a Decimal (fixed-precision decimal).
    pub default_decimal_type: db::Type,

    /// The default storage type for a BigDecimal (arbitrary-precision decimal).
    pub default_bigdecimal_type: db::Type,

    /// The default storage type for a Timestamp (instant in time).
    pub default_timestamp_type: db::Type,

    /// The default storage type for a Zoned (timezone-aware instant).
    pub default_zoned_type: db::Type,

    /// The default storage type for a Date (civil date).
    pub default_date_type: db::Type,

    /// The default storage type for a Time (wall clock time).
    pub default_time_type: db::Type,

    /// The default storage type for a DateTime (civil datetime).
    pub default_datetime_type: db::Type,

    /// Maximum value for unsigned integers. When `Some`, unsigned integers
    /// are limited to this value. When `None`, full u64 range is supported.
    pub max_unsigned_integer: Option<u64>,
}

/// The database's capabilities to mutate the schema (tables, columns, indices).
///
/// Used by the migration generator to decide how to express schema changes.
/// For example, SQLite cannot alter column types so migrations must recreate
/// the table instead.
///
/// Pre-built configurations: [`SQLITE`](Self::SQLITE),
/// [`POSTGRESQL`](Self::POSTGRESQL), [`MYSQL`](Self::MYSQL),
/// [`DYNAMODB`](Self::DYNAMODB).
///
/// # Examples
///
/// Access through [`Capability::schema_mutations`]:
///
/// ```
/// use toasty_core::driver::Capability;
///
/// let cap = &Capability::POSTGRESQL;
/// assert!(cap.schema_mutations.alter_column_type);
/// assert!(!cap.schema_mutations.alter_column_properties_atomic);
/// ```
#[derive(Debug)]
pub struct SchemaMutations {
    /// Whether the database can change the type of an existing column.
    pub alter_column_type: bool,

    /// Whether the database can change name, type and constraints of a column all
    /// withing a single statement.
    pub alter_column_properties_atomic: bool,
}

impl Capability {
    /// Validates the consistency of the capability configuration.
    ///
    /// This performs sanity checks to ensure the capability fields are
    /// internally consistent. For example, if `native_varchar` is true,
    /// then `storage_types.varchar` must be Some, and vice versa.
    ///
    /// Returns an error if any inconsistencies are found.
    pub fn validate(&self) -> crate::Result<()> {
        // Validate varchar consistency
        if self.native_varchar && self.storage_types.varchar.is_none() {
            return Err(crate::Error::invalid_driver_configuration(
                "native_varchar is true but storage_types.varchar is None",
            ));
        }

        if !self.native_varchar && self.storage_types.varchar.is_some() {
            return Err(crate::Error::invalid_driver_configuration(
                "native_varchar is false but storage_types.varchar is Some",
            ));
        }

        Ok(())
    }

    /// Returns the default string length limit for this database.
    ///
    /// This is useful for tests and applications that need to respect
    /// database-specific string length constraints.
    pub fn default_string_max_length(&self) -> Option<u64> {
        match &self.storage_types.default_string_type {
            db::Type::VarChar(len) => Some(*len),
            _ => None, // Handle other types gracefully
        }
    }

    /// Returns the native database type for an application-level type.
    ///
    /// If the database supports the type natively, returns the same type.
    /// Otherwise, returns the bridge/storage type that the application type
    /// maps to in this database.
    ///
    /// This uses the existing `db::Type::bridge_type()` method to determine
    /// the appropriate bridge type based on the database's storage capabilities.
    pub fn native_type_for(&self, ty: &stmt::Type) -> stmt::Type {
        match ty {
            stmt::Type::Uuid => self.storage_types.default_uuid_type.bridge_type(ty),
            #[cfg(feature = "jiff")]
            stmt::Type::Timestamp => self.storage_types.default_timestamp_type.bridge_type(ty),
            #[cfg(feature = "jiff")]
            stmt::Type::Zoned => self.storage_types.default_zoned_type.bridge_type(ty),
            #[cfg(feature = "jiff")]
            stmt::Type::Date => self.storage_types.default_date_type.bridge_type(ty),
            #[cfg(feature = "jiff")]
            stmt::Type::Time => self.storage_types.default_time_type.bridge_type(ty),
            #[cfg(feature = "jiff")]
            stmt::Type::DateTime => self.storage_types.default_datetime_type.bridge_type(ty),
            _ => ty.clone(),
        }
    }

    /// SQLite capabilities.
    pub const SQLITE: Self = Self {
        sql: true,
        storage_types: StorageTypes::SQLITE,
        schema_mutations: SchemaMutations::SQLITE,
        cte_with_update: false,
        select_for_update: false,
        returning_from_mutation: true,
        primary_key_ne_predicate: true,
        auto_increment: true,
        bigdecimal_implemented: false,

        native_varchar: true,

        // SQLite does not have native date/time types
        native_timestamp: false,
        native_date: false,
        native_time: false,
        native_datetime: false,

        // SQLite does not have native decimal types
        native_decimal: false,
        decimal_arbitrary_precision: false,

        index_or_predicate: true,

        test_connection_pool: false,
    };

    /// PostgreSQL capabilities
    pub const POSTGRESQL: Self = Self {
        cte_with_update: true,
        storage_types: StorageTypes::POSTGRESQL,
        schema_mutations: SchemaMutations::POSTGRESQL,
        select_for_update: true,
        auto_increment: true,
        bigdecimal_implemented: false,

        // PostgreSQL has native date/time types
        native_timestamp: true,
        native_date: true,
        native_time: true,
        native_datetime: true,

        // PostgreSQL has native NUMERIC type with arbitrary precision
        native_decimal: true,
        decimal_arbitrary_precision: true,

        test_connection_pool: true,

        ..Self::SQLITE
    };

    /// MySQL capabilities
    pub const MYSQL: Self = Self {
        cte_with_update: false,
        storage_types: StorageTypes::MYSQL,
        schema_mutations: SchemaMutations::MYSQL,
        select_for_update: true,
        returning_from_mutation: false,
        auto_increment: true,
        bigdecimal_implemented: true,

        // MySQL has native date/time types
        native_timestamp: true,
        native_date: true,
        native_time: true,
        native_datetime: true,

        // MySQL has DECIMAL type but requires fixed precision/scale upfront
        native_decimal: true,
        decimal_arbitrary_precision: false,

        test_connection_pool: true,

        ..Self::SQLITE
    };

    /// DynamoDB capabilities
    pub const DYNAMODB: Self = Self {
        sql: false,
        storage_types: StorageTypes::DYNAMODB,
        schema_mutations: SchemaMutations::DYNAMODB,
        cte_with_update: false,
        select_for_update: false,
        returning_from_mutation: false,
        primary_key_ne_predicate: false,
        auto_increment: false,
        bigdecimal_implemented: false,
        native_varchar: false,

        // DynamoDB does not have native date/time types
        native_timestamp: false,
        native_date: false,
        native_time: false,
        native_datetime: false,

        // DynamoDB does not have native decimal types
        native_decimal: false,
        decimal_arbitrary_precision: false,

        index_or_predicate: false,

        test_connection_pool: false,
    };
}

impl StorageTypes {
    /// SQLite storage types
    pub const SQLITE: StorageTypes = StorageTypes {
        default_string_type: db::Type::Text,

        // SQLite doesn't really enforce the "N" in VARCHAR(N) at all – it
        // treats any type containing "CHAR", "CLOB", or "TEXT" as having TEXT
        // affinity, and simply ignores the length specifier. In other words,
        // whether you declare a column as VARCHAR(10), VARCHAR(1000000), or
        // just TEXT, SQLite won't truncate or complain based on that number.
        //
        // Instead, the only hard limit on how big a string (or BLOB) can be is
        // the SQLITE_MAX_LENGTH parameter, which is set to 1 billion by default.
        varchar: Some(1_000_000_000),

        // SQLite does not have an inbuilt UUID type. The binary blob type is more
        // difficult to read than Text but likely has better performance characteristics.
        default_uuid_type: db::Type::Blob,

        default_bytes_type: db::Type::Blob,

        // SQLite does not have a native decimal type. Store as TEXT.
        default_decimal_type: db::Type::Text,
        default_bigdecimal_type: db::Type::Text,

        // SQLite does not have native date/time types. Store as TEXT in ISO 8601 format.
        default_timestamp_type: db::Type::Text,
        default_zoned_type: db::Type::Text,
        default_date_type: db::Type::Text,
        default_time_type: db::Type::Text,
        default_datetime_type: db::Type::Text,

        // SQLite INTEGER is a signed 64-bit integer, so unsigned integers
        // are limited to i64::MAX to prevent overflow
        max_unsigned_integer: Some(i64::MAX as u64),
    };

    /// PostgreSQL storage types.
    pub const POSTGRESQL: StorageTypes = StorageTypes {
        default_string_type: db::Type::Text,

        // The maximum n you can specify is 10 485 760 characters. Attempts to
        // declare varchar with a larger typmod will be rejected at
        // table‐creation time.
        varchar: Some(10_485_760),

        default_uuid_type: db::Type::Uuid,

        default_bytes_type: db::Type::Blob,

        // PostgreSQL has native NUMERIC type for fixed and arbitrary-precision decimals.
        default_decimal_type: db::Type::Numeric(None),
        // TODO: PostgreSQL has native NUMERIC type for arbitrary-precision decimals,
        // but the encoding is complicated and has to be done separately in the future.
        default_bigdecimal_type: db::Type::Text,

        // PostgreSQL has native support for temporal types with microsecond precision (6 digits)
        default_timestamp_type: db::Type::Timestamp(6),
        default_zoned_type: db::Type::Text,
        default_date_type: db::Type::Date,
        default_time_type: db::Type::Time(6),
        default_datetime_type: db::Type::DateTime(6),

        // PostgreSQL BIGINT is signed 64-bit, so unsigned integers are limited
        // to i64::MAX. While NUMERIC could theoretically support larger values,
        // we prefer explicit limits over implicit type switching.
        max_unsigned_integer: Some(i64::MAX as u64),
    };

    /// MySQL storage types.
    pub const MYSQL: StorageTypes = StorageTypes {
        default_string_type: db::Type::VarChar(191),

        // Values in VARCHAR columns are variable-length strings. The length can
        // be specified as a value from 0 to 65,535. The effective maximum
        // length of a VARCHAR is subject to the maximum row size (65,535 bytes,
        // which is shared among all columns) and the character set used.
        varchar: Some(65_535),

        // MySQL does not have an inbuilt UUID type. The binary blob type is
        // more difficult to read than Text but likely has better performance
        // characteristics. However, limitations in the engine make it easier to
        // use VarChar for now.
        default_uuid_type: db::Type::VarChar(36),

        default_bytes_type: db::Type::Blob,

        // MySQL does not have an arbitrary-precision decimal type. The DECIMAL type
        // requires a fixed precision and scale to be specified upfront. Store as TEXT.
        default_decimal_type: db::Type::Text,
        default_bigdecimal_type: db::Type::Text,

        // MySQL has native support for temporal types with microsecond precision (6 digits)
        // The `TIMESTAMP` time only supports a limited range (1970-2038), so we default to
        // DATETIME and let Toasty do the UTC conversion.
        default_timestamp_type: db::Type::DateTime(6),
        default_zoned_type: db::Type::Text,
        default_date_type: db::Type::Date,
        default_time_type: db::Type::Time(6),
        default_datetime_type: db::Type::DateTime(6),

        // MySQL supports full u64 range via BIGINT UNSIGNED
        max_unsigned_integer: None,
    };

    /// DynamoDB storage types.
    pub const DYNAMODB: StorageTypes = StorageTypes {
        default_string_type: db::Type::Text,

        // DynamoDB does not support varchar types
        varchar: None,

        default_uuid_type: db::Type::Text,

        default_bytes_type: db::Type::Blob,

        // DynamoDB does not have a native decimal type. Store as TEXT.
        default_decimal_type: db::Type::Text,
        default_bigdecimal_type: db::Type::Text,

        // DynamoDB does not have native date/time types. Store as TEXT (strings).
        default_timestamp_type: db::Type::Text,
        default_zoned_type: db::Type::Text,
        default_date_type: db::Type::Text,
        default_time_type: db::Type::Text,
        default_datetime_type: db::Type::Text,

        // DynamoDB supports full u64 range (numbers stored as strings)
        max_unsigned_integer: None,
    };
}

impl SchemaMutations {
    /// SQLite schema mutation capabilities. SQLite cannot alter column types.
    pub const SQLITE: Self = Self {
        alter_column_type: false,
        alter_column_properties_atomic: false,
    };

    /// PostgreSQL schema mutation capabilities. Supports altering column types
    /// but not atomically changing multiple column properties.
    pub const POSTGRESQL: Self = Self {
        alter_column_type: true,
        alter_column_properties_atomic: false,
    };

    /// MySQL schema mutation capabilities. Supports altering column types and
    /// atomically changing multiple column properties in a single statement.
    pub const MYSQL: Self = Self {
        alter_column_type: true,
        alter_column_properties_atomic: true,
    };

    /// DynamoDB schema mutation capabilities. Migrations are not currently supported.
    pub const DYNAMODB: Self = Self {
        alter_column_type: false,
        alter_column_properties_atomic: false,
    };
}

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

    #[test]
    fn test_validate_sqlite_capability() {
        // SQLite has native_varchar=true and varchar=Some, should pass
        assert!(Capability::SQLITE.validate().is_ok());
    }

    #[test]
    fn test_validate_postgresql_capability() {
        // PostgreSQL has native_varchar=true and varchar=Some, should pass
        assert!(Capability::POSTGRESQL.validate().is_ok());
    }

    #[test]
    fn test_validate_mysql_capability() {
        // MySQL has native_varchar=true and varchar=Some, should pass
        assert!(Capability::MYSQL.validate().is_ok());
    }

    #[test]
    fn test_validate_dynamodb_capability() {
        // DynamoDB has native_varchar=false and varchar=None, should pass
        assert!(Capability::DYNAMODB.validate().is_ok());
    }

    #[test]
    fn test_validate_fails_when_native_varchar_true_but_no_varchar() {
        let invalid = Capability {
            native_varchar: true,
            storage_types: StorageTypes {
                varchar: None, // Invalid: native_varchar is true but varchar is None
                ..StorageTypes::SQLITE
            },
            ..Capability::SQLITE
        };

        let result = invalid.validate();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("native_varchar is true but storage_types.varchar is None")
        );
    }

    #[test]
    fn test_validate_fails_when_native_varchar_false_but_has_varchar() {
        let invalid = Capability {
            native_varchar: false,
            storage_types: StorageTypes {
                varchar: Some(1000), // Invalid: native_varchar is false but varchar is Some
                ..StorageTypes::DYNAMODB
            },
            ..Capability::DYNAMODB
        };

        let result = invalid.validate();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("native_varchar is false but storage_types.varchar is Some")
        );
    }
}