drizzle-migrations 0.1.16

Migration infrastructure for drizzle-rs
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! `PostgreSQL` SQL type grammar and naming conventions
//!
//! This module provides type checking, naming conventions, and default value
//! handling for `PostgreSQL` columns matching drizzle-kit grammar.ts

// =============================================================================
// Naming Conventions
// =============================================================================

/// Generate default name for a primary key constraint
#[must_use]
pub fn default_name_for_pk(table: &str) -> String {
    format!("{table}_pkey")
}

/// Generate default name for a foreign key constraint
#[must_use]
pub fn default_name_for_fk(
    table: &str,
    columns: &[String],
    _table_to: &str,
    _columns_to: &[String],
) -> String {
    let first_column = columns.first().map_or("", String::as_str);
    let desired = format!("{table}_{first_column}_fkey");

    // PostgreSQL identifier max length is 63
    if desired.len() > 63 {
        let hash = hash_string(&desired);
        if table.len() < 63 - 18 {
            format!("{table}_{hash}_fkey")
        } else {
            format!("{hash}_fkey")
        }
    } else {
        desired
    }
}

/// Generate default name for a unique constraint
#[must_use]
pub fn default_name_for_unique(table: &str, columns: &[String]) -> String {
    truncate_identifier(&format!("{}_{}_key", table, columns.join("_")), "_key")
}

/// Generate default name for an index
#[must_use]
pub fn default_name_for_index(table: &str, columns: &[String]) -> String {
    truncate_identifier(&format!("{}_{}_idx", table, columns.join("_")), "_idx")
}

/// Generate default name for an identity sequence
#[must_use]
pub fn default_name_for_identity_sequence(table: &str, column: &str) -> String {
    format!("{table}_{column}_seq")
}

/// Generate default name for a check constraint.
///
/// Naming convention (matches the `#[PostgresTable]` macro): table-level
/// checks are numbered 1-based — `{table}_check1`, `{table}_check2`, ...
/// (the macro collapses a *single* table-level check to `{table}_check`;
/// callers with that context should special-case it). Column-level checks
/// use `{table}_{column}_check` and are not produced by this helper.
#[must_use]
pub fn default_name_for_check(table: &str, index: usize) -> String {
    format!("{table}_check{}", index + 1)
}

/// Stable hash for constraint/index naming.
///
/// Uses SHA-256 (first 12 hex chars) so generated names are identical
/// across runs, processes, and Rust versions — `DefaultHasher` output is
/// explicitly not stable and would rename constraints between invocations.
fn hash_string(s: &str) -> String {
    use sha2::{Digest, Sha256};

    let digest = Sha256::digest(s.as_bytes());
    let mut out = String::with_capacity(12);
    for byte in digest.iter().take(6) {
        use std::fmt::Write;
        let _ = write!(out, "{byte:02x}");
    }
    out
}

/// Enforce `PostgreSQL`'s 63-byte identifier limit: names longer than that
/// are truncated and disambiguated with a stable hash, preserving `suffix`
/// (e.g. `_key`, `_idx`) so the object kind stays recognizable.
fn truncate_identifier(name: &str, suffix: &str) -> String {
    const MAX_IDENTIFIER_LEN: usize = 63;
    if name.len() <= MAX_IDENTIFIER_LEN {
        return name.to_string();
    }

    let hash = hash_string(name);
    // Reserve room for `_<hash>` + suffix.
    let budget = MAX_IDENTIFIER_LEN - hash.len() - 1 - suffix.len();
    let mut cutoff = budget.min(name.len());
    while !name.is_char_boundary(cutoff) {
        cutoff -= 1;
    }
    format!("{}_{hash}{suffix}", &name[..cutoff])
}

// =============================================================================
// SQL Type Categories
// =============================================================================

