pg_tviews 0.1.0-beta.11

Transactional materialized views with incremental refresh for PostgreSQL
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
use std::fmt;

pub mod testing;

/// Main error type for `pg_tviews` extension
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TViewError {
    // ============ Metadata Errors (P0xxx) ============
    /// TVIEW metadata not found
    MetadataNotFound { entity: String },

    /// TVIEW already exists
    TViewAlreadyExists { name: String },

    /// Invalid TVIEW name format
    InvalidTViewName { name: String, reason: String },

    /// Invalid function input parameter
    InvalidInput { parameter: String, reason: String },

    // ============ Dependency Errors (55xxx) ============
    /// Circular dependency detected
    CircularDependency { cycle: Vec<String> },

    /// Maximum dependency depth exceeded
    DependencyDepthExceeded { depth: usize, max_depth: usize },

    /// Dependency resolution failed
    DependencyResolutionFailed { view_name: String, reason: String },

    // ============ SQL Parsing Errors (42xxx) ============
    /// Invalid SELECT statement
    InvalidSelectStatement { sql: String, reason: String },

    /// Required column missing
    RequiredColumnMissing {
        column_name: String,
        context: String,
    },

    /// Column type inference failed
    TypeInferenceFailed { column_name: String, reason: String },

    /// SQL parsing failed for cascade path extraction
    SqlParseError { reason: String },

    // ============ Extension Dependency Errors (58xxx) ============
    /// `jsonb_delta` extension not installed
    JsonbIvmNotInstalled,

    /// Extension version mismatch
    ExtensionVersionMismatch {
        extension: String,
        required: String,
        found: String,
    },

    // ============ Concurrency Errors (40xxx) ============
    /// Lock acquisition timeout
    LockTimeout { resource: String, timeout_ms: u64 },

    /// Deadlock detected
    DeadlockDetected { context: String },

    // ============ Refresh Errors (54xxx) ============
    /// Cascade depth limit exceeded
    CascadeDepthExceeded {
        current_depth: usize,
        max_depth: usize,
    },

    /// Refresh operation failed
    RefreshFailed {
        entity: String,
        pk_value: i64,
        reason: String,
    },

    /// Batch operation too large
    BatchTooLarge { size: usize, max_size: usize },

    // ============ Graph and Propagation Errors ============
    /// Dependency cycle detected in entity graph
    DependencyCycle { entities: Vec<String> },

    /// Propagation exceeded maximum depth (possible infinite loop)
    PropagationDepthExceeded { max_depth: usize, processed: usize },

    // ============ I/O and System Errors (XX000) ============
    /// `PostgreSQL` catalog operation failed
    CatalogError { operation: String, pg_error: String },

    /// SPI operation failed
    SpiError { query: String, error: String },

    /// Serialization/deserialization failed
    SerializationError { message: String },

    /// Configuration error (invalid GUC values)
    ConfigError {
        setting: String,
        value: String,
        reason: String,
    },

    /// Cache error (poisoned mutex, corruption)
    CacheError { cache_name: String, reason: String },

    /// FFI callback error (panic in C context)
    CallbackError {
        callback_name: String,
        error: String,
    },

    /// Metrics error (tracking failure)
    MetricsError { operation: String, error: String },

    /// Internal error (bug in extension)
    InternalError {
        message: String,
        file: &'static str,
        line: u32,
    },
}

