remdb 0.3.1

嵌入式内存数据库
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
use rand::random;
use remdb::config::DefaultMemoryAllocator;
use remdb::config::{DbConfig, WALConfig};
use remdb::platform::*;
use remdb::table::*;
use remdb::types::*;
use remdb::{init_global_db, AnySecondaryIndex, PrimaryIndex};
use std::time::Instant;

// 定义一个用于性能测试的大表,max_records设置为100,000(测试插入80,000条,占80%容量)
fn create_large_table_def() -> TableDef {
    TableDef {
        id: 0,
        name: "large_table".to_string(),
        fields: vec![
            FieldDef {
                name: "id".to_string(),
                data_type: DataType::UInt32,
                size: 4,
                string_length: None,
                offset: 0,
                primary_key: true,
                not_null: true,
                unique: true,
                auto_increment: true,
                default_value: None,
                vector_metadata: None,
                json_metadata: None,
            },
            FieldDef {
                name: "value".to_string(),
                data_type: DataType::Float32,
                size: 4,
                string_length: None,
                offset: 4,
                primary_key: false,
                not_null: false,
                unique: false,
                auto_increment: false,
                default_value: None,
                vector_metadata: None,
                json_metadata: None,
            },
            FieldDef {
                name: "name".to_string(),
                data_type: DataType::VarChar,
                size: 32,
                string_length: Some(32),
                offset: 8,
                primary_key: false,
                not_null: false,
                unique: false,
                auto_increment: false,
                default_value: None,
                vector_metadata: None,
                json_metadata: None,
            },
        ],
        primary_key: vec![0],
        secondary_index: None,
        secondary_index_type: IndexType::SortedArray,
        record_size: 4 + 4 + 32, // 40字节记录
        max_records: 100000,
        version: 1,
        created_at: 0,
        updated_at: 0,
    }
}

// 简单的测试平台实现
struct TestPlatform;

impl Platform for TestPlatform {
    fn get_timestamp(&self) -> u64 {
        0
    }

    fn get_timestamp_us(&self) -> u64 {
        0
    }

    fn spin_lock(&self, lock: &mut u32) {
        // 简单的自旋锁实现
        while unsafe {
            core::sync::atomic::AtomicU32::from_ptr(lock as *mut u32)
                .compare_exchange(
                    0,
                    1,
                    core::sync::atomic::Ordering::Acquire,
                    core::sync::atomic::Ordering::Relaxed,
                )
                .is_err()
        } {
            core::hint::spin_loop();
        }
    }

    fn spin_unlock(&self, lock: &mut u32) {
        unsafe {
            core::sync::atomic::AtomicU32::from_ptr(lock as *mut u32)
                .store(0, core::sync::atomic::Ordering::Release);
        }
    }

    fn compiler_barrier(&self) {
        core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
    }

    fn full_memory_barrier(&self) {
        core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
    }

    fn memcpy(&self, dest: *mut u8, src: *const u8, size: usize) {
        unsafe {
            core::ptr::copy_nonoverlapping(src, dest, size);
        }
    }

    fn memset(&self, dest: *mut u8, value: u8, size: usize) {
        unsafe {
            core::ptr::write_bytes(dest, value, size);
        }
    }

    fn delay_ms(&self, ms: u32) {
        std::thread::sleep(std::time::Duration::from_millis(ms as u64));
    }

    fn delay_us(&self, us: u32) {
        std::thread::sleep(std::time::Duration::from_micros(us as u64));
    }

    fn file_open(&self, _path: &str, _mode: FileMode) -> FileResult<FileHandle> {
        Ok(core::ptr::null())
    }

    fn file_close(&self, _handle: FileHandle) -> FileResult<()> {
        Ok(())
    }

    fn file_write(
        &self,
        _handle: FileHandle,
        _buffer: *const u8,
        size: usize,
    ) -> FileResult<usize> {
        Ok(size)
    }

    fn file_read(&self, _handle: FileHandle, _buffer: *mut u8, _size: usize) -> FileResult<usize> {
        Ok(0)
    }

    fn file_seek(&self, _handle: FileHandle, _offset: i64, _whence: SeekWhence) -> FileResult<u64> {
        Ok(0)
    }

    fn file_remove(&self, _path: &str) -> FileResult<()> {
        Ok(())
    }

    fn file_size(&self, _path: &str) -> FileResult<usize> {
        Ok(0)
    }

    fn crc32(&self, _data: *const u8, _size: usize) -> u32 {
        0
    }
}

static TEST_PLATFORM: TestPlatform = TestPlatform;