/// `PostgreSQL` SQL type category
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PgTypeCategory {
    SmallInt,
    Integer,
    BigInt,
    Numeric,
    Real,
    DoublePrecision,
    Boolean,
    Char,
    Varchar,
    Text,
    Json,
    Jsonb,
    Time,
    TimeTz,
    Timestamp,
    TimestampTz,
    Date,
    Uuid,
    Interval,
    Inet,
    Cidr,
    MacAddr,
    MacAddr8,
    Vector,
    HalfVec,
    SparseVec,
    Bit,
    Point,
    Line,
    Geometry,
    Serial,
    SmallSerial,
    BigSerial,
    Enum,
    Custom,
}

impl PgTypeCategory {
    fn type_name_rest<'a>(s: &'a str, type_name: &str) -> Option<&'a str> {
        if !s.starts_with(type_name) {
            return None;
        }
        let rest = &s[type_name.len()..];
        if rest
            .chars()
            .next()
            .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_')
        {
            return None;
        }
        Some(rest)
    }

    fn first_type_argument<'a>(s: &'a str, type_name: &str) -> Option<&'a str> {
        let rest = Self::type_name_rest(s, type_name)?.trim_start();
        let body = rest.strip_prefix('(')?;
        let end = body.find([',', ')'])?;
        Some(body[..end].trim())
    }

    /// Match serial and integer types. Serial aliases must be checked first so
    /// `smallserial` isn't misclassified as `smallint`.
    fn match_numeric(s: &str) -> Option<Self> {
        // Serial aliases first (prefix collides with integer types).
        if s.starts_with("smallserial") {
            return Some(Self::SmallSerial);
        }
        if s.starts_with("bigserial") {
            return Some(Self::BigSerial);
        }
        if s.starts_with("serial") {
            return Some(Self::Serial);
        }

        if s.starts_with("smallint") || s == "int2" {
            return Some(Self::SmallInt);
        }
        if s.starts_with("integer") || s == "int" || s == "int4" {
            return Some(Self::Integer);
        }
        if s.starts_with("bigint") || s == "int8" {
            return Some(Self::BigInt);
        }
        if s.starts_with("numeric") || s.starts_with("decimal") {
            return Some(Self::Numeric);
        }
        if s.starts_with("real") || s == "float4" {
            return Some(Self::Real);
        }
        if s.starts_with("double") {
            return Some(Self::DoublePrecision);
        }
        if s.starts_with("boolean") || s == "bool" {
            return Some(Self::Boolean);
        }
        None
    }

    /// Match string and JSON types. `varchar`/`character varying` must be
    /// checked before `char`/`character`; `jsonb` before `json`.
    fn match_string_or_json(s: &str) -> Option<Self> {
        if s.starts_with("varchar") || s.starts_with("character varying") {
            return Some(Self::Varchar);
        }
        if s.starts_with("char") || s.starts_with("character") {
            return Some(Self::Char);
        }
        if s.starts_with("text") {
            return Some(Self::Text);
        }
        if s.starts_with("jsonb") {
            return Some(Self::Jsonb);
        }
        if s.starts_with("json") {
            return Some(Self::Json);
        }
        None
    }

    /// Match time/date types. The `with time zone` variants are checked before
    /// the base `timestamp` / `time` prefixes.
    fn match_temporal(s: &str) -> Option<Self> {
        if s.starts_with("timestamp") && s.contains("with time zone") {
            return Some(Self::TimestampTz);
        }
        if s.starts_with("timestamp") {
            return Some(Self::Timestamp);
        }
        if s.starts_with("time") && s.contains("with time zone") {
            return Some(Self::TimeTz);
        }
        if s.starts_with("time") {
            return Some(Self::Time);
        }
        if s.starts_with("date") {
            return Some(Self::Date);
        }
        if s.starts_with("interval") {
            return Some(Self::Interval);
        }
        None
    }

    /// Match network, vector, bit, geometric and other specialized types.
    fn match_specialized(s: &str) -> Option<Self> {
        if s.starts_with("uuid") {
            return Some(Self::Uuid);
        }
        if s.starts_with("inet") {
            return Some(Self::Inet);
        }
        if s.starts_with("cidr") {
            return Some(Self::Cidr);
        }
        // macaddr8 must be matched before macaddr
        if s.starts_with("macaddr8") {
            return Some(Self::MacAddr8);
        }
        if s.starts_with("macaddr") {
            return Some(Self::MacAddr);
        }
        if s.starts_with("vector") {
            return Some(Self::Vector);
        }
        if s.starts_with("halfvec") {
            return Some(Self::HalfVec);
        }
        if s.starts_with("sparsevec") {
            return Some(Self::SparseVec);
        }
        if s.starts_with("bit") {
            return Some(Self::Bit);
        }
        if Self::type_name_rest(s, "geometry").is_some() {
            return Some(match Self::first_type_argument(s, "geometry") {
                Some("point") => Self::Geometry,
                _ => Self::Custom,
            });
        }
        if Self::type_name_rest(s, "geography").is_some()
            || Self::type_name_rest(s, "box2d").is_some()
            || Self::type_name_rest(s, "box3d").is_some()
            || Self::type_name_rest(s, "raster").is_some()
        {
            return Some(Self::Custom);
        }
        if s.starts_with("point") {
            return Some(Self::Point);
        }
        if s.starts_with("line") {
            return Some(Self::Line);
        }
        None
    }

    /// Determine the type category for a SQL type string
    #[must_use]
    pub fn from_sql_type(sql_type: &str) -> Self {
        let s = sql_type.trim().to_lowercase();

        Self::match_numeric(&s)
            .or_else(|| Self::match_string_or_json(&s))
            .or_else(|| Self::match_temporal(&s))
            .or_else(|| Self::match_specialized(&s))
            .unwrap_or(Self::Custom)
    }

    /// Get the drizzle import name for this type
    #[must_use]
    pub const fn drizzle_import(&self) -> &'static str {
        match self {
            Self::SmallInt => "smallint",
            Self::Integer => "integer",
            Self::BigInt => "bigint",
            Self::Numeric => "numeric",
            Self::Real => "real",
            Self::DoublePrecision => "doublePrecision",
            Self::Boolean => "boolean",
            Self::Char => "char",
            Self::Varchar => "varchar",
            Self::Text => "text",
            Self::Json => "json",
            Self::Jsonb => "jsonb",
            Self::Time | Self::TimeTz => "time",
            Self::Timestamp | Self::TimestampTz => "timestamp",
            Self::Date => "date",
            Self::Uuid => "uuid",
            Self::Interval => "interval",
            Self::Inet => "inet",
            Self::Cidr => "cidr",
            Self::MacAddr => "macaddr",
            Self::MacAddr8 => "macaddr8",
            Self::Vector => "vector",
            Self::HalfVec => "halfvec",
            Self::SparseVec => "sparsevec",
            Self::Bit => "bit",
            Self::Point => "point",
            Self::Line => "line",
            Self::Geometry => "geometry",
            Self::Serial => "serial",
            Self::SmallSerial => "smallserial",
            Self::BigSerial => "bigserial",
            Self::Enum => "pgEnum",
            Self::Custom => "customType",
        }
    }

    /// Check if this is a serial type
    #[must_use]
    pub const fn is_serial(&self) -> bool {
        matches!(self, Self::Serial | Self::SmallSerial | Self::BigSerial)
    }
}

