12. SQLar Operations

12.1. Check if file exists

SELECT EXISTS(SELECT name FROM sqlar WHERE NAME is ?1);
<<funcdefs>>=
int sqlar_file_exists(sqlite3 *db, const char *name);
<<functions>>=
int sqlar_file_exists(sqlite3 *db, const char *name)
{
    sqlite3_stmt *stmt;
    int rc;

    sqlite3_prepare(db,
                    "SELECT "
                    "EXISTS("
                    "SELECT name FROM sqlar "
                    "WHERE name is ?1"
                    ");",
                    -1,
                    &stmt,
                    NULL);
    sqlite3_bind_text(stmt, 1, name, -1, SQLITE_STATIC);
    sqlite3_step(stmt);
    rc = sqlite3_column_int(stmt, 0);
    sqlite3_finalize(stmt);
    return rc;
}

12.2. Extract to buffer

<<funcdefs>>=
int sqlar_extract_to_buffer(sqlite3 *db,
                            const char *name,
                            char **out,
                            unsigned int *size);
<<functions>>=
int sqlar_extract_to_buffer(sqlite3 *db,
                            const char *name,
                            char **out,
                            unsigned int *size)
{
    char *output;
    unsigned long int out_size;
    int rc;
    sqlite3_stmt *stmt;
    int sz;
    const char *data;
    int data_sz;

    rc = sqlite3_exec(db,
                      "CREATE TABLE IF NOT EXISTS sqlar(\n"
                      "  name TEXT PRIMARY KEY,\n"
                      "  mode INT,\n"
                      "  mtime INT,\n"
                      "  sz INT,\n"
                      "  data BLOB\n"
                      ");", 0, 0, 0);


    sqlite3_prepare(db,
                    "SELECT name, mode, mtime, sz, data FROM sqlar"
                    " WHERE name is ?1",
                    -1,
                    &stmt,
                    NULL);

    sqlite3_bind_text(stmt, 1, name, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);

    if(rc != SQLITE_ROW) {
        fprintf(stderr,
                "SQLar: could find file %s\n",
                name);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return rc;
    }

    sz = sqlite3_column_int(stmt,3);
    data = sqlite3_column_blob(stmt,4);
    data_sz = sqlite3_column_bytes(stmt,4);

    output = calloc(1, sz + 1);
    if(sz != data_sz) {
        out_size = sz;

        rc = uncompress((Bytef*)output,
                        &out_size,
                        (const Bytef*)data,
                        data_sz);
        if(rc != Z_OK) {
            fprintf(stderr,
                    "Error: could not uncompress data\n");
            return SQLITE_ERROR;
        }
    } else {
        memcpy(output, data, sz);
    }

    *size = sz;
    *out = output;
    sqlite3_finalize(stmt);
    return SQLITE_OK;
}



prev | home | next