1#include <string.h>
2#include <stdlib.h>
3#include <stdio.h>
4
5#include "data.h"
6
7const char *insert_into = "INSERT INTO words (LINE) VALUES($VVV);";
8const char *select_words = "SELECT Id, Line FROM words WHERE line like $VVV LIMIT 10;";
9const char *create_table = "CREATE TABLE IF NOT EXISTS words (ID INTEGER PRIMARY KEY AUTOINCREMENT, LINE TEXT NOT NULL);";
10
11Data* new_data(const char* con) {
12 Data* data = (Data*)malloc(sizeof(Data));
13
14 int v = sqlite3_open(con, &(data->db));
15 if (v != SQLITE_OK) {
16 print_result_code(v);
17 return NULL;
18 }
19
20 sqlite3_enable_load_extension(data->db, 1);
21 v = sqlite3_load_extension(data->db, "ext/libsqlite3ext", "sqlite3_spellfix_init",0);
22 if (v != SQLITE_OK) {
23 print_result_code(v);
24 return NULL;
25 }
26
27 return data;
28}
29
30void free_data(Data* data) {
31 sqlite3_close(data->db);
32 free(data);
33}
34
35void insert(Data* data, char* line, int len) {
36 sqlite3_stmt *stmt;
37 int r = sqlite3_prepare_v2(data->db, insert_into, -1, &stmt, NULL);
38
39 if (r != SQLITE_OK) {
40 printf("Error executing insert: ");
41 print_result_code(r);
42 printf("\n");
43 return;
44 }
45
46 sqlite3_bind_text(stmt, 1, line, len, NULL);
47
48 int c = sqlite3_step(stmt);
49 if (c != SQLITE_DONE) {
50 printf("Error executing insert: ");
51 print_result_code(r);
52 printf("\n");
53 }
54
55 sqlite3_finalize(stmt);
56}
57
58void bootstrap(Data* data) {
59 sqlite3_stmt *stmt;
60 int r = sqlite3_prepare_v2(data->db, create_table, -1, &stmt, NULL);
61
62 if (r != SQLITE_OK) {
63 printf("Error preparing bootstrap: ");
64 print_result_code(r);
65 printf("\n");
66 return;
67 }
68
69 int c = sqlite3_step(stmt);
70 if (c != SQLITE_DONE) {
71 printf("Error executing bootstrap: ");
72 print_result_code(r);
73 printf("\n");
74 }
75
76 sqlite3_finalize(stmt);
77}
78
79LIST* data_select(Data* data, char *sch, int len) {
80 sqlite3_stmt *stmt;
81 int r = sqlite3_prepare_v2(data->db, select_words, -1, &stmt, NULL);
82
83 if (r != SQLITE_OK) {
84 printf("Error executing select: ");
85 print_result_code(r);
86 printf("\n");
87 return NULL;
88 }
89
90 LIST *list = NULL;
91
92 sqlite3_bind_text(stmt, 1, sch, len, NULL);
93
94 int m = sqlite3_step(stmt);
95 while(m == SQLITE_ROW) {
96 Word *word = (Word*)malloc(sizeof(Word));
97
98 int id = sqlite3_column_int(stmt, 0);
99 const unsigned char *line = sqlite3_column_text(stmt, 1);
100 unsigned char *line2 = malloc(sizeof(char*)+strlen((char*)line));
101 memcpy(line2, line, strlen((char*)line));
102
103 word->Id = id;
104 word->Line = line2;
105 list = list_add(list, word);
106
107 m = sqlite3_step(stmt);
108 }
109
110 sqlite3_finalize(stmt);
111
112 return list;
113}
114
115void print_result_code(int code) {
116 printf(sqlite3_errstr(code));
117}