ormer 0.2.11

A minimalist ORM framework that supports SQLite, PostgreSQL, MySQL, and SqlServer
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
use crate::abstract_layer::DbType;
use std::error::Error;
use std::fmt;

pub type Result<T> = std::result::Result<T, OrmerError>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstraintKind {
    Unique,
    ForeignKey,
    NotNull,
    Check,
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatabaseErrorKind {
    Constraint(ConstraintKind),
    SerializationFailure,
    Deadlock,
    Timeout,
    Connection,
    Other,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OrmerError {
    OptimisticLock {
        table: &'static str,
        column: &'static str,
    },
    Database {
        backend: DbType,
        kind: DatabaseErrorKind,
        code: Option<String>,
        constraint: Option<String>,
        message: String,
    },
    Decode {
        column: Option<String>,
        rust_type: Option<&'static str>,
        message: String,
    },
    Migration {
        message: String,
    },
    UnmigratableSchema {
        table: String,
        message: String,
    },
    Pool {
        backend: DbType,
        message: String,
    },
    Transaction {
        backend: DbType,
        message: String,
    },
    UnsupportedFeature {
        backend: DbType,
        feature: &'static str,
    },
    InvalidOperation {
        message: String,
    },
    Other {
        message: String,
    },
}

impl OrmerError {
    pub fn optimistic_lock(table: &'static str, column: &'static str) -> Self {
        Self::OptimisticLock { table, column }
    }

    pub fn other(message: impl Into<String>) -> Self {
        Self::Other {
            message: message.into(),
        }
    }

    pub fn decode(message: impl Into<String>) -> Self {
        Self::Decode {
            column: None,
            rust_type: None,
            message: message.into(),
        }
    }

    /// 带定位信息的解码错误(列名 + 目标 Rust 类型)。
    ///
    /// 供行/列解码失败路径迁移使用:相比裸 [`Self::decode`],调用方应尽量
    /// 传入列名与 `std::any::type_name` 等类型信息,避免解码错误退化为
    /// 无定位的 [`Self::Other`](`ormer_error!`)。
    pub fn decode_at(
        column: impl Into<String>,
        rust_type: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::Decode {
            column: Some(column.into()),
            rust_type: Some(rust_type),
            message: message.into(),
        }
    }

    pub fn migration(message: impl Into<String>) -> Self {
        Self::Migration {
            message: message.into(),
        }
    }

    /// 自动迁移无法就地演进的 schema(如主键变更、缺省值的非空新列)。
    /// 调用方通常以此决定是否删表重建;与普通迁移失败区分开。
    pub fn unmigratable_schema(table: impl Into<String>, message: impl Into<String>) -> Self {
        Self::UnmigratableSchema {
            table: table.into(),
            message: message.into(),
        }
    }

    pub fn is_unmigratable_schema(&self) -> bool {
        matches!(self, Self::UnmigratableSchema { .. })
    }

    pub fn invalid_operation(message: impl Into<String>) -> Self {
        Self::InvalidOperation {
            message: message.into(),
        }
    }

    pub fn context(self, context: impl fmt::Display) -> Self {
        Self::Other {
            message: format!("{context}: {self}"),
        }
    }

    pub fn is_unique_violation(&self, constraint: &str) -> bool {
        matches!(
            self,
            Self::Database {
                kind: DatabaseErrorKind::Constraint(ConstraintKind::Unique),
                constraint: Some(error_constraint),
                ..
            } if error_constraint == constraint
        )
    }

    pub fn is_unique_violation_any(&self) -> bool {
        matches!(
            self,
            Self::Database {
                kind: DatabaseErrorKind::Constraint(ConstraintKind::Unique),
                ..
            }
        )
    }

    pub fn is_retryable_transaction_error(&self) -> bool {
        matches!(
            self,
            Self::Database {
                kind: DatabaseErrorKind::SerializationFailure | DatabaseErrorKind::Deadlock,
                ..
            }
        )
    }

    pub(crate) fn from_external<E: Error>(context: &str, error: E) -> Self {
        let message = external_error_message(context, &error);
        let type_name = std::any::type_name::<E>();

        #[cfg(feature = "sqlite")]
        if type_name.contains("turso") {
            return Self::database(DbType::Sqlite, message);
        }
        #[cfg(feature = "postgresql")]
        if type_name.contains("tokio_postgres") || type_name.contains("bb8_postgres") {
            return Self::database(DbType::PostgreSQL, message);
        }
        #[cfg(feature = "mysql")]
        if type_name.contains("mysql_async") {
            return Self::database(DbType::MySQL, message);
        }
        #[cfg(feature = "mssql")]
        if type_name.contains("tiberius") {
            return Self::database(DbType::MSSQL, message);
        }
        #[cfg(feature = "clickhouse")]
        if type_name.contains("clickhouse") {
            return Self::database(DbType::ClickHouse, message);
        }
        #[cfg(feature = "influxdb")]
        if type_name.contains("reqwest") {
            return Self::database(DbType::InfluxDB, message);
        }
        #[cfg(feature = "duckdb")]
        if type_name.contains("duckdb") || type_name.contains("duckcompat") {
            return Self::database(DbType::DuckDB, message);
        }

        Self::other(message)
    }

    fn database(backend: DbType, message: String) -> Self {
        let (kind, code) = classify_database_error(&message);
        Self::Database {
            backend,
            kind,
            code,
            constraint: extract_constraint(&message),
            message,
        }
    }
}

impl fmt::Display for OrmerError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OptimisticLock { table, column } => {
                write!(formatter, "optimistic lock conflict on {table}.{column}")
            }
            Self::Database {
                backend,
                kind,
                code,
                constraint,
                message,
            } => {
                write!(
                    formatter,
                    "{} {}",
                    backend_name(*backend),
                    database_error_kind_name(*kind)
                )?;
                if let Some(constraint) = constraint {
                    write!(formatter, " constraint {constraint}")?;
                }
                if let Some(code) = code {
                    write!(formatter, " ({code})")?;
                }
                write!(formatter, ": {message}")
            }
            Self::Decode {
                column,
                rust_type,
                message,
            } => {
                formatter.write_str("decode error")?;
                if let Some(column) = column {
                    write!(formatter, " for column {column}")?;
                }
                if let Some(rust_type) = rust_type {
                    write!(formatter, " as {rust_type}")?;
                }
                write!(formatter, ": {message}")
            }
            Self::Migration { message } => write!(formatter, "migration error: {message}"),
            Self::UnmigratableSchema { table, message } => {
                write!(formatter, "unmigratable schema for table {table}: {message}")
            }
            Self::Pool { backend, message } => {
                write!(
                    formatter,
                    "{} connection pool error: {message}",
                    backend_name(*backend)
                )
            }
            Self::Transaction { backend, message } => {
                write!(
                    formatter,
                    "{} transaction error: {message}",
                    backend_name(*backend)
                )
            }
            Self::UnsupportedFeature { backend, feature } => {
                write!(
                    formatter,
                    "{} does not support {feature}",
                    backend_name(*backend)
                )
            }
            Self::InvalidOperation { message } | Self::Other { message } => {
                formatter.write_str(message)
            }
        }
    }
}

