Skip to content
pi-c Documentation
Login

Documentation

/* The SQLite Archive's compression functions (https://sqlite.org/sqlar.html),
 * as SQLite's ext/misc/sqlar.c defines them, over the vendored zlib:
 *   sqlar_compress(X)       X deflated (zlib format) when that is smaller,
 *                           else X unchanged
 *   sqlar_uncompress(Y, SZ) Y inflated to SZ bytes, or Y itself when SZ is
 *                           its length (stored raw)
 * A row keeps sz = the original length beside the data, so sz = length(data)
 * marks raw content. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <limits.h>
#include <stdlib.h>

#include "sqlar.h"
#include "zlib.h"

static void sqlar_compress(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const Bytef *in;
    int n;
    uLongf out_n;
    Bytef *out;
    (void)argc;
    if (sqlite3_value_type(argv[0]) != SQLITE_BLOB && sqlite3_value_type(argv[0]) != SQLITE_TEXT) {
        sqlite3_result_value(ctx, argv[0]);
        return;
    }
    in = sqlite3_value_blob(argv[0]);
    n = sqlite3_value_bytes(argv[0]);
    out_n = compressBound((uLong)n);
    if (!(out = sqlite3_malloc64(out_n))) {
        sqlite3_result_error_nomem(ctx);
        return;
    }
    if (compress(out, &out_n, in, (uLong)n) == Z_OK && out_n < (uLongf)n) {
        sqlite3_result_blob(ctx, out, (int)out_n, sqlite3_free);
    } else {
        sqlite3_free(out);
        sqlite3_result_value(ctx, argv[0]);
    }
}

static void sqlar_uncompress(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const Bytef *in = sqlite3_value_blob(argv[0]);
    int n = sqlite3_value_bytes(argv[0]);
    sqlite3_int64 sz = sqlite3_value_int64(argv[1]);
    uLongf out_n;
    Bytef *out;
    (void)argc;
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL) { /* pruned content */
        sqlite3_result_null(ctx);
        return;
    }
    if (sz == n || sz < 0 || sz > INT_MAX) {
        sqlite3_result_value(ctx, argv[0]);
        return;
    }
    out_n = (uLongf)sz;
    if (!(out = sqlite3_malloc64((sqlite3_uint64)sz + 1))) {
        sqlite3_result_error_nomem(ctx);
        return;
    }
    if (uncompress(out, &out_n, in, (uLong)n) != Z_OK || out_n != (uLongf)sz) {
        sqlite3_free(out);
        sqlite3_result_error(ctx, "sqlar_uncompress: corrupt data", -1);
        return;
    }
    sqlite3_result_blob(ctx, out, (int)out_n, sqlite3_free);
}

int pic_sqlar_register(sqlite3 *db) {
    int flags = SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS;
    return sqlite3_create_function(db, "sqlar_compress", 1, flags, NULL, sqlar_compress, NULL, NULL) == SQLITE_OK &&
                   sqlite3_create_function(db, "sqlar_uncompress", 2, flags, NULL, sqlar_uncompress, NULL, NULL) == SQLITE_OK
               ? 0
               : -1;
}