#[test]
fn test_large_table_performance() {
    let large_table_def = create_large_table_def();
    println!("=== 大表性能测试开始 ===");
    println!("表定义: {}", large_table_def.name);
    println!("记录大小: {} 字节", large_table_def.record_size);
    println!("最大记录数: {}", large_table_def.max_records);
    println!("目标测试记录数: {} (80%容量)", 80000);

    // 初始化平台
    unsafe {
        init_platform(&TEST_PLATFORM);
    }

    // 创建数据库配置
    static DEFAULT_ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;
    static TEST_DB_CONFIG: std::sync::LazyLock<DbConfig> = std::sync::LazyLock::new(|| DbConfig {
        tables: vec![create_large_table_def()],
        total_memory: 100_000_000, // 100MB,减小内存大小以避免内存分配失败
        low_power_mode_supported: false,
        low_power_max_records: Some(10000),
        default_max_records: 100000,
        memory_allocator: &DEFAULT_ALLOCATOR,
        wal_config: WALConfig {
            log_path: "./wal",
            log_mode: remdb::config::LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: remdb::config::WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: remdb::time_series::TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(remdb::config::HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: remdb::ha::HARole::Auto,
            replication_mode: remdb::ha::ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),
        model_worker_config: remdb::config::ModelWorkerConfig::DEFAULT,
    });

    unsafe {
        // 预分配内存缓冲区并初始化全局分配器
        // 使用安全的内存初始化方式,创建一个全零的Vec
        let mut memory_buffer = vec![0u8; TEST_DB_CONFIG.total_memory];
        remdb::memory::allocator::init_global_allocator(
            memory_buffer.as_mut_ptr(),
            TEST_DB_CONFIG.total_memory,
        )
        .unwrap();

        // 初始化数据库实例
        let db = init_global_db(&TEST_DB_CONFIG).unwrap();

        // 输出初始监控指标
        println!("\n初始监控指标:");
        println!("{}", db.dump_metrics());

        // 1. 插入80,000条记录(达到80%容量)
        println!("\n1. 插入80,000条记录...");
        let start_time = Instant::now();

        // 获取large_table(用户表在索引0,系统表在索引1)
        let table = db.get_table_mut(0).unwrap();
        let mut inserted_ids = Vec::with_capacity(80000);
        for i in 0..80000 {
            let mut record_data = [0u8; 40]; // 40字节记录

            // 设置ID字段(UInt32)
            let id: u32 = (i + 1) as u32;
            core::ptr::copy_nonoverlapping(
                &id as *const u32 as *const u8,
                record_data.as_mut_ptr(),
                4,
            );

            // 设置value字段(Float32)
            let value: f32 = (i as f32) * 1.5;
            core::ptr::copy_nonoverlapping(
                &value as *const f32 as *const u8,
                record_data.as_mut_ptr().add(4),
                4,
            );

            // 设置name字段(String,32字节)
            let name_str = format!("record_{:08}", i);
            let name_bytes = name_str.as_bytes();
            core::ptr::copy_nonoverlapping(
                name_bytes.as_ptr(),
                record_data.as_mut_ptr().add(8),
                name_bytes.len(),
            );

            // 插入记录
            let result = table.insert(record_data.as_ptr());
            assert!(result.is_ok(), "插入记录 {} 失败: {:?}", i, result);
            inserted_ids.push(result.unwrap());
        }

        // 先获取当前记录数,然后释放表引用
        let record_count = table.record_count();
        drop(table); // 释放表的可变引用

        let insert_duration = start_time.elapsed();
        println!("插入完成,耗时: {:?}", insert_duration);
        println!(
            "插入速率: {:.2} 条/秒",
            80000 as f64 / insert_duration.as_secs_f64()
        );
        println!("当前记录数: {}", record_count);

        // 输出监控指标
        println!("\n插入80,000条记录后的监控指标:");
        println!("{}", db.dump_metrics());

        // 2. 测试查询性能(查询10,000条随机记录)
        println!("\n2. 查询性能测试(10,000条随机记录)...");
        let start_time = Instant::now();

        // 获取表引用(large_table在索引0)
        let table = db.get_table_mut(0).unwrap();

        let mut query_success = 0;
        for _ in 0..10000 {
            // 生成随机记录ID(0-79999之间)
            let random_index = (random::<u32>() % 80000) as usize;
            let record_id = inserted_ids[random_index];

            // 读取记录数据
            let mut result_data = [0u8; 40];
            let get_result = table.get_by_id(record_id, result_data.as_mut_ptr());
            if get_result.is_ok() {
                query_success += 1;
            }
        }

        let query_duration = start_time.elapsed();
        println!("查询完成,耗时: {:?}", query_duration);
        println!(
            "查询速率: {:.2} 条/秒",
            query_success as f64 / query_duration.as_secs_f64()
        );
        println!(
            "查询成功率: {:.2}%",
            (query_success as f64 / 10000.0) * 100.0
        );

        // 释放表引用
        drop(table);

        // 输出监控指标
        println!("\n查询10,000条记录后的监控指标:");
        println!("{}", db.dump_metrics());

        // 3. 测试删除性能(删除10,000条记录)
        println!("\n3. 删除性能测试(10,000条记录)...");
        let start_time = Instant::now();

        // 获取表引用(large_table在索引0)
        let table = db.get_table_mut(0).unwrap();
        let mut delete_success = 0;
        let mut deleted_ids = Vec::with_capacity(10000);
        for i in 0..10000 {
            // 删除前10,000条记录
            let record_id = inserted_ids[i];
            let delete_result = table.delete(record_id);
            if delete_result.is_ok() {
                delete_success += 1;
                deleted_ids.push(record_id);
            }
        }

        let record_count_after_delete = table.record_count();
        let delete_duration = start_time.elapsed();
        println!("删除完成,耗时: {:?}", delete_duration);
        println!(
            "删除速率: {:.2} 条/秒",
            delete_success as f64 / delete_duration.as_secs_f64()
        );
        println!("当前记录数: {}", record_count_after_delete);

        // 释放表引用
        drop(table);

        // 输出监控指标
        println!("\n删除10,000条记录后的监控指标:");
        println!("{}", db.dump_metrics());

        // 4. 测试插入性能(插入10,000条新记录,填充被删除的空间)
        println!("\n4. 插入性能测试(10,000条新记录)...");
        let start_time = Instant::now();

        // 获取表引用(large_table在索引0)
        let table = db.get_table_mut(0).unwrap();
        let mut insert_success = 0;
        for i in 80000..90000 {
            let mut record_data = [0u8; 40];

            // 设置ID字段
            let id: u32 = (i + 1) as u32;
            core::ptr::copy_nonoverlapping(
                &id as *const u32 as *const u8,
                record_data.as_mut_ptr(),
                4,
            );

            // 设置value字段
            let value: f32 = (i as f32) * 1.5;
            core::ptr::copy_nonoverlapping(
                &value as *const f32 as *const u8,
                record_data.as_mut_ptr().add(4),
                4,
            );

            // 设置name字段
            let name_str = format!("record_{:08}", i);
            let name_bytes = name_str.as_bytes();
            core::ptr::copy_nonoverlapping(
                name_bytes.as_ptr(),
                record_data.as_mut_ptr().add(8),
                name_bytes.len(),
            );

            // 插入记录
            let result = table.insert(record_data.as_ptr());
            if result.is_ok() {
                insert_success += 1;
            }
        }

        let record_count_after_insert = table.record_count();
        let second_insert_duration = start_time.elapsed();
        println!("插入完成,耗时: {:?}", second_insert_duration);
        println!(
            "插入速率: {:.2} 条/秒",
            insert_success as f64 / second_insert_duration.as_secs_f64()
        );
        println!("当前记录数: {}", record_count_after_insert);

        // 释放表引用
        drop(table);

        // 输出监控指标
        println!("\n第二次插入10,000条记录后的监控指标:");
        println!("{}", db.dump_metrics());

        // 5. 测试批量查询性能(顺序查询10,000条记录)
        println!("\n5. 批量查询性能测试(顺序查询10,000条记录)...");
        let start_time = Instant::now();

        // 获取表引用
        let table = db.get_table_mut(0).unwrap();
        let mut batch_query_success = 0;
        for i in 10000..20000 {
            // 使用预先保存的记录ID查询
            let record_id = inserted_ids[i];

            // 读取记录数据
            let mut result_data = [0u8; 40];
            let get_result = table.get_by_id(record_id, result_data.as_mut_ptr());
            if get_result.is_ok() {
                batch_query_success += 1;
            }
        }

        let batch_query_duration = start_time.elapsed();
        println!("批量查询完成,耗时: {:?}", batch_query_duration);
        println!(
            "批量查询速率: {:.2} 条/秒",
            batch_query_success as f64 / batch_query_duration.as_secs_f64()
        );

        // 释放表引用
        drop(table);

        // 输出监控指标
        println!("\n批量查询10,000条记录后的监控指标:");
        println!("{}", db.dump_metrics());

        // 执行健康检查(暂时注释,health_check方法不存在)
        // println!("\n健康检查结果:");
        // let health_result = db.health_check();
        // println!("{}", health_result.to_text());

        // 输出最终指标快照
        println!("\n测试完成,最终指标快照:");
        let snapshot = db.metrics_snapshot();
        println!("{}", snapshot.to_text());

        // 重置指标
        db.reset_metrics();
        println!("\n指标已重置,准备下次测试");

        println!("\n=== 大表性能测试结束 ===");
    }
}