Skip to content

Instantly share code, notes, and snippets.

@rogerbinns
Created Jul 19, 2021
Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#define CHECK \
do \
{ \
if (res != SQLITE_OK) \
{ \
fprintf(stderr, "Failed at line %d with code %d\n", __LINE__, res); \
exit(1); \
} \
} while (0)
int main(int argc, char **argv)
{
int res;
sqlite3 *db = NULL;
unsigned char *serialized = NULL;
sqlite3_int64 serial_size = 0;
void *datacopy = NULL;
/* in memory db with default flags */
res = sqlite3_open_v2("", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
CHECK;
/* create a table so the database is not empty */
res = sqlite3_exec(db, "create table foo(x)", NULL, NULL, NULL);
CHECK;
/* serialize */
serialized = sqlite3_serialize(db, "main", &serial_size, 0);
/* verify we got data back */
res = (serial_size != 0) ? SQLITE_OK : SQLITE_ERROR;
CHECK;
/* copy the data */
datacopy = sqlite3_malloc64(serial_size);
memcpy(datacopy, serialized, serial_size);
/* free serialized (caller is responsible for freeing the returned value to avoid a memory leak) */
sqlite3_free(serialized);
/* now load data into temp */
res = sqlite3_deserialize(db, "temp", datacopy, serial_size, serial_size, SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE);
CHECK;
sqlite3_close(db);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment