OLD | NEW |
| (Empty) |
1 /* | |
2 ** 2007 May 6 | |
3 ** | |
4 ** The author disclaims copyright to this source code. In place of | |
5 ** a legal notice, here is a blessing: | |
6 ** | |
7 ** May you do good and not evil. | |
8 ** May you find forgiveness for yourself and forgive others. | |
9 ** May you share freely, never taking more than you give. | |
10 ** | |
11 ************************************************************************* | |
12 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ | |
13 ** | |
14 ** This file implements an integration between the ICU library | |
15 ** ("International Components for Unicode", an open-source library | |
16 ** for handling unicode data) and SQLite. The integration uses | |
17 ** ICU to provide the following to SQLite: | |
18 ** | |
19 ** * An implementation of the SQL regexp() function (and hence REGEXP | |
20 ** operator) using the ICU uregex_XX() APIs. | |
21 ** | |
22 ** * Implementations of the SQL scalar upper() and lower() functions | |
23 ** for case mapping. | |
24 ** | |
25 ** * Integration of ICU and SQLite collation sequences. | |
26 ** | |
27 ** * An implementation of the LIKE operator that uses ICU to | |
28 ** provide case-independent matching. | |
29 */ | |
30 | |
31 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) | |
32 | |
33 /* Include ICU headers */ | |
34 #include <unicode/utypes.h> | |
35 #include <unicode/uregex.h> | |
36 #include <unicode/ustring.h> | |
37 #include <unicode/ucol.h> | |
38 | |
39 #include <assert.h> | |
40 | |
41 #ifndef SQLITE_CORE | |
42 #include "sqlite3ext.h" | |
43 SQLITE_EXTENSION_INIT1 | |
44 #else | |
45 #include "sqlite3.h" | |
46 #endif | |
47 | |
48 /* | |
49 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB | |
50 ** operator. | |
51 */ | |
52 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH | |
53 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 | |
54 #endif | |
55 | |
56 /* | |
57 ** Version of sqlite3_free() that is always a function, never a macro. | |
58 */ | |
59 static void xFree(void *p){ | |
60 sqlite3_free(p); | |
61 } | |
62 | |
63 /* | |
64 ** Compare two UTF-8 strings for equality where the first string is | |
65 ** a "LIKE" expression. Return true (1) if they are the same and | |
66 ** false (0) if they are different. | |
67 */ | |
68 static int icuLikeCompare( | |
69 const uint8_t *zPattern, /* LIKE pattern */ | |
70 const uint8_t *zString, /* The UTF-8 string to compare against */ | |
71 const UChar32 uEsc /* The escape character */ | |
72 ){ | |
73 static const int MATCH_ONE = (UChar32)'_'; | |
74 static const int MATCH_ALL = (UChar32)'%'; | |
75 | |
76 int iPattern = 0; /* Current byte index in zPattern */ | |
77 int iString = 0; /* Current byte index in zString */ | |
78 | |
79 int prevEscape = 0; /* True if the previous character was uEsc */ | |
80 | |
81 while( zPattern[iPattern]!=0 ){ | |
82 | |
83 /* Read (and consume) the next character from the input pattern. */ | |
84 UChar32 uPattern; | |
85 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern); | |
86 | |
87 /* There are now 4 possibilities: | |
88 ** | |
89 ** 1. uPattern is an unescaped match-all character "%", | |
90 ** 2. uPattern is an unescaped match-one character "_", | |
91 ** 3. uPattern is an unescaped escape character, or | |
92 ** 4. uPattern is to be handled as an ordinary character | |
93 */ | |
94 if( !prevEscape && uPattern==MATCH_ALL ){ | |
95 /* Case 1. */ | |
96 uint8_t c; | |
97 | |
98 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a | |
99 ** MATCH_ALL. For each MATCH_ONE, skip one character in the | |
100 ** test string. | |
101 */ | |
102 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){ | |
103 if( c==MATCH_ONE ){ | |
104 if( zString[iString]==0 ) return 0; | |
105 U8_FWD_1_UNSAFE(zString, iString); | |
106 } | |
107 iPattern++; | |
108 } | |
109 | |
110 if( zPattern[iPattern]==0 ) return 1; | |
111 | |
112 while( zString[iString] ){ | |
113 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){ | |
114 return 1; | |
115 } | |
116 U8_FWD_1_UNSAFE(zString, iString); | |
117 } | |
118 return 0; | |
119 | |
120 }else if( !prevEscape && uPattern==MATCH_ONE ){ | |
121 /* Case 2. */ | |
122 if( zString[iString]==0 ) return 0; | |
123 U8_FWD_1_UNSAFE(zString, iString); | |
124 | |
125 }else if( !prevEscape && uPattern==uEsc){ | |
126 /* Case 3. */ | |
127 prevEscape = 1; | |
128 | |
129 }else{ | |
130 /* Case 4. */ | |
131 UChar32 uString; | |
132 U8_NEXT_UNSAFE(zString, iString, uString); | |
133 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); | |
134 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); | |
135 if( uString!=uPattern ){ | |
136 return 0; | |
137 } | |
138 prevEscape = 0; | |
139 } | |
140 } | |
141 | |
142 return zString[iString]==0; | |
143 } | |
144 | |
145 /* | |
146 ** Implementation of the like() SQL function. This function implements | |
147 ** the build-in LIKE operator. The first argument to the function is the | |
148 ** pattern and the second argument is the string. So, the SQL statements: | |
149 ** | |
150 ** A LIKE B | |
151 ** | |
152 ** is implemented as like(B, A). If there is an escape character E, | |
153 ** | |
154 ** A LIKE B ESCAPE E | |
155 ** | |
156 ** is mapped to like(B, A, E). | |
157 */ | |
158 static void icuLikeFunc( | |
159 sqlite3_context *context, | |
160 int argc, | |
161 sqlite3_value **argv | |
162 ){ | |
163 const unsigned char *zA = sqlite3_value_text(argv[0]); | |
164 const unsigned char *zB = sqlite3_value_text(argv[1]); | |
165 UChar32 uEsc = 0; | |
166 | |
167 /* Limit the length of the LIKE or GLOB pattern to avoid problems | |
168 ** of deep recursion and N*N behavior in patternCompare(). | |
169 */ | |
170 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ | |
171 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); | |
172 return; | |
173 } | |
174 | |
175 | |
176 if( argc==3 ){ | |
177 /* The escape character string must consist of a single UTF-8 character. | |
178 ** Otherwise, return an error. | |
179 */ | |
180 int nE= sqlite3_value_bytes(argv[2]); | |
181 const unsigned char *zE = sqlite3_value_text(argv[2]); | |
182 int i = 0; | |
183 if( zE==0 ) return; | |
184 U8_NEXT(zE, i, nE, uEsc); | |
185 if( i!=nE){ | |
186 sqlite3_result_error(context, | |
187 "ESCAPE expression must be a single character", -1); | |
188 return; | |
189 } | |
190 } | |
191 | |
192 if( zA && zB ){ | |
193 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); | |
194 } | |
195 } | |
196 | |
197 /* | |
198 ** This function is called when an ICU function called from within | |
199 ** the implementation of an SQL scalar function returns an error. | |
200 ** | |
201 ** The scalar function context passed as the first argument is | |
202 ** loaded with an error message based on the following two args. | |
203 */ | |
204 static void icuFunctionError( | |
205 sqlite3_context *pCtx, /* SQLite scalar function context */ | |
206 const char *zName, /* Name of ICU function that failed */ | |
207 UErrorCode e /* Error code returned by ICU function */ | |
208 ){ | |
209 char zBuf[128]; | |
210 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); | |
211 zBuf[127] = '\0'; | |
212 sqlite3_result_error(pCtx, zBuf, -1); | |
213 } | |
214 | |
215 /* | |
216 ** Function to delete compiled regexp objects. Registered as | |
217 ** a destructor function with sqlite3_set_auxdata(). | |
218 */ | |
219 static void icuRegexpDelete(void *p){ | |
220 URegularExpression *pExpr = (URegularExpression *)p; | |
221 uregex_close(pExpr); | |
222 } | |
223 | |
224 /* | |
225 ** Implementation of SQLite REGEXP operator. This scalar function takes | |
226 ** two arguments. The first is a regular expression pattern to compile | |
227 ** the second is a string to match against that pattern. If either | |
228 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result | |
229 ** is 1 if the string matches the pattern, or 0 otherwise. | |
230 ** | |
231 ** SQLite maps the regexp() function to the regexp() operator such | |
232 ** that the following two are equivalent: | |
233 ** | |
234 ** zString REGEXP zPattern | |
235 ** regexp(zPattern, zString) | |
236 ** | |
237 ** Uses the following ICU regexp APIs: | |
238 ** | |
239 ** uregex_open() | |
240 ** uregex_matches() | |
241 ** uregex_close() | |
242 */ | |
243 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ | |
244 UErrorCode status = U_ZERO_ERROR; | |
245 URegularExpression *pExpr; | |
246 UBool res; | |
247 const UChar *zString = sqlite3_value_text16(apArg[1]); | |
248 | |
249 (void)nArg; /* Unused parameter */ | |
250 | |
251 /* If the left hand side of the regexp operator is NULL, | |
252 ** then the result is also NULL. | |
253 */ | |
254 if( !zString ){ | |
255 return; | |
256 } | |
257 | |
258 pExpr = sqlite3_get_auxdata(p, 0); | |
259 if( !pExpr ){ | |
260 const UChar *zPattern = sqlite3_value_text16(apArg[0]); | |
261 if( !zPattern ){ | |
262 return; | |
263 } | |
264 pExpr = uregex_open(zPattern, -1, 0, 0, &status); | |
265 | |
266 if( U_SUCCESS(status) ){ | |
267 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); | |
268 }else{ | |
269 assert(!pExpr); | |
270 icuFunctionError(p, "uregex_open", status); | |
271 return; | |
272 } | |
273 } | |
274 | |
275 /* Configure the text that the regular expression operates on. */ | |
276 uregex_setText(pExpr, zString, -1, &status); | |
277 if( !U_SUCCESS(status) ){ | |
278 icuFunctionError(p, "uregex_setText", status); | |
279 return; | |
280 } | |
281 | |
282 /* Attempt the match */ | |
283 res = uregex_matches(pExpr, 0, &status); | |
284 if( !U_SUCCESS(status) ){ | |
285 icuFunctionError(p, "uregex_matches", status); | |
286 return; | |
287 } | |
288 | |
289 /* Set the text that the regular expression operates on to a NULL | |
290 ** pointer. This is not really necessary, but it is tidier than | |
291 ** leaving the regular expression object configured with an invalid | |
292 ** pointer after this function returns. | |
293 */ | |
294 uregex_setText(pExpr, 0, 0, &status); | |
295 | |
296 /* Return 1 or 0. */ | |
297 sqlite3_result_int(p, res ? 1 : 0); | |
298 } | |
299 | |
300 /* | |
301 ** Implementations of scalar functions for case mapping - upper() and | |
302 ** lower(). Function upper() converts its input to upper-case (ABC). | |
303 ** Function lower() converts to lower-case (abc). | |
304 ** | |
305 ** ICU provides two types of case mapping, "general" case mapping and | |
306 ** "language specific". Refer to ICU documentation for the differences | |
307 ** between the two. | |
308 ** | |
309 ** To utilise "general" case mapping, the upper() or lower() scalar | |
310 ** functions are invoked with one argument: | |
311 ** | |
312 ** upper('ABC') -> 'abc' | |
313 ** lower('abc') -> 'ABC' | |
314 ** | |
315 ** To access ICU "language specific" case mapping, upper() or lower() | |
316 ** should be invoked with two arguments. The second argument is the name | |
317 ** of the locale to use. Passing an empty string ("") or SQL NULL value | |
318 ** as the second argument is the same as invoking the 1 argument version | |
319 ** of upper() or lower(). | |
320 ** | |
321 ** lower('I', 'en_us') -> 'i' | |
322 ** lower('I', 'tr_tr') -> 'ı' (small dotless i) | |
323 ** | |
324 ** http://www.icu-project.org/userguide/posix.html#case_mappings | |
325 */ | |
326 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ | |
327 const UChar *zInput; | |
328 UChar *zOutput; | |
329 int nInput; | |
330 int nOutput; | |
331 | |
332 UErrorCode status = U_ZERO_ERROR; | |
333 const char *zLocale = 0; | |
334 | |
335 assert(nArg==1 || nArg==2); | |
336 if( nArg==2 ){ | |
337 zLocale = (const char *)sqlite3_value_text(apArg[1]); | |
338 } | |
339 | |
340 zInput = sqlite3_value_text16(apArg[0]); | |
341 if( !zInput ){ | |
342 return; | |
343 } | |
344 nInput = sqlite3_value_bytes16(apArg[0]); | |
345 | |
346 nOutput = nInput * 2 + 2; | |
347 zOutput = sqlite3_malloc(nOutput); | |
348 if( !zOutput ){ | |
349 return; | |
350 } | |
351 | |
352 if( sqlite3_user_data(p) ){ | |
353 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); | |
354 }else{ | |
355 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); | |
356 } | |
357 | |
358 if( !U_SUCCESS(status) ){ | |
359 icuFunctionError(p, "u_strToLower()/u_strToUpper", status); | |
360 return; | |
361 } | |
362 | |
363 sqlite3_result_text16(p, zOutput, -1, xFree); | |
364 } | |
365 | |
366 /* | |
367 ** Collation sequence destructor function. The pCtx argument points to | |
368 ** a UCollator structure previously allocated using ucol_open(). | |
369 */ | |
370 static void icuCollationDel(void *pCtx){ | |
371 UCollator *p = (UCollator *)pCtx; | |
372 ucol_close(p); | |
373 } | |
374 | |
375 /* | |
376 ** Collation sequence comparison function. The pCtx argument points to | |
377 ** a UCollator structure previously allocated using ucol_open(). | |
378 */ | |
379 static int icuCollationColl( | |
380 void *pCtx, | |
381 int nLeft, | |
382 const void *zLeft, | |
383 int nRight, | |
384 const void *zRight | |
385 ){ | |
386 UCollationResult res; | |
387 UCollator *p = (UCollator *)pCtx; | |
388 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); | |
389 switch( res ){ | |
390 case UCOL_LESS: return -1; | |
391 case UCOL_GREATER: return +1; | |
392 case UCOL_EQUAL: return 0; | |
393 } | |
394 assert(!"Unexpected return value from ucol_strcoll()"); | |
395 return 0; | |
396 } | |
397 | |
398 /* | |
399 ** Implementation of the scalar function icu_load_collation(). | |
400 ** | |
401 ** This scalar function is used to add ICU collation based collation | |
402 ** types to an SQLite database connection. It is intended to be called | |
403 ** as follows: | |
404 ** | |
405 ** SELECT icu_load_collation(<locale>, <collation-name>); | |
406 ** | |
407 ** Where <locale> is a string containing an ICU locale identifier (i.e. | |
408 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the | |
409 ** collation sequence to create. | |
410 */ | |
411 static void icuLoadCollation( | |
412 sqlite3_context *p, | |
413 int nArg, | |
414 sqlite3_value **apArg | |
415 ){ | |
416 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); | |
417 UErrorCode status = U_ZERO_ERROR; | |
418 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ | |
419 const char *zName; /* SQL Collation sequence name (eg. "japanese") */ | |
420 UCollator *pUCollator; /* ICU library collation object */ | |
421 int rc; /* Return code from sqlite3_create_collation_x() */ | |
422 | |
423 assert(nArg==2); | |
424 (void)nArg; /* Unused parameter */ | |
425 zLocale = (const char *)sqlite3_value_text(apArg[0]); | |
426 zName = (const char *)sqlite3_value_text(apArg[1]); | |
427 | |
428 if( !zLocale || !zName ){ | |
429 return; | |
430 } | |
431 | |
432 pUCollator = ucol_open(zLocale, &status); | |
433 if( !U_SUCCESS(status) ){ | |
434 icuFunctionError(p, "ucol_open", status); | |
435 return; | |
436 } | |
437 assert(p); | |
438 | |
439 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, | |
440 icuCollationColl, icuCollationDel | |
441 ); | |
442 if( rc!=SQLITE_OK ){ | |
443 ucol_close(pUCollator); | |
444 sqlite3_result_error(p, "Error registering collation function", -1); | |
445 } | |
446 } | |
447 | |
448 /* | |
449 ** Register the ICU extension functions with database db. | |
450 */ | |
451 int sqlite3IcuInit(sqlite3 *db){ | |
452 struct IcuScalar { | |
453 const char *zName; /* Function name */ | |
454 int nArg; /* Number of arguments */ | |
455 int enc; /* Optimal text encoding */ | |
456 void *pContext; /* sqlite3_user_data() context */ | |
457 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); | |
458 } scalars[] = { | |
459 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc}, | |
460 | |
461 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16}, | |
462 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16}, | |
463 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16}, | |
464 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16}, | |
465 | |
466 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16}, | |
467 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16}, | |
468 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16}, | |
469 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16}, | |
470 | |
471 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc}, | |
472 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc}, | |
473 | |
474 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation}, | |
475 }; | |
476 | |
477 int rc = SQLITE_OK; | |
478 int i; | |
479 | |
480 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ | |
481 struct IcuScalar *p = &scalars[i]; | |
482 rc = sqlite3_create_function( | |
483 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0 | |
484 ); | |
485 } | |
486 | |
487 return rc; | |
488 } | |
489 | |
490 #if !SQLITE_CORE | |
491 #ifdef _WIN32 | |
492 __declspec(dllexport) | |
493 #endif | |
494 int sqlite3_icu_init( | |
495 sqlite3 *db, | |
496 char **pzErrMsg, | |
497 const sqlite3_api_routines *pApi | |
498 ){ | |
499 SQLITE_EXTENSION_INIT2(pApi) | |
500 return sqlite3IcuInit(db); | |
501 } | |
502 #endif | |
503 | |
504 #endif | |
OLD | NEW |