razeri_plugin_contract/data_type.rs
1// Copyright (C) 2026 Gabriel Shea
2// Licensed under either of the Apache License, Version 2.0 or the MIT
3// license, at your option.
4
5//! Generic data types for cross-database compatibility.
6//!
7//! This module defines the unified [`DataType`] enum and all component types
8//! (integer, decimal, float, boolean, string, binary, date/time, special, and
9//! collection types) that serve as the foundation for SQL rendering across
10//! all supported database platforms.
11//!
12//! # Design Philosophy
13//!
14//! - **Abstract over database-specific implementations** — `DataType` captures
15//! enough metadata to generate correct DDL for each target, but does not
16//! embed platform-specific syntax.
17//! - **Preserve precision metadata** — Decimal types carry precision and scale;
18//! string types carry length constraints; timestamp types carry fractional
19//! seconds precision.
20//! - **Every type renders somewhere** — a dialect answers for every variant,
21//! emulating a type it does not have (JSON stored as `NVARCHAR(MAX)` on SQL
22//! Server, a struct stored as `jsonb` on `PostgreSQL`) rather than refusing.
23//!
24//! # Type Categories
25//!
26//! | Category | Types | Example |
27//! |----------|-------|---------|
28//! | Integer | [`IntegerDataType`] | `INT`, `BIGINT`, `TINYINT` |
29//! | Decimal | [`DecimalDataType`] | `DECIMAL(19,4)`, `DECIMAL(5,2)` |
30//! | Float | [`FloatDataType`] | `REAL`, `DOUBLE` |
31//! | Boolean | [`BooleanDataType`] | `BOOLEAN`, `BIT` |
32//! | String | [`CharDataType`], [`VarCharDataType`], [`TextDataType`] | `VARCHAR(100)`, `TEXT` |
33//! | Binary | [`BinaryDataType`], [`VarBinaryDataType`] | `BYTEA`, `VARBINARY` |
34//! | Date/Time | [`DateDataType`], [`TimestampDataType`], [`TimestampTzDataType`] | `DATE`, `TIMESTAMP` |
35//! | Special | [`UuidDataType`], [`JsonDataType`] | `UUID`, `JSONB` |
36//! | Collection | [`ArrayDataType`], [`MapDataType`], [`StructDataType`] | `INTEGER[]`, `MAP<TEXT,INT>`, `STRUCT<a INT>` |
37//!
38//! # Usage
39//!
40//! Convenience constructors for common types:
41//!
42//! ```rust
43//! use razeri_plugin_contract::DataType;
44//!
45//! let id = DataType::bigint();
46//! let name = DataType::varchar(255);
47//! let price = DataType::decimal(19, 4);
48//! let created = DataType::timestamp();
49//!
50//! // JSON with binary storage (JSONB in PostgreSQL, VARIANT in Snowflake)
51//! let data = DataType::json();
52//! ```
53//!
54//! Each variant maps to platform-specific types as documented in the variant
55//! definitions. Dialect plugins resolve the final SQL type string during
56//! rendering; the rendering traits live in this crate's `renderer` module.
57
58// ============================================================================
59// Integer Types
60// ============================================================================
61
62/// Integer size variants matching common database integer types.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub enum IntegerSize {
65 /// 1 byte: -128 to 127 (signed) or 0 to 255 (unsigned)
66 /// Maps to: TINYINT (SQL Server, Snowflake, Databricks), SMALLINT (`PostgreSQL`), Int8/UInt8 (`ClickHouse`)
67 Tiny,
68 /// 2 bytes: -32,768 to 32,767 (signed)
69 /// Maps to: SMALLINT (all databases), Int16/UInt16 (`ClickHouse`)
70 Small,
71 /// 4 bytes: -2.1B to 2.1B (signed)
72 /// Maps to: INT/INTEGER (all databases), Int32/UInt32 (`ClickHouse`)
73 Standard,
74 /// 8 bytes: -9.2E18 to 9.2E18 (signed)
75 /// Maps to: BIGINT (all databases), Int64/UInt64 (`ClickHouse`)
76 Big,
77}
78
79/// Integer data type supporting signed/unsigned variants.
80///
81/// Most databases only support signed integers. `ClickHouse` is the exception,
82/// supporting unsigned variants via `UInt8`, `UInt16`, `UInt32`, `UInt64`.
83/// Other dialect plugins will map unsigned types to the next larger signed type
84/// when unsigned is not supported.
85///
86/// # Example
87///
88/// ```rust
89/// use razeri_plugin_contract::{DataType, data_type::{IntegerDataType, IntegerSize}};
90///
91/// // Signed 4-byte integer (INT/INTEGER on most platforms)
92/// let _id = DataType::int();
93///
94/// // Unsigned 8-byte integer (UInt64 in ClickHouse, BIGINT elsewhere)
95/// let big = IntegerDataType::unsigned(IntegerSize::Big);
96/// assert_eq!(big.byte_size(), 8);
97/// ```
98#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct IntegerDataType {
100 /// Size of the integer (Tiny, Small, Standard, Big).
101 pub size: IntegerSize,
102
103 /// Whether the integer is unsigned.
104 ///
105 /// Only `ClickHouse` fully supports unsigned integers. Other dialect plugins
106 /// will map unsigned types to the next larger signed type when unsigned is
107 /// not supported by the target platform.
108 ///
109 /// # Example
110 ///
111 /// ```rust
112 /// use razeri_plugin_contract::data_type::{IntegerDataType, IntegerSize};
113 ///
114 /// let signed = IntegerDataType::new(IntegerSize::Standard);
115 /// assert!(!signed.unsigned);
116 ///
117 /// let unsigned = IntegerDataType::unsigned(IntegerSize::Big);
118 /// assert!(unsigned.unsigned);
119 /// ```
120 pub unsigned: bool,
121}
122
123impl IntegerDataType {
124 /// Creates a new signed integer with the given [`IntegerSize`].
125 ///
126 /// # Example
127 ///
128 /// ```rust
129 /// use razeri_plugin_contract::data_type::{IntegerDataType, IntegerSize};
130 ///
131 /// let small = IntegerDataType::new(IntegerSize::Small);
132 /// assert_eq!(small.byte_size(), 2);
133 /// ```
134 #[must_use]
135 pub fn new(size: IntegerSize) -> Self {
136 Self { size, unsigned: false }
137 }
138
139 /// Creates a new unsigned integer with the given [`IntegerSize`].
140 ///
141 /// # Example
142 ///
143 /// ```rust
144 /// use razeri_plugin_contract::data_type::{IntegerDataType, IntegerSize};
145 ///
146 /// let unsigned_big = IntegerDataType::unsigned(IntegerSize::Big);
147 /// assert!(unsigned_big.unsigned);
148 /// assert_eq!(unsigned_big.byte_size(), 8);
149 /// ```
150 #[must_use]
151 pub fn unsigned(size: IntegerSize) -> Self {
152 Self { size, unsigned: true }
153 }
154
155 /// Returns the byte size of this integer type.
156 ///
157 /// # Example
158 ///
159 /// ```rust
160 /// use razeri_plugin_contract::data_type::{IntegerDataType, IntegerSize};
161 ///
162 /// assert_eq!(IntegerDataType::new(IntegerSize::Tiny).byte_size(), 1);
163 /// assert_eq!(IntegerDataType::new(IntegerSize::Small).byte_size(), 2);
164 /// assert_eq!(IntegerDataType::new(IntegerSize::Standard).byte_size(), 4);
165 /// assert_eq!(IntegerDataType::new(IntegerSize::Big).byte_size(), 8);
166 /// ```
167 #[must_use]
168 pub fn byte_size(&self) -> usize {
169 match self.size {
170 IntegerSize::Tiny => 1,
171 IntegerSize::Small => 2,
172 IntegerSize::Standard => 4,
173 IntegerSize::Big => 8,
174 }
175 }
176}
177
178// ============================================================================
179// Decimal/Numeric Types (Exact Precision)
180// ============================================================================
181
182/// Exact numeric type with fixed precision and scale.
183///
184/// Maps to: `NUMERIC`/`DECIMAL` (`PostgreSQL`, SQL Server), `NUMBER` (Snowflake),
185/// `DECIMAL` (Databricks), `Decimal` (`ClickHouse`).
186///
187/// # Constraints
188///
189/// - `precision`: 1–38 (most databases), up to 76 (some platforms)
190/// - `scale`: 0 to `precision`
191/// - Panics if `scale > precision` or `precision > 38`
192///
193/// # Example
194///
195/// ```rust
196/// use razeri_plugin_contract::data_type::DecimalDataType;
197///
198/// // Money: DECIMAL(19, 4)
199/// let money = DecimalDataType::money();
200/// assert_eq!(money.precision, 19);
201/// assert_eq!(money.scale, 4);
202///
203/// // Percentage: DECIMAL(5, 2)
204/// let pct = DecimalDataType::percentage();
205/// assert_eq!(pct.precision, 5);
206/// assert_eq!(pct.scale, 2);
207///
208/// // Custom decimal
209/// let custom = DecimalDataType::new(10, 2);
210/// assert_eq!(custom.precision, 10);
211/// assert_eq!(custom.scale, 2);
212/// ```
213#[derive(Debug, Clone, PartialEq, Eq, Hash)]
214pub struct DecimalDataType {
215 /// Total number of digits (1–38 for most databases, up to 76 for some).
216 pub precision: u8,
217
218 /// Number of digits after the decimal point (0 to `precision`).
219 pub scale: u8,
220}
221
222impl DecimalDataType {
223 /// Creates a new decimal type with the given precision and scale.
224 ///
225 /// # Panics
226 ///
227 /// Panics if `precision` is 0 or exceeds 38, or if `scale > precision`.
228 ///
229 /// # Example
230 ///
231 /// ```rust
232 /// use razeri_plugin_contract::data_type::DecimalDataType;
233 ///
234 /// let dec = DecimalDataType::new(10, 2);
235 /// assert_eq!(dec.precision, 10);
236 /// assert_eq!(dec.scale, 2);
237 /// ```
238 ///
239 /// # Panics
240 ///
241 /// ```should_panic
242 /// use razeri_plugin_contract::data_type::DecimalDataType;
243 ///
244 /// // Precision must be 1-38
245 /// let _ = DecimalDataType::new(0, 0); // panics
246 ///
247 /// // Scale cannot exceed precision
248 /// let _ = DecimalDataType::new(5, 10); // panics
249 /// ```
250 #[must_use]
251 pub fn new(precision: u8, scale: u8) -> Self {
252 assert!(precision > 0 && precision <= 38, "Precision must be 1-38");
253 assert!(scale <= precision, "Scale cannot exceed precision");
254 Self { precision, scale }
255 }
256
257 /// Creates the common money type: `DECIMAL(19, 4)`.
258 ///
259 /// # Example
260 ///
261 /// ```rust
262 /// use razeri_plugin_contract::data_type::DecimalDataType;
263 ///
264 /// let money = DecimalDataType::money();
265 /// assert_eq!(money.precision, 19);
266 /// assert_eq!(money.scale, 4);
267 /// ```
268 #[must_use]
269 pub fn money() -> Self {
270 Self { precision: 19, scale: 4 }
271 }
272
273 /// Creates a percentage type with 2 decimal places: `DECIMAL(5, 2)`.
274 ///
275 /// # Example
276 ///
277 /// ```rust
278 /// use razeri_plugin_contract::data_type::DecimalDataType;
279 ///
280 /// let pct = DecimalDataType::percentage();
281 /// assert_eq!(pct.precision, 5);
282 /// assert_eq!(pct.scale, 2);
283 /// ```
284 #[must_use]
285 pub fn percentage() -> Self {
286 Self { precision: 5, scale: 2 }
287 }
288}
289
290// ============================================================================
291// Floating Point Types (Approximate)
292// ============================================================================
293
294/// Floating point precision variants.
295///
296/// # Example
297///
298/// ```rust
299/// use razeri_plugin_contract::data_type::FloatPrecision;
300///
301/// let single = FloatPrecision::Single;
302/// let double = FloatPrecision::Double;
303///
304/// assert_eq!(format!("{:?}", single), "Single");
305/// assert_eq!(format!("{:?}", double), "Double");
306/// ```
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
308pub enum FloatPrecision {
309 /// Single precision (4 bytes, ~7 decimal digits).
310 ///
311 /// Maps to: `REAL`/`FLOAT4` (`PostgreSQL`), `REAL`/`FLOAT(24)` (SQL Server),
312 /// `FLOAT` (Snowflake, Databricks), `Float32` (`ClickHouse`).
313 Single,
314 /// Double precision (8 bytes, ~15 decimal digits).
315 ///
316 /// Maps to: `DOUBLE PRECISION`/`FLOAT8` (`PostgreSQL`), `FLOAT` (SQL Server),
317 /// `DOUBLE` (Snowflake, Databricks), `Float64` (`ClickHouse`).
318 Double,
319}
320
321/// Approximate floating-point numeric type.
322///
323/// Maps to: `REAL`/`DOUBLE PRECISION` (`PostgreSQL`), `REAL`/`FLOAT` (SQL Server),
324/// `FLOAT`/`DOUBLE` (Snowflake, Databricks), `Float32`/`Float64` (`ClickHouse`).
325///
326/// # Example
327///
328/// ```
329/// use razeri_plugin_contract::DataType;
330///
331/// // Single precision (REAL)
332/// let real = DataType::float();
333///
334/// // Double precision (DOUBLE)
335/// let double = DataType::double();
336/// ```
337#[derive(Debug, Clone, PartialEq, Eq, Hash)]
338pub struct FloatDataType {
339 /// Precision level (Single or Double).
340 pub precision: FloatPrecision,
341}
342
343impl FloatDataType {
344 /// Creates a single-precision (4-byte) float type.
345 ///
346 /// # Example
347 ///
348 /// ```rust
349 /// use razeri_plugin_contract::data_type::{FloatDataType, FloatPrecision};
350 ///
351 /// let single = FloatDataType::single();
352 /// assert_eq!(single.precision, FloatPrecision::Single);
353 /// ```
354 #[must_use]
355 pub fn single() -> Self {
356 Self { precision: FloatPrecision::Single }
357 }
358
359 /// Creates a double-precision (8-byte) float type.
360 ///
361 /// # Example
362 ///
363 /// ```rust
364 /// use razeri_plugin_contract::data_type::{FloatDataType, FloatPrecision};
365 ///
366 /// let double = FloatDataType::double();
367 /// assert_eq!(double.precision, FloatPrecision::Double);
368 /// ```
369 #[must_use]
370 pub fn double() -> Self {
371 Self { precision: FloatPrecision::Double }
372 }
373}
374
375// ============================================================================
376// Boolean Type
377// ============================================================================
378
379/// Boolean data type (true/false).
380///
381/// Maps to: `BOOLEAN` (`PostgreSQL`, Snowflake, Databricks, `ClickHouse`),
382/// `BIT` (SQL Server), `Bool`/`UInt8` (`ClickHouse`).
383///
384/// # Example
385///
386/// ```
387/// use razeri_plugin_contract::DataType;
388///
389/// let bool_type = DataType::boolean();
390/// ```
391#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
392pub struct BooleanDataType;
393
394// ============================================================================
395// String/Text Types
396// ============================================================================
397
398/// Character encoding for string types.
399///
400/// Determines whether strings use ASCII/Latin1 (1 byte per character) or
401/// UTF-8/Unicode (variable bytes per character). The default is `Unicode`.
402///
403/// # Example
404///
405/// ```rust
406/// use razeri_plugin_contract::data_type::StringEncoding;
407///
408/// let ascii = StringEncoding::Ascii;
409/// let unicode = StringEncoding::Unicode;
410///
411/// assert_eq!(ascii, StringEncoding::Ascii);
412/// assert_eq!(unicode, StringEncoding::Unicode);
413/// ```
414#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
415pub enum StringEncoding {
416 /// ASCII/Latin1 encoding (1 byte per character).
417 ///
418 /// Maps to: `CHAR`/`VARCHAR` (SQL Server), `CHAR`/`VARCHAR` (`PostgreSQL`).
419 Ascii,
420 /// UTF-8/Unicode encoding (variable bytes per character).
421 ///
422 /// Maps to: `NCHAR`/`NVARCHAR` (SQL Server), all strings in
423 /// `PostgreSQL`/Snowflake/`ClickHouse`.
424 #[default]
425 Unicode,
426}
427
428/// Fixed-length character string.
429///
430/// Maps to: `CHAR(n)` (`PostgreSQL`, SQL Server, Snowflake), `FixedString(n)` (`ClickHouse`).
431/// Note: Databricks does not have a fixed-length char type.
432///
433/// # Example
434///
435/// ```rust
436/// use razeri_plugin_contract::data_type::{CharDataType, StringEncoding};
437///
438/// // Default: Unicode encoding
439/// let char_type = CharDataType::new(50);
440/// assert_eq!(char_type.length, 50);
441///
442/// // Explicit ASCII encoding
443/// let ascii_char = CharDataType::with_encoding(10, StringEncoding::Ascii);
444/// ```
445#[derive(Debug, Clone, PartialEq, Eq, Hash)]
446pub struct CharDataType {
447 /// Fixed length in characters (1-8000 for SQL Server, 1-16777216 for Snowflake).
448 pub length: u32,
449
450 /// Character encoding (default: Unicode).
451 pub encoding: StringEncoding,
452}
453
454impl CharDataType {
455 /// Creates a fixed-length character string with Unicode encoding.
456 ///
457 /// # Example
458 ///
459 /// ```rust
460 /// use razeri_plugin_contract::data_type::CharDataType;
461 ///
462 /// let char = CharDataType::new(100);
463 /// assert_eq!(char.length, 100);
464 /// ```
465 #[must_use]
466 pub fn new(length: u32) -> Self {
467 Self { length, encoding: StringEncoding::Unicode }
468 }
469
470 /// Creates a fixed-length character string with the specified encoding.
471 ///
472 /// # Example
473 ///
474 /// ```rust
475 /// use razeri_plugin_contract::data_type::{CharDataType, StringEncoding};
476 ///
477 /// let ascii = CharDataType::with_encoding(20, StringEncoding::Ascii);
478 /// assert_eq!(ascii.encoding, StringEncoding::Ascii);
479 /// ```
480 #[must_use]
481 pub fn with_encoding(length: u32, encoding: StringEncoding) -> Self {
482 Self { length, encoding }
483 }
484}
485
486/// Variable-length character string with optional max length.
487///
488/// Maps to: `VARCHAR(n)` (`PostgreSQL`, SQL Server, Snowflake), `STRING` (Databricks, `ClickHouse`).
489///
490/// # Example
491///
492/// ```rust
493/// use razeri_plugin_contract::data_type::{VarCharDataType, StringEncoding};
494///
495/// // Fixed max length
496/// let varchar = VarCharDataType::new(255);
497/// assert_eq!(varchar.max_length, Some(255));
498///
499/// // Unlimited length (TEXT/VARCHAR(MAX)/STRING)
500/// let text = VarCharDataType::unlimited();
501/// assert_eq!(text.max_length, None);
502///
503/// // Explicit ASCII encoding
504/// let ascii = VarCharDataType::with_encoding(Some(100), StringEncoding::Ascii);
505/// ```
506#[derive(Debug, Clone, PartialEq, Eq, Hash)]
507pub struct VarCharDataType {
508 /// Maximum length in characters (None = unlimited/MAX).
509 ///
510 /// Platform limits:
511 /// - `PostgreSQL`: up to 10,485,760
512 /// - SQL Server: up to 8,000 (or MAX)
513 /// - Snowflake: up to 16,777,216
514 /// - `ClickHouse`: unlimited
515 pub max_length: Option<u32>,
516
517 /// Character encoding (default: Unicode).
518 pub encoding: StringEncoding,
519}
520
521impl VarCharDataType {
522 /// Creates a VARCHAR with specified max length.
523 ///
524 /// # Example
525 ///
526 /// ```rust
527 /// use razeri_plugin_contract::data_type::VarCharDataType;
528 ///
529 /// let varchar = VarCharDataType::new(100);
530 /// assert_eq!(varchar.max_length, Some(100));
531 /// ```
532 #[must_use]
533 pub fn new(max_length: u32) -> Self {
534 Self { max_length: Some(max_length), encoding: StringEncoding::Unicode }
535 }
536
537 /// Creates an unlimited length text type (`VARCHAR(MAX)`, `TEXT`, `STRING`).
538 ///
539 /// # Example
540 ///
541 /// ```rust
542 /// use razeri_plugin_contract::data_type::VarCharDataType;
543 ///
544 /// let text = VarCharDataType::unlimited();
545 /// assert_eq!(text.max_length, None);
546 /// ```
547 #[must_use]
548 pub fn unlimited() -> Self {
549 Self { max_length: None, encoding: StringEncoding::Unicode }
550 }
551
552 /// Creates a VARCHAR with the specified length and encoding.
553 ///
554 /// # Example
555 ///
556 /// ```rust
557 /// use razeri_plugin_contract::data_type::{VarCharDataType, StringEncoding};
558 ///
559 /// let ascii = VarCharDataType::with_encoding(Some(50), StringEncoding::Ascii);
560 /// assert_eq!(ascii.max_length, Some(50));
561 /// assert_eq!(ascii.encoding, StringEncoding::Ascii);
562 /// ```
563 #[must_use]
564 pub fn with_encoding(max_length: Option<u32>, encoding: StringEncoding) -> Self {
565 Self { max_length, encoding }
566 }
567}
568
569/// Unbounded text type for large text storage.
570///
571/// Maps to: `TEXT` (`PostgreSQL`), `VARCHAR(MAX)` (SQL Server),
572/// `STRING` (Snowflake, Databricks, `ClickHouse`).
573///
574/// # Example
575///
576/// ```
577/// use razeri_plugin_contract::DataType;
578///
579/// let text = DataType::text();
580/// ```
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
582pub struct TextDataType;
583
584// ============================================================================
585// Binary Types
586// ============================================================================
587
588/// Fixed-length binary data.
589///
590/// Maps to: `BYTEA` (`PostgreSQL`), `BINARY(n)` (SQL Server, Snowflake),
591/// `FixedString(n)` (`ClickHouse`).
592///
593/// # Example
594///
595/// ```rust
596/// use razeri_plugin_contract::data_type::BinaryDataType;
597///
598/// let binary = BinaryDataType::new(256);
599/// assert_eq!(binary.length, 256);
600/// ```
601#[derive(Debug, Clone, PartialEq, Eq, Hash)]
602pub struct BinaryDataType {
603 /// Fixed length in bytes.
604 pub length: u32,
605}
606
607impl BinaryDataType {
608 /// Creates a fixed-length binary type with the given length in bytes.
609 ///
610 /// # Example
611 ///
612 /// ```rust
613 /// use razeri_plugin_contract::data_type::BinaryDataType;
614 ///
615 /// let binary = BinaryDataType::new(128);
616 /// assert_eq!(binary.length, 128);
617 /// ```
618 #[must_use]
619 pub fn new(length: u32) -> Self {
620 Self { length }
621 }
622}
623
624/// Variable-length binary data.
625///
626/// Maps to: `BYTEA` (`PostgreSQL`), `VARBINARY(n)` (SQL Server, Snowflake),
627/// `String` (`ClickHouse`), `BINARY` (Databricks).
628///
629/// # Example
630///
631/// ```rust
632/// use razeri_plugin_contract::data_type::VarBinaryDataType;
633///
634/// // Fixed max length
635/// let vb = VarBinaryDataType::new(1024);
636/// assert_eq!(vb.max_length, Some(1024));
637///
638/// // Unlimited length
639/// let blob = VarBinaryDataType::unlimited();
640/// assert_eq!(blob.max_length, None);
641/// ```
642#[derive(Debug, Clone, PartialEq, Eq, Hash)]
643pub struct VarBinaryDataType {
644 /// Maximum length in bytes (None = unlimited/MAX).
645 pub max_length: Option<u32>,
646}
647
648impl VarBinaryDataType {
649 /// Creates a variable-length binary type with the specified max length in bytes.
650 ///
651 /// # Example
652 ///
653 /// ```rust
654 /// use razeri_plugin_contract::data_type::VarBinaryDataType;
655 ///
656 /// let vb = VarBinaryDataType::new(2048);
657 /// assert_eq!(vb.max_length, Some(2048));
658 /// ```
659 #[must_use]
660 pub fn new(max_length: u32) -> Self {
661 Self { max_length: Some(max_length) }
662 }
663
664 /// Creates an unlimited-length binary type (BYTEA, VARBINARY(MAX), etc.).
665 ///
666 /// # Example
667 ///
668 /// ```rust
669 /// use razeri_plugin_contract::data_type::VarBinaryDataType;
670 ///
671 /// let blob = VarBinaryDataType::unlimited();
672 /// assert_eq!(blob.max_length, None);
673 /// ```
674 #[must_use]
675 pub fn unlimited() -> Self {
676 Self { max_length: None }
677 }
678}
679
680// ============================================================================
681// Date and Time Types
682// ============================================================================
683
684/// Date only (year, month, day) without time component.
685///
686/// Maps to: `DATE` (all databases), `Date`/`Date32` (`ClickHouse`).
687///
688/// # Example
689///
690/// ```
691/// use razeri_plugin_contract::DataType;
692///
693/// let date = DataType::date();
694/// ```
695#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
696pub struct DateDataType;
697
698/// Time only without date component.
699///
700/// Maps to: `TIME` (`PostgreSQL`, SQL Server, Snowflake), not directly supported in
701/// `ClickHouse`/Databricks.
702///
703/// # Precision
704///
705/// - `PostgreSQL`: 0-6
706/// - SQL Server: 0-7
707/// - Snowflake: 0-9
708/// - `ClickHouse`: 0-9
709///
710/// # Example
711///
712/// ```rust
713/// use razeri_plugin_contract::data_type::TimeDataType;
714///
715/// // Default precision: 6, no timezone
716/// let time = TimeDataType::default();
717/// assert_eq!(time.precision, 6);
718/// assert!(!time.with_timezone);
719///
720/// // Precision 3, with timezone
721/// let tz_time = TimeDataType::with_timezone(3);
722/// assert_eq!(tz_time.precision, 3);
723/// assert!(tz_time.with_timezone);
724/// ```
725#[derive(Debug, Clone, PartialEq, Eq, Hash)]
726pub struct TimeDataType {
727 /// Fractional seconds precision (0-7 for SQL Server, 0-6 for `PostgreSQL`, 0-9 for Snowflake).
728 pub precision: u8,
729
730 /// Whether to include timezone offset.
731 ///
732 /// Maps to: `TIME WITH TIME ZONE` (`PostgreSQL`), not supported in SQL Server.
733 pub with_timezone: bool,
734}
735
736impl TimeDataType {
737 /// Creates a new `TimeDataType` with the given fractional seconds precision.
738 ///
739 /// # Panics
740 ///
741 /// Panics if `precision` exceeds 9.
742 ///
743 /// # Example
744 ///
745 /// ```rust
746 /// use razeri_plugin_contract::data_type::TimeDataType;
747 ///
748 /// let time = TimeDataType::new(3);
749 /// assert_eq!(time.precision, 3);
750 /// assert!(!time.with_timezone);
751 /// ```
752 ///
753 /// ```rust,should_panic
754 /// use razeri_plugin_contract::data_type::TimeDataType;
755 ///
756 /// let _ = TimeDataType::new(10); // panics: precision must be 0-9
757 /// ```
758 #[must_use]
759 pub fn new(precision: u8) -> Self {
760 assert!(precision <= 9, "Time precision must be 0-9");
761 Self { precision, with_timezone: false }
762 }
763
764 /// Creates a `TimeDataType` with timezone and the given precision.
765 ///
766 /// # Panics
767 ///
768 /// Panics if `precision` exceeds 9.
769 ///
770 /// # Example
771 ///
772 /// ```rust
773 /// use razeri_plugin_contract::data_type::TimeDataType;
774 ///
775 /// let tz_time = TimeDataType::with_timezone(3);
776 /// assert_eq!(tz_time.precision, 3);
777 /// assert!(tz_time.with_timezone);
778 /// ```
779 #[must_use]
780 pub fn with_timezone(precision: u8) -> Self {
781 assert!(precision <= 9, "Time precision must be 0-9");
782 Self { precision, with_timezone: true }
783 }
784}
785
786impl Default for TimeDataType {
787 fn default() -> Self {
788 Self { precision: 6, with_timezone: false }
789 }
790}
791
792/// Timestamp (date and time) without timezone.
793///
794/// Maps to: `TIMESTAMP` (`PostgreSQL`), `DATETIME2` (SQL Server),
795/// `TIMESTAMP_NTZ` (Snowflake), `TIMESTAMP` (Databricks), `DateTime` (`ClickHouse`).
796///
797/// # Precision
798///
799/// - `PostgreSQL`: 0-6
800/// - SQL Server: 0-7
801/// - Snowflake: 0-9
802/// - `ClickHouse`: 0-9
803///
804/// # Example
805///
806/// ```rust
807/// use razeri_plugin_contract::data_type::{DataType, TimestampDataType};
808///
809/// // Default: precision 6
810/// let ts = TimestampDataType::default();
811/// assert_eq!(ts.precision, 6);
812///
813/// // Custom precision
814/// let ts3 = TimestampDataType::new(3);
815/// assert_eq!(ts3.precision, 3);
816///
817/// // Via DataType convenience
818/// let created = DataType::timestamp();
819/// ```
820#[derive(Debug, Clone, PartialEq, Eq, Hash)]
821pub struct TimestampDataType {
822 /// Fractional seconds precision (0-9).
823 ///
824 /// - `PostgreSQL`: 0-6
825 /// - SQL Server: 0-7
826 /// - Snowflake: 0-9
827 /// - `ClickHouse`: 0-9
828 pub precision: u8,
829}
830
831impl TimestampDataType {
832 /// Creates a new `TimestampDataType` with the given fractional seconds precision.
833 ///
834 /// # Panics
835 ///
836 /// Panics if `precision` exceeds 9.
837 ///
838 /// # Example
839 ///
840 /// ```rust
841 /// use razeri_plugin_contract::data_type::TimestampDataType;
842 ///
843 /// let ts = TimestampDataType::new(3);
844 /// assert_eq!(ts.precision, 3);
845 /// ```
846 ///
847 /// ```should_panic
848 /// use razeri_plugin_contract::data_type::TimestampDataType;
849 ///
850 /// let _ = TimestampDataType::new(10); // panics: precision must be 0-9
851 /// ```
852 #[must_use]
853 pub fn new(precision: u8) -> Self {
854 assert!(precision <= 9, "Timestamp precision must be 0-9");
855 Self { precision }
856 }
857}
858
859impl Default for TimestampDataType {
860 fn default() -> Self {
861 Self { precision: 6 }
862 }
863}
864
865/// Timestamp with timezone awareness.
866///
867/// Maps to: `TIMESTAMPTZ` (`PostgreSQL`), `DATETIMEOFFSET` (SQL Server),
868/// `TIMESTAMP_TZ`/`TIMESTAMP_LTZ` (Snowflake), `TIMESTAMP` (Databricks),
869/// `DateTime64` (`ClickHouse`).
870///
871/// # Example
872///
873/// ```rust
874/// use razeri_plugin_contract::DataType;
875/// use razeri_plugin_contract::data_type::TimestampTzDataType;
876///
877/// // Default: precision 6
878/// let ts = TimestampTzDataType::default();
879/// assert_eq!(ts.precision, 6);
880///
881/// // Via DataType convenience
882/// let created_tz = DataType::timestamp_tz();
883/// ```
884#[derive(Debug, Clone, PartialEq, Eq, Hash)]
885pub struct TimestampTzDataType {
886 /// Fractional seconds precision (0-9).
887 pub precision: u8,
888}
889
890impl TimestampTzDataType {
891 /// Creates a new `TimestampTzDataType` with the given fractional seconds precision.
892 ///
893 /// # Panics
894 ///
895 /// Panics if `precision` exceeds 9.
896 ///
897 /// # Example
898 ///
899 /// ```rust
900 /// use razeri_plugin_contract::data_type::TimestampTzDataType;
901 ///
902 /// let ts = TimestampTzDataType::new(3);
903 /// assert_eq!(ts.precision, 3);
904 /// ```
905 ///
906 /// ```should_panic
907 /// use razeri_plugin_contract::data_type::TimestampTzDataType;
908 ///
909 /// let _ = TimestampTzDataType::new(10); // panics: precision must be 0-9
910 /// ```
911 #[must_use]
912 pub fn new(precision: u8) -> Self {
913 assert!(precision <= 9, "Timestamp precision must be 0-9");
914 Self { precision }
915 }
916}
917
918impl Default for TimestampTzDataType {
919 fn default() -> Self {
920 Self { precision: 6 }
921 }
922}
923
924/// Combined date and time for legacy compatibility.
925///
926/// Maps to: `DATETIME` (SQL Server legacy), `TIMESTAMP` (`PostgreSQL`).
927/// Prefer [`TimestampDataType`] for new designs.
928///
929/// # Example
930///
931/// ```rust
932/// use razeri_plugin_contract::data_type::DateTimeDataType;
933///
934/// let dt = DateTimeDataType::new(3, true);
935/// assert_eq!(dt.precision, 3);
936/// assert!(dt.with_timezone);
937/// ```
938#[derive(Debug, Clone, PartialEq, Eq, Hash)]
939pub struct DateTimeDataType {
940 /// Fractional seconds precision (0-9).
941 pub precision: u8,
942
943 /// Whether to include timezone offset.
944 pub with_timezone: bool,
945}
946
947impl DateTimeDataType {
948 /// Creates a new `DateTimeDataType` with the given precision and timezone flag.
949 ///
950 /// # Example
951 ///
952 /// ```rust
953 /// use razeri_plugin_contract::data_type::DateTimeDataType;
954 ///
955 /// let dt = DateTimeDataType::new(6, false);
956 /// assert_eq!(dt.precision, 6);
957 /// assert!(!dt.with_timezone);
958 /// ```
959 #[must_use]
960 pub fn new(precision: u8, with_timezone: bool) -> Self {
961 Self { precision, with_timezone }
962 }
963}
964
965impl Default for DateTimeDataType {
966 fn default() -> Self {
967 Self { precision: 6, with_timezone: false }
968 }
969}
970
971/// Interval/duration type for time spans.
972///
973/// Maps to: `INTERVAL` (`PostgreSQL`, Snowflake, Databricks), not directly supported in
974/// SQL Server/`ClickHouse`.
975///
976/// # Example
977///
978/// ```rust
979/// use razeri_plugin_contract::data_type::IntervalDataType;
980///
981/// let ym = IntervalDataType::YearMonth;
982/// let dt = IntervalDataType::DayTime;
983///
984/// assert_eq!(format!("{:?}", ym), "YearMonth");
985/// assert_eq!(format!("{:?}", dt), "DayTime");
986/// ```
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
988pub enum IntervalDataType {
989 /// Year to month intervals.
990 YearMonth,
991 /// Day to second intervals (with optional fractional seconds precision).
992 DayTime,
993}
994
995// ============================================================================
996// Special Types
997// ============================================================================
998
999/// Universally Unique Identifier (UUID/GUID).
1000///
1001/// Maps to: `UUID` (`PostgreSQL`), `UNIQUEIDENTIFIER` (SQL Server),
1002/// `STRING` (Snowflake, Databricks), `UUID` (`ClickHouse`).
1003///
1004/// # Example
1005///
1006/// ```
1007/// use razeri_plugin_contract::DataType;
1008///
1009/// let uuid = DataType::uuid();
1010/// ```
1011#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1012pub struct UuidDataType;
1013
1014/// JSON storage format preference.
1015///
1016/// Determines whether JSON data is stored as text (preserving whitespace and key order)
1017/// or in a binary-optimized format (normalized, faster queries, indexable).
1018///
1019/// # Example
1020///
1021/// ```rust
1022/// use razeri_plugin_contract::data_type::JsonStorageFormat;
1023///
1024/// let text = JsonStorageFormat::Text;
1025/// let binary = JsonStorageFormat::Binary;
1026///
1027/// assert_eq!(format!("{:?}", text), "Text");
1028/// assert_eq!(format!("{:?}", binary), "Binary");
1029/// assert!(!text.is_binary());
1030/// assert!(binary.is_binary());
1031/// ```
1032#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1033pub enum JsonStorageFormat {
1034 /// Text-based JSON storage (preserves whitespace, key order).
1035 ///
1036 /// Maps to: `JSON` (`PostgreSQL`), `NVARCHAR(MAX)` (SQL Server),
1037 /// `STRING` (Databricks).
1038 Text,
1039 /// Binary-optimized JSON storage (normalized, faster queries, indexable).
1040 ///
1041 /// Maps to: `JSONB` (`PostgreSQL`), `VARIANT` (Snowflake), `JSON` (`ClickHouse`).
1042 ///
1043 /// This is the recommended default for most use cases.
1044 #[default]
1045 Binary,
1046}
1047
1048impl JsonStorageFormat {
1049 /// Returns `true` if this is the binary storage format.
1050 ///
1051 /// # Example
1052 ///
1053 /// ```rust
1054 /// use razeri_plugin_contract::data_type::JsonStorageFormat;
1055 ///
1056 /// assert!(!JsonStorageFormat::Text.is_binary());
1057 /// assert!(JsonStorageFormat::Binary.is_binary());
1058 /// ```
1059 #[must_use]
1060 pub const fn is_binary(&self) -> bool {
1061 matches!(self, Self::Binary)
1062 }
1063}
1064
1065/// JSON/Semi-structured data type.
1066///
1067/// Database mapping details:
1068///
1069/// | Platform | Type | Notes |
1070/// |----------|------|-------|
1071/// | **`PostgreSQL`** | `JSON` or `JSONB` | JSONB supports GIN indexing and is faster for queries |
1072/// | **SQL Server** | `NVARCHAR(MAX)` with JSON functions (2016+), or native JSON (2025+) | |
1073/// | **Snowflake** | `VARIANT` | Native semi-structured type, supports nested data and arrays |
1074/// | **Databricks** | `STRING` with JSON functions, or `VARIANT` | |
1075/// | **`ClickHouse`** | `JSON` (experimental/production), or `String` with JSON functions | |
1076/// | **`CitusDB`** | Same as `PostgreSQL` (JSONB recommended) | |
1077///
1078/// # Storage Formats
1079///
1080/// - **Binary** (default): Normalized storage, faster queries, indexable.
1081/// Maps to `JSONB` in `PostgreSQL`, `VARIANT` in Snowflake.
1082/// - **Text**: Preserves whitespace, key order, and duplicate keys.
1083/// Maps to `JSON` in `PostgreSQL`, `NVARCHAR(MAX)` in SQL Server.
1084///
1085/// # Example
1086///
1087/// ```rust
1088/// use razeri_plugin_contract::DataType;
1089/// use razeri_plugin_contract::data_type::{JsonDataType, JsonStorageFormat};
1090///
1091/// // Binary format (recommended) - uses JSONB in PostgreSQL, VARIANT in Snowflake
1092/// let json_binary = JsonDataType::default();
1093/// assert_eq!(json_binary.storage_format, JsonStorageFormat::Binary);
1094///
1095/// // Text format - preserves original formatting
1096/// let json_text = JsonDataType::text();
1097/// assert_eq!(json_text.storage_format, JsonStorageFormat::Text);
1098///
1099/// // Via DataType convenience
1100/// let data = DataType::json();
1101/// ```
1102#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
1103pub struct JsonDataType {
1104 /// Storage format preference (binary is recommended for most use cases).
1105 pub storage_format: JsonStorageFormat,
1106
1107 /// Whether to validate JSON on insert (if supported by the database).
1108 ///
1109 /// `PostgreSQL` always validates, some other databases may not.
1110 pub validate_on_insert: bool,
1111}
1112
1113impl JsonDataType {
1114 /// Creates a new JSON type with binary storage format (JSONB in `PostgreSQL`).
1115 ///
1116 /// This is the recommended format for most use cases as it enables:
1117 /// - Faster query performance
1118 /// - GIN indexing support (`PostgreSQL`)
1119 /// - Normalized storage (no duplicate keys, sorted keys)
1120 ///
1121 /// # Example
1122 ///
1123 /// ```rust
1124 /// use razeri_plugin_contract::data_type::{JsonDataType, JsonStorageFormat};
1125 ///
1126 /// let json = JsonDataType::new();
1127 /// assert_eq!(json.storage_format, JsonStorageFormat::Binary);
1128 /// assert!(!json.validate_on_insert);
1129 /// ```
1130 #[must_use]
1131 pub fn new() -> Self {
1132 Self::default()
1133 }
1134
1135 /// Creates a JSON type with text storage format.
1136 ///
1137 /// Use this when you need to preserve:
1138 /// - Original whitespace formatting
1139 /// - Original key order
1140 /// - Duplicate keys (not recommended but sometimes required)
1141 ///
1142 /// # Example
1143 ///
1144 /// ```rust
1145 /// use razeri_plugin_contract::data_type::{JsonDataType, JsonStorageFormat};
1146 ///
1147 /// let json = JsonDataType::text();
1148 /// assert_eq!(json.storage_format, JsonStorageFormat::Text);
1149 /// assert!(json.validate_on_insert);
1150 /// ```
1151 #[must_use]
1152 pub fn text() -> Self {
1153 Self { storage_format: JsonStorageFormat::Text, validate_on_insert: true }
1154 }
1155
1156 /// Creates a JSON type with binary storage format.
1157 ///
1158 /// # Example
1159 ///
1160 /// ```rust
1161 /// use razeri_plugin_contract::data_type::{JsonDataType, JsonStorageFormat};
1162 ///
1163 /// let json = JsonDataType::binary();
1164 /// assert_eq!(json.storage_format, JsonStorageFormat::Binary);
1165 /// assert!(json.validate_on_insert);
1166 /// ```
1167 #[must_use]
1168 pub fn binary() -> Self {
1169 Self { storage_format: JsonStorageFormat::Binary, validate_on_insert: true }
1170 }
1171
1172 /// Sets whether to validate JSON on insert.
1173 ///
1174 /// # Example
1175 ///
1176 /// ```rust
1177 /// use razeri_plugin_contract::data_type::JsonDataType;
1178 ///
1179 /// let json = JsonDataType::new().with_validation(false);
1180 /// assert!(!json.validate_on_insert);
1181 /// ```
1182 #[must_use]
1183 pub fn with_validation(mut self, validate: bool) -> Self {
1184 self.validate_on_insert = validate;
1185 self
1186 }
1187}
1188
1189// ============================================================================
1190// Complex/Collection Types
1191// ============================================================================
1192
1193/// Array type containing elements of another type.
1194///
1195/// Supported by: `PostgreSQL`, `ClickHouse`, Snowflake (ARRAY), Databricks (ARRAY).
1196/// Not directly supported by SQL Server.
1197///
1198/// # Example
1199///
1200/// ```rust
1201/// use razeri_plugin_contract::{DataType, data_type::ArrayDataType};
1202///
1203/// let int_array = ArrayDataType::new(DataType::int());
1204/// assert_eq!(*int_array.element_type, DataType::int());
1205///
1206/// let _str_array = ArrayDataType::new(DataType::varchar(100));
1207/// ```
1208#[derive(Debug, Clone, PartialEq, Eq)]
1209pub struct ArrayDataType {
1210 /// The data type of array elements.
1211 pub element_type: Box<DataType>,
1212}
1213
1214impl ArrayDataType {
1215 /// Creates a new array type with the given element type.
1216 ///
1217 /// # Example
1218 ///
1219 /// ```rust
1220 /// use razeri_plugin_contract::{DataType, data_type::ArrayDataType};
1221 ///
1222 /// let arr = ArrayDataType::new(DataType::bigint());
1223 /// assert_eq!(*arr.element_type, DataType::bigint());
1224 /// ```
1225 #[must_use]
1226 pub fn new(element_type: DataType) -> Self {
1227 Self { element_type: Box::new(element_type) }
1228 }
1229}
1230
1231/// Map/Dictionary type with key-value pairs.
1232///
1233/// Supported by: `ClickHouse`, Snowflake (OBJECT), Databricks (MAP).
1234/// `PostgreSQL` uses JSONB, SQL Server uses JSON string.
1235///
1236/// # Example
1237///
1238/// ```rust
1239/// use razeri_plugin_contract::DataType;
1240/// use razeri_plugin_contract::data_type::MapDataType;
1241///
1242/// let map = MapDataType::new(DataType::varchar(50), DataType::int());
1243/// assert_eq!(*map.key_type, DataType::varchar(50));
1244/// assert_eq!(*map.value_type, DataType::int());
1245/// ```
1246#[derive(Debug, Clone, PartialEq, Eq)]
1247pub struct MapDataType {
1248 /// The data type of map keys.
1249 pub key_type: Box<DataType>,
1250
1251 /// The data type of map values.
1252 pub value_type: Box<DataType>,
1253}
1254
1255impl MapDataType {
1256 /// Creates a new map type with the given key and value types.
1257 ///
1258 /// # Example
1259 ///
1260 /// ```rust
1261 /// use razeri_plugin_contract::DataType;
1262 /// use razeri_plugin_contract::data_type::MapDataType;
1263 ///
1264 /// let map = MapDataType::new(DataType::varchar(50), DataType::int());
1265 /// assert_eq!(*map.key_type, DataType::varchar(50));
1266 /// assert_eq!(*map.value_type, DataType::int());
1267 /// ```
1268 #[must_use]
1269 pub fn new(key_type: DataType, value_type: DataType) -> Self {
1270 Self { key_type: Box::new(key_type), value_type: Box::new(value_type) }
1271 }
1272}
1273
1274/// One named field inside a [`StructDataType`], in the order it was declared.
1275///
1276/// A struct's fields are named on every engine that has a record type, and
1277/// positional on some, so both the name and the position are part of the type.
1278///
1279/// # Example
1280///
1281/// ```rust
1282/// use razeri_plugin_contract::{DataType, data_type::StructField};
1283///
1284/// let zip = StructField::new("zip", DataType::varchar(10));
1285/// assert_eq!(zip.name, "zip");
1286/// assert_eq!(zip.data_type, DataType::varchar(10));
1287/// ```
1288#[derive(Debug, Clone, PartialEq, Eq)]
1289pub struct StructField {
1290 /// The field's name, as the design declared it.
1291 pub name: String,
1292
1293 /// The field's type. May itself be a collection or another struct.
1294 pub data_type: DataType,
1295}
1296
1297impl StructField {
1298 /// Creates a named field of the given type.
1299 ///
1300 /// # Example
1301 ///
1302 /// ```rust
1303 /// use razeri_plugin_contract::{DataType, data_type::StructField};
1304 ///
1305 /// let field = StructField::new("category", DataType::varchar(100));
1306 /// assert_eq!(field.data_type, DataType::varchar(100));
1307 /// ```
1308 pub fn new(name: impl Into<String>, data_type: DataType) -> Self {
1309 Self { name: name.into(), data_type }
1310 }
1311}
1312
1313/// Struct/record type: an ordered list of named fields.
1314///
1315/// Supported natively by `BigQuery` (`STRUCT`), Databricks (`STRUCT`),
1316/// `ClickHouse` (named `Tuple`) and `DuckDB` (`STRUCT`). Engines without a
1317/// record type render their JSON type instead; the field names and types are
1318/// still part of the declared type, they are simply not restated in the DDL.
1319///
1320/// Field order is significant: it is the order the design declared, it is the
1321/// order every engine with a record type writes, and two structs holding the
1322/// same fields in a different order are different types.
1323///
1324/// # Example
1325///
1326/// ```rust
1327/// use razeri_plugin_contract::{DataType, data_type::{StructDataType, StructField}};
1328///
1329/// let address = StructDataType::new(vec![
1330/// StructField::new("street", DataType::varchar(200)),
1331/// StructField::new("zip", DataType::varchar(10)),
1332/// ]);
1333/// assert_eq!(address.fields.len(), 2);
1334/// assert_eq!(address.fields[0].name, "street");
1335/// ```
1336#[derive(Debug, Clone, PartialEq, Eq)]
1337pub struct StructDataType {
1338 /// The struct's fields, in declaration order.
1339 pub fields: Vec<StructField>,
1340}
1341
1342impl StructDataType {
1343 /// Creates a struct type from an ordered list of named fields.
1344 ///
1345 /// # Example
1346 ///
1347 /// ```rust
1348 /// use razeri_plugin_contract::{DataType, data_type::{StructDataType, StructField}};
1349 ///
1350 /// let point = StructDataType::new(vec![
1351 /// StructField::new("x", DataType::int()),
1352 /// StructField::new("y", DataType::int()),
1353 /// ]);
1354 /// assert_eq!(point.fields[1].name, "y");
1355 /// ```
1356 #[must_use]
1357 pub fn new(fields: Vec<StructField>) -> Self {
1358 Self { fields }
1359 }
1360}
1361
1362// ============================================================================
1363// Unified Data Type Enum
1364// ============================================================================
1365
1366/// Unified data type enumeration covering all supported types across databases.
1367///
1368/// This is the **primary type system** for Razeri. Every field, column, and
1369/// parameter in a design document is typed using `DataType`. The enum captures
1370/// enough metadata to generate correct DDL for every target while remaining
1371/// abstract over platform-specific implementation details.
1372///
1373/// # Type Categories
1374///
1375/// | Category | Variants | Example |
1376/// |----------|----------|---------|
1377/// | Numeric | `Integer`, `Decimal`, `Float` | `INT`, `DECIMAL(19,4)`, `DOUBLE` |
1378/// | Boolean | `Boolean` | `BOOLEAN`, `BIT` |
1379/// | String | `Char`, `VarChar`, `Text` | `VARCHAR(100)`, `TEXT` |
1380/// | Binary | `Binary`, `VarBinary` | `BYTEA`, `VARBINARY` |
1381/// | Date/Time | `Date`, `Time`, `Timestamp`, `TimestampTz`, `DateTime`, `Interval` | `DATE`, `TIMESTAMP` |
1382/// | Special | `Uuid`, `Json` | `UUID`, `JSONB` |
1383/// | Collection | `Array`, `Map`, `Struct` | `INTEGER[]`, `MAP<TEXT,INT>`, `STRUCT<a INT>` |
1384///
1385/// # Design Principles
1386///
1387/// 1. **Abstract over database-specific implementations** — `DataType` captures
1388/// enough metadata to generate correct DDL for each target, but does not
1389/// embed platform-specific syntax.
1390/// 2. **Preserve precision metadata** — Decimal types carry precision and scale;
1391/// string types carry length constraints; timestamp types carry fractional
1392/// seconds precision.
1393/// 3. **Every type renders somewhere** — a dialect answers for every variant,
1394/// emulating a type it does not have (JSON stored as `NVARCHAR(MAX)` on SQL
1395/// Server, a struct stored as `jsonb` on `PostgreSQL`) rather than refusing.
1396///
1397/// # Usage
1398///
1399/// ```
1400/// use razeri_plugin_contract::DataType;
1401///
1402/// // Convenience constructors for common types
1403/// let id = DataType::bigint();
1404/// let name = DataType::varchar(255);
1405/// let price = DataType::decimal(19, 4);
1406/// let created = DataType::timestamp();
1407///
1408/// // JSON with binary storage (JSONB in PostgreSQL, VARIANT in Snowflake)
1409/// let data = DataType::json();
1410/// ```
1411///
1412/// # Cross-Database Mapping
1413///
1414/// Each variant maps to platform-specific types as documented in the variant
1415/// definitions. Dialect plugins resolve the final SQL type string during
1416/// rendering; the rendering traits live in this crate's `renderer` module.
1417///
1418/// # The enum is `#[non_exhaustive]`
1419///
1420/// New types are added over time, so a `match` outside this crate needs a
1421/// fallback arm. A dialect's fallback should render the closest type the engine
1422/// does have — its JSON or text type — rather than panicking: a type the
1423/// dialect has not been taught about is still a column someone declared.
1424#[derive(Debug, Clone, PartialEq, Eq)]
1425#[non_exhaustive]
1426pub enum DataType {
1427 // Numeric types
1428 /// Signed/unsigned integer (1, 2, 4, or 8 bytes).
1429 Integer(IntegerDataType),
1430
1431 /// Exact numeric with fixed precision and scale.
1432 Decimal(DecimalDataType),
1433
1434 /// Approximate floating-point (4 or 8 bytes).
1435 Float(FloatDataType),
1436
1437 /// Boolean (true/false).
1438 Boolean(BooleanDataType),
1439
1440 // String types
1441 /// Fixed-length character string.
1442 Char(CharDataType),
1443
1444 /// Variable-length character string.
1445 VarChar(VarCharDataType),
1446
1447 /// Unbounded text type.
1448 Text(TextDataType),
1449
1450 // Binary types
1451 /// Fixed-length binary data.
1452 Binary(BinaryDataType),
1453
1454 /// Variable-length binary data.
1455 VarBinary(VarBinaryDataType),
1456
1457 // Date/Time types
1458 /// Date only (year, month, day).
1459 Date(DateDataType),
1460
1461 /// Time only (hour, minute, second, optional timezone).
1462 Time(TimeDataType),
1463
1464 /// Timestamp without timezone.
1465 Timestamp(TimestampDataType),
1466
1467 /// Timestamp with timezone.
1468 TimestampTz(TimestampTzDataType),
1469
1470 /// Combined date and time (legacy).
1471 DateTime(DateTimeDataType),
1472
1473 /// Interval/duration.
1474 Interval(IntervalDataType),
1475
1476 // Special types
1477 /// UUID/GUID.
1478 Uuid(UuidDataType),
1479
1480 /// JSON/semi-structured data.
1481 Json(JsonDataType),
1482
1483 // Complex types
1484 /// Array of elements.
1485 Array(ArrayDataType),
1486
1487 /// Map/dictionary with key-value pairs.
1488 Map(MapDataType),
1489
1490 /// Record with an ordered list of named fields.
1491 Struct(StructDataType),
1492}
1493
1494impl DataType {
1495 /// Whether this type holds more than one value inside one column — an
1496 /// array, a map, or a record.
1497 ///
1498 /// Nested columns are answered differently from scalars in several places:
1499 /// they cannot be part of a key, nothing aggregates them, and an engine
1500 /// with no record type of its own stores them as JSON or text. This is the
1501 /// one question all of those ask, so they ask it the same way.
1502 ///
1503 /// # Example
1504 ///
1505 /// ```
1506 /// use razeri_plugin_contract::{DataType, data_type::ArrayDataType};
1507 ///
1508 /// assert!(DataType::Array(ArrayDataType::new(DataType::int())).is_nested());
1509 /// assert!(!DataType::bigint().is_nested());
1510 /// ```
1511 #[must_use]
1512 pub const fn is_nested(&self) -> bool {
1513 matches!(self, DataType::Array(_) | DataType::Map(_) | DataType::Struct(_))
1514 }
1515
1516 // ==========================================================================
1517 // Numeric Type Constructors
1518 // ==========================================================================
1519
1520 /// Creates a 1-byte signed integer (`TINYINT` / `SMALLINT` / `Int8`).
1521 ///
1522 /// # Example
1523 ///
1524 /// ```
1525 /// use razeri_plugin_contract::DataType;
1526 ///
1527 /// let ty = DataType::tinyint();
1528 /// assert!(matches!(ty, DataType::Integer(_)));
1529 /// ```
1530 #[must_use]
1531 pub fn tinyint() -> Self {
1532 DataType::Integer(IntegerDataType::new(IntegerSize::Tiny))
1533 }
1534
1535 /// Creates a 2-byte signed integer (`SMALLINT` / `Int16`).
1536 ///
1537 /// # Example
1538 ///
1539 /// ```
1540 /// use razeri_plugin_contract::DataType;
1541 ///
1542 /// let ty = DataType::smallint();
1543 /// assert!(matches!(ty, DataType::Integer(_)));
1544 /// ```
1545 #[must_use]
1546 pub fn smallint() -> Self {
1547 DataType::Integer(IntegerDataType::new(IntegerSize::Small))
1548 }
1549
1550 /// Creates a 4-byte signed integer (`INT` / `INTEGER` / `Int32`).
1551 ///
1552 /// # Example
1553 ///
1554 /// ```
1555 /// use razeri_plugin_contract::DataType;
1556 ///
1557 /// let id = DataType::int();
1558 /// assert!(matches!(id, DataType::Integer(_)));
1559 /// ```
1560 #[must_use]
1561 pub fn int() -> Self {
1562 DataType::Integer(IntegerDataType::new(IntegerSize::Standard))
1563 }
1564
1565 /// Creates an 8-byte signed integer (`BIGINT` / `Int64`).
1566 ///
1567 /// # Example
1568 ///
1569 /// ```
1570 /// use razeri_plugin_contract::DataType;
1571 ///
1572 /// let id = DataType::bigint();
1573 /// assert!(matches!(id, DataType::Integer(_)));
1574 /// ```
1575 #[must_use]
1576 pub fn bigint() -> Self {
1577 DataType::Integer(IntegerDataType::new(IntegerSize::Big))
1578 }
1579
1580 /// Creates a `DECIMAL(precision, scale)` type.
1581 ///
1582 /// # Panics
1583 ///
1584 /// Panics if `precision` is 0 or exceeds 38, or if `scale > precision`.
1585 ///
1586 /// # Example
1587 ///
1588 /// ```
1589 /// use razeri_plugin_contract::DataType;
1590 ///
1591 /// let price = DataType::decimal(19, 4);
1592 /// assert!(matches!(price, DataType::Decimal(_)));
1593 /// ```
1594 ///
1595 /// ```should_panic
1596 /// use razeri_plugin_contract::DataType;
1597 ///
1598 /// let _ = DataType::decimal(0, 0); // panics: precision must be 1-38
1599 /// ```
1600 #[must_use]
1601 pub fn decimal(precision: u8, scale: u8) -> Self {
1602 DataType::Decimal(DecimalDataType::new(precision, scale))
1603 }
1604
1605 /// Creates a single-precision float (`REAL` / `FLOAT4`).
1606 ///
1607 /// # Example
1608 ///
1609 /// ```
1610 /// use razeri_plugin_contract::DataType;
1611 ///
1612 /// let ty = DataType::float();
1613 /// assert!(matches!(ty, DataType::Float(_)));
1614 /// ```
1615 #[must_use]
1616 pub fn float() -> Self {
1617 DataType::Float(FloatDataType::single())
1618 }
1619
1620 /// Creates a double-precision float (`DOUBLE PRECISION` / `DOUBLE`).
1621 ///
1622 /// # Example
1623 ///
1624 /// ```
1625 /// use razeri_plugin_contract::DataType;
1626 ///
1627 /// let ty = DataType::double();
1628 /// assert!(matches!(ty, DataType::Float(_)));
1629 /// ```
1630 #[must_use]
1631 pub fn double() -> Self {
1632 DataType::Float(FloatDataType::double())
1633 }
1634
1635 // ==========================================================================
1636 // Boolean Type Constructor
1637 // ==========================================================================
1638
1639 /// Creates a boolean type (`BOOLEAN` / `BIT`).
1640 ///
1641 /// # Example
1642 ///
1643 /// ```
1644 /// use razeri_plugin_contract::DataType;
1645 ///
1646 /// let ty = DataType::boolean();
1647 /// assert!(matches!(ty, DataType::Boolean(_)));
1648 /// ```
1649 #[must_use]
1650 pub fn boolean() -> Self {
1651 DataType::Boolean(BooleanDataType)
1652 }
1653
1654 // ==========================================================================
1655 // String Type Constructors
1656 // ==========================================================================
1657
1658 /// Creates a `VARCHAR(max_length)` type.
1659 ///
1660 /// # Example
1661 ///
1662 /// ```
1663 /// use razeri_plugin_contract::DataType;
1664 ///
1665 /// let name = DataType::varchar(255);
1666 /// assert!(matches!(name, DataType::VarChar(_)));
1667 /// ```
1668 #[must_use]
1669 pub fn varchar(max_length: u32) -> Self {
1670 DataType::VarChar(VarCharDataType::new(max_length))
1671 }
1672
1673 /// Creates an unbounded text type (`TEXT` / `VARCHAR(MAX)` / `STRING`).
1674 ///
1675 /// # Example
1676 ///
1677 /// ```
1678 /// use razeri_plugin_contract::DataType;
1679 ///
1680 /// let ty = DataType::text();
1681 /// assert!(matches!(ty, DataType::Text(_)));
1682 /// ```
1683 #[must_use]
1684 pub fn text() -> Self {
1685 DataType::Text(TextDataType)
1686 }
1687
1688 // ==========================================================================
1689 // Date/Time Type Constructors
1690 // ==========================================================================
1691
1692 /// Creates a date-only type (`DATE`).
1693 ///
1694 /// # Example
1695 ///
1696 /// ```
1697 /// use razeri_plugin_contract::DataType;
1698 ///
1699 /// let ty = DataType::date();
1700 /// assert!(matches!(ty, DataType::Date(_)));
1701 /// ```
1702 #[must_use]
1703 pub fn date() -> Self {
1704 DataType::Date(DateDataType)
1705 }
1706
1707 /// Creates a timestamp without timezone (`TIMESTAMP`).
1708 ///
1709 /// # Example
1710 ///
1711 /// ```
1712 /// use razeri_plugin_contract::DataType;
1713 ///
1714 /// let created = DataType::timestamp();
1715 /// assert!(matches!(created, DataType::Timestamp(_)));
1716 /// ```
1717 #[must_use]
1718 pub fn timestamp() -> Self {
1719 DataType::Timestamp(TimestampDataType::default())
1720 }
1721
1722 /// Creates a timestamp with timezone (`TIMESTAMPTZ` / `DATETIMEOFFSET`).
1723 ///
1724 /// # Example
1725 ///
1726 /// ```
1727 /// use razeri_plugin_contract::DataType;
1728 ///
1729 /// let created_tz = DataType::timestamp_tz();
1730 /// assert!(matches!(created_tz, DataType::TimestampTz(_)));
1731 /// ```
1732 #[must_use]
1733 pub fn timestamp_tz() -> Self {
1734 DataType::TimestampTz(TimestampTzDataType::default())
1735 }
1736
1737 // ==========================================================================
1738 // Special Type Constructors
1739 // ==========================================================================
1740
1741 /// Creates a UUID type (`UUID` / `UNIQUEIDENTIFIER`).
1742 ///
1743 /// # Example
1744 ///
1745 /// ```
1746 /// use razeri_plugin_contract::DataType;
1747 ///
1748 /// let ty = DataType::uuid();
1749 /// assert!(matches!(ty, DataType::Uuid(_)));
1750 /// ```
1751 #[must_use]
1752 pub fn uuid() -> Self {
1753 DataType::Uuid(UuidDataType)
1754 }
1755
1756 /// Creates a JSON type with binary storage (JSONB in `PostgreSQL`, VARIANT in Snowflake).
1757 ///
1758 /// # Example
1759 ///
1760 /// ```
1761 /// use razeri_plugin_contract::DataType;
1762 ///
1763 /// let data = DataType::json();
1764 /// assert!(matches!(data, DataType::Json(_)));
1765 /// ```
1766 #[must_use]
1767 pub fn json() -> Self {
1768 DataType::Json(JsonDataType::binary())
1769 }
1770
1771 /// Creates a JSON type with text storage (preserves formatting).
1772 ///
1773 /// # Example
1774 ///
1775 /// ```
1776 /// use razeri_plugin_contract::DataType;
1777 ///
1778 /// let data = DataType::json_text();
1779 /// assert!(matches!(data, DataType::Json(_)));
1780 /// ```
1781 #[must_use]
1782 pub fn json_text() -> Self {
1783 DataType::Json(JsonDataType::text())
1784 }
1785}
1786
1787// ============================================================================
1788// Tests
1789// ============================================================================
1790
1791#[cfg(test)]
1792mod tests {
1793 use super::*;
1794
1795 #[test]
1796 fn test_integer_types() {
1797 let tiny = IntegerDataType::new(IntegerSize::Tiny);
1798 assert_eq!(tiny.byte_size(), 1);
1799 assert!(!tiny.unsigned);
1800
1801 let big_unsigned = IntegerDataType::unsigned(IntegerSize::Big);
1802 assert_eq!(big_unsigned.byte_size(), 8);
1803 assert!(big_unsigned.unsigned);
1804 }
1805
1806 #[test]
1807 fn test_decimal_type() {
1808 let money = DecimalDataType::money();
1809 assert_eq!(money.precision, 19);
1810 assert_eq!(money.scale, 4);
1811 }
1812
1813 #[test]
1814 #[should_panic(expected = "Scale cannot exceed precision")]
1815 fn test_decimal_invalid_scale() {
1816 let _ = DecimalDataType::new(5, 10);
1817 }
1818
1819 #[test]
1820 fn test_convenience_constructors() {
1821 assert!(matches!(DataType::int(), DataType::Integer(_)));
1822 assert!(matches!(DataType::varchar(100), DataType::VarChar(_)));
1823 assert!(matches!(DataType::timestamp(), DataType::Timestamp(_)));
1824 }
1825
1826 /// A struct is built from named fields and keeps them in the order given.
1827 #[test]
1828 fn a_struct_keeps_its_fields_in_declaration_order() {
1829 let address = StructDataType::new(vec![
1830 StructField::new("street", DataType::varchar(200)),
1831 StructField::new("city", DataType::varchar(100)),
1832 StructField::new("zip", DataType::varchar(10)),
1833 ]);
1834
1835 let names: Vec<&str> = address.fields.iter().map(|f| f.name.as_str()).collect();
1836 assert_eq!(names, ["street", "city", "zip"]);
1837 assert_eq!(address.fields[2].data_type, DataType::varchar(10));
1838 assert!(matches!(DataType::Struct(address), DataType::Struct(_)));
1839 }
1840
1841 /// Field order is part of the type: the same fields in another order are a
1842 /// different struct, and the same fields in the same order are the same one.
1843 #[test]
1844 fn two_structs_are_equal_only_when_their_fields_agree_in_order() {
1845 let field = |name: &str| StructField::new(name, DataType::int());
1846 let xy = StructDataType::new(vec![field("x"), field("y")]);
1847 let xy_again = StructDataType::new(vec![field("x"), field("y")]);
1848 let yx = StructDataType::new(vec![field("y"), field("x")]);
1849 let renamed = StructDataType::new(vec![field("x"), field("z")]);
1850 let retyped = StructDataType::new(vec![
1851 StructField::new("x", DataType::int()),
1852 StructField::new("y", DataType::bigint()),
1853 ]);
1854
1855 assert_eq!(DataType::Struct(xy.clone()), DataType::Struct(xy_again));
1856 assert_ne!(DataType::Struct(xy.clone()), DataType::Struct(yx));
1857 assert_ne!(DataType::Struct(xy.clone()), DataType::Struct(renamed));
1858 assert_ne!(DataType::Struct(xy), DataType::Struct(retyped));
1859 }
1860
1861 /// A struct nests: its fields may themselves be collections or structs, so
1862 /// the array of structs a nested source table carries is one value.
1863 #[test]
1864 fn a_struct_field_may_itself_be_a_collection_or_a_struct() {
1865 let inner = StructDataType::new(vec![
1866 StructField::new("key", DataType::varchar(100)),
1867 StructField::new("value", DataType::varchar(1000)),
1868 ]);
1869 let outer = StructDataType::new(vec![
1870 StructField::new("id", DataType::bigint()),
1871 StructField::new(
1872 "extras",
1873 DataType::Array(ArrayDataType::new(DataType::Struct(inner))),
1874 ),
1875 StructField::new(
1876 "labels",
1877 DataType::Map(MapDataType::new(DataType::varchar(50), DataType::text())),
1878 ),
1879 ]);
1880
1881 let DataType::Array(extras) = &outer.fields[1].data_type else {
1882 panic!("the second field is an array");
1883 };
1884 let DataType::Struct(element) = extras.element_type.as_ref() else {
1885 panic!("the array's element is a struct");
1886 };
1887 assert_eq!(element.fields[0].name, "key");
1888 assert!(matches!(outer.fields[2].data_type, DataType::Map(_)));
1889 }
1890}
1891
1892// ============================================================================
1893// Simplified Data Type Reference (for CAST expressions)
1894// ============================================================================
1895
1896/// Simplified data type reference used in CAST / `TRY_CAST` / CONVERT expressions.
1897///
1898/// Unlike [`DataType`], which captures full type metadata for DDL generation,
1899/// `DataTypeRef` represents the type names commonly used in SQL expressions.
1900///
1901/// # Purpose
1902///
1903/// `DataTypeRef` is a lightweight, platform-agnostic type reference suitable for
1904/// embedding in SQL expressions such as:
1905///
1906/// ```sql
1907/// SELECT CAST(column_name AS VARCHAR(100)) FROM table
1908/// SELECT TRY_CAST(value AS DECIMAL(19, 4)) FROM source
1909/// SELECT CONVERT(DATETIME2, timestamp_col) FROM events
1910/// ```
1911///
1912/// # Differences from `DataType`
1913///
1914/// | Aspect | `DataType` | `DataTypeRef` |
1915/// |--------|-----------|---------------|
1916/// | **Use case** | DDL generation | CAST / CONVERT expressions |
1917/// | **Metadata** | Full (encoding, precision, storage format) | Minimal (precision, scale, length) |
1918/// | **Platform variants** | Unified (one variant per type) | Separate (`Decimal` vs `Numeric`, `DateTime` vs `DateTime2`) |
1919/// | **Collections** | Array, Map, Struct | Not supported |
1920///
1921/// # Platform-Specific Variants
1922///
1923/// Some types have separate variants for platform-specific naming:
1924///
1925/// - `Decimal` vs `Numeric` — equivalent in SQL, but some dialects prefer one over the other
1926/// - `DateTime` vs `DateTime2` — SQL Server uses `DATETIME2` for precision
1927/// - `Json` vs `Jsonb` — `PostgreSQL` distinguishes between text and binary JSON
1928/// - `Boolean` vs `Bit` — SQL Server uses `BIT` for boolean
1929///
1930/// # Example
1931///
1932/// ```
1933/// use razeri_plugin_contract::DataTypeRef;
1934///
1935/// let varchar = DataTypeRef::Varchar { length: Some(100) };
1936/// let decimal = DataTypeRef::Decimal { precision: 19, scale: 4 };
1937/// let timestamp = DataTypeRef::Timestamp { precision: Some(6) };
1938/// ```
1939#[derive(Debug, Clone, PartialEq)]
1940pub enum DataTypeRef {
1941 // ==========================================================================
1942 // Numeric Types
1943 // ==========================================================================
1944 /// 4-byte signed integer (`INT` / `INTEGER`).
1945 Int,
1946
1947 /// 8-byte signed integer (`BIGINT`).
1948 BigInt,
1949
1950 /// 2-byte signed integer (`SMALLINT`).
1951 SmallInt,
1952
1953 /// 1-byte signed integer (`TINYINT` / `SMALLINT` in `PostgreSQL`).
1954 TinyInt,
1955
1956 /// Single-precision float (`REAL` / `FLOAT4`).
1957 Float,
1958
1959 /// Double-precision float (`DOUBLE PRECISION` / `DOUBLE`).
1960 Double,
1961
1962 /// Single-precision float (`REAL` / `FLOAT4`).
1963 Real,
1964
1965 /// Exact numeric with precision and scale (`DECIMAL(p, s)`).
1966 Decimal {
1967 /// Total number of digits.
1968 precision: u8,
1969 /// Number of digits after the decimal point.
1970 scale: u8,
1971 },
1972
1973 /// Exact numeric with precision and scale (`NUMERIC(p, s)`).
1974 ///
1975 /// Equivalent to `Decimal` in SQL, but some dialects prefer `NUMERIC`
1976 /// over `DECIMAL` for exact numeric types.
1977 Numeric {
1978 /// Total number of digits.
1979 precision: u8,
1980 /// Number of digits after the decimal point.
1981 scale: u8,
1982 },
1983
1984 // ==========================================================================
1985 // String Types
1986 // ==========================================================================
1987 /// Variable-length character string (`VARCHAR(n)`).
1988 Varchar {
1989 /// Maximum length in characters (None = unlimited/MAX).
1990 length: Option<u16>,
1991 },
1992
1993 /// Fixed-length character string (`CHAR(n)`).
1994 Char {
1995 /// Length in characters.
1996 length: u16,
1997 },
1998
1999 /// Unbounded text type (`TEXT`).
2000 Text,
2001
2002 /// Variable-length Unicode string (`NVARCHAR(n)` — SQL Server).
2003 NVarchar {
2004 /// Maximum length in characters (None = unlimited/MAX).
2005 length: Option<u16>,
2006 },
2007
2008 /// Fixed-length Unicode string (`NCHAR(n)` — SQL Server).
2009 NChar {
2010 /// Length in characters.
2011 length: u16,
2012 },
2013
2014 // ==========================================================================
2015 // Binary Types
2016 // ==========================================================================
2017 /// Fixed-length binary data (`BINARY(n)`).
2018 Binary {
2019 /// Length in bytes.
2020 length: Option<u16>,
2021 },
2022
2023 /// Variable-length binary data (`VARBINARY(n)`).
2024 VarBinary {
2025 /// Maximum length in bytes (None = unlimited/MAX).
2026 length: Option<u16>,
2027 },
2028
2029 /// Unbounded binary data (`BLOB` / `BYTEA`).
2030 Blob,
2031
2032 // ==========================================================================
2033 // Date/Time Types
2034 // ==========================================================================
2035 /// Date only (`DATE`).
2036 Date,
2037
2038 /// Time with optional precision (`TIME(p)`).
2039 Time {
2040 /// Fractional seconds precision (None = default).
2041 precision: Option<u8>,
2042 },
2043
2044 /// Combined date and time (`DATETIME` — SQL Server legacy).
2045 DateTime,
2046
2047 /// Combined date and time with precision (`DATETIME2(p)` — SQL Server).
2048 DateTime2 {
2049 /// Fractional seconds precision (None = default).
2050 precision: Option<u8>,
2051 },
2052
2053 /// Timestamp with optional precision (`TIMESTAMP(p)`).
2054 Timestamp {
2055 /// Fractional seconds precision (None = default).
2056 precision: Option<u8>,
2057 },
2058
2059 /// Timestamp with timezone and optional precision (`TIMESTAMPTZ(p)`).
2060 TimestampTz {
2061 /// Fractional seconds precision (None = default).
2062 precision: Option<u8>,
2063 },
2064
2065 /// Interval/duration (`INTERVAL`).
2066 Interval,
2067
2068 // ==========================================================================
2069 // Boolean Types
2070 // ==========================================================================
2071 /// Boolean (`BOOLEAN` — `PostgreSQL`, Snowflake, `ClickHouse`).
2072 Boolean,
2073
2074 /// Bit (`BIT` — SQL Server).
2075 Bit,
2076
2077 // ==========================================================================
2078 // JSON/Semi-structured Types
2079 // ==========================================================================
2080 /// Text-based JSON (`JSON` — `PostgreSQL`).
2081 Json,
2082
2083 /// Binary-optimized JSON (`JSONB` — `PostgreSQL`).
2084 Jsonb,
2085
2086 /// Semi-structured variant (`VARIANT` — Snowflake).
2087 Variant,
2088
2089 // ==========================================================================
2090 // Other Types
2091 // ==========================================================================
2092 /// UUID/GUID (`UUID` / `UNIQUEIDENTIFIER`).
2093 Uuid,
2094
2095 /// XML data (`XML`).
2096 Xml,
2097
2098 /// Custom type name (for types not covered by the enum variants).
2099 Custom(String),
2100}