iridium_core 0.1.12

SQL Server-compatible Rust engine core for Iridium SQL
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
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorClass {
    Parse,
    Semantic,
    Execution,
    Storage,
}

#[derive(Debug, Clone, Error)]
pub enum DbError {
    #[error("Incorrect syntax near '{0}'.")]
    Parse(String),

    #[error("{0}")]
    Semantic(String),

    #[error("execution error: {0}")]
    Execution(String),

    #[error("{0}")]
    Storage(String),

    #[error("Transaction (Process ID 0) was deadlocked on resources with another process and has been chosen as the deadlock victim. Rerun the transaction.")]
    Deadlock(String),

    /// A custom error with an explicit SQL Server–style class and number.
    /// Allows callers to raise domain-specific errors (e.g. timeout, permission)
    /// without modifying the DbError enum itself.
    #[error("{message}")]
    Custom {
        class: u8,
        number: i32,
        message: String,
    },

    // -- Strongly-typed semantic errors --
    #[error("Invalid schema name '{schema}'.")]
    SchemaNotFound { schema: String },

    #[error("Invalid object name '{table}'.")]
    TableNotFound { schema: String, table: String },

    #[error("Invalid column name '{column}'.")]
    ColumnNotFound { column: String },

    #[error("Invalid column name '{column}'.")]
    ColumnNotFoundQualified { table: String, column: String },

    #[error("Type mismatch: expected {expected}, found {found}")]
    TypeMismatch { expected: String, found: String },

    #[error("Index '{index}' not found on table '{table}'.")]
    IndexNotFound { table: String, index: String },

    #[error("Primary key not found on table '{table}'.")]
    PrimaryKeyNotFound { table: String },

    #[error("Constraint '{constraint}' not found on table '{table}'.")]
    ConstraintNotFound { table: String, constraint: String },

    #[error("Database '{database}' does not exist. Make sure that the name is entered correctly and try again.")]
    DatabaseNotFound { database: String },

    #[error("Invalid object name '{object}'.")]
    ObjectNotFound { object: String },

    #[error("Column names in each table must be unique. Column name '{column}' in table is specified more than once.")]
    DuplicateColumn { column: String },

    #[error("There is already an object named '{table}' in the database.")]
    DuplicateTable { schema: String, table: String },

    #[error("The identifier '{identifier}' is too long. Maximum length is 128.")]
    InvalidIdentifier { identifier: String },

    #[error("Invalid object name '{schema}.{trigger}'.")]
    TriggerNotFound { schema: String, trigger: String },

    #[error("There is already an object named '{trigger}' in the database.")]
    DuplicateTrigger { schema: String, trigger: String },

    #[error("Invalid object name '{schema}.{view}'.")]
    ViewNotFound { schema: String, view: String },

    #[error("There is already an object named '{view}' in the database.")]
    DuplicateView { schema: String, view: String },

    #[error("Type '{schema}.{type_name}' not found.")]
    TypeNotFound { schema: String, type_name: String },

    #[error("There is already an object named '{type_name}' in the database.")]
    DuplicateType { schema: String, type_name: String },

    #[error("There is already a schema named '{schema}' in the database.")]
    DuplicateSchema { schema: String },

    #[error("The cursor '{cursor}' does not exist.")]
    CursorNotDeclared { cursor: String },

    #[error("The cursor '{cursor}' has no query.")]
    CursorHasNoQuery { cursor: String },

    #[error("Divide by zero error encountered.")]
    DivideByZero,

    #[error(
        "Conversion failed when converting the {from_type} value '{value}' to data type {to_type}."
    )]
    ConversionFailed {
        from_type: String,
        value: String,
        to_type: String,
    },
}

