rat_quickdb 0.5.2

强大的跨数据库ODM库,支持自动索引创建、统一接口和现代异步架构
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
//! JSON队列桥接器
//!
//! 使用JSON字符串与Python进行通信,通过全局任务队列系统执行数据库操作

use pyo3::prelude::*;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::oneshot;

use crate::error::{QuickDbResult, QuickDbError};
use crate::task_queue::{get_global_task_queue, DbTask};
use crate::types::{DataValue, QueryCondition, QueryOptions};

/// JSON队列桥接器 - 使用JSON字符串与Python通信
#[pyclass(name = "JsonQueueBridge")]
pub struct PyJsonQueueBridge {
    // 桥接器本身不需要状态,所有操作都通过全局任务队列
}

#[pymethods]
impl PyJsonQueueBridge {
    #[new]
    pub fn new() -> Self {
        Self {}
    }

    /// 创建记录
    pub fn create(&self, table: String, data_json: String) -> PyResult<String> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析JSON数据
            let data: HashMap<String, Value> = serde_json::from_str(&data_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的JSON数据: {}", e)))?;

            // 转换为DataValue
            let data_values: HashMap<String, DataValue> = data
                .into_iter()
                .map(|(k, v)| (k, json_value_to_data_value(v)))
                .collect();

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.create(table, data_values, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库操作失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 查询记录
    pub fn find(&self, table: String, conditions_json: String, options_json: Option<String>) -> PyResult<String> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询条件
            let conditions: Vec<Value> = serde_json::from_str(&conditions_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询条件JSON: {}", e)))?;

            let query_conditions: Vec<QueryCondition> = conditions
                .into_iter()
                .map(|v| parse_query_condition(v))
                .collect::<Result<Vec<_>, _>>()?;

            // 解析查询选项
            let options = if let Some(options_json) = options_json {
                let opts: Value = serde_json::from_str(&options_json)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询选项JSON: {}", e)))?;
                Some(parse_query_options(opts)?)
            } else {
                None
            };

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.find(table, query_conditions, options).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库查询失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 根据ID查询记录
    pub fn find_by_id(&self, table: String, id: String, options_json: Option<String>) -> PyResult<Option<String>> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询选项
            let options = if let Some(options_json) = options_json {
                let opts: Value = serde_json::from_str(&options_json)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询选项JSON: {}", e)))?;
                Some(parse_query_options(opts)?)
            } else {
                None
            };

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.find_by_id(table, id, options).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库查询失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 更新记录
    pub fn update(&self, table: String, conditions_json: String, data_json: String, options_json: Option<String>) -> PyResult<u64> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询条件
            let conditions: Vec<Value> = serde_json::from_str(&conditions_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询条件JSON: {}", e)))?;

            let query_conditions: Vec<QueryCondition> = conditions
                .into_iter()
                .map(|v| parse_query_condition(v))
                .collect::<Result<Vec<_>, _>>()?;

            // 解析更新数据
            let data: HashMap<String, Value> = serde_json::from_str(&data_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的更新数据JSON: {}", e)))?;

            let data_values: HashMap<String, DataValue> = data
                .into_iter()
                .map(|(k, v)| (k, json_value_to_data_value(v)))
                .collect();

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.update(table, query_conditions, data_values, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库更新失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 根据ID更新记录
    pub fn update_by_id(&self, table: String, id: String, data_json: String, options_json: Option<String>) -> PyResult<bool> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析更新数据
            let data: HashMap<String, Value> = serde_json::from_str(&data_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的更新数据JSON: {}", e)))?;

            let data_values: HashMap<String, DataValue> = data
                .into_iter()
                .map(|(k, v)| (k, json_value_to_data_value(v)))
                .collect();

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.update_by_id(table, id, data_values, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库更新失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 删除记录
    pub fn delete(&self, table: String, conditions_json: String, options_json: Option<String>) -> PyResult<u64> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询条件
            let conditions: Vec<Value> = serde_json::from_str(&conditions_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询条件JSON: {}", e)))?;

            let query_conditions: Vec<QueryCondition> = conditions
                .into_iter()
                .map(|v| parse_query_condition(v))
                .collect::<Result<Vec<_>, _>>()?;

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.delete(table, query_conditions, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库删除失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 根据ID删除记录
    pub fn delete_by_id(&self, table: String, id: String, options_json: Option<String>) -> PyResult<bool> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.delete_by_id(table, id, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库删除失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 计数记录
    pub fn count(&self, table: String, conditions_json: String, options_json: Option<String>) -> PyResult<u64> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询条件
            let conditions: Vec<Value> = serde_json::from_str(&conditions_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询条件JSON: {}", e)))?;

            let query_conditions: Vec<QueryCondition> = conditions
                .into_iter()
                .map(|v| parse_query_condition(v))
                .collect::<Result<Vec<_>, _>>()?;

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.count(table, query_conditions, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库计数失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 检查记录是否存在
    pub fn exists(&self, table: String, conditions_json: String, options_json: Option<String>) -> PyResult<bool> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 解析查询条件
            let conditions: Vec<Value> = serde_json::from_str(&conditions_json)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("无效的查询条件JSON: {}", e)))?;

            let query_conditions: Vec<QueryCondition> = conditions
                .into_iter()
                .map(|v| parse_query_condition(v))
                .collect::<Result<Vec<_>, _>>()?;

            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.exists(table, query_conditions, None).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("数据库存在性检查失败: {}", e)))?;

            Ok(result)
        })
    }

    /// 检查表是否存在
    pub fn check_table(&self, table: String) -> PyResult<bool> {
        let rt = tokio::runtime::Runtime::new().map_err(|e| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("无法创建运行时: {}", e))
        })?;

        rt.block_on(async {
            // 通过全局任务队列执行
            let task_queue = get_global_task_queue();
            let result = task_queue.check_table(table).await
                .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("表检查失败: {}", e)))?;

            Ok(result)
        })
    }
}

/// 创建JSON队列桥接器
#[pyfunction]
pub fn create_json_queue_bridge() -> PyResult<PyJsonQueueBridge> {
    Ok(PyJsonQueueBridge::new())
}

// === 辅助函数 ===

/// 将JSON值转换为DataValue
pub(crate) fn json_value_to_data_value(value: Value) -> DataValue {
    match value {
        Value::Null => DataValue::Null,
        Value::Bool(b) => DataValue::Bool(b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                DataValue::Int(i)
            } else if let Some(f) = n.as_f64() {
                DataValue::Float(f)
            } else {
                DataValue::Json(Value::Number(n))
            }
        },
        Value::String(s) => DataValue::String(s),
        Value::Array(arr) => {
            let data_array: Vec<DataValue> = arr.into_iter()
                .map(json_value_to_data_value)
                .collect();
            DataValue::Array(data_array)
        },
        Value::Object(obj) => {
            let data_object: HashMap<String, DataValue> = obj.into_iter()
                .map(|(k, v)| (k, json_value_to_data_value(v)))
                .collect();
            DataValue::Object(data_object)
        }
    }
}

/// 解析查询条件
pub fn parse_query_condition(value: Value) -> PyResult<QueryCondition> {
    let obj = value.as_object().ok_or_else(||
        pyo3::exceptions::PyValueError::new_err("查询条件必须是JSON对象")
    )?;

    let field = obj.get("field")
        .and_then(|v| v.as_str())
        .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("缺少字段名"))?
        .to_string();