// =============================================================================
// Type Parsing Utilities
// =============================================================================

/// Extract parameters from a type like "varchar(255)" or "numeric(10,2)"
#[must_use]
pub fn parse_type_params(sql_type: &str) -> Option<(String, Option<String>)> {
    let start = sql_type.find('(')?;
    let end = sql_type.find(')')?;
    let params = &sql_type[start + 1..end];

    let parts: Vec<&str> = params.split(',').map(str::trim).collect();
    match parts.len() {
        1 => Some((parts[0].to_string(), None)),
        2 => Some((parts[0].to_string(), Some(parts[1].to_string()))),
        _ => None,
    }
}

/// Check if a string is a serial expression
#[must_use]
pub fn is_serial_expression(expr: &str, schema: &str) -> bool {
    let schema_prefix = if schema == "public" {
        String::new()
    } else {
        format!("{schema}.")
    };

    (expr.starts_with(&format!("nextval('{schema_prefix}"))
        || expr.starts_with(&format!("nextval('\"{schema_prefix}")))
        && (expr.ends_with("_seq'::regclass)") || expr.ends_with("_seq\"'::regclass)"))
}

/// Extract the sequence name from a `nextval('...'::regclass)` expression.
///
/// Returns just the sequence name (without schema prefix or quotes):
/// - `nextval('users_id_seq'::regclass)` → `users_id_seq`
/// - `nextval('public.users_id_seq'::regclass)` → `users_id_seq`
/// - `nextval('"myschema"."users_id_seq"'::regclass)` → `users_id_seq`
#[must_use]
pub fn extract_nextval_sequence(expr: &str) -> Option<String> {
    let inner = expr
        .strip_prefix("nextval('")?
        .strip_suffix("'::regclass)")?;
    let name_part = inner.rfind('.').map_or(inner, |pos| &inner[pos + 1..]);
    let name = name_part.trim_matches('"');
    if name.is_empty() {
        return None;
    }
    Some(name.to_string())
}