impl DbError {
    pub fn class(&self) -> ErrorClass {
        match self {
            DbError::Parse(_) => ErrorClass::Parse,
            DbError::Semantic(_)
            | DbError::SchemaNotFound { .. }
            | DbError::TableNotFound { .. }
            | DbError::ColumnNotFound { .. }
            | DbError::ColumnNotFoundQualified { .. }
            | DbError::TypeMismatch { .. }
            | DbError::IndexNotFound { .. }
            | DbError::PrimaryKeyNotFound { .. }
            | DbError::ConstraintNotFound { .. }
            | DbError::DatabaseNotFound { .. }
            | DbError::ObjectNotFound { .. }
            | DbError::DuplicateColumn { .. }
            | DbError::DuplicateTable { .. }
            | DbError::InvalidIdentifier { .. }
            | DbError::TriggerNotFound { .. }
            | DbError::DuplicateTrigger { .. }
            | DbError::ViewNotFound { .. }
            | DbError::DuplicateView { .. }
            | DbError::TypeNotFound { .. }
            | DbError::DuplicateType { .. }
            | DbError::DuplicateSchema { .. }
            | DbError::CursorNotDeclared { .. }
            | DbError::CursorHasNoQuery { .. } => ErrorClass::Semantic,
            DbError::Execution(_)
            | DbError::Deadlock(_)
            | DbError::Custom { .. }
            | DbError::DivideByZero
            | DbError::ConversionFailed { .. } => ErrorClass::Execution,
            DbError::Storage(_) => ErrorClass::Storage,
        }
    }

    pub fn class_severity(&self) -> u8 {
        match self.class() {
            ErrorClass::Parse => 15,
            ErrorClass::Semantic => 16,
            ErrorClass::Execution => 16,
            ErrorClass::Storage => 17,
        }
    }

    pub fn number(&self) -> i32 {
        match self {
            DbError::Parse(_) => 102,
            DbError::SchemaNotFound { .. }
            | DbError::TableNotFound { .. }
            | DbError::ObjectNotFound { .. }
            | DbError::TriggerNotFound { .. }
            | DbError::ViewNotFound { .. } => 208, // Invalid object name
            DbError::ColumnNotFound { .. } | DbError::ColumnNotFoundQualified { .. } => 207, // Invalid column name
            DbError::DatabaseNotFound { .. } => 911,
            DbError::DuplicateTable { .. }
            | DbError::DuplicateTrigger { .. }
            | DbError::DuplicateView { .. }
            | DbError::DuplicateType { .. }
            | DbError::DuplicateSchema { .. } => 2714, // There is already an object named...
            DbError::DuplicateColumn { .. } => 2705,
            DbError::Deadlock(_) => 1205,
            DbError::CursorNotDeclared { .. } => 16916,
            DbError::DivideByZero => 8134,
            DbError::ConversionFailed { .. } => 245,
            DbError::Semantic(_) => 50000,
            DbError::Execution(_) => 50000,
            DbError::Storage(_) => 50001,
            DbError::Custom { number, .. } => *number,
            _ => 50000,
        }
    }

