loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! SQL 执行链路记录与 SQLx 错误映射。

use std::collections::BTreeMap;

use serde::Serialize;
use serde_json::Value;

/// SQL 执行方式。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SqlExecutionMethod {
    /// 只执行语句并返回影响行数。
    Execute,
    /// 读取所有结果行。
    FetchAll,
    /// 读取可选的第一行。
    FetchOptional,
    /// 读取必须存在的第一行。
    FetchOne,
}

/// SQL 执行结果。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SqlExecutionOutcome {
    /// SQL 执行且结果校验成功。
    Success,
    /// SQLx 返回执行错误。
    Failure,
    /// SQL 执行成功,但影响行数或可选结果不符合业务要求。
    BusinessFailure,
}

/// SQL 执行失败的服务端诊断。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct SqlExecutionError {
    /// 稳定的错误分类。
    pub class: String,
    /// 数据库或结果校验返回的原始错误。
    pub message: String,
    /// 数据库错误码。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    /// 约束或索引名称。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraint: Option<String>,
}

/// 一次 SQL 执行的结构化链路记录。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct SqlExecution {
    /// 当前请求中递增的 SQL 执行编号。
    pub execution_id: u64,
    /// 稳定的查询名称。
    pub query_name: String,
    /// SQL 操作类别。
    pub operation: super::SqlOperation,
    /// SQL 执行方式。
    pub method: SqlExecutionMethod,
    /// 带占位符的 SQL 模板。
    pub statement: String,
    /// 执行结果。
    pub outcome: SqlExecutionOutcome,
    /// 数据库等待及结果解析耗时,单位为毫秒。
    pub elapsed_ms: f64,
    /// `execute` 返回的影响行数。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rows_affected: Option<u64>,
    /// `fetch_*` 返回的结果行数。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rows_returned: Option<usize>,
    /// 已确认可以写入日志的参数。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub safe_parameters: BTreeMap<String, Value>,
    /// 失败诊断。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<SqlExecutionError>,
    /// 最终返回给客户端的业务错误码。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_error_code: Option<u32>,
}

impl SqlExecution {
    /// 返回该记录是否表示 SQL 或业务结果失败。
    #[must_use]
    pub const fn is_failure(&self) -> bool {
        matches!(
            self.outcome,
            SqlExecutionOutcome::Failure | SqlExecutionOutcome::BusinessFailure
        )
    }
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
mod sqlx_support {
    use std::{
        borrow::Cow,
        collections::BTreeMap,
        fmt::Display,
        future::Future,
        time::{Duration, Instant},
    };

    use serde::Serialize;
    use serde_json::Value;

    use super::{SqlExecution, SqlExecutionError, SqlExecutionMethod, SqlExecutionOutcome};
    use crate::{
        observability::{
            RequestLogContext, SqlDiagnostic, SqlOperation,
            bounded_json::{BoundedJsonValue, to_bounded_json_value},
            diagnostic::{
                MAX_DETAIL_FIELDS, MAX_DETAIL_JSON_BYTES, MAX_DETAIL_STRING_BYTES, MAX_ERROR_BYTES,
                MAX_NAME_BYTES, MAX_STATEMENT_BYTES, bound_json_value, bounded_display,
                truncate_owned,
            },
            sqlx_capture::{SqlxQueryEvent, capture_sqlx_query},
        },
        web::response::{ApiError, SqlErrorClass, default_sqlx_api_error},
    };

    #[derive(Debug)]
    struct SqlLogMetadata {
        query_name: Cow<'static, str>,
        operation: SqlOperation,
        statement: Cow<'static, str>,
        safe_parameters: BTreeMap<String, Value>,
        class_errors: BTreeMap<SqlErrorClass, ApiError>,
        constraint_errors: BTreeMap<String, ApiError>,
        fallback_error: Option<ApiError>,
        zero_rows_error: Option<ApiError>,
        none_error: Option<ApiError>,
    }

    impl SqlLogMetadata {
        fn captured(query_name: impl Into<Cow<'static, str>>) -> Self {
            Self {
                query_name: query_name.into(),
                operation: SqlOperation::Other,
                statement: Cow::Borrowed(""),
                safe_parameters: BTreeMap::new(),
                class_errors: BTreeMap::new(),
                constraint_errors: BTreeMap::new(),
                fallback_error: None,
                zero_rows_error: None,
                none_error: None,
            }
        }

