1use super::Record;
4#[cfg(any(feature = "mysql", feature = "postgres"))]
5use super::{TableDefinition, TableQuery};
6#[cfg(any(feature = "mysql", feature = "postgres"))]
7use crate::database::AnyDatabase;
8use crate::definition::FieldRef;
9use crate::error::BaseError;
10use async_trait::async_trait;
11use serde_json::Value;
12#[cfg(any(feature = "mysql", feature = "postgres"))]
13use std::collections::HashSet;
14use std::collections::{BTreeMap, HashMap};
15#[cfg(any(feature = "mysql", feature = "postgres"))]
16use std::sync::Arc;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct RelationSpec {
21 source: FieldRef,
22 target: FieldRef,
23 display: Vec<FieldRef>,
24}
25
26impl RelationSpec {
27 pub fn new(source: FieldRef, target: FieldRef) -> Self {
29 Self {
30 source,
31 target,
32 display: Vec::new(),
33 }
34 }
35
36 pub fn display<I>(mut self, fields: I) -> Self
38 where
39 I: IntoIterator<Item = FieldRef>,
40 {
41 self.display = fields.into_iter().collect();
42 self
43 }
44
45 pub fn source(&self) -> &FieldRef {
47 &self.source
48 }
49
50 pub fn target(&self) -> &FieldRef {
52 &self.target
53 }
54
55 pub fn display_fields(&self) -> &[FieldRef] {
57 &self.display
58 }
59}
60
61#[cfg(any(feature = "mysql", feature = "postgres"))]
75pub struct DatabaseRelationExecutor<'a> {
76 database: &'a AnyDatabase,
77 roles: Arc<[String]>,
78 roles_set: HashSet<String>,
79 tenant_value: Option<Value>,
80 tenant_scope_disabled: bool,
81 targets: HashMap<String, TableDefinition>,
82}
83
84#[cfg(any(feature = "mysql", feature = "postgres"))]
85impl<'a> DatabaseRelationExecutor<'a> {
86 pub fn new<I, S>(database: &'a AnyDatabase, roles: I) -> Self
88 where
89 I: IntoIterator<Item = S>,
90 S: Into<String>,
91 {
92 let roles: Arc<[String]> =
93 Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
94 let roles_set = roles.iter().cloned().collect();
95 Self {
96 database,
97 roles,
98 roles_set,
99 tenant_value: None,
100 tenant_scope_disabled: false,
101 targets: HashMap::new(),
102 }
103 }
104
105 pub fn new_on<I, S>(datasource: &'a crate::database::Datasource, roles: I) -> Self
107 where
108 I: IntoIterator<Item = S>,
109 S: Into<String>,
110 {
111 Self::new(datasource.database(), roles)
112 }
113
114 pub fn target(mut self, definition: TableDefinition) -> Self {
116 self.targets
117 .insert(definition.name().to_string(), definition);
118 self
119 }
120
121 pub fn with_tenant(mut self, value: Value) -> Self {
126 self.tenant_value = Some(value);
127 self
128 }
129
130 pub fn without_tenant_scope(mut self) -> Self {
136 self.tenant_scope_disabled = true;
137 self
138 }
139
140 fn target_query(&self, batch: &RelationBatch) -> Result<TableQuery, BaseError> {
142 let spec = batch.spec();
143 let table = spec.target().table().as_str();
144 let definition = self.targets.get(table).ok_or_else(|| {
145 BaseError::ConfigError(format!(
146 "关系加载缺少目标表定义: {table}(拒绝执行无权限/租户/软删守卫的关联查询)"
147 ))
148 })?;
149 let table_config = definition.shared_config();
150 let key = spec.target().field().as_str();
151 let key_config = table_config
152 .get_field(key)
153 .ok_or_else(|| BaseError::FieldNotFound(table.to_string(), key.to_string()))?;
154 if !key_config.permissions.can_read(&self.roles_set) {
156 return Err(BaseError::FieldPermissionDenied(
157 table.to_string(),
158 key.to_string(),
159 "用户无关联键读取权限".to_string(),
160 ));
161 }
162
163 let mut projection: Vec<&str> = vec![key];
165 for field in spec.display_fields() {
166 let name = field.field().as_str();
167 let config = table_config
168 .get_field(name)
169 .ok_or_else(|| BaseError::FieldNotFound(table.to_string(), name.to_string()))?;
170 if config.permissions.can_read(&self.roles_set)
171 && !config.hidden
172 && !projection.contains(&name)
173 {
174 projection.push(name);
175 }
176 }
177
178 let source_pool = self.database.source_pool();
179 let mut query = TableQuery::new_sourced(
180 table_config,
181 self.roles.clone(),
182 Some(source_pool.pool().clone()),
183 source_pool.source().clone(),
184 );
185 query = query.select_fields(&projection)?;
186 if let Some(tenant_field) = definition.tenant_key_field() {
187 match &self.tenant_value {
188 Some(value) => {
189 query = query.scope_tenant(tenant_field, value.clone())?;
190 }
191 None if !self.tenant_scope_disabled => {
192 return Err(BaseError::ConfigError(format!(
193 "关系加载目标表 {table} 声明了租户字段 {tenant_field},但执行器未绑定租户值;\
194 请调用 with_tenant(...) 绑定租户,或显式 without_tenant_scope() 允许跨租户查询"
195 )));
196 }
197 None => {}
198 }
199 }
200 query.where_in_trusted(key, batch.keys().to_vec())
202 }
203}
204
205#[cfg(any(feature = "mysql", feature = "postgres"))]
206#[async_trait]
207impl RelationBatchExecutor for DatabaseRelationExecutor<'_> {
208 async fn load_batch(&self, batch: &RelationBatch) -> Result<Vec<Record>, BaseError> {
209 self.target_query(batch)?.all().await
210 }
211}
212
213#[derive(Debug, Clone)]
215pub struct RelationBatch {
216 spec: RelationSpec,
217 keys: Vec<Value>,
218}
219
220impl RelationBatch {
221 pub fn spec(&self) -> &RelationSpec {
223 &self.spec
224 }
225
226 pub fn keys(&self) -> &[Value] {
228 &self.keys
229 }
230}
231
232#[async_trait]
234pub trait RelationBatchExecutor: Send + Sync {
235 async fn load_batch(&self, batch: &RelationBatch) -> Result<Vec<Record>, BaseError>;
237}
238
239pub type RelationData = HashMap<String, Vec<Record>>;
241
242#[derive(Debug, Clone, Default)]
244pub struct RelationLoader {
245 relations: Vec<RelationSpec>,
246}
247
248impl RelationLoader {
249 pub fn new(relations: Vec<RelationSpec>) -> Self {
251 Self { relations }
252 }
253
254 pub fn plan(&self, rows: &[Record]) -> Vec<RelationBatch> {
256 self.relations
257 .iter()
258 .filter_map(|relation| {
259 let mut values = BTreeMap::new();
260 for row in rows {
261 let Some(value) = row.get(relation.source.field().as_str()) else {
262 continue;
263 };
264 if value.is_null() {
265 continue;
266 }
267 if let Ok(key) = serde_json::to_string(value) {
268 values.entry(key).or_insert_with(|| value.clone());
269 }
270 }
271 (!values.is_empty()).then(|| RelationBatch {
272 spec: relation.clone(),
273 keys: values.into_values().collect(),
274 })
275 })
276 .collect()
277 }
278
279 pub async fn load<E>(&self, rows: &[Record], executor: &E) -> Result<RelationData, BaseError>
281 where
282 E: RelationBatchExecutor,
283 {
284 let mut data = HashMap::new();
285 for batch in self.plan(rows) {
286 let source = batch.spec.source().to_string();
287 data.insert(source, executor.load_batch(&batch).await?);
288 }
289 Ok(data)
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::definition::{FieldName, TableName};
297 use std::sync::atomic::{AtomicUsize, Ordering};
298
299 fn field(table: &str, field: &str) -> FieldRef {
300 FieldRef::new(
301 TableName::new(table).expect("合法表名"),
302 FieldName::new(field).expect("合法字段名"),
303 )
304 }
305
306 struct CountingExecutor(AtomicUsize);
307
308 #[async_trait]
309 impl RelationBatchExecutor for CountingExecutor {
310 async fn load_batch(&self, _batch: &RelationBatch) -> Result<Vec<Record>, BaseError> {
311 self.0.fetch_add(1, Ordering::Relaxed);
312 Ok(Vec::new())
313 }
314 }
315
316 #[tokio::test]
317 async fn query_count_depends_on_relation_kinds_not_row_count() {
318 let loader = RelationLoader::new(vec![RelationSpec::new(
319 field("orders", "user_id"),
320 field("users", "id"),
321 )]);
322 let rows = (0..1_000)
323 .map(|index| Record::new().set("user_id", index % 10))
324 .collect::<Vec<_>>();
325 let executor = CountingExecutor(AtomicUsize::new(0));
326 let batches = loader.plan(&rows);
327 assert_eq!(batches.len(), 1);
328 assert_eq!(batches[0].keys().len(), 10);
329 loader
330 .load(&rows, &executor)
331 .await
332 .expect("批量关系加载应成功");
333 assert_eq!(executor.0.load(Ordering::Relaxed), 1);
334 }
335}
336
337#[cfg(all(test, feature = "postgres"))]
338mod guard_tests {
339 use super::*;
340 use crate::database::AnyDatabase;
341 use crate::definition::{FieldName, TableName};
342 use crate::table::{Field, Table};
343 use serde_json::json;
344 use yang_db::postgres::{Database as PgDatabase, DatabaseConfig as PgDatabaseConfig};
345
346 fn field(table: &str, field: &str) -> FieldRef {
347 FieldRef::new(
348 TableName::new(table).expect("合法表名"),
349 FieldName::new(field).expect("合法字段名"),
350 )
351 }
352
353 fn lazy_database() -> AnyDatabase {
354 let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
355 .expect("惰性 PG 连接池应创建成功");
356 AnyDatabase::postgres(
357 PgDatabase::from_pool(pool, PgDatabaseConfig::default())
358 .expect("默认 PG 配置应通过校验"),
359 )
360 }
361
362 fn child_definition() -> TableDefinition {
363 Table::new("w3_rel_child")
364 .fields([
365 Field::id("id"),
366 Field::string("label", 64).required(),
367 Field::string("secret", 64).readable_by(["admin"]),
368 Field::bigint("tenant_id").tenant_key(),
369 Field::soft_delete("deleted_at"),
370 ])
371 .build()
372 .expect("关系目标表定义应有效")
373 }
374
375 fn batch() -> RelationBatch {
376 RelationBatch {
377 spec: RelationSpec::new(
378 field("w3_rel_parent", "child_id"),
379 field("w3_rel_child", "id"),
380 )
381 .display([
382 field("w3_rel_child", "label"),
383 field("w3_rel_child", "secret"),
384 ]),
385 keys: vec![json!(1), json!(2)],
386 }
387 }
388
389 #[tokio::test]
391 async fn target_query_applies_tenant_guard_and_trims_unreadable_columns() {
392 let database = lazy_database();
393 let executor = DatabaseRelationExecutor::new(&database, ["user"])
394 .target(child_definition())
395 .with_tenant(json!(1));
396
397 let query = executor.target_query(&batch()).expect("目标查询应构造成功");
398 let params = query.get_query_params();
399
400 assert_eq!(
401 params.fields.as_deref(),
402 Some(["id".to_string(), "label".to_string()].as_slice()),
403 "不可读的 secret 必须从投影中裁剪"
404 );
405 assert!(
406 params.where_conditions.iter().any(|condition| matches!(
407 condition,
408 crate::table::WhereCondition::Eq { field, value }
409 if field == "tenant_id" && value == &json!(1)
410 )),
411 "必须追加租户等值条件: {:?}",
412 params.where_conditions
413 );
414 assert!(
415 params.where_conditions.iter().any(|condition| matches!(
416 condition,
417 crate::table::WhereCondition::In { field, values }
418 if field == "id" && values == &vec![json!(1), json!(2)]
419 )),
420 "必须追加关联键 IN 条件: {:?}",
421 params.where_conditions
422 );
423 }
424
425 #[tokio::test]
427 async fn target_query_fails_closed_when_tenant_scope_unbound() {
428 let database = lazy_database();
429 let executor =
430 DatabaseRelationExecutor::new(&database, ["user"]).target(child_definition());
431
432 let error = executor
433 .target_query(&batch())
434 .expect_err("未绑定租户值必须失败");
435 assert!(
436 matches!(error, BaseError::ConfigError(ref message)
437 if message.contains("w3_rel_child") && message.contains("with_tenant")),
438 "应返回提示绑定租户的 ConfigError,实际: {error:?}"
439 );
440 }
441
442 #[tokio::test]
444 async fn without_tenant_scope_explicitly_allows_cross_tenant_query() {
445 let database = lazy_database();
446 let executor = DatabaseRelationExecutor::new(&database, ["user"])
447 .target(child_definition())
448 .without_tenant_scope();
449
450 let query = executor
451 .target_query(&batch())
452 .expect("显式 opt-out 后应允许构造目标查询");
453 let params = query.get_query_params();
454 assert!(
455 !params.where_conditions.iter().any(|condition| matches!(
456 condition,
457 crate::table::WhereCondition::Eq { field, .. } if field == "tenant_id"
458 )),
459 "显式 opt-out 后不应追加租户条件: {:?}",
460 params.where_conditions
461 );
462 }
463
464 #[tokio::test]
466 async fn missing_target_definition_fails_closed() {
467 let database = lazy_database();
468 let executor = DatabaseRelationExecutor::new(&database, ["user"]).with_tenant(json!(1));
469
470 let error = executor
471 .target_query(&batch())
472 .expect_err("缺少目标表定义必须失败");
473 assert!(
474 matches!(error, BaseError::ConfigError(ref message) if message.contains("w3_rel_child")),
475 "应返回目标表缺失的 ConfigError,实际: {error:?}"
476 );
477 }
478}