yang_base/table/table_config.rs
1//! 表配置
2//!
3//! 提供数据表的完整配置功能,包括表结构、字段、索引、排序和软删除等。
4
5use crate::error::BaseError;
6use crate::table::FieldConfig;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10/// 表配置
11///
12/// 定义数据表的完整配置,包括:
13/// - 表名和显示名称
14/// - 主键字段
15/// - 字段列表
16/// - 索引配置(唯一索引、普通索引)
17/// - 默认排序规则
18/// - 软删除字段
19/// - 时间戳字段配置
20///
21/// # 示例
22///
23/// ```rust
24/// use yang_base::table::{TableConfig, FieldConfig, FieldType, SortOrder};
25///
26/// // 创建一个用户表配置
27/// let table = TableConfig::new("users")
28/// .display_name("用户表")
29/// .primary_key("id")
30/// .field(FieldConfig::new("id", FieldType::BigInt).required(true)).expect("有效字段配置应注册成功")
31/// .field(FieldConfig::new("username", FieldType::String { max_length: 50 }).required(true)).expect("有效字段配置应注册成功")
32/// .field(FieldConfig::new("email", FieldType::String { max_length: 100 }).required(true)).expect("有效字段配置应注册成功")
33/// .unique_index(vec!["username".to_string()])
34/// .unique_index(vec!["email".to_string()])
35/// .default_order(vec![("created_at".to_string(), SortOrder::Desc)])
36/// .soft_delete_field("deleted_at")
37/// .timestamps(true, true, true);
38/// ```
39#[derive(Debug, Clone)]
40#[non_exhaustive]
41pub struct TableConfig {
42 /// 表名
43 ///
44 /// 数据库中的表名称,通常使用蛇形命名法(snake_case)
45 pub table_name: String,
46
47 /// 显示名称
48 ///
49 /// 用于前端展示的表名称,通常使用中文
50 pub display_name: String,
51
52 /// 主键字段名
53 ///
54 /// 表的主键字段,通常为 "id"
55 pub primary_key: String,
56
57 /// 字段配置列表
58 ///
59 /// 使用 HashMap 存储字段配置,键为字段名,值为字段配置
60 pub fields: HashMap<String, FieldConfig>,
61
62 /// 唯一索引配置列表
63 ///
64 /// 每个唯一索引由一个或多个字段组成
65 pub unique_indexes: Vec<IndexConfig>,
66
67 /// 普通索引配置列表
68 ///
69 /// 每个普通索引由一个或多个字段组成
70 pub indexes: Vec<IndexConfig>,
71
72 /// 默认排序规则
73 ///
74 /// 定义查询时的默认排序字段和排序方向
75 pub default_order: Vec<(String, SortOrder)>,
76
77 /// 软删除字段名
78 ///
79 /// 如果设置了软删除字段,删除操作将更新该字段而非物理删除记录
80 pub soft_delete_field: Option<String>,
81
82 /// 时间戳字段配置
83 ///
84 /// 定义创建时间、更新时间和删除时间字段
85 pub timestamp_fields: Option<TimestampFields>,
86}
87
88impl TableConfig {
89 /// 创建新的表配置
90 ///
91 /// # 参数
92 ///
93 /// - `table_name`: 表名
94 ///
95 /// # 返回值
96 ///
97 /// 返回一个新的 TableConfig 实例,使用默认配置
98 ///
99 /// # 示例
100 ///
101 /// ```rust
102 /// use yang_base::table::TableConfig;
103 ///
104 /// let table = TableConfig::new("users");
105 /// assert_eq!(table.table_name, "users");
106 /// assert_eq!(table.primary_key, "id");
107 /// ```
108 pub fn new(table_name: impl Into<String>) -> Self {
109 Self {
110 table_name: table_name.into(),
111 display_name: String::new(),
112 primary_key: "id".to_string(),
113 fields: HashMap::new(),
114 unique_indexes: Vec::new(),
115 indexes: Vec::new(),
116 default_order: Vec::new(),
117 soft_delete_field: None,
118 timestamp_fields: None,
119 }
120 }
121
122 /// 设置显示名称
123 ///
124 /// # 参数
125 ///
126 /// - `name`: 显示名称
127 ///
128 /// # 返回值
129 ///
130 /// 返回 `Result<Self, BaseError>`,支持通过 `?` 或 `expect` 继续链式调用
131 ///
132 /// # 错误
133 ///
134 /// - `BaseError::ConfigError`:字段名为空白字符串
135 ///
136 /// # 示例
137 ///
138 /// ```rust
139 /// use yang_base::table::TableConfig;
140 ///
141 /// let table = TableConfig::new("users")
142 /// .display_name("用户表");
143 /// assert_eq!(table.display_name, "用户表");
144 /// ```
145 pub fn display_name(mut self, name: impl Into<String>) -> Self {
146 self.display_name = name.into();
147 self
148 }
149
150 /// 设置主键字段
151 ///
152 /// # 参数
153 ///
154 /// - `key`: 主键字段名
155 ///
156 /// # 返回值
157 ///
158 /// 返回 self,支持链式调用
159 ///
160 /// # 示例
161 ///
162 /// ```rust
163 /// use yang_base::table::TableConfig;
164 ///
165 /// let table = TableConfig::new("users")
166 /// .primary_key("user_id");
167 /// assert_eq!(table.primary_key, "user_id");
168 /// ```
169 pub fn primary_key(mut self, key: impl Into<String>) -> Self {
170 self.primary_key = key.into();
171 self
172 }
173
174 /// 添加字段配置
175 ///
176 /// # 参数
177 ///
178 /// - `field`: 字段配置
179 ///
180 /// # 返回值
181 ///
182 /// 返回 self,支持链式调用
183 ///
184 /// # 示例
185 ///
186 /// ```rust
187 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
188 ///
189 /// let table = TableConfig::new("users")
190 /// .field(FieldConfig::new("id", FieldType::BigInt)).expect("有效字段配置应注册成功")
191 /// .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");
192 /// assert_eq!(table.fields.len(), 2);
193 /// ```
194 pub fn field(mut self, field: FieldConfig) -> Result<Self, BaseError> {
195 Self::validate_field_config(&field)?;
196 self.fields.insert(field.name.clone(), field);
197 Ok(self)
198 }
199
200 /// 批量添加字段配置
201 ///
202 /// # 参数
203 ///
204 /// - `fields`: 字段配置列表
205 ///
206 /// # 返回值
207 ///
208 /// 返回 `Result<Self, BaseError>`,支持通过 `?` 或 `expect` 继续链式调用
209 ///
210 /// # 错误
211 ///
212 /// - `BaseError::ConfigError`:任一字段名为空白字符串
213 ///
214 /// # 示例
215 ///
216 /// ```rust
217 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
218 ///
219 /// let table = TableConfig::new("users")
220 /// .fields(vec![
221 /// FieldConfig::new("id", FieldType::BigInt).required(true),
222 /// FieldConfig::new("username", FieldType::String { max_length: 50 }).required(true),
223 /// FieldConfig::new("email", FieldType::String { max_length: 100 }).required(true),
224 /// ]).expect("有效字段配置应注册成功");
225 /// assert_eq!(table.fields.len(), 3);
226 /// ```
227 pub fn fields(mut self, fields: Vec<FieldConfig>) -> Result<Self, BaseError> {
228 for field in fields {
229 self = self.field(field)?;
230 }
231 Ok(self)
232 }
233
234 /// 从迭代器批量添加字段配置
235 ///
236 /// # 参数
237 ///
238 /// - `fields`: 字段配置迭代器
239 ///
240 /// # 返回值
241 ///
242 /// 返回 `Result<Self, BaseError>`,支持通过 `?` 或 `expect` 继续链式调用
243 ///
244 /// # 错误
245 ///
246 /// - `BaseError::ConfigError`:任一字段名为空白字符串
247 ///
248 /// # 示例
249 ///
250 /// ```rust
251 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
252 ///
253 /// let field_configs = vec![
254 /// FieldConfig::new("id", FieldType::BigInt),
255 /// FieldConfig::new("username", FieldType::String { max_length: 50 }),
256 /// ];
257 ///
258 /// let table = TableConfig::new("users")
259 /// .fields_from_iter(field_configs.into_iter()).expect("有效字段配置应注册成功");
260 /// assert_eq!(table.fields.len(), 2);
261 /// ```
262 pub fn fields_from_iter<I>(mut self, fields: I) -> Result<Self, BaseError>
263 where
264 I: IntoIterator<Item = FieldConfig>,
265 {
266 for field in fields {
267 self = self.field(field)?;
268 }
269 Ok(self)
270 }
271
272 fn validate_field_config(field: &FieldConfig) -> Result<(), BaseError> {
273 if field.name.trim().is_empty() {
274 return Err(BaseError::ConfigError("字段名称不能为空".to_string()));
275 }
276
277 Ok(())
278 }
279
280 /// 添加唯一索引
281 ///
282 /// # 参数
283 ///
284 /// - `fields`: 索引字段列表
285 ///
286 /// # 返回值
287 ///
288 /// 返回 self,支持链式调用
289 ///
290 /// # 示例
291 ///
292 /// ```rust
293 /// use yang_base::table::TableConfig;
294 ///
295 /// let table = TableConfig::new("users")
296 /// .unique_index(vec!["username".to_string()])
297 /// .unique_index(vec!["email".to_string()]);
298 /// assert_eq!(table.unique_indexes.len(), 2);
299 /// ```
300 pub fn unique_index(mut self, fields: Vec<String>) -> Self {
301 self.unique_indexes.push(IndexConfig { name: None, fields });
302 self
303 }
304
305 /// 添加普通索引
306 ///
307 /// # 参数
308 ///
309 /// - `fields`: 索引字段列表
310 ///
311 /// # 返回值
312 ///
313 /// 返回 self,支持链式调用
314 ///
315 /// # 示例
316 ///
317 /// ```rust
318 /// use yang_base::table::TableConfig;
319 ///
320 /// let table = TableConfig::new("users")
321 /// .index(vec!["created_at".to_string()])
322 /// .index(vec!["status".to_string(), "created_at".to_string()]);
323 /// assert_eq!(table.indexes.len(), 2);
324 /// ```
325 pub fn index(mut self, fields: Vec<String>) -> Self {
326 self.indexes.push(IndexConfig { name: None, fields });
327 self
328 }
329
330 /// 设置默认排序规则
331 ///
332 /// # 参数
333 ///
334 /// - `order`: 排序规则列表,每项为 (字段名, 排序方向)
335 ///
336 /// # 返回值
337 ///
338 /// 返回 self,支持链式调用
339 ///
340 /// # 示例
341 ///
342 /// ```rust
343 /// use yang_base::table::{TableConfig, SortOrder};
344 ///
345 /// let table = TableConfig::new("users")
346 /// .default_order(vec![
347 /// ("created_at".to_string(), SortOrder::Desc),
348 /// ("id".to_string(), SortOrder::Asc),
349 /// ]);
350 /// assert_eq!(table.default_order.len(), 2);
351 /// ```
352 pub fn default_order(mut self, order: Vec<(String, SortOrder)>) -> Self {
353 self.default_order = order;
354 self
355 }
356
357 /// 设置软删除字段
358 ///
359 /// # 参数
360 ///
361 /// - `field`: 软删除字段名
362 ///
363 /// # 返回值
364 ///
365 /// 返回 self,支持链式调用
366 ///
367 /// # 示例
368 ///
369 /// ```rust
370 /// use yang_base::table::TableConfig;
371 ///
372 /// let table = TableConfig::new("users")
373 /// .soft_delete_field("deleted_at");
374 /// assert_eq!(table.soft_delete_field, Some("deleted_at".to_string()));
375 /// ```
376 pub fn soft_delete_field(mut self, field: impl Into<String>) -> Self {
377 self.soft_delete_field = Some(field.into());
378 self
379 }
380
381 /// 设置时间戳字段配置
382 ///
383 /// # 参数
384 ///
385 /// - `created_at`: 是否启用创建时间字段
386 /// - `updated_at`: 是否启用更新时间字段
387 /// - `deleted_at`: 是否启用删除时间字段
388 ///
389 /// # 返回值
390 ///
391 /// 返回 self,支持链式调用
392 ///
393 /// # 示例
394 ///
395 /// ```rust
396 /// use yang_base::table::TableConfig;
397 ///
398 /// let table = TableConfig::new("users")
399 /// .timestamps(true, true, true);
400 /// assert!(table.timestamp_fields.is_some());
401 /// ```
402 pub fn timestamps(mut self, created_at: bool, updated_at: bool, deleted_at: bool) -> Self {
403 self.timestamp_fields = Some(TimestampFields {
404 created_at: if created_at {
405 Some("created_at".to_string())
406 } else {
407 None
408 },
409 updated_at: if updated_at {
410 Some("updated_at".to_string())
411 } else {
412 None
413 },
414 deleted_at: if deleted_at {
415 Some("deleted_at".to_string())
416 } else {
417 None
418 },
419 });
420 self
421 }
422
423 /// 验证字段是否存在
424 ///
425 /// # 参数
426 ///
427 /// - `field_name`: 字段名
428 ///
429 /// # 返回值
430 ///
431 /// 如果字段存在返回 Ok(()),否则返回 FieldNotFound 错误
432 ///
433 /// # 示例
434 ///
435 /// ```rust
436 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
437 ///
438 /// let table = TableConfig::new("users")
439 /// .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");
440 ///
441 /// assert!(table.validate_field("username").is_ok());
442 /// assert!(table.validate_field("nonexistent").is_err());
443 /// ```
444 pub fn validate_field(&self, field_name: &str) -> Result<(), BaseError> {
445 if self.fields.contains_key(field_name) {
446 Ok(())
447 } else {
448 Err(BaseError::FieldNotFound(
449 self.table_name.clone(),
450 field_name.to_string(),
451 ))
452 }
453 }
454
455 /// 获取字段配置
456 ///
457 /// # 参数
458 ///
459 /// - `field_name`: 字段名
460 ///
461 /// # 返回值
462 ///
463 /// 如果字段存在返回字段配置的引用,否则返回 None
464 ///
465 /// # 示例
466 ///
467 /// ```rust
468 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
469 ///
470 /// let table = TableConfig::new("users")
471 /// .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");
472 ///
473 /// let field = table.get_field("username");
474 /// assert!(field.is_some());
475 /// assert_eq!(field.unwrap().name, "username");
476 /// ```
477 pub fn get_field(&self, field_name: &str) -> Option<&FieldConfig> {
478 self.fields.get(field_name)
479 }
480
481 /// 验证查询参数
482 ///
483 /// 验证查询中引用的所有字段是否存在于表配置中
484 ///
485 /// # 参数
486 ///
487 /// - `field_names`: 字段名列表
488 ///
489 /// # 返回值
490 ///
491 /// 如果所有字段都存在返回 Ok(()),否则返回第一个不存在的字段的错误
492 ///
493 /// # 示例
494 ///
495 /// ```rust
496 /// use yang_base::table::{TableConfig, FieldConfig, FieldType};
497 ///
498 /// let table = TableConfig::new("users")
499 /// .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功")
500 /// .field(FieldConfig::new("email", FieldType::String { max_length: 100 })).expect("有效字段配置应注册成功");
501 ///
502 /// assert!(table.validate_query(&["username", "email"]).is_ok());
503 /// assert!(table.validate_query(&["username", "nonexistent"]).is_err());
504 /// ```
505 pub fn validate_query(&self, field_names: &[&str]) -> Result<(), BaseError> {
506 for field_name in field_names {
507 self.validate_field(field_name)?;
508 }
509 Ok(())
510 }
511}
512
513/// 索引配置
514///
515/// 定义数据库索引的配置信息
516///
517/// # 示例
518///
519/// ```rust
520/// use yang_base::table::IndexConfig;
521///
522/// let index = IndexConfig::new(Some("idx_username".to_string()), vec!["username".to_string()]);
523/// ```
524#[derive(Debug, Clone, Serialize, Deserialize)]
525#[non_exhaustive]
526pub struct IndexConfig {
527 /// 索引名称
528 ///
529 /// 如果为 None,将自动生成索引名称
530 pub name: Option<String>,
531
532 /// 索引字段列表
533 ///
534 /// 组成索引的字段名列表,支持复合索引
535 pub fields: Vec<String>,
536}
537
538impl IndexConfig {
539 /// 创建索引配置;`name` 为 `None` 时由迁移层生成索引名。
540 pub fn new(name: Option<String>, fields: Vec<String>) -> Self {
541 Self { name, fields }
542 }
543}
544
545/// 排序方向
546///
547/// 定义查询结果的排序方向
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
549pub enum SortOrder {
550 /// 升序排序
551 Asc,
552 /// 降序排序
553 Desc,
554}
555
556/// 时间戳字段配置
557///
558/// 定义表的时间戳字段,包括创建时间、更新时间和删除时间
559///
560/// # 示例
561///
562/// ```rust
563/// use yang_base::table::TimestampFields;
564///
565/// let timestamps = TimestampFields::new(
566/// Some("created_at".to_string()),
567/// Some("updated_at".to_string()),
568/// Some("deleted_at".to_string()),
569/// );
570/// ```
571#[derive(Debug, Clone, Serialize, Deserialize)]
572#[non_exhaustive]
573pub struct TimestampFields {
574 /// 创建时间字段名
575 ///
576 /// 记录创建时自动设置的时间戳字段
577 pub created_at: Option<String>,
578
579 /// 更新时间字段名
580 ///
581 /// 记录更新时自动更新的时间戳字段
582 pub updated_at: Option<String>,
583
584 /// 删除时间字段名
585 ///
586 /// 软删除时设置的时间戳字段
587 pub deleted_at: Option<String>,
588}
589
590impl TimestampFields {
591 /// 创建时间戳字段配置;不使用的字段传入 `None`。
592 pub fn new(
593 created_at: Option<String>,
594 updated_at: Option<String>,
595 deleted_at: Option<String>,
596 ) -> Self {
597 Self {
598 created_at,
599 updated_at,
600 deleted_at,
601 }
602 }
603}