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
use remdb::config::{
    DbConfig, DefaultMemoryAllocator, LogMode, TimeSeriesConfig, WALCompressionType, WALConfig,
};
use remdb::platform::{file_size, get_timestamp_us};
use remdb::transaction::{LogItem, LogManager, LogOperation, VariableSizeLogItem};

mod common;
use common::setup_test_db_with_posix;

#[cfg(windows)]
fn get_test_wal_path(name: &str) -> &'static str {
    let s = format!("C:\\temp\\{}", name);
    Box::leak(s.into_boxed_str())
}

#[cfg(not(windows))]
fn get_test_wal_path(name: &str) -> &'static str {
    let s = format!("/tmp/{}", name);
    Box::leak(s.into_boxed_str())
}

/// 测试不同压缩类型的 WAL 功能
fn test_wal_compression(compression_type: WALCompressionType, test_name: &str) {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path(test_name),
            log_mode: 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,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: None,

        model_worker_config: Default::default(),
    };

    unsafe {
        let mut log_manager = LogManager::new(&config).unwrap();

        // 测试1:创建小型可变大小日志项(小于512字节)
        let small_new_data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
        let mut small_log_item = VariableSizeLogItem {
            header: LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: 1,
                old_data_size: 0,
                new_data_size: small_new_data.len() as u16,
                tx_id: 1,
                timestamp: 1234567890,
                checksum: 0,
            },
            old_data: vec![],
            new_data: small_new_data,
        };

        let calculated_checksum =
            remdb::transaction::Transaction::calculate_variable_size_log_item_checksum(
                &small_log_item,
            );
        small_log_item.header.checksum = calculated_checksum;

        let result = log_manager.write_variable_size_log_item(&small_log_item);
        assert!(
            result.is_ok(),
            "Failed to write small variable size log item with {:?} compression",
            compression_type
        );

        // 测试2:创建大型可变大小日志项(大于512字节)
        let mut large_new_data = vec![0u8; 1024];
        for i in 0..1024 {
            large_new_data[i] = (i % 256) as u8;
        }
        let mut large_log_item = VariableSizeLogItem {
            header: LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: 2,
                old_data_size: 0,
                new_data_size: large_new_data.len() as u16,
                tx_id: 2,
                timestamp: 1234567891,
                checksum: 0,
            },
            old_data: vec![],
            new_data: large_new_data,
        };

        let calculated_checksum =
            remdb::transaction::Transaction::calculate_variable_size_log_item_checksum(
                &large_log_item,
            );
        large_log_item.header.checksum = calculated_checksum;

        let result = log_manager.write_variable_size_log_item(&large_log_item);
        assert!(
            result.is_ok(),
            "Failed to write large variable size log item with {:?} compression",
            compression_type
        );

        // 测试3:读取并验证日志项
        let read_small = log_manager.read_variable_size_log_item(0);
        assert!(
            read_small.is_ok(),
            "Failed to read small variable size log item with {:?} compression",
            compression_type
        );
        let read_small = read_small.unwrap();
        assert_eq!(read_small.header.op_type, LogOperation::Insert);
        assert_eq!(read_small.header.table_id, 0);
        assert_eq!(read_small.header.record_id, 1);
        assert_eq!(read_small.header.new_data_size, 8);
        assert_eq!(read_small.new_data.len(), 8);
        assert_eq!(read_small.new_data, vec![1u8, 2, 3, 4, 5, 6, 7, 8]);

        let read_large = log_manager.read_variable_size_log_item(1);
        assert!(
            read_large.is_ok(),
            "Failed to read large variable size log item with {:?} compression",
            compression_type
        );
        let read_large = read_large.unwrap();
        assert_eq!(read_large.header.op_type, LogOperation::Insert);
        assert_eq!(read_large.header.table_id, 0);
        assert_eq!(read_large.header.record_id, 2);
        assert_eq!(read_large.header.new_data_size, 1024);
        assert_eq!(read_large.new_data.len(), 1024);
        for i in 0..1024 {
            assert_eq!(read_large.new_data[i], (i % 256) as u8);
        }

        // 测试4:创建检查点并验证
        let result = log_manager.create_checkpoint();
        assert!(
            result.is_ok(),
            "Failed to create checkpoint with {:?} compression",
            compression_type
        );

        println!("{:?} compression test passed!", compression_type);
    }
}

#[test]
fn test_wal_compression_none() {
    test_wal_compression(WALCompressionType::None, "test_compression_none");
}

#[cfg(feature = "wal-compression-lz4")]
#[test]
fn test_wal_compression_lz4() {
    test_wal_compression(WALCompressionType::LZ4, "test_compression_lz4");
}

#[cfg(feature = "wal-compression-zstd")]
#[test]
fn test_wal_compression_zstd() {
    test_wal_compression(WALCompressionType::ZSTD, "test_compression_zstd");
}