impl TViewError {
    /// Get `PostgreSQL` SQLSTATE code for this error
    #[must_use]
    pub const fn sqlstate(&self) -> &'static str {
        match self {
            Self::MetadataNotFound { .. } => "P0001", // Raise exception
            Self::TViewAlreadyExists { .. } => "42710", // Duplicate object
            Self::InvalidTViewName { .. } => "42602", // Invalid name
            Self::InvalidInput { .. } => "22023",     // Invalid parameter value

            Self::CircularDependency { .. } | Self::DependencyCycle { .. } => "55P03", // Lock not available (cycle)
            Self::DependencyDepthExceeded { .. }
            | Self::CascadeDepthExceeded { .. }
            | Self::PropagationDepthExceeded { .. } => "54001", // Statement too complex
            Self::DependencyResolutionFailed { .. } => "55000", // Object not in prerequisite state

            Self::InvalidSelectStatement { .. } => "42601", // Syntax error
            Self::RequiredColumnMissing { .. } => "42703",  // Undefined column
            Self::TypeInferenceFailed { .. } => "42804",    // Datatype mismatch
            Self::SqlParseError { .. } => "42601",          // Syntax error

            Self::JsonbIvmNotInstalled | Self::ExtensionVersionMismatch { .. } => "58P01", // Undefined file (extension)

            Self::LockTimeout { .. } | Self::DeadlockDetected { .. } => "40P01", // Deadlock detected (timeout)

            Self::RefreshFailed { .. }
            | Self::CatalogError { .. }
            | Self::SpiError { .. }
            | Self::SerializationError { .. }
            | Self::ConfigError { .. }
            | Self::CacheError { .. }
            | Self::CallbackError { .. }
            | Self::MetricsError { .. }
            | Self::InternalError { .. } => "XX000", // Internal error
            Self::BatchTooLarge { .. } => "54000", // Program limit exceeded
        }
    }

    /// Create internal error with file/line info
    #[must_use]
    pub const fn internal(message: String, file: &'static str, line: u32) -> Self {
        Self::InternalError {
            message,
            file,
            line,
        }
    }
}

impl fmt::Display for TViewError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MetadataNotFound { entity } => {
                write!(f, "TVIEW metadata not found for entity '{entity}'")
            }
            Self::TViewAlreadyExists { name } => {
                write!(f, "TVIEW '{name}' already exists")
            }
            Self::InvalidTViewName { name, reason } => {
                write!(f, "Invalid TVIEW name '{name}': {reason}")
            }
            Self::InvalidInput { parameter, reason } => {
                write!(f, "Invalid input for parameter '{parameter}': {reason}")
            }
            Self::CircularDependency { cycle } => {
                write!(f, "Circular dependency detected: {}", cycle.join(" → "))
            }
            Self::DependencyDepthExceeded { depth, max_depth } => {
                write!(f, "Dependency depth {depth} exceeds maximum {max_depth}")
            }
            Self::DependencyResolutionFailed { view_name, reason } => {
                write!(
                    f,
                    "Failed to resolve dependencies for '{view_name}': {reason}"
                )
            }
            Self::InvalidSelectStatement { sql, reason } => {
                write!(
                    f,
                    "Invalid SELECT statement: {reason}\nSQL: {}",
                    if sql.len() > 100 { &sql[..100] } else { sql }
                )
            }
            Self::RequiredColumnMissing {
                column_name,
                context,
            } => {
                write!(f, "Required column '{column_name}' missing in {context}")
            }
            Self::TypeInferenceFailed {
                column_name,
                reason,
            } => {
                write!(
                    f,
                    "Failed to infer type for column '{column_name}': {reason}"
                )
            }
            Self::SqlParseError { reason } => {
                write!(f, "SQL parsing failed: {reason}")
            }
            Self::JsonbIvmNotInstalled => {
                write!(
                    f,
                    "Required extension 'jsonb_delta' is not installed. Run: CREATE EXTENSION jsonb_delta;"
                )
            }
            Self::ExtensionVersionMismatch {
                extension,
                required,
                found,
            } => {
                write!(
                    f,
                    "Extension '{extension}' version mismatch: required {required}, found {found}"
                )
            }
            Self::LockTimeout {
                resource,
                timeout_ms,
            } => {
                write!(
                    f,
                    "Lock timeout on resource '{resource}' after {timeout_ms}ms"
                )
            }
            Self::DeadlockDetected { context } => {
                write!(f, "Deadlock detected in {context}")
            }
            Self::CascadeDepthExceeded {
                current_depth,
                max_depth,
            } => {
                write!(
                    f,
                    "Cascade depth {current_depth} exceeds maximum {max_depth}. Possible infinite cascade loop."
                )
            }
            Self::RefreshFailed {
                entity,
                pk_value,
                reason,
            } => {
                write!(
                    f,
                    "Failed to refresh TVIEW '{entity}' row {pk_value}: {reason}"
                )
            }
            Self::BatchTooLarge { size, max_size } => {
                write!(f, "Batch size {size} exceeds maximum {max_size}")
            }
            Self::DependencyCycle { entities } => {
                write!(
                    f,
                    "Dependency cycle detected in entity graph: {}",
                    entities.join(" -> ")
                )
            }
            Self::PropagationDepthExceeded {
                max_depth,
                processed,
            } => {
                write!(
                    f,
                    "Propagation exceeded maximum depth of {max_depth} iterations ({processed} entities processed). \
                     Possible infinite loop or extremely deep dependency chain."
                )
            }
            Self::CatalogError {
                operation,
                pg_error,
            } => {
                write!(f, "Catalog operation '{operation}' failed: {pg_error}")
            }
            Self::SpiError { query, error } => {
                write!(
                    f,
                    "SPI query failed: {error}\nQuery: {}",
                    if query.len() > 100 {
                        &query[..100]
                    } else {
                        query
                    }
                )
            }
            Self::SerializationError { message } => {
                write!(f, "Serialization error: {message}")
            }
            Self::ConfigError {
                setting,
                value,
                reason,
            } => {
                write!(
                    f,
                    "Configuration error for '{setting}': {reason} (value: {value})"
                )
            }
            Self::CacheError { cache_name, reason } => {
                write!(f, "Cache '{cache_name}' error: {reason}")
            }
            Self::CallbackError {
                callback_name,
                error,
            } => {
                write!(f, "FFI callback '{callback_name}' failed: {error}")
            }
            Self::MetricsError { operation, error } => {
                write!(f, "Metrics operation '{operation}' failed: {error}")
            }
            Self::InternalError {
                message,
                file,
                line,
            } => {
                write!(
                    f,
                    "Internal error at {file}:{line}: {message}\nPlease report this bug."
                )
            }
        }
    }
}