impl Error for OrmerError {}

impl From<chrono::ParseError> for OrmerError {
    fn from(error: chrono::ParseError) -> Self {
        Self::decode(error.to_string())
    }
}

impl From<serde_json::Error> for OrmerError {
    fn from(error: serde_json::Error) -> Self {
        Self::Decode {
            column: None,
            rust_type: Some("serde_json::Value"),
            message: error.to_string(),
        }
    }
}

impl From<std::io::Error> for OrmerError {
    fn from(error: std::io::Error) -> Self {
        Self::other(error.to_string())
    }
}

impl From<std::num::TryFromIntError> for OrmerError {
    fn from(error: std::num::TryFromIntError) -> Self {
        Self::decode(error.to_string())
    }
}

#[cfg(feature = "sqlite")]
impl From<turso::Error> for OrmerError {
    fn from(error: turso::Error) -> Self {
        Self::from_external("turso::Error", error)
    }
}

#[cfg(feature = "postgresql")]
impl From<tokio_postgres::Error> for OrmerError {
    fn from(error: tokio_postgres::Error) -> Self {
        Self::from_external("tokio_postgres::Error", error)
    }
}

#[cfg(feature = "postgresql")]
impl From<bb8::RunError<tokio_postgres::Error>> for OrmerError {
    fn from(error: bb8::RunError<tokio_postgres::Error>) -> Self {
        Self::Pool {
            backend: DbType::PostgreSQL,
            message: error.to_string(),
        }
    }
}

#[cfg(feature = "mysql")]
impl From<mysql_async::Error> for OrmerError {
    fn from(error: mysql_async::Error) -> Self {
        Self::from_external("mysql_async::Error", error)
    }
}

#[cfg(feature = "mssql")]
impl From<tiberius::error::Error> for OrmerError {
    fn from(error: tiberius::error::Error) -> Self {
        Self::from_external("tiberius::error::Error", error)
    }
}

#[cfg(feature = "clickhouse")]
impl From<clickhouse::error::Error> for OrmerError {
    fn from(error: clickhouse::error::Error) -> Self {
        Self::from_external("clickhouse::error::Error", error)
    }
}

#[cfg(feature = "duckdb")]
impl From<crate::abstract_layer::duckdb_backend::duckcompat::Error> for OrmerError {
    fn from(error: crate::abstract_layer::duckdb_backend::duckcompat::Error) -> Self {
        Self::from_external("duckdb::Error", error)
    }
}

fn backend_name(backend: DbType) -> &'static str {
    match backend {
        #[cfg(feature = "sqlite")]
        DbType::Sqlite => "SQLite",
        #[cfg(feature = "postgresql")]
        DbType::PostgreSQL => "PostgreSQL",
        #[cfg(feature = "questdb")]
        DbType::QuestDB => "QuestDB",
        #[cfg(feature = "mysql")]
        DbType::MySQL => "MySQL",
        #[cfg(feature = "mssql")]
        DbType::MSSQL => "MSSQL",
        #[cfg(feature = "duckdb")]
        DbType::DuckDB => "DuckDB",
        #[cfg(feature = "clickhouse")]
        DbType::ClickHouse => "ClickHouse",
        #[cfg(feature = "influxdb")]
        DbType::InfluxDB => "InfluxDB",
    }
}