// =============================================================================
// Identity Defaults
// =============================================================================

/// Default values for identity columns
pub struct IdentityDefaults;

impl IdentityDefaults {
    pub const START_WITH: &'static str = "1";
    pub const INCREMENT: &'static str = "1";
    pub const MIN: &'static str = "1";
    pub const CACHE: i32 = 1;
    pub const CYCLE: bool = false;

    /// Get the maximum value for an identity column based on type.
    ///
    /// Falls back to the `integer` range for unknown/unspecified types.
    #[must_use]
    pub fn max_for(column_type: &str) -> &'static str {
        match column_type {
            "smallint" => "32767",
            "bigint" => "9223372036854775807",
            // "integer" and fallback share the same range
            _ => "2147483647",
        }
    }

    /// Get the minimum value for an identity column based on type.
    ///
    /// Falls back to the `integer` range for unknown/unspecified types.
    #[must_use]
    pub fn min_for(column_type: &str) -> &'static str {
        match column_type {
            "smallint" => "-32768",
            "bigint" => "-9223372036854775808",
            // "integer" and fallback share the same range
            _ => "-2147483648",
        }
    }
}

// =============================================================================
// System Checks
// =============================================================================

/// System namespace names that should be skipped
pub const SYSTEM_NAMESPACE_NAMES: &[&str] = &["pg_toast", "pg_catalog", "information_schema"];

/// Check if a namespace is a system namespace
#[must_use]
pub fn is_system_namespace(name: &str) -> bool {
    name.starts_with("pg_toast")
        || name == "pg_default"
        || name == "pg_global"
        || name.starts_with("pg_temp_")
        || SYSTEM_NAMESPACE_NAMES.contains(&name)
}

/// Check if a role is a system role
#[must_use]
pub fn is_system_role(name: &str) -> bool {
    name == "postgres" || name.starts_with("pg_")
}

// =============================================================================
// Default Values
// =============================================================================

/// `PostgreSQL` default values and settings
pub struct PgDefaults;

impl PgDefaults {
    /// Default tablespace
    pub const TABLESPACE: &'static str = "pg_default";

    /// Default access method
    pub const ACCESS_METHOD: &'static str = "heap";

    /// Default nulls not distinct setting
    pub const NULLS_NOT_DISTINCT: bool = false;

