drizzle-migrations 0.1.5

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
//! 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
pub fn default_name_for_pk(table: &str) -> String {
    format!("{}_pkey", table)
}

/// Generate default name for a foreign key constraint
pub fn default_name_for_fk(
    table: &str,
    columns: &[String],
    table_to: &str,
    columns_to: &[String],
) -> String {
    let desired = format!(
        "{}_{}_{}_{}_fkey",
        table,
        columns.join("_"),
        table_to,
        columns_to.join("_")
    );

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

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

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

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

/// Generate default name for a check constraint
pub fn default_name_for_check(table: &str, index: usize) -> String {
    format!("{}_check_{}", table, index)
}

/// Simple hash function for constraint naming
fn hash_string(s: &str) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);
    format!("{:x}", hasher.finish())[..12].to_string()
}

// =============================================================================
// 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 {
    /// Determine the type category for a SQL type string
    pub fn from_sql_type(sql_type: &str) -> Self {
        let normalized = sql_type.trim().to_lowercase();

        // Serial types (must check before integer)
        if is_match(&normalized, r"(?:smallserial)(?:\s.*)?") {
            return Self::SmallSerial;
        }
        if is_match(&normalized, r"(?:bigserial)(?:\s.*)?") {
            return Self::BigSerial;
        }
        if is_match(&normalized, r"(?:serial)(?:\s.*)?") {
            return Self::Serial;
        }

        // Integer types
        if is_match(&normalized, r"smallint(?:\s*\[\s*\])*") {
            return Self::SmallInt;
        }
        if is_match(&normalized, r"integer(?:\s*\[\s*\])*") {
            return Self::Integer;
        }
        if is_match(&normalized, r"bigint(?:\s*\[\s*\])*") {
            return Self::BigInt;
        }

        // Numeric types
        if is_match(
            &normalized,
            r"(?:numeric|decimal)(?:\(\d+(?:,\d+)?\))?(?:\s*\[\s*\])*",
        ) {
            return Self::Numeric;
        }
        if is_match(&normalized, r"real(?:\s*\[\s*\])*") {
            return Self::Real;
        }
        if is_match(&normalized, r"(?:double|double precision)(?:\s*\[\s*\])*") {
            return Self::DoublePrecision;
        }

        // Boolean
        if is_match(&normalized, r"boolean(?:\s*\[\s*\])*") {
            return Self::Boolean;
        }

        // String types
        if is_match(
            &normalized,
            r"(?:char|character)(?:\(\d+\))?(?:\s*\[\s*\])*",
        ) {
            return Self::Char;
        }
        if is_match(
            &normalized,
            r"(?:varchar|character varying)(?:\(\d+\))?(?:\s*\[\s*\])*",
        ) {
            return Self::Varchar;
        }
        if is_match(&normalized, r"text(?:\s*\[\s*\])*") {
            return Self::Text;
        }

        // JSON types
        if is_match(&normalized, r"jsonb(?:\s*\[\s*\])*") {
            return Self::Jsonb;
        }
        if is_match(&normalized, r"json(?:\s*\[\s*\])*") {
            return Self::Json;
        }

        // Time/Date types
        if is_match(&normalized, r"time(?:\(\d+\))?\s+with time zone(?:\[\])*") {
            return Self::TimeTz;
        }
        if is_match(&normalized, r"time(?:\(\d+\))?(?:\[\])*") {
            return Self::Time;
        }
        if is_match(
            &normalized,
            r"timestamp(?:\s)?(?:\(\d+\))?\s+with time zone(?:\[\])*",
        ) {
            return Self::TimestampTz;
        }
        if is_match(&normalized, r"timestamp(?:\s)?(?:\(\d+\))?(?:\[\])*") {
            return Self::Timestamp;
        }
        if is_match(&normalized, r"date(?:\s*\[\s*\])*") {
            return Self::Date;
        }

        // Other types
        if is_match(&normalized, r"uuid(?:\s*\[\s*\])*") {
            return Self::Uuid;
        }
        if is_match(
            &normalized,
            r"interval(\s+(year|month|day|hour|minute|second)(\s+to\s+(month|day|hour|minute|second))?)?(?:\(\d+\))?(?:\s*\[\s*\])*",
        ) {
            return Self::Interval;
        }
        if is_match(&normalized, r"inet(?:\(\d+\))?(?:\[\])?") {
            return Self::Inet;
        }
        if is_match(&normalized, r"cidr(?:\(\d+\))?(?:\[\])?") {
            return Self::Cidr;
        }
        if is_match(&normalized, r"macaddr(?:\s*\[\s*\])*") {
            return Self::MacAddr;
        }
        if is_match(&normalized, r"macaddr8(?:\s*\[\s*\])*") {
            return Self::MacAddr8;
        }

        // Vector types
        if is_match(&normalized, r"vector(?:\(\d+\))?(?:\s*\[\s*\])*") {
            return Self::Vector;
        }
        if is_match(&normalized, r"halfvec(?:\(\d+(?:,\d+)?\))?(?:\s*\[\s*\])*") {
            return Self::HalfVec;
        }
        if is_match(
            &normalized,
            r"sparsevec(?:\(\d+(?:,\d+)?\))?(?:\s*\[\s*\])*",
        ) {
            return Self::SparseVec;
        }

        // Bit type
        if is_match(&normalized, r"bit(?:\(\d+(?:,\d+)?\))?(?:\s*\[\s*\])*") {
            return Self::Bit;
        }

        // Geometric types
        if is_match(&normalized, r"point(?:\s*\[\s*\])*") {
            return Self::Point;
        }
        if is_match(&normalized, r"line(?:\s*\[\s*\])*") {
            return Self::Line;
        }
        if is_match(&normalized, r"geometry\(point(?:,\d+)?\)(?:\[\s*\])*") {
            return Self::Geometry;
        }

        Self::Custom
    }

    /// Get the drizzle import name for this type
    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
    pub const fn is_serial(&self) -> bool {
        matches!(self, Self::Serial | Self::SmallSerial | Self::BigSerial)
    }
}