    pub fn code(&self) -> &'static str {
        match self {
            DbError::Parse(_) => "TSQL_PARSE_ERROR",
            DbError::Semantic(_) => "TSQL_SEMANTIC_ERROR",
            DbError::SchemaNotFound { .. } => "TSQL_SCHEMA_NOT_FOUND",
            DbError::TableNotFound { .. } => "TSQL_TABLE_NOT_FOUND",
            DbError::ColumnNotFound { .. } => "TSQL_COLUMN_NOT_FOUND",
            DbError::ColumnNotFoundQualified { .. } => "TSQL_COLUMN_NOT_FOUND_QUALIFIED",
            DbError::TypeMismatch { .. } => "TSQL_TYPE_MISMATCH",
            DbError::IndexNotFound { .. } => "TSQL_INDEX_NOT_FOUND",
            DbError::PrimaryKeyNotFound { .. } => "TSQL_PRIMARY_KEY_NOT_FOUND",
            DbError::ConstraintNotFound { .. } => "TSQL_CONSTRAINT_NOT_FOUND",
            DbError::DatabaseNotFound { .. } => "TSQL_DATABASE_NOT_FOUND",
            DbError::ObjectNotFound { .. } => "TSQL_OBJECT_NOT_FOUND",
            DbError::DuplicateColumn { .. } => "TSQL_DUPLICATE_COLUMN",
            DbError::DuplicateTable { .. } => "TSQL_DUPLICATE_TABLE",
            DbError::InvalidIdentifier { .. } => "TSQL_INVALID_IDENTIFIER",
            DbError::TriggerNotFound { .. } => "TSQL_TRIGGER_NOT_FOUND",
            DbError::DuplicateTrigger { .. } => "TSQL_DUPLICATE_TRIGGER",
            DbError::ViewNotFound { .. } => "TSQL_VIEW_NOT_FOUND",
            DbError::DuplicateView { .. } => "TSQL_DUPLICATE_VIEW",
            DbError::TypeNotFound { .. } => "TSQL_TYPE_NOT_FOUND",
            DbError::DuplicateType { .. } => "TSQL_DUPLICATE_TYPE",
            DbError::DuplicateSchema { .. } => "TSQL_DUPLICATE_SCHEMA",
            DbError::CursorNotDeclared { .. } => "TSQL_CURSOR_NOT_DECLARED",
            DbError::CursorHasNoQuery { .. } => "TSQL_CURSOR_HAS_NO_QUERY",
            DbError::DivideByZero => "TSQL_DIVIDE_BY_ZERO",
            DbError::ConversionFailed { .. } => "TSQL_CONVERSION_FAILED",
            DbError::Execution(_) => "TSQL_EXECUTION_ERROR",
            DbError::Storage(_) => "TSQL_STORAGE_ERROR",
            DbError::Deadlock(_) => "TSQL_DEADLOCK_ERROR",
            DbError::Custom { .. } => "TSQL_CUSTOM_ERROR",
        }
    }

    // -- Strongly-typed constructors --
    pub fn schema_not_found(schema: impl Into<String>) -> Self {
        DbError::SchemaNotFound {
            schema: schema.into(),
        }
    }

    pub fn table_not_found(schema: impl Into<String>, table: impl Into<String>) -> Self {
        DbError::TableNotFound {
            schema: schema.into(),
            table: table.into(),
        }
    }

    pub fn column_not_found(column: impl Into<String>) -> Self {
        DbError::ColumnNotFound {
            column: column.into(),
        }
    }

    pub fn column_not_found_qualified(table: impl Into<String>, column: impl Into<String>) -> Self {
        DbError::ColumnNotFoundQualified {
            table: table.into(),
            column: column.into(),
        }
    }

    pub fn type_mismatch(expected: impl Into<String>, found: impl Into<String>) -> Self {
        DbError::TypeMismatch {
            expected: expected.into(),
            found: found.into(),
        }
    }

    pub fn index_not_found(table: impl Into<String>, index: impl Into<String>) -> Self {
        DbError::IndexNotFound {
            table: table.into(),
            index: index.into(),
        }
    }

    pub fn primary_key_not_found(table: impl Into<String>) -> Self {
        DbError::PrimaryKeyNotFound {
            table: table.into(),
        }
    }

    pub fn constraint_not_found(table: impl Into<String>, constraint: impl Into<String>) -> Self {
        DbError::ConstraintNotFound {
            table: table.into(),
            constraint: constraint.into(),
        }
    }

    pub fn database_not_found(database: impl Into<String>) -> Self {
        DbError::DatabaseNotFound {
            database: database.into(),
        }
    }

    pub fn object_not_found(object: impl Into<String>) -> Self {
        DbError::ObjectNotFound {
            object: object.into(),
        }
    }

    pub fn duplicate_column(column: impl Into<String>) -> Self {
        DbError::DuplicateColumn {
            column: column.into(),
        }
    }

    pub fn duplicate_table(schema: impl Into<String>, table: impl Into<String>) -> Self {
        DbError::DuplicateTable {
            schema: schema.into(),
            table: table.into(),
        }
    }

    pub fn invalid_identifier(identifier: impl Into<String>) -> Self {
        DbError::InvalidIdentifier {
            identifier: identifier.into(),
        }
    }

    pub fn trigger_not_found(schema: impl Into<String>, trigger: impl Into<String>) -> Self {
        DbError::TriggerNotFound {
            schema: schema.into(),
            trigger: trigger.into(),
        }
    }

    pub fn duplicate_trigger(schema: impl Into<String>, trigger: impl Into<String>) -> Self {
        DbError::DuplicateTrigger {
            schema: schema.into(),
            trigger: trigger.into(),
        }
    }

    pub fn view_not_found(schema: impl Into<String>, view: impl Into<String>) -> Self {
        DbError::ViewNotFound {
            schema: schema.into(),
            view: view.into(),
        }
    }

    pub fn duplicate_view(schema: impl Into<String>, view: impl Into<String>) -> Self {
        DbError::DuplicateView {
            schema: schema.into(),
            view: view.into(),
        }
    }

    pub fn type_not_found(schema: impl Into<String>, type_name: impl Into<String>) -> Self {
        DbError::TypeNotFound {
            schema: schema.into(),
            type_name: type_name.into(),
        }
    }

    pub fn duplicate_type(schema: impl Into<String>, type_name: impl Into<String>) -> Self {
        DbError::DuplicateType {
            schema: schema.into(),
            type_name: type_name.into(),
        }
    }

    pub fn duplicate_schema(schema: impl Into<String>) -> Self {
        DbError::DuplicateSchema {
            schema: schema.into(),
        }
    }

    pub fn cursor_not_declared(cursor: impl Into<String>) -> Self {
        DbError::CursorNotDeclared {
            cursor: cursor.into(),
        }
    }

    pub fn cursor_has_no_query(cursor: impl Into<String>) -> Self {
        DbError::CursorHasNoQuery {
            cursor: cursor.into(),
        }
    }

    pub fn divide_by_zero() -> Self {
        DbError::DivideByZero
    }

    pub fn conversion_failed(
        from_type: impl Into<String>,
        value: impl Into<String>,
        to_type: impl Into<String>,
    ) -> Self {
        DbError::ConversionFailed {
            from_type: from_type.into(),
            value: value.into(),
            to_type: to_type.into(),
        }
    }
}

