blob: b3ae28ce0e723382ee0c7056f5a31fa6437b47ab [file] [log] [blame]
The Android Open Source Project7790ef52009-03-03 19:30:40 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "sqlite3_android"
18
19#include <ctype.h>
20#include <stdlib.h>
21#include <string.h>
22#include <unistd.h>
23
24#include <unicode/ucol.h>
25#include <unicode/ustring.h>
26#include <cutils/log.h>
27
28#include "sqlite3_android.h"
29#include "PhoneNumberUtils.h"
The Android Open Source Project455ed292009-03-13 13:04:22 -070030#include "PhoneticStringUtils.h"
The Android Open Source Project7790ef52009-03-03 19:30:40 -080031
32#define ENABLE_ANDROID_LOG 0
33
34static int collate16(void *p, int n1, const void *v1, int n2, const void *v2)
35{
36 UCollator *coll = (UCollator *) p;
37 UCollationResult result = ucol_strcoll(coll, (const UChar *) v1, n1,
38 (const UChar *) v2, n2);
39
40 if (result == UCOL_LESS) {
41 return -1;
42 } else if (result == UCOL_GREATER) {
43 return 1;
44 } else {
45 return 0;
46 }
47}
48
49static int collate8(void *p, int n1, const void *v1, int n2, const void *v2)
50{
51 UCollator *coll = (UCollator *) p;
52 UCharIterator i1, i2;
53 UErrorCode status = U_ZERO_ERROR;
54
55 uiter_setUTF8(&i1, (const char *) v1, n1);
56 uiter_setUTF8(&i2, (const char *) v2, n2);
57
58 UCollationResult result = ucol_strcollIter(coll, &i1, &i2, &status);
59
60 if (U_FAILURE(status)) {
61// LOGE("Collation iterator error: %d\n", status);
62 }
63
64 if (result == UCOL_LESS) {
65 return -1;
66 } else if (result == UCOL_GREATER) {
67 return 1;
68 } else {
69 return 0;
70 }
71}
72
The Android Open Source Project455ed292009-03-13 13:04:22 -070073static void get_phonetically_sortable_string(
74 sqlite3_context * context, int argc, sqlite3_value ** argv)
75{
76 if (argc != 1) {
77 sqlite3_result_null(context);
78 return;
79 }
80 char const * src = (char const *)sqlite3_value_text(argv[0]);
81 char * ret;
82 size_t len;
83
84 if (!android::GetPhoneticallySortableString(src, &ret, &len)) {
Daisuke Miyakawa0c45e822009-03-27 19:41:52 -070085 // Put this text at the end of a list.
86 sqlite3_result_text(context, "\xF0\x9F\xBF\xBD", -1, SQLITE_STATIC);
87 // sqlite3_result_null(context);
The Android Open Source Project455ed292009-03-13 13:04:22 -070088 } else {
89 sqlite3_result_text(context, ret, len, free);
90 }
91}
92
Daisuke Miyakawad28cdc42009-05-18 14:51:52 +090093static void get_normalized_string(
94 sqlite3_context * context, int argc, sqlite3_value ** argv)
95{
96 if (argc != 1) {
97 sqlite3_result_null(context);
98 return;
99 }
100 char const * src = (char const *)sqlite3_value_text(argv[0]);
101 char * ret;
102 size_t len;
103
104 if (!android::GetNormalizedString(src, &ret, &len)) {
105 // Probably broken string. Return 0 length string.
106 sqlite3_result_text(context, "", -1, SQLITE_STATIC);
107 } else {
108 sqlite3_result_text(context, ret, len, free);
109 }
110}
111
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800112static void phone_numbers_equal(sqlite3_context * context, int argc, sqlite3_value ** argv)
113{
114 if (argc != 2) {
115 sqlite3_result_int(context, 0);
116 return;
117 }
118
119 char const * num1 = (char const *)sqlite3_value_text(argv[0]);
120 char const * num2 = (char const *)sqlite3_value_text(argv[1]);
121
122 if (num1 == NULL || num2 == NULL) {
123 sqlite3_result_null(context);
124 return;
125 }
126
127 bool equal = android::phone_number_compare(num1, num2);
128
129 if (equal) {
130 sqlite3_result_int(context, 1);
131 } else {
132 sqlite3_result_int(context, 0);
133 }
134}
135
136#if ENABLE_ANDROID_LOG
137static void android_log(sqlite3_context * context, int argc, sqlite3_value ** argv)
138{
139 char const * tag = "sqlite_trigger";
140 char const * msg = "";
141 int msgIndex = 0;
142
143 switch (argc) {
144 case 2:
145 tag = (char const *)sqlite3_value_text(argv[0]);
146 if (tag == NULL) {
147 tag = "sqlite_trigger";
148 }
149 msgIndex = 1;
150 case 1:
151 msg = (char const *)sqlite3_value_text(argv[msgIndex]);
152 if (msg == NULL) {
153 msg = "";
154 }
155 LOG(LOG_INFO, tag, msg);
156 sqlite3_result_int(context, 1);
157 return;
158
159 default:
160 sqlite3_result_int(context, 0);
161 return;
162 }
163}
164#endif
165
166static void delete_file(sqlite3_context * context, int argc, sqlite3_value ** argv)
167{
168 if (argc != 1) {
169 sqlite3_result_int(context, 0);
170 return;
171 }
172
173 char const * path = (char const *)sqlite3_value_text(argv[0]);
174 if (path == NULL) {
175 sqlite3_result_null(context);
176 return;
177 }
178
179 if (strncmp("/sdcard/", path, 8) != 0) {
180 sqlite3_result_null(context);
181 return;
182 }
Marco Nelissen2da78c02009-05-06 11:08:08 -0700183 if (strstr(path, "/../") != NULL) {
184 sqlite3_result_null(context);
185 return;
186 }
187
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800188 int err = unlink(path);
189 if (err != -1) {
190 // No error occured, return true
191 sqlite3_result_int(context, 1);
192 } else {
193 // An error occured, return false
194 sqlite3_result_int(context, 0);
195 }
196}
197
198static void tokenize_auxdata_delete(void * data)
199{
200 sqlite3_stmt * statement = (sqlite3_stmt *)data;
201 sqlite3_finalize(statement);
202}
203
204static void base16Encode(char* dest, const char* src, uint32_t size)
205{
206 static const char * BASE16_TABLE = "0123456789abcdef";
207 for (uint32_t i = 0; i < size; i++) {
208 char ch = *src++;
209 *dest++ = BASE16_TABLE[ (ch & 0xf0) >> 4 ];
210 *dest++ = BASE16_TABLE[ (ch & 0x0f) ];
211 }
212}
213
214struct SqliteUserData {
215 sqlite3 * handle;
216 UCollator* collator;
217};
218
219/**
220 * This function is invoked as:
221 *
Bjorn Bringert687f1162009-05-13 22:13:09 +0100222 * _TOKENIZE('<token_table>', <data_row_id>, <data>, <delimiter>, <use token index>)
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800223 *
Bjorn Bringert687f1162009-05-13 22:13:09 +0100224 * If <use token index> is omitted, is is treated as 0.
225 *
226 * It will split <data> on each instance of <delimiter> and insert each token
227 * into <token_table>. <token_table> must have 3 columns:
228 * token TEXT, source INTEGER, token_index INTEGER
229 * The token_index column is not needed if <use token index> is 0.
230 *
231 * One row is inserted for each token in <data>.
232 * In each inserted row, 'source' is <data_row_id>.
233 * In the first inserted row, 'token' is the hex collation key of
234 * the entire <data> string, and 'token_index' is 0.
235 * In each row I (where 1 <= I < N, and N is the number of tokens in <data>)
236 * 'token' will be set to the hex collation key of the I:th token (0-based).
237 * If <use token index> != 0, 'token_index' will be set to I.
238 *
239 * In other words, there will be one row for the entire string,
240 * and one row for each token except the first one.
241 *
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800242 * The function returns the number of tokens generated.
243 */
244static void tokenize(sqlite3_context * context, int argc, sqlite3_value ** argv)
245{
246 //LOGD("enter tokenize");
247 int err;
Bjorn Bringert687f1162009-05-13 22:13:09 +0100248 int useTokenIndex = 0;
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800249
Bjorn Bringert687f1162009-05-13 22:13:09 +0100250 if (!(argc == 4 || argc == 5)) {
251 LOGE("Tokenize requires 4 or 5 arguments");
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800252 sqlite3_result_null(context);
253 return;
254 }
255
Bjorn Bringert687f1162009-05-13 22:13:09 +0100256 if (argc > 4) {
257 useTokenIndex = sqlite3_value_int(argv[4]);
258 }
259
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800260 sqlite3 * handle = sqlite3_context_db_handle(context);
261 UCollator* collator = (UCollator*)sqlite3_user_data(context);
262 char const * tokenTable = (char const *)sqlite3_value_text(argv[0]);
263 if (tokenTable == NULL) {
264 LOGE("tokenTable null");
265 sqlite3_result_null(context);
266 return;
267 }
268
269 // Get or create the prepared statement for the insertions
270 sqlite3_stmt * statement = (sqlite3_stmt *)sqlite3_get_auxdata(context, 0);
271 if (!statement) {
Bjorn Bringert687f1162009-05-13 22:13:09 +0100272 char * sql;
273 if (useTokenIndex) {
274 sql = sqlite3_mprintf("INSERT INTO %s (token, source, token_index) VALUES (?, ?, ?);", tokenTable);
275 } else {
276 sql = sqlite3_mprintf("INSERT INTO %s (token, source) VALUES (?, ?);", tokenTable);
277 }
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800278 err = sqlite3_prepare_v2(handle, sql, -1, &statement, NULL);
279 sqlite3_free(sql);
280 if (err) {
281 LOGE("prepare failed");
282 sqlite3_result_null(context);
283 return;
284 }
285 // This binds the statement to the table it was compiled against, which is argv[0].
286 // If this function is ever called with a different table the finalizer will be called
287 // and sqlite3_get_auxdata() will return null above, forcing a recompile for the new table.
288 sqlite3_set_auxdata(context, 0, statement, tokenize_auxdata_delete);
289 } else {
290 // Reset the cached statement so that binding the row ID will work properly
291 sqlite3_reset(statement);
292 }
293
294 // Bind the row ID of the source row
295 int64_t rowID = sqlite3_value_int64(argv[1]);
296 err = sqlite3_bind_int64(statement, 2, rowID);
297 if (err != SQLITE_OK) {
298 LOGE("bind failed");
299 sqlite3_result_null(context);
300 return;
301 }
302
303 // Get the raw bytes for the string to tokenize
304 // the string will be modified by following code
305 // however, sqlite did not reuse the string, so it is safe to not dup it
306 UChar * origData = (UChar *)sqlite3_value_text16(argv[2]);
307 if (origData == NULL) {
308 sqlite3_result_null(context);
309 return;
310 }
311
312 // Get the raw bytes for the delimiter
313 const UChar * delim = (const UChar *)sqlite3_value_text16(argv[3]);
314 if (delim == NULL) {
315 LOGE("can't get delimiter");
316 sqlite3_result_null(context);
317 return;
318 }
319
320 UChar * token = NULL;
321 UChar *state;
322 int numTokens = 0;
323
324 do {
325 if (numTokens == 0) {
326 token = origData;
327 }
328
329 // Reset the program so we can use it to perform the insert
330 sqlite3_reset(statement);
331 UErrorCode status = U_ZERO_ERROR;
332 char keybuf[1024];
333 uint32_t result = ucol_getSortKey(collator, token, -1, (uint8_t*)keybuf, sizeof(keybuf)-1);
334 if (result > sizeof(keybuf)) {
335 // TODO allocate memory for this super big string
336 LOGE("ucol_getSortKey needs bigger buffer %d", result);
337 break;
338 }
339 uint32_t keysize = result-1;
340 uint32_t base16Size = keysize*2;
341 char *base16buf = (char*)malloc(base16Size);
342 base16Encode(base16buf, keybuf, keysize);
343 err = sqlite3_bind_text(statement, 1, base16buf, base16Size, SQLITE_STATIC);
344
345 if (err != SQLITE_OK) {
346 LOGE(" sqlite3_bind_text16 error %d", err);
347 free(base16buf);
348 break;
349 }
350
Bjorn Bringert687f1162009-05-13 22:13:09 +0100351 if (useTokenIndex) {
352 err = sqlite3_bind_int(statement, 3, numTokens);
353 if (err != SQLITE_OK) {
354 LOGE(" sqlite3_bind_int error %d", err);
355 free(base16buf);
356 break;
357 }
358 }
359
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800360 err = sqlite3_step(statement);
361 free(base16buf);
362
363 if (err != SQLITE_DONE) {
364 LOGE(" sqlite3_step error %d", err);
365 break;
366 }
367 numTokens++;
368 if (numTokens == 1) {
369 // first call
370 u_strtok_r(origData, delim, &state);
371 }
372 } while ((token = u_strtok_r(NULL, delim, &state)) != NULL);
373 sqlite3_result_int(context, numTokens);
374}
375
376static void localized_collator_dtor(UCollator* collator)
377{
378 ucol_close(collator);
379}
380
381#define LOCALIZED_COLLATOR_NAME "LOCALIZED"
382
383extern "C" int register_localized_collators(sqlite3* handle, const char* systemLocale, int utf16Storage)
384{
385 int err;
386 UErrorCode status = U_ZERO_ERROR;
387 void* icudata;
388
389 UCollator* collator = ucol_open(systemLocale, &status);
390 if (U_FAILURE(status)) {
391 return -1;
392 }
393
394 ucol_setAttribute(collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
395 if (U_FAILURE(status)) {
396 return -1;
397 }
398
399 status = U_ZERO_ERROR;
400 char buf[1024];
401 int n = ucol_getShortDefinitionString(collator, NULL, buf, 1024, &status);
402
403 if (utf16Storage) {
404 err = sqlite3_create_collation_v2(handle, LOCALIZED_COLLATOR_NAME, SQLITE_UTF16, collator,
405 collate16, (void(*)(void*))localized_collator_dtor);
406 } else {
407 err = sqlite3_create_collation_v2(handle, LOCALIZED_COLLATOR_NAME, SQLITE_UTF8, collator,
408 collate8, (void(*)(void*))localized_collator_dtor);
409 }
410 if (err != SQLITE_OK) {
411 return err;
412 }
413
414 // Register the _TOKENIZE function
415 err = sqlite3_create_function(handle, "_TOKENIZE", 4, SQLITE_UTF16, collator, tokenize, NULL, NULL);
416 if (err != SQLITE_OK) {
417 return err;
Bjorn Bringert687f1162009-05-13 22:13:09 +0100418 }
419 err = sqlite3_create_function(handle, "_TOKENIZE", 5, SQLITE_UTF16, collator, tokenize, NULL, NULL);
420 if (err != SQLITE_OK) {
421 return err;
422 }
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800423
424 return SQLITE_OK;
425}
426
427
428extern "C" int register_android_functions(sqlite3 * handle, int utf16Storage)
429{
430 int err;
431 UErrorCode status = U_ZERO_ERROR;
432
433 UCollator * collator = ucol_open(NULL, &status);
434 if (U_FAILURE(status)) {
435 return -1;
436 }
437
438 if (utf16Storage) {
439 // Note that text should be stored as UTF-16
440 err = sqlite3_exec(handle, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
441 if (err != SQLITE_OK) {
442 return err;
443 }
444
445 // Register the UNICODE collation
446 err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF16, collator, collate16,
447 (void(*)(void*))localized_collator_dtor);
448 } else {
449 err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF8, collator, collate8,
450 (void(*)(void*))localized_collator_dtor);
451 }
452
453 if (err != SQLITE_OK) {
454 return err;
455 }
456
457 // Register the PHONE_NUM_EQUALS function
458 err = sqlite3_create_function(handle, "PHONE_NUMBERS_EQUAL", 2, SQLITE_UTF8, NULL, phone_numbers_equal, NULL, NULL);
459 if (err != SQLITE_OK) {
460 return err;
461 }
462
463 // Register the _DELETE_FILE function
464 err = sqlite3_create_function(handle, "_DELETE_FILE", 1, SQLITE_UTF8, NULL, delete_file, NULL, NULL);
465 if (err != SQLITE_OK) {
466 return err;
467 }
468
469#if ENABLE_ANDROID_LOG
470 // Register the _LOG function
471 err = sqlite3_create_function(handle, "_LOG", 1, SQLITE_UTF8, NULL, android_log, NULL, NULL);
472 if (err != SQLITE_OK) {
473 return err;
474 }
475#endif
476
The Android Open Source Project455ed292009-03-13 13:04:22 -0700477 // Register the GET_PHONETICALLY_SORTABLE_STRING function
478 err = sqlite3_create_function(handle,
479 "GET_PHONETICALLY_SORTABLE_STRING",
480 1, SQLITE_UTF8, NULL,
481 get_phonetically_sortable_string,
482 NULL, NULL);
483 if (err != SQLITE_OK) {
484 return err;
485 }
486
Daisuke Miyakawad28cdc42009-05-18 14:51:52 +0900487 // Register the GET_NORMALIZED_STRING function
488 err = sqlite3_create_function(handle,
489 "GET_NORMALIZED_STRING",
490 1, SQLITE_UTF8, NULL,
491 get_normalized_string,
492 NULL, NULL);
493 if (err != SQLITE_OK) {
494 return err;
495 }
496
The Android Open Source Project7790ef52009-03-03 19:30:40 -0800497 return SQLITE_OK;
498}