/// Simple pattern matching helper (basic implementation without regex dependency)
fn is_match(s: &str, _pattern: &str) -> bool {
    // Simplified matching - in production, use regex crate
    // For now, we do basic string checks
    let s = s.trim();

    // Handle common cases directly
    if s.starts_with("smallint") {
        return true;
    }
    if s.starts_with("integer") || s == "int" {
        return true;
    }
    if s.starts_with("bigint") {
        return true;
    }
    if s.starts_with("numeric") || s.starts_with("decimal") {
        return true;
    }
    if s.starts_with("real") {
        return true;
    }
    if s.starts_with("double") {
        return true;
    }
    if s.starts_with("boolean") || s == "bool" {
        return true;
    }
    if s.starts_with("char") || s.starts_with("character") {
        return true;
    }
    if s.starts_with("varchar") || s.starts_with("character varying") {
        return true;
    }
    if s.starts_with("text") {
        return true;
    }
    if s.starts_with("json") {
        return true;
    }
    if s.starts_with("time") {
        return true;
    }
    if s.starts_with("timestamp") {
        return true;
    }
    if s.starts_with("date") {
        return true;
    }
    if s.starts_with("uuid") {
        return true;
    }
    if s.starts_with("interval") {
        return true;
    }
    if s.starts_with("inet") {
        return true;
    }
    if s.starts_with("cidr") {
        return true;
    }
    if s.starts_with("macaddr") {
        return true;
    }
    if s.starts_with("vector") || s.starts_with("halfvec") || s.starts_with("sparsevec") {
        return true;
    }
    if s.starts_with("bit") {
        return true;
    }
    if s.starts_with("point") || s.starts_with("line") || s.starts_with("geometry") {
        return true;
    }
    if s.starts_with("serial") || s.starts_with("smallserial") || s.starts_with("bigserial") {
        return true;
    }

    false
}

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

/// Extract parameters from a type like "varchar(255)" or "numeric(10,2)"
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(|s| s.trim()).collect();
    match parts.len() {
        1 => Some((parts[0].to_string(), None)),
        2 => Some((parts[0].to_string(), Some(parts[1].to_string()))),
        _ => None,
    }
}

/// Split SQL type into base type and options
pub fn split_sql_type(sql_type: &str) -> (String, Option<String>) {
    let normalized = sql_type.replace("[]", "");

    if let Some(start) = normalized.find('(')
        && let Some(end) = normalized.find(')')
    {
        let base = normalized[..start].trim().to_string();
        let options = normalized[start + 1..end].replace(", ", ",");
        return (base, Some(options));
    }

    (normalized.trim().to_string(), None)
}

/// Trim a character from both ends of a string
pub fn trim_char(s: &str, c: char) -> &str {
    s.trim_start_matches(c).trim_end_matches(c)
}

/// Check if a string is a serial expression
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)"))
}

// =============================================================================
// 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
    pub fn max_for(column_type: &str) -> &'static str {
        match column_type {
            "smallint" => "32767",
            "integer" => "2147483647",
            "bigint" => "9223372036854775807",
            _ => "2147483647", // Default to integer
        }
    }

    /// Get the minimum value for an identity column based on type
    pub fn min_for(column_type: &str) -> &'static str {
        match column_type {
            "smallint" => "-32768",
            "integer" => "-2147483648",
            "bigint" => "-9223372036854775808",
            _ => "-2147483648", // Default to integer
        }
    }
}

// =============================================================================
// 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
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
pub fn is_system_role(name: &str) -> bool {
    name == "postgres" || name.starts_with("pg_")
}

/// Check if an action is the default (NO ACTION)
pub fn is_default_action(action: &str) -> bool {
    action.eq_ignore_ascii_case("no action")
}

// =============================================================================
// 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
pub fn parse_check_definition(value: &str) -> String {
    value
        .trim_start_matches("CHECK ((")
        .trim_end_matches("))")
        .to_string()
}

/// Parse a VIEW definition
pub fn parse_view_definition(value: Option<&str>) -> Option<String> {
    value.map(|v| {
        v.split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
            .trim_end_matches(';')
            .to_string()
    })
}

/// Parse ON DELETE/UPDATE action from PostgreSQL code
pub fn parse_on_type(code: &str) -> &'static str {
    match code {
        "a" => "NO ACTION",
        "r" => "RESTRICT",
        "n" => "SET NULL",
        "c" => "CASCADE",
        "d" => "SET DEFAULT",
        _ => "NO ACTION",
    }
}

#[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_users_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");
    }
}