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
| #define FDB_API_VERSION 710
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
#include <fdb_c.h> #include <unistd.h>
FDBTransaction *tr = NULL; FDBDatabase *db = NULL; pthread_t netThread;
static void checkError(fdb_error_t errorNum) { if (errorNum) { fprintf(stderr, "Error (%d): %s\n", errorNum, fdb_get_error(errorNum)); exit(errorNum); } }
static void waitAndCheckError(FDBFuture *future) { checkError(fdb_future_block_until_ready(future)); if (fdb_future_get_error(future) != 0) { checkError(fdb_future_get_error(future)); } }
static void runNetwork() { checkError(fdb_run_network()); }
void createDataInDatabase() { int committed = 0; checkError(fdb_database_create_transaction(db, &tr));
while (!committed) { char *key1 = "Test Key1"; char *val1 = "Test Value1"; fdb_transaction_set(tr, key1, (int)strlen(key1), val1, (int)strlen(val1));
FDBFuture *commitFuture = fdb_transaction_commit(tr); checkError(fdb_future_block_until_ready(commitFuture)); if (fdb_future_get_error(commitFuture) != 0) { waitAndCheckError( fdb_transaction_on_error(tr, fdb_future_get_error(commitFuture))); } else { committed = 1; } fdb_future_destroy(commitFuture); } fdb_transaction_destroy(tr); }
void readDataFromDatabase() { FDBTransaction *tr = NULL; const uint8_t *value = NULL; fdb_bool_t valuePresent; int valueLength; char *key = "Test Key1";
checkError(fdb_database_create_transaction(db, &tr)); FDBFuture *getFuture = fdb_transaction_get(tr, key, (int)strlen(key), 0); waitAndCheckError(getFuture);
checkError( fdb_future_get_value(getFuture, &valuePresent, &value, &valueLength));
printf("Got Value from db. %s: '%.*s'\n", key, valueLength, value); fdb_transaction_destroy(tr); fdb_future_destroy(getFuture); }
int main() { char *cluster_file = "/etc/foundationdb/fdb.cluster";
checkError(fdb_select_api_version(FDB_API_VERSION)); checkError(fdb_setup_network()); puts("Created network.");
pthread_create(&netThread, NULL, (void *)runNetwork, NULL);
checkError(fdb_create_database(cluster_file, &db)); puts("Created database.");
createDataInDatabase(); readDataFromDatabase();
puts("Program done. Now exiting..."); fdb_database_destroy(db); db = NULL; checkError(fdb_stop_network()); int rc = pthread_join(netThread, NULL); if (rc) fprintf(stderr, "ERROR: network thread failed to join\n"); exit(0); }
|