]> pd.if.org Git - zpackage/blob - lib/addfile.c
9d75d96e2fb7bccccfc8da143539938422d46a2e
[zpackage] / lib / addfile.c
1 /*
2  * add a file/files to an sqlite db
3  * in the 'files' table.
4  */
5
6 #include <stdio.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11
12 #include <sys/mman.h>
13
14 #include <sqlite3.h>
15 #include "sha256.h"
16
17 #include "lzma.h"
18
19 void *compresslzma(void *buf, size_t bufsize, size_t *len) {
20         /* xz compress it */
21         size_t outsize;
22         void *outbuf;
23         size_t outlen = 0;
24
25         outsize = lzma_stream_buffer_bound(bufsize);
26         outbuf = malloc(outsize);
27         if (!outbuf) {
28                 *len = 0;
29                 return NULL;
30         }
31         /* TODO adjust encoding level for size */
32         lzma_easy_buffer_encode(6, LZMA_CHECK_CRC64, NULL,
33                         buf, bufsize,
34                         outbuf, &outlen, outsize
35                         );
36         *len = outlen;
37         return outbuf;
38 }
39
40 static int callback(void *NotUsed, int argc, char **argv, char **azColName){
41         int i;
42         for(i=0; i<argc; i++){
43                 printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
44         }
45         printf("\n");
46         return 0;
47 }
48
49 static char *create_table = "create table if not exists files (hash text primary key, size integer, compression text, content blob)";
50
51 struct dbh {
52         sqlite3 *db;
53         char *errmsg;
54         int rc;
55 };
56
57 #define SQLERROR(x) fprintf(stderr, "%s %d: %s\n", __func__, __LINE__, (x))
58 static int begin(sqlite3 *db) {
59         int rc;
60         char *err;
61
62         rc = sqlite3_exec(db, "begin;", callback, 0, &err);
63         if (rc != SQLITE_OK) {
64                 SQLERROR(err);
65                 sqlite3_free(err);
66         }
67         return rc;
68 }
69
70 static int commit(sqlite3 *db) {
71         int rc;
72         char *err;
73
74         rc = sqlite3_exec(db, "commit;", callback, 0, &err);
75         if (rc != SQLITE_OK) {
76                 SQLERROR(err);
77                 sqlite3_free(err);
78         }
79         return rc;
80 }
81 static int rollback(sqlite3 *db) {
82         int rc;
83         char *err;
84
85         rc = sqlite3_exec(db, "rollback;", callback, 0, &err);
86         if (rc != SQLITE_OK) {
87                 SQLERROR(err);
88                 sqlite3_free(err);
89         }
90         return rc;
91 }
92