impl std::error::Error for TViewError {}

/// Result type for TVIEW operations
pub type TViewResult<T> = Result<T, TViewError>;

/// Convert `SpiError` to `TViewError`
impl From<pgrx::spi::Error> for TViewError {
    fn from(e: pgrx::spi::Error) -> Self {
        Self::SpiError {
            query: "Unknown".to_string(),
            error: e.to_string(),
        }
    }
}

/// Convert `serde_json::Error` to `TViewError`
impl From<serde_json::Error> for TViewError {
    fn from(e: serde_json::Error) -> Self {
        Self::SerializationError {
            message: format!("JSON serialization error: {e}"),
        }
    }
}

/// Convert `bincode::Error` to `TViewError`
impl From<bincode::Error> for TViewError {
    fn from(e: bincode::Error) -> Self {
        Self::SerializationError {
            message: format!("Binary serialization error: {e}"),
        }
    }
}

/// Convert `regex::Error` to `TViewError`
impl From<regex::Error> for TViewError {
    fn from(e: regex::Error) -> Self {
        Self::InvalidSelectStatement {
            sql: "Unknown".to_string(),
            reason: format!("Regex compilation failed: {e}"),
        }
    }
}

/// Convert `std::io::Error` to `TViewError`
impl From<std::io::Error> for TViewError {
    fn from(e: std::io::Error) -> Self {
        Self::SerializationError {
            message: format!("I/O error: {e}"),
        }
    }
}

/// Convert `TViewError` to pgrx `SpiError` for use in SPI closures.
///
/// `pgrx::spi::SpiError` has no string-carrying variant, so the original
/// error detail cannot be preserved in the return value. We log it as a
/// PostgreSQL WARNING before converting so the message is not silently lost.
impl From<TViewError> for pgrx::spi::Error {
    fn from(e: TViewError) -> Self {
        pgrx::warning!("TViewError crossing SPI boundary (detail will be lost): {e}");
        Self::SpiError(pgrx::spi::SpiErrorCodes::OpUnknown)
    }
}