fn database_error_kind_name(kind: DatabaseErrorKind) -> &'static str {
    match kind {
        DatabaseErrorKind::Constraint(ConstraintKind::Unique) => "unique constraint violation",
        DatabaseErrorKind::Constraint(ConstraintKind::ForeignKey) => "foreign key violation",
        DatabaseErrorKind::Constraint(ConstraintKind::NotNull) => "not-null violation",
        DatabaseErrorKind::Constraint(ConstraintKind::Check) => "check constraint violation",
        DatabaseErrorKind::Constraint(ConstraintKind::Other) => "constraint violation",
        DatabaseErrorKind::SerializationFailure => "serialization failure",
        DatabaseErrorKind::Deadlock => "deadlock",
        DatabaseErrorKind::Timeout => "timeout",
        DatabaseErrorKind::Connection => "connection error",
        DatabaseErrorKind::Other => "database error",
    }
}

fn classify_database_error(message: &str) -> (DatabaseErrorKind, Option<String>) {
    let lower = message.to_ascii_lowercase();
    let code = extract_code(message);
    let kind = if matches!(
        code.as_deref(),
        Some("23505") | Some("1062") | Some("2601") | Some("2627")
    ) || lower.contains("unique constraint failed")
        || lower.contains("duplicate key")
    {
        DatabaseErrorKind::Constraint(ConstraintKind::Unique)
    } else if matches!(code.as_deref(), Some("23503") | Some("1451") | Some("1452"))
        || lower.contains("foreign key constraint failed")
    {
        DatabaseErrorKind::Constraint(ConstraintKind::ForeignKey)
    } else if matches!(code.as_deref(), Some("23502") | Some("1048") | Some("515"))
        || lower.contains("not null constraint failed")
    {
        DatabaseErrorKind::Constraint(ConstraintKind::NotNull)
    } else if matches!(code.as_deref(), Some("23514") | Some("3819") | Some("4025"))
        || lower.contains("check constraint failed")
    {
        DatabaseErrorKind::Constraint(ConstraintKind::Check)
    } else if matches!(code.as_deref(), Some("40001")) || lower.contains("serialization failure") {
        DatabaseErrorKind::SerializationFailure
    } else if matches!(code.as_deref(), Some("40P01") | Some("1213")) || lower.contains("deadlock")
    {
        // 40P01(PG SQLSTATE,含字母)依赖 extract_code 的放宽规则按 code 命中;
        // 1213(MySQL 4 位厂商码)不会被提取为 code,由消息文本兜底。
        DatabaseErrorKind::Deadlock
    } else if matches!(code.as_deref(), Some("1205") | Some("1222")) || lower.contains("timeout") {
        DatabaseErrorKind::Timeout
    } else if lower.contains("connection") {
        DatabaseErrorKind::Connection
    } else if lower.contains("constraint") {
        DatabaseErrorKind::Constraint(ConstraintKind::Other)
    } else {
        DatabaseErrorKind::Other
    };
    (kind, code)
}

/// 从错误消息中提取 SQLSTATE 风格的错误码:5 位、首字符为数字的
/// 字母数字 token(标准 SQLSTATE 为 5 字符且类别位为数字,如 `23505`、
/// PG 死锁 `40P01`;首字符为数字可排除普通英文单词)。
///
/// 注意:MySQL/MSSQL 的 4 位厂商错误码(`1062`、`1213` 等)不符合该形状,
/// 不会被提取,`classify_database_error` 中对它们的 code 匹配仅作兜底记录,
/// 实际依赖消息文本("duplicate key"/"deadlock" 等)命中分类。
fn extract_code(message: &str) -> Option<String> {
    message
        .split(|character: char| !character.is_ascii_alphanumeric())
        .find(|word| word.len() == 5 && word.as_bytes()[0].is_ascii_digit())
        .map(str::to_string)
}

fn extract_constraint(message: &str) -> Option<String> {
    let marker = "constraint \"";
    let start = message.find(marker)? + marker.len();
    let end = message[start..].find('"')? + start;
    Some(message[start..end].to_string())
}

fn external_error_message(context: &str, error: &dyn Error) -> String {
    let error_message = error.to_string();
    if looks_traced(&error_message) {
        return format!("{context}->{error}");
    }

    let mut deepest = error;
    while let Some(source) = deepest.source() {
        deepest = source;
    }

    if std::ptr::eq(deepest, error) {
        format!("{context} failed: {error}")
    } else {
        format!("{context} failed: {deepest}")
    }
}

fn looks_traced(message: &str) -> bool {
    let Some(prefix) = message.split(" failed: ").next() else {
        return false;
    };
    if prefix.is_empty() {
        return false;
    }
    prefix
        .split("->")
        .all(|part| part.split("::").all(is_ident_like))
}

fn is_ident_like(part: &str) -> bool {
    let mut chars = part.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first == '_' || first.is_ascii_alphabetic())
        && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
}