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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
 * RemDB C API Example
 *
 * This example demonstrates the basic usage of RemDB C API,
 * including database initialization, CRUD operations, transactions,
 * snapshot management, and health monitoring.
 *
 * Compile with:
 * gcc -o c_api_example c_api_example.c -lremdb -L../target/release -I../include
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "remdb.h"

// Define a simple table structure for demonstration
typedef struct User {
    uint32_t id;
    char name[REMDB_MAX_STRING_LEN];
    uint32_t age;
} User;

// Define field names as constants
const char* USER_ID_FIELD = "id";
const char* USER_NAME_FIELD = "name";
const char* USER_AGE_FIELD = "age";

int main() {
    printf("RemDB C API Example\n");
    printf("=====================\n\n");

    // Step 1: Define field definitions
    RemDbFieldDef user_fields[] = {
        { USER_ID_FIELD, REMDB_TYPE_UINT32, sizeof(uint32_t), offsetof(User, id) },
        { USER_NAME_FIELD, REMDB_TYPE_STRING, sizeof(((User*)0)->name), offsetof(User, name) },
        { USER_AGE_FIELD, REMDB_TYPE_UINT32, sizeof(uint32_t), offsetof(User, age) }
    };
    size_t user_fields_count = sizeof(user_fields) / sizeof(user_fields[0]);

    // Step 2: Define table definition
    RemDbTableDef user_table = {
        .id = 0,
        .name = "users",
        .fields = user_fields,
        .fields_count = user_fields_count,
        .primary_key = 0,  // id is primary key
        .secondary_index = -1,  // no secondary index
        .record_size = sizeof(User),
        .max_records = 1000
    };

    // Step 3: Define database configuration
    RemDbTableDef tables[] = { user_table };
    RemDbConfig config = {
        .tables = tables,
        .tables_count = sizeof(tables) / sizeof(tables[0]),
        .time_series_tables = NULL,
        .time_series_tables_count = 0,
        .total_memory = 1024 * 1024 * 100,  // 100 MB
        .low_power_mode_supported = 1,
        .low_power_max_records = 500
    };

    // Step 4: Initialize database
    RemDbHandle handle = NULL;
    enum RemDbError err = remdb_init_global(&config, &handle);
    if (err != REMDB_SUCCESS) {
        printf("Failed to initialize database: error code %d\n", err);
        return 1;
    }
    printf("Database initialized successfully!\n\n");

    // Step 5: Insert records
    printf("Inserting records...\n");
    
    User user1 = { .id = 1, .name = "Alice", .age = 25 };
    err = remdb_table_insert(handle, 0, &user1);
    if (err != REMDB_SUCCESS) {
        printf("Failed to insert user 1: error code %d\n", err);
    } else {
        printf("Inserted user: %d, %s, %d\n", user1.id, user1.name, user1.age);
    }

    User user2 = { .id = 2, .name = "Bob", .age = 30 };
    err = remdb_table_insert(handle, 0, &user2);
    if (err != REMDB_SUCCESS) {
        printf("Failed to insert user 2: error code %d\n", err);
    } else {
        printf("Inserted user: %d, %s, %d\n", user2.id, user2.name, user2.age);
    }

    User user3 = { .id = 3, .name = "Charlie", .age = 35 };
    err = remdb_table_insert(handle, 0, &user3);
    if (err != REMDB_SUCCESS) {
        printf("Failed to insert user 3: error code %d\n", err);
    } else {
        printf("Inserted user: %d, %s, %d\n", user3.id, user3.name, user3.age);
    }
    printf("\n");

    // Step 6: Query records
    printf("Querying records...\n");
    
    RemDbValue key;
    key.u32 = 2;
    User retrieved_user;
    
    err = remdb_table_get(handle, 0, &key, &retrieved_user);
    if (err != REMDB_SUCCESS) {
        printf("Failed to get user 2: error code %d\n", err);
    } else {
        printf("Retrieved user: %d, %s, %d\n", retrieved_user.id, retrieved_user.name, retrieved_user.age);
    }
    printf("\n");

    // Step 7: Update record
    printf("Updating record...\n");
    
    User updated_user = { .id = 2, .name = "Robert", .age = 31 };
    err = remdb_table_update(handle, 0, &key, &updated_user);
    if (err != REMDB_SUCCESS) {
        printf("Failed to update user 2: error code %d\n", err);
    } else {
        printf("Updated user 2 to: %d, %s, %d\n", updated_user.id, updated_user.name, updated_user.age);
        
        // Verify update
        err = remdb_table_get(handle, 0, &key, &retrieved_user);
        if (err == REMDB_SUCCESS) {
            printf("Verified updated user: %d, %s, %d\n", retrieved_user.id, retrieved_user.name, retrieved_user.age);
        }
    }
    printf("\n");

    // Step 8: Transaction example
    printf("Transaction example...\n");
    
    // Start transaction
    err = remdb_begin_transaction(handle, REMDB_TX_WRITE, REMDB_ISO_READ_COMMITTED);
    if (err != REMDB_SUCCESS) {
        printf("Failed to begin transaction: error code %d\n", err);
    } else {
        printf("Transaction started successfully\n");
        
        // Insert a record in transaction
        User user4 = { .id = 4, .name = "David", .age = 28 };
        err = remdb_table_insert(handle, 0, &user4);
        if (err != REMDB_SUCCESS) {
            printf("Failed to insert user 4 in transaction: error code %d\n", err);
            remdb_rollback_transaction(handle);
            printf("Transaction rolled back\n");
        } else {
            printf("Inserted user 4 in transaction: %d, %s, %d\n", user4.id, user4.name, user4.age);
            
            // Commit transaction
            err = remdb_commit_transaction(handle);
            if (err != REMDB_SUCCESS) {
                printf("Failed to commit transaction: error code %d\n", err);
                remdb_rollback_transaction(handle);
                printf("Transaction rolled back\n");
            } else {
                printf("Transaction committed successfully\n");
            }
        }
    }
    printf("\n");

    // Step 9: Get record count
    printf("Getting record count...\n");
    size_t record_count = 0;
    err = remdb_table_get_record_count(handle, 0, &record_count);
    if (err != REMDB_SUCCESS) {
        printf("Failed to get record count: error code %d\n", err);
    } else {
        printf("Current record count: %zu\n", record_count);
    }
    printf("\n");

    // Step 10: Snapshot management
    printf("Snapshot management...\n");
    
    // Save snapshot
    err = remdb_save_snapshot(handle, "example_snapshot");
    if (err != REMDB_SUCCESS) {
        printf("Failed to save snapshot: error code %d\n", err);
    } else {
        printf("Snapshot saved successfully to 'example_snapshot'\n");
    }
    
    // Delete a record
    printf("Deleting user 3...\n");
    RemDbValue delete_key;
    delete_key.u32 = 3;
    err = remdb_table_delete(handle, 0, &delete_key);
    if (err != REMDB_SUCCESS) {
        printf("Failed to delete user 3: error code %d\n", err);
    } else {
        printf("Deleted user 3\n");
        
        // Get updated record count
        err = remdb_table_get_record_count(handle, 0, &record_count);
        if (err == REMDB_SUCCESS) {
            printf("Record count after deletion: %zu\n", record_count);
        }
        
        // Restore snapshot
        printf("Restoring snapshot...\n");
        err = remdb_restore_snapshot(handle, "example_snapshot");
        if (err != REMDB_SUCCESS) {
            printf("Failed to restore snapshot: error code %d\n", err);
        } else {
            printf("Snapshot restored successfully\n");
            
            // Get record count after restoration
            err = remdb_table_get_record_count(handle, 0, &record_count);
            if (err == REMDB_SUCCESS) {
                printf("Record count after restoration: %zu\n", record_count);
            }
        }
    }
    printf("\n");

    // Step 11: Health check
    printf("Health check...\n");
    RemDbHealthCheckResult health_result;
    err = remdb_health_check(handle, &health_result);
    if (err != REMDB_SUCCESS) {
        printf("Failed to perform health check: error code %d\n", err);
    } else {
        const char* health_status_str = NULL;
        switch (health_result.status) {
            case REMDB_HEALTH_HEALTHY:
                health_status_str = "Healthy";
                break;
            case REMDB_HEALTH_WARNING:
                health_status_str = "Warning";
                break;
            case REMDB_HEALTH_UNHEALTHY:
                health_status_str = "Unhealthy";
                break;
            default:
                health_status_str = "Unknown";
        }
        printf("Health status: %s\n", health_status_str);
        printf("Health details: %s\n", health_result.details);
        printf("Memory usage: %zu / %zu bytes\n", health_result.metrics.used_memory, health_result.metrics.total_memory);
    }
    printf("\n");

    // Step 12: Dump metrics
    printf("Dumping metrics...\n");
    char metrics_buffer[1024];
    size_t written = 0;
    err = remdb_dump_metrics(handle, metrics_buffer, sizeof(metrics_buffer), &written);
    if (err != REMDB_SUCCESS) {
        printf("Failed to dump metrics: error code %d\n", err);
    } else {
        printf("Metrics:\n%s\n", metrics_buffer);
    }
    printf("\n");

    // Step 13: Get snapshot version
    printf("Getting snapshot version...\n");
    uint32_t snapshot_version = 0;
    err = remdb_get_snapshot_version(handle, &snapshot_version);
    if (err != REMDB_SUCCESS) {
        printf("Failed to get snapshot version: error code %d\n", err);
    } else {
        printf("Current snapshot version: %u\n", snapshot_version);
    }
    printf("\n");

    // Step 14: Low power mode example
    printf("Low power mode example...\n");
    uint8_t is_low_power = 0;
    err = remdb_is_low_power_mode(handle, &is_low_power);
    if (err != REMDB_SUCCESS) {
        printf("Failed to check low power mode: error code %d\n", err);
    } else {
        printf("Current low power mode status: %s\n", is_low_power ? "Enabled" : "Disabled");
        
        // Enter low power mode
        err = remdb_enter_low_power_mode(handle);
        if (err != REMDB_SUCCESS) {
            printf("Failed to enter low power mode: error code %d\n", err);
        } else {
            printf("Entered low power mode\n");
            
            // Check status again
            err = remdb_is_low_power_mode(handle, &is_low_power);
            if (err == REMDB_SUCCESS) {
                printf("Updated low power mode status: %s\n", is_low_power ? "Enabled" : "Disabled");
            }
            
            // Exit low power mode
            err = remdb_exit_low_power_mode(handle);
            if (err != REMDB_SUCCESS) {
                printf("Failed to exit low power mode: error code %d\n", err);
            } else {
                printf("Exited low power mode\n");
                
                // Check status again
                err = remdb_is_low_power_mode(handle, &is_low_power);
                if (err == REMDB_SUCCESS) {
                    printf("Final low power mode status: %s\n", is_low_power ? "Enabled" : "Disabled");
                }
            }
        }
    }
    printf("\n");

    // Step 15: SQL Query Example
    printf("SQL Query Example...\n");
    
    // Execute SQL query
    RemDbResultSet* result_set = NULL;
    err = remdb_sql_query(handle, "SELECT id, name, age FROM users WHERE age > 25", &result_set);
    if (err != REMDB_SUCCESS) {
        printf("Failed to execute SQL query: error code %d\n", err);
    } else {
        printf("SQL query executed successfully!\n");
        printf("Query results: %zu rows\n", result_set->rows_count);
        printf("Columns: %zu\n", result_set->columns_count);
        
        // Print column names
        printf("Column names: ");
        for (size_t i = 0; i < result_set->columns_count; i++) {
            const char* column_name = *(result_set->columns + i);
            printf("%s", column_name);
            if (i < result_set->columns_count - 1) {
                printf(", ");
            }
        }
        printf("\n\n");
        
        // Print rows
        for (size_t i = 0; i < result_set->rows_count; i++) {
            const RemDbResultRow* row = &result_set->rows[i];
            printf("Row %zu: ", i + 1);
            
            for (size_t j = 0; j < row->values_count; j++) {
                const RemDbTypedValue* value = &row->values[j];
                
                // Print value based on data type
                switch (value->data_type) {
                    case REMDB_TYPE_UINT32:
                        printf("%u", value->value.u32);
                        break;
                    case REMDB_TYPE_STRING:
                        printf("%s", (const char*)value->value.string);
                        break;
                    default:
                        printf("<unsupported type>");
                        break;
                }
                
                if (j < row->values_count - 1) {
                    printf(", ");
                }
            }
            printf("\n");
        }
        
        // Free result set
        err = remdb_free_result_set(result_set);
        if (err != REMDB_SUCCESS) {
            printf("Failed to free result set: error code %d\n", err);
        } else {
            printf("\nResult set freed successfully\n");
        }
    }
    printf("\n");
    
    // Step 16: Execute Query Example
    printf("Execute Query Example...\n");
    
    // Define columns to query
    const char* columns[] = {"id", "name"};
    size_t columns_count = sizeof(columns) / sizeof(columns[0]);
    
    // Execute query
    err = remdb_execute_query(handle, "users", columns, columns_count, "age < 30", 10, &result_set);
    if (err != REMDB_SUCCESS) {
        printf("Failed to execute query: error code %d\n", err);
    } else {
        printf("Query executed successfully! %zu rows returned\n", result_set->rows_count);
        
        // Free result set
        err = remdb_free_result_set(result_set);
        if (err != REMDB_SUCCESS) {
            printf("Failed to free result set: error code %d\n", err);
        }
    }
    printf("\n");
    
    // Step 17: Batch Insert Example
    printf("Batch Insert Example...\n");
    
    // Define column names for batch insert
    const char* batch_columns[] = {"id", "name", "age"};
    size_t batch_columns_count = sizeof(batch_columns) / sizeof(batch_columns[0]);
    
    // Prepare batch data
    const char* record1[] = {"5", "Eve", "29"};
    const char* record2[] = {"6", "Frank", "32"};
    const char* record3[] = {"7", "Grace", "27"};
    const char*** records = (const char***)malloc(3 * sizeof(const char**));
    records[0] = (const char**)record1;
    records[1] = (const char**)record2;
    records[2] = (const char**)record3;
    
    size_t affected_rows = 0;
    err = remdb_batch_insert_record(handle, "users", batch_columns, batch_columns_count, records, 3, 3, &affected_rows);
    if (err != REMDB_SUCCESS) {
        printf("Failed to batch insert records: error code %d\n", err);
    } else {
        printf("Batch inserted %zu records successfully!\n", affected_rows);
    }
    free(records);
    printf("\n");
    
    // Step 18: Create Table Example
    printf("Create Table Example...\n");
    
    // Define new table fields
    RemDbFieldDef product_fields[] = {
        { "id", REMDB_TYPE_UINT32, sizeof(uint32_t), 0 },
        { "name", REMDB_TYPE_STRING, REMDB_MAX_STRING_LEN, sizeof(uint32_t) },
        { "price", REMDB_TYPE_FLOAT32, sizeof(float), sizeof(uint32_t) + REMDB_MAX_STRING_LEN }
    };
    size_t product_fields_count = sizeof(product_fields) / sizeof(product_fields[0]);
    
    // Create new table
    err = remdb_create_table(handle, "products", product_fields, product_fields_count, 0);
    if (err != REMDB_SUCCESS) {
        printf("Failed to create table: error code %d\n", err);
    } else {
        printf("Table 'products' created successfully!\n");
    }
    printf("\n");
    
    // Step 19: Get Table by Name Example
    printf("Get Table by Name Example...\n");
    size_t table_id = 0;
    err = remdb_table_get_by_name(handle, "products", &table_id);
    if (err != REMDB_SUCCESS) {
        printf("Failed to get table by name: error code %d\n", err);
    } else {
        printf("Table 'products' found with ID: %zu\n", table_id);
    }
    printf("\n");
    
    // Step 20: Metrics Snapshot Example
    printf("Metrics Snapshot Example...\n");
    RemDbMetricsSnapshot metrics;
    err = remdb_get_metrics_snapshot(handle, &metrics);
    if (err != REMDB_SUCCESS) {
        printf("Failed to get metrics snapshot: error code %d\n", err);
    } else {
        printf("Metrics Snapshot:\n");
        printf("  Total Memory: %zu bytes\n", metrics.total_memory);
        printf("  Used Memory: %zu bytes\n", metrics.used_memory);
        printf("  Read Operations: %llu\n", (unsigned long long)metrics.read_ops);
        printf("  Write Operations: %llu\n", (unsigned long long)metrics.write_ops);
        printf("  Delete Operations: %llu\n", (unsigned long long)metrics.delete_ops);
        printf("  Update Operations: %llu\n", (unsigned long long)metrics.update_ops);
        printf("  Transactions: %llu\n", (unsigned long long)metrics.transactions);
        printf("  Committed Transactions: %llu\n", (unsigned long long)metrics.committed_transactions);
        printf("  Rolled Back Transactions: %llu\n", (unsigned long long)metrics.rolled_back_transactions);
    }
    printf("\n");
    
    // Step 21: Reset Metrics Example
    printf("Reset Metrics Example...\n");
    err = remdb_reset_metrics(handle);
    if (err != REMDB_SUCCESS) {
        printf("Failed to reset metrics: error code %d\n", err);
    } else {
        printf("Metrics reset successfully!\n");
    }
    printf("\n");
    
    // Step 22: Export DDL Example
    printf("Export DDL Example...\n");
    
    err = remdb_export_ddl(handle, "exported_ddl.sql");
    if (err != REMDB_SUCCESS) {
        printf("Failed to export DDL: error code %d\n", err);
    } else {
        printf("DDL exported successfully to 'exported_ddl.sql'\n");
    }
    printf("\n");
    
    // Step 23: Export Data Example
    printf("Export Data Example...\n");
    
    err = remdb_export_data(handle, "exported_data.sql");
    if (err != REMDB_SUCCESS) {
        printf("Failed to export data: error code %d\n", err);
    } else {
        printf("Data exported successfully to 'exported_data.sql'\n");
    }
    printf("\n");
    
    printf("RemDB C API Example completed successfully!\n");
    printf("========================================\n");

    return 0;
}