Files
2024-12-10 19:40:34 +08:00

121 lines
3.2 KiB
C

#include "unqlite.h"
#include "unqlite.c"
#include <stdio.h>
#include <stdlib.h>
/*
* Extract the database error log and exit.
*/
static void Fatal(unqlite *pDb, const char *zMsg)
{
if (pDb)
{
const char *zErr;
int iLen = 0; /* Stupid cc warning */
/* Extract the database error log */
unqlite_config(pDb, UNQLITE_CONFIG_ERR_LOG, &zErr, &iLen);
if (iLen > 0)
{
/* Output the DB error log */
puts(zErr); /* Always null terminated */
}
}
else
{
if (zMsg)
{
puts(zMsg);
}
}
/* Manually shutdown the library */
unqlite_lib_shutdown();
/* Exit immediately */
exit(0);
}
static int DataConsumerCallback(const void *pData, unsigned int nDatalen, void *pUserData /* Unused */)
{
#ifdef __WINNT__
BOOL rc;
rc = WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), pData, (DWORD)nDatalen, 0, 0);
if (!rc)
{
/* Abort processing */
return UNQLITE_ABORT;
}
#else
ssize_t nWr;
nWr = write(STDOUT_FILENO, pData, nDatalen);
if (nWr < 0)
{
/* Abort processing */
return UNQLITE_ABORT;
}
#endif /* __WINT__ */
/* All done, data was redirected to STDOUT */
return UNQLITE_OK;
}
int main(int argc, char *argv[])
{
printf("Start Test Unqlite\n");
unqlite *pDb; /* Database handle */
unqlite_kv_cursor *pCur; /* Cursor handle */
int i, rc;
rc = unqlite_open(&pDb, ":mem:", UNQLITE_OPEN_CREATE);
if (rc != UNQLITE_OK)
{
Fatal(0, "Out of memory");
}
/* Store some records */
rc = unqlite_kv_store(pDb, "test1", -1, "Hello World", 11); /* test => 'Hello World' */
rc = unqlite_kv_store(pDb, "test2", -1, "Hello World", 11); /* test => 'Hello World' */
rc = unqlite_kv_store(pDb, "test3", -1, "Hello World", 11); /* test => 'Hello World' */
rc = unqlite_kv_store(pDb, "test4", -1, "Hello World", 11); /* test => 'Hello World' */
rc = unqlite_kv_store(pDb, "test5", -1, "Hello World", 11); /* test => 'Hello World' */
if (rc != UNQLITE_OK)
{
/* Insertion fail, extract database error log and exit */
Fatal(pDb, 0);
}
rc = unqlite_kv_cursor_init(pDb, &pCur);
if (rc != UNQLITE_OK)
{
Fatal(0, "Out of memory");
}
/* Point to the first record */
unqlite_kv_cursor_first_entry(pCur);
/* Iterate over the entries */
while (unqlite_kv_cursor_valid_entry(pCur))
{
int nKeyLen;
unqlite_int64 nDataLen;
/* Consume the key */
unqlite_kv_cursor_key(pCur, 0, &nKeyLen); /* Extract key length */
printf("\nKey ==> %u\n\t", nKeyLen);
unqlite_kv_cursor_key_callback(pCur, DataConsumerCallback, 0);
/* Consume the data */
unqlite_kv_cursor_data(pCur, 0, &nDataLen);
printf("\nData ==> %lld\n\t", nDataLen);
unqlite_kv_cursor_data_callback(pCur, DataConsumerCallback, 0);
/* Point to the next entry */
unqlite_kv_cursor_next_entry(pCur);
}
/* Finally, Release our cursor */
unqlite_kv_cursor_release(pDb, pCur);
/* Auto-commit the transaction and close our database */
unqlite_close(pDb);
}