    let operator_str = obj.get("operator")
        .and_then(|v| v.as_str())
        .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("缺少操作符"))?;

    let operator = match operator_str {
        "eq" => crate::types::QueryOperator::Eq,
        "ne" => crate::types::QueryOperator::Ne,
        "gt" => crate::types::QueryOperator::Gt,
        "gte" => crate::types::QueryOperator::Gte,
        "lt" => crate::types::QueryOperator::Lt,
        "lte" => crate::types::QueryOperator::Lte,
        "contains" => crate::types::QueryOperator::Contains,
        "startsWith" => crate::types::QueryOperator::StartsWith,
        "endsWith" => crate::types::QueryOperator::EndsWith,
        "in" => crate::types::QueryOperator::In,
        "notIn" => crate::types::QueryOperator::NotIn,
        "regex" => crate::types::QueryOperator::Regex,
        "exists" => crate::types::QueryOperator::Exists,
        "isNull" => crate::types::QueryOperator::IsNull,
        "isNotNull" => crate::types::QueryOperator::IsNotNull,
        _ => return Err(pyo3::exceptions::PyValueError::new_err(format!("不支持的操作符: {}", operator_str))),
    };

    let value = obj.get("value")
        .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("缺少值"))
        .map(|v| json_value_to_data_value(v.clone()))?;

    Ok(QueryCondition {
        field,
        operator,
        value,
    })
}

/// 解析查询选项
fn parse_query_options(value: Value) -> PyResult<QueryOptions> {
    let mut options = QueryOptions::new();

    if let Some(obj) = value.as_object() {
        // 解析排序配置
        if let Some(sort_array) = obj.get("sort") {
            if let Value::Array(arr) = sort_array {
                let sort_configs: Vec<crate::types::SortConfig> = arr.iter()
                    .map(|v| {
                        let sort_obj = v.as_object().ok_or_else(||
                            pyo3::exceptions::PyValueError::new_err("排序配置必须是JSON对象")
                        )?;

                        let field = sort_obj.get("field")
                            .and_then(|v| v.as_str())
                            .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("缺少排序字段名"))?
                            .to_string();

                        let direction_str = sort_obj.get("direction")
                            .and_then(|v| v.as_str())
                            .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("缺少排序方向"))?;

                        let direction = match direction_str {
                            "asc" => crate::types::SortDirection::Asc,
                            "desc" => crate::types::SortDirection::Desc,
                            _ => return Err(pyo3::exceptions::PyValueError::new_err(format!("不支持的排序方向: {}", direction_str))),
                        };

                        Ok(crate::types::SortConfig {
                            field,
                            direction,
                        })
                    })
                    .collect::<PyResult<Vec<_>>>()?;

                options = options.with_sort(sort_configs);
            }
        }

        // 解析分页配置
        if let Some(pagination_obj) = obj.get("pagination") {
            if let Value::Object(pag_obj) = pagination_obj {
                let skip = pag_obj.get("skip")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0);

                let limit = pag_obj.get("limit")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(100);

                let pagination = crate::types::PaginationConfig {
                    skip,
                    limit,
                };

                options = options.with_pagination(pagination);
            }
        }

        // 解析字段选择
        if let Some(fields_array) = obj.get("fields") {
            if let Value::Array(arr) = fields_array {
                let fields: Vec<String> = arr.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect();

                options = options.with_fields(fields);
            }
        }
    }

    Ok(options)
}