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