/// Helper macro for creating internal errors with automatic file/line
#[macro_export]
macro_rules! internal_error {
    ($msg:expr) => {
        TViewError::internal($msg.to_string(), file!(), line!())
    };
    ($fmt:expr, $($arg:tt)*) => {
        TViewError::internal(format!($fmt, $($arg)*), file!(), line!())
    };
}

/// Helper macro for requiring a value or returning error
#[macro_export]
macro_rules! require {
    ($opt:expr, $err:expr) => {
        match $opt {
            Some(v) => v,
            None => return Err($err),
        }
    };
}

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

    #[test]
    fn test_metadata_not_found_message() {
        let err = TViewError::MetadataNotFound {
            entity: "post".to_string(),
        };

        let msg = err.to_string();
        assert!(msg.contains("post"));
        assert!(msg.contains("not found"));
        assert_eq!(err.sqlstate(), "P0001");
    }

    #[test]
    fn test_circular_dependency_message() {
        let err = TViewError::CircularDependency {
            cycle: vec!["v_a".to_string(), "v_b".to_string(), "v_a".to_string()],
        };

        let msg = err.to_string();
        assert!(msg.contains("v_a → v_b → v_a"));
        assert_eq!(err.sqlstate(), "55P03");
    }

    #[test]
    fn test_internal_error_macro() {
        let err = internal_error!("Test error at {}", "location");

        match err {
            TViewError::InternalError {
                message,
                file,
                line,
            } => {
                assert!(message.contains("Test error"));
                assert!(file.ends_with("mod.rs"));
                assert!(line > 0);
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_all_error_sqlstates_unique() {
        let errors = vec![
            TViewError::MetadataNotFound {
                entity: "test".to_string(),
            },
            TViewError::TViewAlreadyExists {
                name: "test".to_string(),
            },
            TViewError::InvalidTViewName {
                name: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::InvalidInput {
                parameter: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::CircularDependency { cycle: vec![] },
            TViewError::DependencyDepthExceeded {
                depth: 1,
                max_depth: 1,
            },
            TViewError::DependencyResolutionFailed {
                view_name: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::InvalidSelectStatement {
                sql: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::RequiredColumnMissing {
                column_name: "test".to_string(),
                context: "test".to_string(),
            },
            TViewError::TypeInferenceFailed {
                column_name: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::JsonbIvmNotInstalled,
            TViewError::ExtensionVersionMismatch {
                extension: "test".to_string(),
                required: "1".to_string(),
                found: "2".to_string(),
            },
            TViewError::LockTimeout {
                resource: "test".to_string(),
                timeout_ms: 1000,
            },
            TViewError::DeadlockDetected {
                context: "test".to_string(),
            },
            TViewError::CascadeDepthExceeded {
                current_depth: 1,
                max_depth: 1,
            },
            TViewError::RefreshFailed {
                entity: "test".to_string(),
                pk_value: 1,
                reason: "test".to_string(),
            },
            TViewError::BatchTooLarge {
                size: 1,
                max_size: 1,
            },
            TViewError::CatalogError {
                operation: "test".to_string(),
                pg_error: "test".to_string(),
            },
            TViewError::SpiError {
                query: "test".to_string(),
                error: "test".to_string(),
            },
            TViewError::SerializationError {
                message: "test".to_string(),
            },
            TViewError::ConfigError {
                setting: "test".to_string(),
                value: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::CacheError {
                cache_name: "test".to_string(),
                reason: "test".to_string(),
            },
            TViewError::CallbackError {
                callback_name: "test".to_string(),
                error: "test".to_string(),
            },
            TViewError::MetricsError {
                operation: "test".to_string(),
                error: "test".to_string(),
            },
            TViewError::InternalError {
                message: "test".to_string(),
                file: "test",
                line: 1,
            },
        ];

        let sqlstates: Vec<&str> = errors.iter().map(TViewError::sqlstate).collect();
        let unique_sqlstates: std::collections::HashSet<&str> = sqlstates.iter().copied().collect();

        // All SQLSTATEs should be unique (though some may share codes intentionally)
        assert!(
            unique_sqlstates.len() >= 15,
            "Too many duplicate SQLSTATE codes"
        );
    }
}