        fn with_safe_parameter(mut self, key: impl Into<String>, value: impl Display) -> Self {
            let key = truncate_owned(key.into(), MAX_NAME_BYTES);
            if !self.safe_parameters.contains_key(&key)
                && self.safe_parameters.len() >= MAX_DETAIL_FIELDS
            {
                return self;
            }
            self.safe_parameters.insert(
                key,
                Value::String(bounded_display(&value, MAX_DETAIL_STRING_BYTES)),
            );
            self
        }

        fn with_safe_json_parameter<T>(
            mut self,
            key: impl Into<String>,
            value: T,
        ) -> Result<Self, serde_json::Error>
        where
            T: Serialize,
        {
            let key = truncate_owned(key.into(), MAX_NAME_BYTES);
            if !self.safe_parameters.contains_key(&key)
                && self.safe_parameters.len() >= MAX_DETAIL_FIELDS
            {
                return Ok(self);
            }
            let value = match to_bounded_json_value(&value, MAX_DETAIL_JSON_BYTES)? {
                BoundedJsonValue::Value(mut value) => {
                    bound_json_value(&mut value, 0);
                    value
                }
                BoundedJsonValue::TooLarge => Value::String("内容过大,已省略".into()),
            };
            self.safe_parameters.insert(key, value);
            Ok(self)
        }

        fn on_error(mut self, class: SqlErrorClass, error: ApiError) -> Self {
            self.class_errors.insert(class, error);
            self
        }

        fn on_constraint(mut self, constraint: impl Into<String>, error: ApiError) -> Self {
            if self.constraint_errors.len() < MAX_DETAIL_FIELDS {
                self.constraint_errors
                    .insert(truncate_owned(constraint.into(), MAX_NAME_BYTES), error);
            }
            self
        }

        fn api_error(mut self, error: ApiError) -> Self {
            self.fallback_error = Some(error);
            self
        }

        fn not_found(self, message: impl Into<String>) -> Self {
            self.on_error(SqlErrorClass::NotFound, ApiError::err_not_found(message))
        }

        fn unique_conflict(self, message: impl Into<String>) -> Self {
            self.on_error(
                SqlErrorClass::UniqueViolation,
                ApiError::err_unique_index_conflict(message),
            )
        }

        fn foreign_key_conflict(self, message: impl Into<String>) -> Self {
            self.on_error(
                SqlErrorClass::ForeignKeyViolation,
                ApiError::err_foreign_key_conflict(message),
            )
        }

        fn check_conflict(self, message: impl Into<String>) -> Self {
            self.on_error(
                SqlErrorClass::CheckViolation,
                ApiError::err_constraint_conflict(message),
            )
        }

        fn not_found_if_zero(mut self, message: impl Into<String>) -> Self {
            self.zero_rows_error = Some(ApiError::err_not_found(message));
            self
        }

        fn not_found_if_none(mut self, message: impl Into<String>) -> Self {
            self.none_error = Some(ApiError::err_not_found(message));
            self
        }

        fn take_api_error(
            &mut self,
            source: &sqlx::Error,
            class: SqlErrorClass,
            constraint: Option<&str>,
        ) -> ApiError {
            if let Some(constraint) = constraint
                && let Some(error) = self.constraint_errors.remove(constraint)
            {
                return error;
            }
            self.class_errors
                .remove(&class)
                .or_else(|| self.fallback_error.take())
                .unwrap_or_else(|| default_sqlx_api_error(source))
        }

        fn apply_captured_event(&mut self, event: &SqlxQueryEvent) {
            if let Some(statement) = &event.statement {
                if matches!(self.operation, SqlOperation::Other) {
                    self.operation = infer_sql_operation(statement);
                }
                self.statement = Cow::Owned(statement.clone());
            }
        }

        fn sql_diagnostic(
            &self,
            source: &sqlx::Error,
            code: Option<&str>,
            constraint: Option<&str>,
        ) -> SqlDiagnostic {
            let mut diagnostic = SqlDiagnostic::new(
                self.query_name.as_ref(),
                self.operation,
                self.statement.as_ref(),
                source,
            );
            diagnostic.safe_parameters = self.safe_parameters.clone();
            diagnostic.error_code = code.map(ToOwned::to_owned);
            diagnostic.constraint = constraint.map(ToOwned::to_owned);
            diagnostic
        }

        fn business_diagnostic(&self, reason: &str) -> SqlDiagnostic {
            let mut diagnostic = SqlDiagnostic::new(
                self.query_name.as_ref(),
                self.operation,
                self.statement.as_ref(),
                reason,
            );
            diagnostic.safe_parameters = self.safe_parameters.clone();
            diagnostic
        }