    /// Default index method
    pub const INDEX_METHOD: &'static str = "btree";

    /// Default geometry SRID
    pub const GEOMETRY_SRID: i32 = 0;
}

/// Vector operator classes for indexes
pub const VECTOR_OPS: &[&str] = &[
    "vector_l2_ops",
    "vector_ip_ops",
    "vector_cosine_ops",
    "vector_l1_ops",
    "bit_hamming_ops",
    "bit_jaccard_ops",
    "halfvec_l2_ops",
    "sparsevec_l2_ops",
];

// =============================================================================
// Parsing Helpers
// =============================================================================

/// Parse a CHECK constraint definition: strip a leading `CHECK` keyword,
/// leaving the (possibly parenthesized) expression intact. Balanced outer
/// parentheses are the caller's concern — naive suffix trimming corrupts
/// expressions like `((a) AND (b))`.
#[must_use]
pub fn parse_check_definition(value: &str) -> String {
    let trimmed = value.trim();
    let rest = trimmed
        .strip_prefix("CHECK")
        .or_else(|| trimmed.strip_prefix("check"))
        .map_or(trimmed, str::trim_start);
    rest.to_string()
}

/// Parse a VIEW definition.
///
/// Callers with `Option<&str>` can pair this with [`Option::map`].
#[must_use]
pub fn parse_view_definition(value: &str) -> String {
    value
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .trim_end_matches(';')
        .to_string()
}

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

    #[test]
    fn test_default_name_for_pk() {
        assert_eq!(default_name_for_pk("users"), "users_pkey");
    }

    #[test]
    fn test_default_name_for_fk() {
        let name = default_name_for_fk(
            "posts",
            &["author_id".to_string()],
            "users",
            &["id".to_string()],
        );
        assert_eq!(name, "posts_author_id_fkey");
    }

    #[test]
    fn test_default_name_for_composite_fk_uses_first_column() {
        let name = default_name_for_fk(
            "order_lines",
            &["order_id".to_string(), "tenant_id".to_string()],
            "orders",
            &["id".to_string(), "tenant_id".to_string()],
        );
        assert_eq!(name, "order_lines_order_id_fkey");
    }

    #[test]
    fn test_default_name_for_unique() {
        let name = default_name_for_unique("users", &["email".to_string()]);
        assert_eq!(name, "users_email_key");
    }

    #[test]
    fn test_default_name_for_index() {
        let name = default_name_for_index("users", &["email".to_string(), "name".to_string()]);
        assert_eq!(name, "users_email_name_idx");
    }

    #[test]
    fn test_parse_type_params() {
        assert_eq!(
            parse_type_params("varchar(255)"),
            Some(("255".to_string(), None))
        );
        assert_eq!(
            parse_type_params("numeric(10,2)"),
            Some(("10".to_string(), Some("2".to_string())))
        );
        assert_eq!(parse_type_params("text"), None);
    }

    #[test]
    fn test_is_system_namespace() {
        assert!(is_system_namespace("pg_catalog"));
        assert!(is_system_namespace("pg_toast_12345"));
        assert!(!is_system_namespace("public"));
        assert!(!is_system_namespace("myschema"));
    }

    #[test]
    fn test_identity_defaults() {
        assert_eq!(IdentityDefaults::max_for("smallint"), "32767");
        assert_eq!(IdentityDefaults::max_for("integer"), "2147483647");
        assert_eq!(IdentityDefaults::max_for("bigint"), "9223372036854775807");
    }

    #[test]
    fn test_from_sql_type_serial_vs_integer() {
        // These must NOT be classified as serial
        assert_eq!(
            PgTypeCategory::from_sql_type("integer"),
            PgTypeCategory::Integer
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("int"),
            PgTypeCategory::Integer
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("int4"),
            PgTypeCategory::Integer
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("bigint"),
            PgTypeCategory::BigInt
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("int8"),
            PgTypeCategory::BigInt
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("smallint"),
            PgTypeCategory::SmallInt
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("int2"),
            PgTypeCategory::SmallInt
        );

        // These must be serial
        assert_eq!(
            PgTypeCategory::from_sql_type("serial"),
            PgTypeCategory::Serial
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("SERIAL"),
            PgTypeCategory::Serial
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("bigserial"),
            PgTypeCategory::BigSerial
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("smallserial"),
            PgTypeCategory::SmallSerial
        );

        assert!(PgTypeCategory::Serial.is_serial());
        assert!(PgTypeCategory::BigSerial.is_serial());
        assert!(PgTypeCategory::SmallSerial.is_serial());
        assert!(!PgTypeCategory::Integer.is_serial());
        assert!(!PgTypeCategory::BigInt.is_serial());
    }

    #[test]
    fn test_from_sql_type_common() {
        assert_eq!(PgTypeCategory::from_sql_type("text"), PgTypeCategory::Text);
        assert_eq!(
            PgTypeCategory::from_sql_type("varchar(255)"),
            PgTypeCategory::Varchar
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("boolean"),
            PgTypeCategory::Boolean
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("bool"),
            PgTypeCategory::Boolean
        );
        assert_eq!(PgTypeCategory::from_sql_type("uuid"), PgTypeCategory::Uuid);
        assert_eq!(
            PgTypeCategory::from_sql_type("jsonb"),
            PgTypeCategory::Jsonb
        );
        assert_eq!(PgTypeCategory::from_sql_type("json"), PgTypeCategory::Json);
        assert_eq!(
            PgTypeCategory::from_sql_type("timestamp with time zone"),
            PgTypeCategory::TimestampTz
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("timestamp without time zone"),
            PgTypeCategory::Timestamp
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("timestamp"),
            PgTypeCategory::Timestamp
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("time without time zone"),
            PgTypeCategory::Time
        );
        assert_eq!(PgTypeCategory::from_sql_type("date"), PgTypeCategory::Date);
        assert_eq!(
            PgTypeCategory::from_sql_type("numeric(10,2)"),
            PgTypeCategory::Numeric
        );
        assert_eq!(PgTypeCategory::from_sql_type("real"), PgTypeCategory::Real);
        assert_eq!(
            PgTypeCategory::from_sql_type("double precision"),
            PgTypeCategory::DoublePrecision
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("macaddr8"),
            PgTypeCategory::MacAddr8
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("macaddr"),
            PgTypeCategory::MacAddr
        );
    }

    #[test]
    fn test_from_sql_type_postgis_surface() {
        assert_eq!(
            PgTypeCategory::from_sql_type("geometry(point)"),
            PgTypeCategory::Geometry
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("geometry(point, 4326)"),
            PgTypeCategory::Geometry
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("geometry(polygon, 4326)"),
            PgTypeCategory::Custom
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("geography(point)"),
            PgTypeCategory::Custom
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("box2d"),
            PgTypeCategory::Custom
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("box3d"),
            PgTypeCategory::Custom
        );
        assert_eq!(
            PgTypeCategory::from_sql_type("raster"),
            PgTypeCategory::Custom
        );
    }

    #[test]
    fn test_extract_nextval_sequence() {
        assert_eq!(
            extract_nextval_sequence("nextval('users_id_seq'::regclass)"),
            Some("users_id_seq".to_string())
        );
        assert_eq!(
            extract_nextval_sequence("nextval('public.users_id_seq'::regclass)"),
            Some("users_id_seq".to_string())
        );
        assert_eq!(
            extract_nextval_sequence("nextval('\"myschema\".\"users_id_seq\"'::regclass)"),
            Some("users_id_seq".to_string())
        );
        assert_eq!(extract_nextval_sequence("not_a_nextval"), None);
        assert_eq!(extract_nextval_sequence("nextval(''::regclass)"), None);
    }
}