/// 测试压缩对存储空间的影响
#[test]
fn test_wal_compression_storage_impact() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 测试不同压缩类型的存储空间使用
    let compression_types = vec![
        (WALCompressionType::None, "test_storage_none"),
        #[cfg(feature = "wal-compression-lz4")]
        (WALCompressionType::LZ4, "test_storage_lz4"),
        #[cfg(feature = "wal-compression-zstd")]
        (WALCompressionType::ZSTD, "test_storage_zstd"),
    ];

    for (compression_type, test_name) in compression_types {
        // 创建数据库配置
        let config = DbConfig {
            tables: vec![],
            total_memory: 1024 * 1024, // 1MB
            low_power_mode_supported: false,
            low_power_max_records: None,
            default_max_records: 1000,
            memory_allocator: &ALLOCATOR,
            wal_config: WALConfig {
                log_path: &get_test_wal_path(test_name),
                log_mode: 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,
                compression_level: 3,
            },
            time_series_defaults: TimeSeriesConfig::DEFAULT,
            #[cfg(feature = "pubsub")]
            pubsub_config: None,
            #[cfg(feature = "ha")]
            ha_config: None,

            model_worker_config: Default::default(),
        };

        unsafe {
            let mut log_manager = LogManager::new(&config).unwrap();

            // 写入大量重复数据以测试压缩效果
            let mut repeated_data = vec![0u8; 1024];
            for i in 0..1024 {
                repeated_data[i] = (i % 16) as u8; // 创建重复模式
            }

            // 写入100个日志项
            for i in 0..100 {
                let mut log_item = VariableSizeLogItem {
                    header: LogItem {
                        op_type: LogOperation::Insert,
                        table_id: 0,
                        record_id: i as u16,
                        old_data_size: 0,
                        new_data_size: repeated_data.len() as u16,
                        tx_id: i as u32,
                        timestamp: 1234567890 + i as u64,
                        checksum: 0,
                    },
                    old_data: vec![],
                    new_data: repeated_data.clone(),
                };

                let calculated_checksum =
                    remdb::transaction::Transaction::calculate_variable_size_log_item_checksum(
                        &log_item,
                    );
                log_item.header.checksum = calculated_checksum;

                let result = log_manager.write_variable_size_log_item(&log_item);
                assert!(
                    result.is_ok(),
                    "Failed to write log item with {:?} compression",
                    compression_type
                );
            }

            // 获取日志文件大小
            let wal_file_path = format!("{}/remdb.wal", config.wal_config.log_path);
            let file_size = file_size(wal_file_path.as_str()).unwrap();
            println!(
                "📊 {:?} compression: WAL file size = {} bytes for 100 log items",
                compression_type, file_size
            );
        }
    }

    println!("✅ WAL compression storage impact test completed!");
}

/// 测试压缩对性能的影响
#[test]
fn test_wal_compression_performance() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 测试不同压缩类型的性能
    let compression_types = vec![
        (WALCompressionType::None, "test_perf_none"),
        #[cfg(feature = "wal-compression-lz4")]
        (WALCompressionType::LZ4, "test_perf_lz4"),
        #[cfg(feature = "wal-compression-zstd")]
        (WALCompressionType::ZSTD, "test_perf_zstd"),
    ];

    for (compression_type, test_name) in compression_types {
        // 创建数据库配置
        let config = DbConfig {
            tables: vec![],
            total_memory: 1024 * 1024, // 1MB
            low_power_mode_supported: false,
            low_power_max_records: None,
            default_max_records: 1000,
            memory_allocator: &ALLOCATOR,
            wal_config: WALConfig {
                log_path: &get_test_wal_path(test_name),
                log_mode: 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,
                compression_level: 3,
            },
            time_series_defaults: TimeSeriesConfig::DEFAULT,
            #[cfg(feature = "pubsub")]
            pubsub_config: None,
            #[cfg(feature = "ha")]
            ha_config: None,

            model_worker_config: Default::default(),
        };

        unsafe {
            let mut log_manager = LogManager::new(&config).unwrap();

            // 准备测试数据
            let mut test_data = vec![0u8; 512];
            for i in 0..512 {
                test_data[i] = (i % 256) as u8;
            }

            // 测试写入性能
            let start_time = get_timestamp_us();

            // 写入500个日志项
            for i in 0..500 {
                let mut log_item = VariableSizeLogItem {
                    header: LogItem {
                        op_type: LogOperation::Insert,
                        table_id: 0,
                        record_id: i as u16,
                        old_data_size: 0,
                        new_data_size: test_data.len() as u16,
                        tx_id: i as u32,
                        timestamp: 1234567890 + i as u64,
                        checksum: 0,
                    },
                    old_data: vec![],
                    new_data: test_data.clone(),
                };

                let calculated_checksum =
                    remdb::transaction::Transaction::calculate_variable_size_log_item_checksum(
                        &log_item,
                    );
                log_item.header.checksum = calculated_checksum;

                let result = log_manager.write_variable_size_log_item(&log_item);
                assert!(
                    result.is_ok(),
                    "Failed to write log item with {:?} compression",
                    compression_type
                );
            }

            let end_time = get_timestamp_us();
            let write_time = end_time - start_time;
            println!(
                "📈 {:?} compression: Write time = {} us for 500 log items",
                compression_type, write_time
            );

            // 测试读取性能
            let start_time = get_timestamp_us();

            // 读取所有日志项
            for i in 0..500 {
                let result = log_manager.read_variable_size_log_item(i as u32);
                assert!(
                    result.is_ok(),
                    "Failed to read log item {} with {:?} compression",
                    i,
                    compression_type
                );
            }

            let end_time = get_timestamp_us();
            let read_time = end_time - start_time;
            println!(
                "📈 {:?} compression: Read time = {} us for 500 log items",
                compression_type, read_time
            );
        }
    }

    println!("✅ WAL compression performance test completed!");
}