        #[allow(clippy::too_many_arguments)]
        fn into_execution(
            self,
            method: SqlExecutionMethod,
            outcome: SqlExecutionOutcome,
            elapsed: std::time::Duration,
            rows_affected: Option<u64>,
            rows_returned: Option<usize>,
            error: Option<SqlExecutionError>,
            api_error_code: Option<u32>,
        ) -> SqlExecution {
            SqlExecution {
                execution_id: 0,
                query_name: bounded_display(self.query_name.as_ref(), MAX_NAME_BYTES),
                operation: self.operation,
                method,
                statement: bounded_display(self.statement.as_ref(), MAX_STATEMENT_BYTES),
                outcome,
                elapsed_ms: elapsed.as_secs_f64() * 1_000.0,
                rows_affected,
                rows_returned,
                safe_parameters: self.safe_parameters,
                error,
                api_error_code,
            }
        }
    }

    /// 已配置日志与错误策略、等待执行的 SQLx 查询。
    #[must_use = "需要调用 execute 或 fetch_* 执行查询"]
    pub struct LoggedSql<Q> {
        query: Q,
        trace: SqlLogMetadata,
        record_success: bool,
        record_failure: bool,
    }

    impl<Q> LoggedSql<Q> {
        fn new(query: Q, query_name: impl Into<Cow<'static, str>>) -> Self {
            Self {
                query,
                trace: SqlLogMetadata::captured(query_name),
                record_success: false,
                record_failure: false,
            }
        }

        /// 无论成功或失败都记录 SQL 模板、数据库执行耗时和行数。
        ///
        /// SQL 来自 SQLx 实际执行时发出的 `sqlx::query` 事件,不需要再次传入 SQL 常量。
        /// 执行失败时会同时记录错误详情。
        pub fn logger_sql(mut self) -> Self {
            self.record_success = true;
            self.record_failure = true;
            self
        }

        /// 仅在 SQL 执行失败时记录 SQL、耗时、行数和错误详情。
        pub fn logger_err(mut self) -> Self {
            self.record_failure = true;
            self
        }

        /// 设置稳定的查询名称。
        pub fn query_name(mut self, query_name: impl Into<Cow<'static, str>>) -> Self {
            self.trace.query_name = query_name.into();
            self
        }

        /// 显式设置 SQL 操作类型;默认从捕获到的语句推断。
        pub const fn operation(mut self, operation: SqlOperation) -> Self {
            self.trace.operation = operation;
            self
        }

        /// 为所有未被更具体规则匹配的 SQLx 错误设置自定义 API 错误。
        pub fn api_err(mut self, error: ApiError) -> Self {
            self.trace = self.trace.api_error(error);
            self
        }

        /// 为指定 SQL 错误分类设置自定义 API 错误。
        pub fn api_err_for(mut self, class: SqlErrorClass, error: ApiError) -> Self {
            self.trace = self.trace.on_error(class, error);
            self
        }

        /// 为指定约束或索引设置自定义 API 错误。
        pub fn api_err_for_constraint(
            mut self,
            constraint: impl Into<String>,
            error: ApiError,
        ) -> Self {
            self.trace = self.trace.on_constraint(constraint, error);
            self
        }

        /// 自定义未找到数据时返回的客户端提示。
        pub fn not_found(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.not_found(message);
            self
        }

        /// 自定义唯一索引冲突时返回的客户端提示。
        pub fn unique_conflict(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.unique_conflict(message);
            self
        }

        /// 自定义外键冲突时返回的客户端提示。
        pub fn foreign_key_conflict(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.foreign_key_conflict(message);
            self
        }

        /// 自定义检查约束冲突时返回的客户端提示。
        pub fn check_conflict(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.check_conflict(message);
            self
        }

        /// `execute` 影响 0 行时返回未找到错误。
        pub fn not_found_if_zero(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.not_found_if_zero(message);
            self
        }

        /// `fetch_optional` 返回 `None` 时返回未找到错误。
        pub fn not_found_if_none(mut self, message: impl Into<String>) -> Self {
            self.trace = self.trace.not_found_if_none(message);
            self
        }

        /// 添加已确认可以写入日志的字符串参数。
        pub fn with_safe_parameter(mut self, key: impl Into<String>, value: impl Display) -> Self {
            self.trace = self.trace.with_safe_parameter(key, value);
            self
        }

        /// 添加已确认可以写入日志的 JSON 参数。
        ///
        /// # Errors
        ///
        /// `value` 无法序列化为 JSON 时返回错误;超过字节上限时会安全省略。
        pub fn with_safe_json_parameter<T>(
            mut self,
            key: impl Into<String>,
            value: T,
        ) -> Result<Self, serde_json::Error>
        where
            T: Serialize,
        {
            self.trace = self.trace.with_safe_json_parameter(key, value)?;
            Ok(self)
        }

