interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / icu / icu.c

592 lines · 18847 bytes Raw Blame History
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) \
32 || defined(SQLITE_ENABLE_ICU) \
33 || defined(SQLITE_ENABLE_ICU_COLLATIONS)
34
35/* Include ICU headers */
36#include <unicode/utypes.h>
37#include <unicode/uregex.h>
38#include <unicode/ustring.h>
39#include <unicode/ucol.h>
40
41#include <assert.h>
42
43#ifndef SQLITE_CORE
44 #include "sqlite3ext.h"
45 SQLITE_EXTENSION_INIT1
46#else
47 #include "sqlite3.h"
48#endif
49
50/*
51** This function is called when an ICU function called from within
52** the implementation of an SQL scalar function returns an error.
53**
54** The scalar function context passed as the first argument is
55** loaded with an error message based on the following two args.
56*/
57static void icuFunctionError(
58 sqlite3_context *pCtx, /* SQLite scalar function context */
59 const char *zName, /* Name of ICU function that failed */
60 UErrorCode e /* Error code returned by ICU function */
61){
62 char zBuf[128];
63 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
64 zBuf[127] = '\0';
65 sqlite3_result_error(pCtx, zBuf, -1);
66}
67
68#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
69
70/*
71** Maximum length (in bytes) of the pattern in a LIKE or GLOB
72** operator.
73*/
74#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
75# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
76#endif
77
78/*
79** Version of sqlite3_free() that is always a function, never a macro.
80*/
81static void xFree(void *p){
82 sqlite3_free(p);
83}
84
85/*
86** This lookup table is used to help decode the first byte of
87** a multi-byte UTF8 character. It is copied here from SQLite source
88** code file utf8.c.
89*/
90static const unsigned char icuUtf8Trans1[] = {
91 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
92 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
93 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
94 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
95 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
96 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
97 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
98 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
99};
100
101#define SQLITE_ICU_READ_UTF8(zIn, c) \
102 c = *(zIn++); \
103 if( c>=0xc0 ){ \
104 c = icuUtf8Trans1[c-0xc0]; \
105 while( (*zIn & 0xc0)==0x80 ){ \
106 c = (c<<6) + (0x3f & *(zIn++)); \
107 } \
108 if( c<0x80 \
109 || (c&0xFFFFF800)==0xD800 \
110 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
111 }
112
113#define SQLITE_ICU_SKIP_UTF8(zIn) \
114 assert( *zIn ); \
115 if( *(zIn++)>=0xc0 ){ \
116 while( (*zIn & 0xc0)==0x80 ){zIn++;} \
117 }
118
119
120/*
121** Compare two UTF-8 strings for equality where the first string is
122** a "LIKE" expression. Return true (1) if they are the same and
123** false (0) if they are different.
124*/
125static int icuLikeCompare(
126 const uint8_t *zPattern, /* LIKE pattern */
127 const uint8_t *zString, /* The UTF-8 string to compare against */
128 const UChar32 uEsc /* The escape character */
129){
130 static const uint32_t MATCH_ONE = (uint32_t)'_';
131 static const uint32_t MATCH_ALL = (uint32_t)'%';
132
133 int prevEscape = 0; /* True if the previous character was uEsc */
134
135 while( 1 ){
136
137 /* Read (and consume) the next character from the input pattern. */
138 uint32_t uPattern;
139 SQLITE_ICU_READ_UTF8(zPattern, uPattern);
140 if( uPattern==0 ) break;
141
142 /* There are now 4 possibilities:
143 **
144 ** 1. uPattern is an unescaped match-all character "%",
145 ** 2. uPattern is an unescaped match-one character "_",
146 ** 3. uPattern is an unescaped escape character, or
147 ** 4. uPattern is to be handled as an ordinary character
148 */
149 if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){
150 /* Case 1. */
151 uint8_t c;
152
153 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
154 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
155 ** test string.
156 */
157 while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
158 if( c==MATCH_ONE ){
159 if( *zString==0 ) return 0;
160 SQLITE_ICU_SKIP_UTF8(zString);
161 }
162 zPattern++;
163 }
164
165 if( *zPattern==0 ) return 1;
166
167 while( *zString ){
168 if( icuLikeCompare(zPattern, zString, uEsc) ){
169 return 1;
170 }
171 SQLITE_ICU_SKIP_UTF8(zString);
172 }
173 return 0;
174
175 }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){
176 /* Case 2. */
177 if( *zString==0 ) return 0;
178 SQLITE_ICU_SKIP_UTF8(zString);
179
180 }else if( uPattern==(uint32_t)uEsc && !prevEscape ){
181 /* Case 3. */
182 prevEscape = 1;
183
184 }else{
185 /* Case 4. */
186 uint32_t uString;
187 SQLITE_ICU_READ_UTF8(zString, uString);
188 uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
189 uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
190 if( uString!=uPattern ){
191 return 0;
192 }
193 prevEscape = 0;
194 }
195 }
196
197 return *zString==0;
198}
199
200/*
201** Implementation of the like() SQL function. This function implements
202** the build-in LIKE operator. The first argument to the function is the
203** pattern and the second argument is the string. So, the SQL statements:
204**
205** A LIKE B
206**
207** is implemented as like(B, A). If there is an escape character E,
208**
209** A LIKE B ESCAPE E
210**
211** is mapped to like(B, A, E).
212*/
213static void icuLikeFunc(
214 sqlite3_context *context,
215 int argc,
216 sqlite3_value **argv
217){
218 const unsigned char *zA = sqlite3_value_text(argv[0]);
219 const unsigned char *zB = sqlite3_value_text(argv[1]);
220 UChar32 uEsc = 0;
221
222 /* Limit the length of the LIKE or GLOB pattern to avoid problems
223 ** of deep recursion and N*N behavior in patternCompare().
224 */
225 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
226 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
227 return;
228 }
229
230
231 if( argc==3 ){
232 /* The escape character string must consist of a single UTF-8 character.
233 ** Otherwise, return an error.
234 */
235 int nE= sqlite3_value_bytes(argv[2]);
236 const unsigned char *zE = sqlite3_value_text(argv[2]);
237 int i = 0;
238 if( zE==0 ) return;
239 U8_NEXT(zE, i, nE, uEsc);
240 if( i!=nE){
241 sqlite3_result_error(context,
242 "ESCAPE expression must be a single character", -1);
243 return;
244 }
245 }
246
247 if( zA && zB ){
248 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
249 }
250}
251
252/*
253** Function to delete compiled regexp objects. Registered as
254** a destructor function with sqlite3_set_auxdata().
255*/
256static void icuRegexpDelete(void *p){
257 URegularExpression *pExpr = (URegularExpression *)p;
258 uregex_close(pExpr);
259}
260
261/*
262** Implementation of SQLite REGEXP operator. This scalar function takes
263** two arguments. The first is a regular expression pattern to compile
264** the second is a string to match against that pattern. If either
265** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
266** is 1 if the string matches the pattern, or 0 otherwise.
267**
268** SQLite maps the regexp() function to the regexp() operator such
269** that the following two are equivalent:
270**
271** zString REGEXP zPattern
272** regexp(zPattern, zString)
273**
274** Uses the following ICU regexp APIs:
275**
276** uregex_open()
277** uregex_matches()
278** uregex_close()
279*/
280static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
281 UErrorCode status = U_ZERO_ERROR;
282 URegularExpression *pExpr;
283 UBool res;
284 const UChar *zString = sqlite3_value_text16(apArg[1]);
285
286 (void)nArg; /* Unused parameter */
287
288 /* If the left hand side of the regexp operator is NULL,
289 ** then the result is also NULL.
290 */
291 if( !zString ){
292 return;
293 }
294
295 pExpr = sqlite3_get_auxdata(p, 0);
296 if( !pExpr ){
297 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
298 if( !zPattern ){
299 return;
300 }
301 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
302
303 if( U_SUCCESS(status) ){
304 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
305 pExpr = sqlite3_get_auxdata(p, 0);
306 }
307 if( !pExpr ){
308 icuFunctionError(p, "uregex_open", status);
309 return;
310 }
311 }
312
313 /* Configure the text that the regular expression operates on. */
314 uregex_setText(pExpr, zString, -1, &status);
315 if( !U_SUCCESS(status) ){
316 icuFunctionError(p, "uregex_setText", status);
317 return;
318 }
319
320 /* Attempt the match */
321 res = uregex_matches(pExpr, 0, &status);
322 if( !U_SUCCESS(status) ){
323 icuFunctionError(p, "uregex_matches", status);
324 return;
325 }
326
327 /* Set the text that the regular expression operates on to a NULL
328 ** pointer. This is not really necessary, but it is tidier than
329 ** leaving the regular expression object configured with an invalid
330 ** pointer after this function returns.
331 */
332 uregex_setText(pExpr, 0, 0, &status);
333
334 /* Return 1 or 0. */
335 sqlite3_result_int(p, res ? 1 : 0);
336}
337
338/*
339** Implementations of scalar functions for case mapping - upper() and
340** lower(). Function upper() converts its input to upper-case (ABC).
341** Function lower() converts to lower-case (abc).
342**
343** ICU provides two types of case mapping, "general" case mapping and
344** "language specific". Refer to ICU documentation for the differences
345** between the two.
346**
347** To utilise "general" case mapping, the upper() or lower() scalar
348** functions are invoked with one argument:
349**
350** upper('ABC') -> 'abc'
351** lower('abc') -> 'ABC'
352**
353** To access ICU "language specific" case mapping, upper() or lower()
354** should be invoked with two arguments. The second argument is the name
355** of the locale to use. Passing an empty string ("") or SQL NULL value
356** as the second argument is the same as invoking the 1 argument version
357** of upper() or lower().
358**
359** lower('I', 'en_us') -> 'i'
360** lower('I', 'tr_tr') -> '\u131' (small dotless i)
361**
362** http://www.icu-project.org/userguide/posix.html#case_mappings
363*/
364static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
365 const UChar *zInput; /* Pointer to input string */
366 UChar *zOutput = 0; /* Pointer to output buffer */
367 int nInput; /* Size of utf-16 input string in bytes */
368 sqlite3_int64 nOut; /* Size of output buffer in bytes */
369 int cnt;
370 int bToUpper; /* True for toupper(), false for tolower() */
371 UErrorCode status;
372 const char *zLocale = 0;
373
374 assert(nArg==1 || nArg==2);
375 bToUpper = (sqlite3_user_data(p)!=0);
376 if( nArg==2 ){
377 zLocale = (const char *)sqlite3_value_text(apArg[1]);
378 }
379
380 zInput = sqlite3_value_text16(apArg[0]);
381 if( !zInput ){
382 return;
383 }
384 nOut = nInput = sqlite3_value_bytes16(apArg[0]);
385 if( nOut==0 ){
386 sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
387 return;
388 }
389
390 for(cnt=0; cnt<2; cnt++){
391 UChar *zNew = sqlite3_realloc64(zOutput, nOut);
392 if( zNew==0 ){
393 sqlite3_free(zOutput);
394 sqlite3_result_error_nomem(p);
395 return;
396 }
397 zOutput = zNew;
398 status = U_ZERO_ERROR;
399 if( bToUpper ){
400 nOut = 2LL*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
401 }else{
402 nOut = 2LL*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
403 }
404
405 if( U_SUCCESS(status) ){
406 sqlite3_result_text16(p, zOutput, nOut, xFree);
407 }else if( status==U_BUFFER_OVERFLOW_ERROR ){
408 assert( cnt==0 );
409 continue;
410 }else{
411 icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
412 }
413 return;
414 }
415 assert( 0 ); /* Unreachable */
416}
417
418#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
419
420/*
421** Collation sequence destructor function. The pCtx argument points to
422** a UCollator structure previously allocated using ucol_open().
423*/
424static void icuCollationDel(void *pCtx){
425 UCollator *p = (UCollator *)pCtx;
426 ucol_close(p);
427}
428
429/*
430** Collation sequence comparison function. The pCtx argument points to
431** a UCollator structure previously allocated using ucol_open().
432*/
433static int icuCollationColl(
434 void *pCtx,
435 int nLeft,
436 const void *zLeft,
437 int nRight,
438 const void *zRight
439){
440 UCollationResult res;
441 UCollator *p = (UCollator *)pCtx;
442 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
443 switch( res ){
444 case UCOL_LESS: return -1;
445 case UCOL_GREATER: return +1;
446 case UCOL_EQUAL: return 0;
447 }
448 assert(!"Unexpected return value from ucol_strcoll()");
449 return 0;
450}
451
452/*
453** Implementation of the scalar function icu_load_collation().
454**
455** This scalar function is used to add ICU collation based collation
456** types to an SQLite database connection. It is intended to be called
457** as follows:
458**
459** SELECT icu_load_collation(<locale>, <collation-name>);
460**
461** Where <locale> is a string containing an ICU locale identifier (i.e.
462** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
463** collation sequence to create.
464*/
465static void icuLoadCollation(
466 sqlite3_context *p,
467 int nArg,
468 sqlite3_value **apArg
469){
470 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
471 UErrorCode status = U_ZERO_ERROR;
472 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
473 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
474 UCollator *pUCollator; /* ICU library collation object */
475 int rc; /* Return code from sqlite3_create_collation_x() */
476
477 assert(nArg==2 || nArg==3);
478 (void)nArg; /* Unused parameter */
479 zLocale = (const char *)sqlite3_value_text(apArg[0]);
480 zName = (const char *)sqlite3_value_text(apArg[1]);
481
482 if( !zLocale || !zName ){
483 return;
484 }
485
486 pUCollator = ucol_open(zLocale, &status);
487 if( !U_SUCCESS(status) ){
488 icuFunctionError(p, "ucol_open", status);
489 return;
490 }
491 assert(p);
492 if(nArg==3){
493 const char *zOption = (const char*)sqlite3_value_text(apArg[2]);
494 static const struct {
495 const char *zName;
496 UColAttributeValue val;
497 } aStrength[] = {
498 { "PRIMARY", UCOL_PRIMARY },
499 { "SECONDARY", UCOL_SECONDARY },
500 { "TERTIARY", UCOL_TERTIARY },
501 { "DEFAULT", UCOL_DEFAULT_STRENGTH },
502 { "QUARTERNARY", UCOL_QUATERNARY },
503 { "IDENTICAL", UCOL_IDENTICAL },
504 };
505 unsigned int i;
506 for(i=0; i<sizeof(aStrength)/sizeof(aStrength[0]); i++){
507 if( sqlite3_stricmp(zOption,aStrength[i].zName)==0 ){
508 ucol_setStrength(pUCollator, aStrength[i].val);
509 break;
510 }
511 }
512 if( i>=sizeof(aStrength)/sizeof(aStrength[0]) ){
513 sqlite3_str *pStr = sqlite3_str_new(sqlite3_context_db_handle(p));
514 sqlite3_str_appendf(pStr,
515 "unknown collation strength \"%s\" - should be one of:",
516 zOption);
517 for(i=0; i<sizeof(aStrength)/sizeof(aStrength[0]); i++){
518 sqlite3_str_appendf(pStr, " %s", aStrength[i].zName);
519 }
520 sqlite3_result_error(p, sqlite3_str_value(pStr), -1);
521 sqlite3_free(sqlite3_str_finish(pStr));
522 ucol_close(pUCollator);
523 return;
524 }
525 }
526 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
527 icuCollationColl, icuCollationDel
528 );
529 if( rc!=SQLITE_OK ){
530 ucol_close(pUCollator);
531 sqlite3_result_error(p, "Error registering collation function", -1);
532 }
533}
534
535/*
536** Register the ICU extension functions with database db.
537*/
538int sqlite3IcuInit(sqlite3 *db){
539# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
540 static const struct IcuScalar {
541 const char *zName; /* Function name */
542 unsigned char nArg; /* Number of arguments */
543 unsigned int enc; /* Optimal text encoding */
544 unsigned char iContext; /* sqlite3_user_data() context */
545 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
546 } scalars[] = {
547 {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
548 {"icu_load_collation",3,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
549#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
550 {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS, 0, icuRegexpFunc},
551 {"lower", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
552 {"lower", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
553 {"upper", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
554 {"upper", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
555 {"lower", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
556 {"lower", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
557 {"upper", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
558 {"upper", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
559 {"like", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
560 {"like", 3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
561#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
562 };
563 int rc = SQLITE_OK;
564 int i;
565
566 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
567 const struct IcuScalar *p = &scalars[i];
568 rc = sqlite3_create_function(
569 db, p->zName, p->nArg, p->enc,
570 p->iContext ? (void*)db : (void*)0,
571 p->xFunc, 0, 0
572 );
573 }
574
575 return rc;
576}
577
578#ifndef SQLITE_CORE
579#ifdef _WIN32
580__declspec(dllexport)
581#endif
582int sqlite3_icu_init(
583 sqlite3 *db,
584 char **pzErrMsg,
585 const sqlite3_api_routines *pApi
586){
587 SQLITE_EXTENSION_INIT2(pApi)
588 return sqlite3IcuInit(db);
589}
590#endif
591
592#endif