/// Represents the outcome of executing a SQL statement.
/// Control flow signals (BREAK, CONTINUE, RETURN) are modeled on the success path
/// rather than as error variants, preventing accidental swallowing by catch-all
/// error handlers and keeping TRY...CATCH semantics clean.
#[derive(Debug, Clone)]
pub enum StmtOutcome<T> {
    /// Statement completed normally.
    Ok(T),
    /// T-SQL BREAK statement inside a WHILE loop.
    Break,
    /// T-SQL CONTINUE statement inside a WHILE loop.
    Continue,
    /// T-SQL RETURN statement, optionally carrying a value (for functions/procedures).
    Return(Option<crate::types::Value>),
}

/// Convenience type alias for statement execution results.
pub type StmtResult<T> = Result<StmtOutcome<T>, DbError>;

impl<T> StmtOutcome<T> {
    /// Returns true if this is a normal completion (Ok).
    pub fn is_ok(&self) -> bool {
        matches!(self, StmtOutcome::Ok(_))
    }

    /// Returns true if this is any control flow signal.
    pub fn is_control_flow(&self) -> bool {
        !matches!(self, StmtOutcome::Ok(_))
    }

    /// Maps the Ok value using the given function, preserving control flow signals.
    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> StmtOutcome<U> {
        match self {
            StmtOutcome::Ok(v) => StmtOutcome::Ok(f(v)),
            StmtOutcome::Break => StmtOutcome::Break,
            StmtOutcome::Continue => StmtOutcome::Continue,
            StmtOutcome::Return(v) => StmtOutcome::Return(v),
        }
    }

    /// Converts a StmtOutcome into a Result, treating control flow signals as errors.
    /// This is used at boundaries where control flow signals should not escape
    /// (e.g., top-level statement execution outside loops/functions).
    pub fn into_result(self) -> Result<T, DbError> {
        match self {
            StmtOutcome::Ok(v) => Ok(v),
            StmtOutcome::Break => Err(DbError::Execution("BREAK outside of WHILE".into())),
            StmtOutcome::Continue => Err(DbError::Execution("CONTINUE outside of WHILE".into())),
            StmtOutcome::Return(_) => Err(DbError::Execution(
                "RETURN outside of procedure/function".into(),
            )),
        }
    }

    /// Converts a StmtOutcome into a Result, swallowing RETURN signals as Ok(None).
    /// Used at procedure/function boundaries where RETURN is expected.
    pub fn into_result_swallow_return(self) -> Result<T, DbError>
    where
        T: Default,
    {
        match self {
            StmtOutcome::Ok(v) => Ok(v),
            StmtOutcome::Break => Err(DbError::Execution("BREAK outside of WHILE".into())),
            StmtOutcome::Continue => Err(DbError::Execution("CONTINUE outside of WHILE".into())),
            StmtOutcome::Return(_) => Ok(T::default()),
        }
    }

    /// Returns the inner value if Ok, or the provided default.
    pub fn unwrap_or(self, default: T) -> T {
        match self {
            StmtOutcome::Ok(v) => v,
            _ => default,
        }
    }
}