Skip to content

Instantly share code, notes, and snippets.

@rogerbinns
Created July 19, 2021 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerbinns/d11994c1d85e36c341e20f25ec491f5e to your computer and use it in GitHub Desktop.
Save rogerbinns/d11994c1d85e36c341e20f25ec491f5e to your computer and use it in GitHub Desktop.
#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