        fn default_operation(&mut self, operation: SqlOperation) {
            if matches!(self.trace.operation, SqlOperation::Other) {
                self.trace.operation = operation;
            }
        }
    }

    /// 为 SQLx 查询增加按需日志与 API 错误映射。
    pub trait SqlLoggerExt: Sized {
        /// 无论成功或失败都记录 SQL、耗时和行数;失败时同时记录错误详情。
        fn logger_sql(self, query_name: impl Into<Cow<'static, str>>) -> LoggedSql<Self> {
            LoggedSql::new(self, query_name).logger_sql()
        }

        /// 仅在 SQL 执行失败时记录 SQL、耗时、行数和错误详情。
        fn logger_err(self) -> LoggedSql<Self> {
            LoggedSql::new(self, "sqlx.query").logger_err()
        }

        /// 自定义返回给客户端的错误并记录执行失败;未配置时由工具库自动匹配。
        fn api_err(self, error: ApiError) -> LoggedSql<Self> {
            LoggedSql::new(self, "sqlx.query")
                .logger_err()
                .api_err(error)
        }
    }

    impl<'q, DB, A> SqlLoggerExt for sqlx::query::Query<'q, DB, A> where DB: sqlx::Database {}
    impl<'q, DB, O, A> SqlLoggerExt for sqlx::query::QueryAs<'q, DB, O, A> where DB: sqlx::Database {}
    impl<'q, DB, O, A> SqlLoggerExt for sqlx::query::QueryScalar<'q, DB, O, A> where DB: sqlx::Database {}
    impl<'q, DB, F, A> SqlLoggerExt for sqlx::query::Map<'q, DB, F, A> where DB: sqlx::Database {}

    struct SqlLogConfig {
        trace: SqlLogMetadata,
        record_success: bool,
        record_failure: bool,
    }

    impl<Q> LoggedSql<Q> {
        fn into_parts(self) -> (Q, SqlLogConfig) {
            (
                self.query,
                SqlLogConfig {
                    trace: self.trace,
                    record_success: self.record_success,
                    record_failure: self.record_failure,
                },
            )
        }
    }

    impl<'q, DB, A> LoggedSql<sqlx::query::Query<'q, DB, A>>
    where
        DB: sqlx::Database,
        A: 'q + Send + sqlx::IntoArguments<DB>,
    {
        /// 执行语句并应用已配置的日志与错误策略。
        pub async fn execute<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<DB::QueryResult, ApiError>
        where
            'q: 'e,
            A: 'e,
            E: sqlx::Executor<'c, Database = DB>,
        {
            self.default_operation(SqlOperation::Other);
            let (query, config) = self.into_parts();
            run_logged_execute(query.execute(executor), config).await
        }

        /// 读取所有结果行并应用已配置的日志与错误策略。
        pub async fn fetch_all<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<Vec<DB::Row>, ApiError>
        where
            'q: 'e,
            A: 'e,
            E: sqlx::Executor<'c, Database = DB>,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_all(query.fetch_all(executor), config).await
        }

        /// 读取可选的第一行并应用已配置的日志与错误策略。
        pub async fn fetch_optional<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<Option<DB::Row>, ApiError>
        where
            'q: 'e,
            A: 'e,
            E: sqlx::Executor<'c, Database = DB>,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_optional(query.fetch_optional(executor), config).await
        }

        /// 读取必须存在的第一行并应用已配置的日志与错误策略。
        pub async fn fetch_one<'e, 'c: 'e, E>(mut self, executor: E) -> Result<DB::Row, ApiError>
        where
            'q: 'e,
            A: 'e,
            E: sqlx::Executor<'c, Database = DB>,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_one(query.fetch_one(executor), config).await
        }
    }

    impl<'q, DB, O, A> LoggedSql<sqlx::query::QueryAs<'q, DB, O, A>>
    where
        DB: sqlx::Database,
        A: 'q + sqlx::IntoArguments<DB>,
        O: Send + Unpin + for<'r> sqlx::FromRow<'r, DB::Row>,
    {
        /// 读取所有映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_all<'e, 'c: 'e, E>(mut self, executor: E) -> Result<Vec<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            O: 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_all(query.fetch_all(executor), config).await
        }

        /// 读取可选的第一条映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_optional<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<Option<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            O: 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_optional(query.fetch_optional(executor), config).await
        }

        /// 读取必须存在的第一条映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_one<'e, 'c: 'e, E>(mut self, executor: E) -> Result<O, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            O: 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_one(query.fetch_one(executor), config).await
        }
    }

    impl<'q, DB, O, A> LoggedSql<sqlx::query::QueryScalar<'q, DB, O, A>>
    where
        DB: sqlx::Database,
        O: Send + Unpin,
        A: 'q + sqlx::IntoArguments<DB>,
        (O,): Send + Unpin + for<'r> sqlx::FromRow<'r, DB::Row>,
    {
        /// 读取所有标量结果并应用已配置的日志与错误策略。
        pub async fn fetch_all<'e, 'c: 'e, E>(mut self, executor: E) -> Result<Vec<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            (O,): 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_all(query.fetch_all(executor), config).await
        }

        /// 读取可选的第一条标量结果并应用已配置的日志与错误策略。
        pub async fn fetch_optional<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<Option<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            O: 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_optional(query.fetch_optional(executor), config).await
        }

        /// 读取必须存在的第一条标量结果并应用已配置的日志与错误策略。
        pub async fn fetch_one<'e, 'c: 'e, E>(mut self, executor: E) -> Result<O, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            O: 'e,
            A: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_one(query.fetch_one(executor), config).await
        }
    }

    impl<'q, DB, F, O, A> LoggedSql<sqlx::query::Map<'q, DB, F, A>>
    where
        DB: sqlx::Database,
        F: FnMut(DB::Row) -> Result<O, sqlx::Error> + Send,
        O: Send + Unpin,
        A: 'q + Send + sqlx::IntoArguments<DB>,
    {
        /// 读取所有自定义映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_all<'e, 'c: 'e, E>(mut self, executor: E) -> Result<Vec<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            F: 'e,
            O: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_all(query.fetch_all(executor), config).await
        }

        /// 读取可选的第一条自定义映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_optional<'e, 'c: 'e, E>(
            mut self,
            executor: E,
        ) -> Result<Option<O>, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            F: 'e,
            O: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_optional(query.fetch_optional(executor), config).await
        }

        /// 读取必须存在的第一条自定义映射结果并应用已配置的日志与错误策略。
        pub async fn fetch_one<'e, 'c: 'e, E>(mut self, executor: E) -> Result<O, ApiError>
        where
            'q: 'e,
            E: 'e + sqlx::Executor<'c, Database = DB>,
            DB: 'e,
            F: 'e,
            O: 'e,
        {
            self.default_operation(SqlOperation::Select);
            let (query, config) = self.into_parts();
            run_logged_fetch_one(query.fetch_one(executor), config).await
        }
    }

    async fn await_logged<F>(
        future: F,
        capture_sql: bool,
    ) -> (F::Output, Option<SqlxQueryEvent>, Duration)
    where
        F: Future,
    {
        let started_at = Instant::now();
        let (output, event) = if capture_sql {
            capture_sqlx_query(future).await
        } else {
            (future.await, None)
        };
        (output, event, started_at.elapsed())
    }

    fn apply_captured_event(
        config: &mut SqlLogConfig,
        event: Option<SqlxQueryEvent>,
        fallback_elapsed: Duration,
    ) -> (Duration, Option<u64>, Option<usize>) {
        let Some(event) = event else {
            return (fallback_elapsed, None, None);
        };
        let elapsed = event
            .elapsed_secs
            .map(Duration::from_secs_f64)
            .unwrap_or(fallback_elapsed);
        let rows_affected = event.rows_affected;
        let rows_returned = event
            .rows_returned
            .and_then(|rows| usize::try_from(rows).ok());
        config.trace.apply_captured_event(&event);
        (elapsed, rows_affected, rows_returned)
    }

    async fn run_logged_execute<F, R>(future: F, mut config: SqlLogConfig) -> Result<R, ApiError>
    where
        F: Future<Output = Result<R, sqlx::Error>>,
    {
        let capture_sql = config.record_failure || config.trace.zero_rows_error.is_some();
        let (result, event, fallback_elapsed) = await_logged(future, capture_sql).await;
        let (elapsed, captured_rows_affected, captured_rows_returned) =
            apply_captured_event(&mut config, event, fallback_elapsed);
        match result {
            Ok(result) => {
                if captured_rows_affected == Some(0)
                    && let Some(error) = config.trace.zero_rows_error.take()
                {
                    return Err(finish_logged_business_failure(
                        config,
                        SqlExecutionMethod::Execute,
                        elapsed,
                        Some(0),
                        captured_rows_returned,
                        error,
                        "SQL 执行成功但影响行数为 0",
                    ));
                }
                if config.record_success {
                    record_execution(
                        config.trace,
                        SqlExecutionMethod::Execute,
                        SqlExecutionOutcome::Success,
                        elapsed,
                        captured_rows_affected,
                        captured_rows_returned,
                        None,
                        None,
                    );
                }
                Ok(result)
            }
            Err(source) => Err(finish_logged_sqlx_failure(
                config,
                SqlExecutionMethod::Execute,
                elapsed,
                captured_rows_affected,
                captured_rows_returned,
                source,
            )),
        }
    }

    async fn run_logged_fetch_all<F, T>(
        future: F,
        mut config: SqlLogConfig,
    ) -> Result<Vec<T>, ApiError>
    where
        F: Future<Output = Result<Vec<T>, sqlx::Error>>,
    {
        let (result, event, fallback_elapsed) = await_logged(future, config.record_failure).await;
        let (elapsed, rows_affected, captured_rows_returned) =
            apply_captured_event(&mut config, event, fallback_elapsed);
        match result {
            Ok(rows) => {
                if config.record_success {
                    record_execution(
                        config.trace,
                        SqlExecutionMethod::FetchAll,
                        SqlExecutionOutcome::Success,
                        elapsed,
                        rows_affected,
                        Some(rows.len()),
                        None,
                        None,
                    );
                }
                Ok(rows)
            }
            Err(source) => Err(finish_logged_sqlx_failure(
                config,
                SqlExecutionMethod::FetchAll,
                elapsed,
                rows_affected,
                captured_rows_returned,
                source,
            )),
        }
    }

    async fn run_logged_fetch_optional<F, T>(
        future: F,
        mut config: SqlLogConfig,
    ) -> Result<Option<T>, ApiError>
    where
        F: Future<Output = Result<Option<T>, sqlx::Error>>,
    {
        let (result, event, fallback_elapsed) = await_logged(future, config.record_failure).await;
        let (elapsed, rows_affected, captured_rows_returned) =
            apply_captured_event(&mut config, event, fallback_elapsed);
        match result {
            Ok(row) => {
                let rows_returned = usize::from(row.is_some());
                if row.is_none()
                    && let Some(error) = config.trace.none_error.take()
                {
                    return Err(finish_logged_business_failure(
                        config,
                        SqlExecutionMethod::FetchOptional,
                        elapsed,
                        rows_affected,
                        Some(0),
                        error,
                        "SQL 执行成功但没有返回数据",
                    ));
                }
                if config.record_success {
                    record_execution(
                        config.trace,
                        SqlExecutionMethod::FetchOptional,
                        SqlExecutionOutcome::Success,
                        elapsed,
                        rows_affected,
                        Some(rows_returned),
                        None,
                        None,
                    );
                }
                Ok(row)
            }
            Err(source) => Err(finish_logged_sqlx_failure(
                config,
                SqlExecutionMethod::FetchOptional,
                elapsed,
                rows_affected,
                captured_rows_returned,
                source,
            )),
        }
    }

    async fn run_logged_fetch_one<F, T>(future: F, mut config: SqlLogConfig) -> Result<T, ApiError>
    where
        F: Future<Output = Result<T, sqlx::Error>>,
    {
        let (result, event, fallback_elapsed) = await_logged(future, config.record_failure).await;
        let (elapsed, rows_affected, captured_rows_returned) =
            apply_captured_event(&mut config, event, fallback_elapsed);
        match result {
            Ok(row) => {
                if config.record_success {
                    record_execution(
                        config.trace,
                        SqlExecutionMethod::FetchOne,
                        SqlExecutionOutcome::Success,
                        elapsed,
                        rows_affected,
                        Some(1),
                        None,
                        None,
                    );
                }
                Ok(row)
            }
            Err(source) => Err(finish_logged_sqlx_failure(
                config,
                SqlExecutionMethod::FetchOne,
                elapsed,
                rows_affected,
                captured_rows_returned,
                source,
            )),
        }
    }

    fn finish_logged_sqlx_failure(
        mut config: SqlLogConfig,
        method: SqlExecutionMethod,
        elapsed: Duration,
        rows_affected: Option<u64>,
        rows_returned: Option<usize>,
        source: sqlx::Error,
    ) -> ApiError {
        let class = SqlErrorClass::classify(&source);
        let (code, constraint) = database_error_metadata(&source);
        let diagnostic = config.record_failure.then(|| {
            config
                .trace
                .sql_diagnostic(&source, code.as_deref(), constraint.as_deref())
        });
        let api_error = config
            .trace
            .take_api_error(&source, class, constraint.as_deref());
        let api_error_code = api_error.code;
        let error = config.record_failure.then(|| SqlExecutionError {
            class: class.as_str().to_owned(),
            message: bounded_display(&source, MAX_ERROR_BYTES),
            code,
            constraint,
        });
        let execution_id = config
            .record_failure
            .then(|| {
                record_execution(
                    config.trace,
                    method,
                    SqlExecutionOutcome::Failure,
                    elapsed,
                    rows_affected,
                    rows_returned,
                    error,
                    Some(api_error_code),
                )
            })
            .flatten();

        if let Some(execution_id) = execution_id {
            api_error.with_context("sql_execution_id", execution_id)
        } else if let Some(diagnostic) = diagnostic {
            api_error.with_source(&source).with_sql_error(diagnostic)
        } else {
            api_error
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn finish_logged_business_failure(
        config: SqlLogConfig,
        method: SqlExecutionMethod,
        elapsed: Duration,
        rows_affected: Option<u64>,
        rows_returned: Option<usize>,
        api_error: ApiError,
        reason: &'static str,
    ) -> ApiError {
        let diagnostic = config
            .record_failure
            .then(|| config.trace.business_diagnostic(reason));
        let api_error_code = api_error.code;
        let error = config.record_failure.then(|| SqlExecutionError {
            class: "not_found".to_owned(),
            message: reason.to_owned(),
            code: None,
            constraint: None,
        });
        let execution_id = config
            .record_failure
            .then(|| {
                record_execution(
                    config.trace,
                    method,
                    SqlExecutionOutcome::BusinessFailure,
                    elapsed,
                    rows_affected,
                    rows_returned,
                    error,
                    Some(api_error_code),
                )
            })
            .flatten();
        if let Some(execution_id) = execution_id {
            api_error.with_context("sql_execution_id", execution_id)
        } else if let Some(diagnostic) = diagnostic {
            api_error.with_sql_error(diagnostic)
        } else {
            api_error
        }
    }

    fn infer_sql_operation(statement: &str) -> SqlOperation {
        match statement
            .split_whitespace()
            .next()
            .unwrap_or_default()
            .to_ascii_uppercase()
            .as_str()
        {
            "SELECT" => SqlOperation::Select,
            "INSERT" => SqlOperation::Insert,
            "UPDATE" => SqlOperation::Update,
            "DELETE" => SqlOperation::Delete,
            _ => SqlOperation::Other,
        }
    }

    /// 记录连接池默认策略捕获到的 SQLx 失败。
    pub(crate) fn record_default_sqlx_failure(
        event: Option<SqlxQueryEvent>,
        method: SqlExecutionMethod,
        fallback_elapsed: Duration,
        source: &sqlx::Error,
    ) {
        let mut trace = SqlLogMetadata::captured("sqlx.query");
        let (elapsed, rows_affected, rows_returned) = if let Some(event) = event {
            let elapsed = event
                .elapsed_secs
                .map(Duration::from_secs_f64)
                .unwrap_or(fallback_elapsed);
            let rows_affected = event.rows_affected;
            let rows_returned = event
                .rows_returned
                .and_then(|rows| usize::try_from(rows).ok());
            trace.apply_captured_event(&event);
            (elapsed, rows_affected, rows_returned)
        } else {
            (fallback_elapsed, None, None)
        };
        if matches!(trace.operation, SqlOperation::Other)
            && !matches!(method, SqlExecutionMethod::Execute)
        {
            trace.operation = SqlOperation::Select;
        }

        let class = SqlErrorClass::classify(source);
        let (code, constraint) = database_error_metadata(source);
        let api_error_code = default_sqlx_api_error(source).code;
        record_execution(
            trace,
            method,
            SqlExecutionOutcome::Failure,
            elapsed,
            rows_affected,
            rows_returned,
            Some(SqlExecutionError {
                class: class.as_str().to_owned(),
                message: bounded_display(source, MAX_ERROR_BYTES),
                code,
                constraint,
            }),
            Some(api_error_code),
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn record_execution(
        trace: SqlLogMetadata,
        method: SqlExecutionMethod,
        outcome: SqlExecutionOutcome,
        elapsed: std::time::Duration,
        rows_affected: Option<u64>,
        rows_returned: Option<usize>,
        error: Option<SqlExecutionError>,
        api_error_code: Option<u32>,
    ) -> Option<u64> {
        let context = RequestLogContext::try_current()?;
        context.record_sql_execution(trace.into_execution(
            method,
            outcome,
            elapsed,
            rows_affected,
            rows_returned,
            error,
            api_error_code,
        ))
    }

    fn database_error_metadata(error: &sqlx::Error) -> (Option<String>, Option<String>) {
        let sqlx::Error::Database(error) = error else {
            return (None, None);
        };
        (
            error.code().map(Cow::into_owned),
            error.constraint().map(ToOwned::to_owned),
        )
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::observability::context::scope_request_log;
        use tracing_subscriber::prelude::*;

        fn captured_config(record_success: bool, record_failure: bool) -> SqlLogConfig {
            SqlLogConfig {
                trace: SqlLogMetadata::captured("student.list"),
                record_success,
                record_failure,
            }
        }

        fn emit_sqlx_event(statement: &'static str, rows_returned: u64) {
            tracing::event!(
                target: "sqlx::query",
                tracing::Level::DEBUG,
                {
                    db.statement = statement,
                    rows_affected = 0_u64,
                    rows_returned = rows_returned,
                    elapsed_secs = 0.012_f64
                },
                "SELECT id FROM students"
            );
        }

        #[test]
        fn constraint_error_has_priority_over_class_error() {
            let source = sqlx::Error::RowNotFound;
            let mut trace = SqlLogMetadata::captured("user.create")
                .unique_conflict("数据已存在")
                .on_constraint(
                    "uk_users_email",
                    ApiError::err_unique_index_conflict("该邮箱已经注册"),
                );

            let error = trace.take_api_error(
                &source,
                SqlErrorClass::UniqueViolation,
                Some("uk_users_email"),
            );
            assert_eq!(error.code, 409_001);
            assert_eq!(error.msg, "该邮箱已经注册");
        }

        #[tokio::test(flavor = "current_thread")]
        async fn new_logging_policies_capture_expected_executions() {
            let subscriber = tracing_subscriber::registry()
                .with(crate::observability::SqlxQueryLayer::new().with_capture_filter());
            let _guard = tracing::subscriber::set_default(subscriber);
            let context = RequestLogContext::new();

            scope_request_log(context.clone(), async {
                let rows = run_logged_fetch_all(
                    async {
                        emit_sqlx_event("SELECT id FROM students", 2);
                        Ok::<_, sqlx::Error>(vec![1_u64, 2])
                    },
                    captured_config(true, true),
                )
                .await
                .unwrap();
                assert_eq!(rows, vec![1, 2]);
                run_logged_fetch_all(
                    async {
                        emit_sqlx_event("SELECT id FROM students", 1);
                        Ok::<_, sqlx::Error>(vec![1_u64])
                    },
                    captured_config(false, true),
                )
                .await
                .unwrap();
                assert_eq!(context.structured_snapshot().sql_executions.len(), 1);

                let error = run_logged_fetch_one(
                    async {
                        emit_sqlx_event("SELECT id FROM students WHERE id = ?", 0);
                        Err::<u64, _>(sqlx::Error::RowNotFound)
                    },
                    captured_config(false, true),
                )
                .await
                .unwrap_err();
                assert_eq!(error.code, 404_000);
                let _ = run_logged_fetch_one(
                    async {
                        emit_sqlx_event("SELECT id FROM students WHERE id = ? LIMIT 1", 0);
                        Err::<u64, _>(sqlx::Error::RowNotFound)
                    },
                    captured_config(true, true),
                )
                .await
                .unwrap_err();

                let mut custom_error_config = captured_config(false, false);
                custom_error_config.trace = custom_error_config
                    .trace
                    .api_error(ApiError::err_database("自定义数据库错误"));
                let error = run_logged_fetch_one(
                    async { Err::<u64, _>(sqlx::Error::RowNotFound) },
                    custom_error_config,
                )
                .await
                .unwrap_err();
                assert_eq!(error.msg, "自定义数据库错误");
            })
            .await;

            let snapshot = context.structured_snapshot();
            assert_eq!(snapshot.sql_executions.len(), 3);
            assert_eq!(
                snapshot.sql_executions[0].statement,
                "SELECT id FROM students"
            );
            assert_eq!(snapshot.sql_executions[0].rows_returned, Some(2));
            assert_eq!(
                snapshot.sql_executions[0].outcome,
                SqlExecutionOutcome::Success
            );
            assert!(snapshot.sql_executions[0].error.is_none());
            for execution in &snapshot.sql_executions[1..] {
                assert_eq!(execution.outcome, SqlExecutionOutcome::Failure);
                assert!(execution.error.is_some());
            }
        }
    }
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
pub(crate) use sqlx_support::record_default_sqlx_failure;
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
pub use sqlx_support::{LoggedSql, SqlLoggerExt};