File indexing completed on 2024-05-12 16:14:00

0001 /*
0002 ** 2007 May 6
0003 **
0004 ** The author disclaims copyright to this source code.  In place of
0005 ** a legal notice, here is a blessing:
0006 **
0007 **    May you do good and not evil.
0008 **    May you find forgiveness for yourself and forgive others.
0009 **    May you share freely, never taking more than you give.
0010 **
0011 *************************************************************************
0012 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
0013 **
0014 ** This file implements an integration between the ICU library
0015 ** ("International Components for Unicode", an open-source library
0016 ** for handling unicode data) and SQLite. The integration uses
0017 ** ICU to provide the following to SQLite:
0018 **
0019 **   * An implementation of the SQL regexp() function (and hence REGEXP
0020 **     operator) using the ICU uregex_XX() APIs.
0021 **
0022 **   * Implementations of the SQL scalar upper() and lower() functions
0023 **     for case mapping.
0024 **
0025 **   * Integration of ICU and SQLite collation seqences.
0026 **
0027 **   * An implementation of the LIKE operator that uses ICU to
0028 **     provide case-independent matching.
0029 */
0030 
0031 #include "sqliteicu.h"
0032 
0033 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
0034 
0035 /* Include ICU headers */
0036 #include <unicode/utypes.h>
0037 #include <unicode/uregex.h>
0038 #include <unicode/ustring.h>
0039 #include <unicode/ucol.h>
0040 #include <unicode/uvernum.h>
0041 #if U_ICU_VERSION_MAJOR_NUM>=51
0042 #include <unicode/utf_old.h>
0043 #endif
0044 
0045 #include <assert.h>
0046 
0047 #ifndef SQLITE_CORE
0048   #include "sqlite3ext.h"
0049   SQLITE_EXTENSION_INIT1
0050 #else
0051   #include "sqlite3.h"
0052 #endif
0053 
0054 /*
0055 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
0056 ** operator.
0057 */
0058 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
0059 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
0060 #endif
0061 
0062 /*
0063 ** Version of sqlite3_free() that is always a function, never a macro.
0064 */
0065 static void xFree(void *p){
0066   sqlite3_free(p);
0067 }
0068 
0069 /*
0070 ** Compare two UTF-8 strings for equality where the first string is
0071 ** a "LIKE" expression. Return true (1) if they are the same and
0072 ** false (0) if they are different.
0073 */
0074 static int icuLikeCompare(
0075   const uint8_t *zPattern,   /* LIKE pattern */
0076   const uint8_t *zString,    /* The UTF-8 string to compare against */
0077   const UChar32 uEsc         /* The escape character */
0078 ){
0079   static const int MATCH_ONE = (UChar32)'_';
0080   static const int MATCH_ALL = (UChar32)'%';
0081 
0082   int iPattern = 0;       /* Current byte index in zPattern */
0083   int iString = 0;        /* Current byte index in zString */
0084 
0085   int prevEscape = 0;     /* True if the previous character was uEsc */
0086 
0087   while( zPattern[iPattern]!=0 ){
0088 
0089     /* Read (and consume) the next character from the input pattern. */
0090     UChar32 uPattern;
0091     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
0092     assert(uPattern!=0);
0093 
0094     /* There are now 4 possibilities:
0095     **
0096     **     1. uPattern is an unescaped match-all character "%",
0097     **     2. uPattern is an unescaped match-one character "_",
0098     **     3. uPattern is an unescaped escape character, or
0099     **     4. uPattern is to be handled as an ordinary character
0100     */
0101     if( !prevEscape && uPattern==MATCH_ALL ){
0102       /* Case 1. */
0103       uint8_t c;
0104 
0105       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
0106       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
0107       ** test string.
0108       */
0109       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
0110         if( c==MATCH_ONE ){
0111           if( zString[iString]==0 ) return 0;
0112           U8_FWD_1_UNSAFE(zString, iString);
0113         }
0114         iPattern++;
0115       }
0116 
0117       if( zPattern[iPattern]==0 ) return 1;
0118 
0119       while( zString[iString] ){
0120         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
0121           return 1;
0122         }
0123         U8_FWD_1_UNSAFE(zString, iString);
0124       }
0125       return 0;
0126 
0127     }else if( !prevEscape && uPattern==MATCH_ONE ){
0128       /* Case 2. */
0129       if( zString[iString]==0 ) return 0;
0130       U8_FWD_1_UNSAFE(zString, iString);
0131 
0132     }else if( !prevEscape && uPattern==uEsc){
0133       /* Case 3. */
0134       prevEscape = 1;
0135 
0136     }else{
0137       /* Case 4. */
0138       UChar32 uString;
0139       U8_NEXT_UNSAFE(zString, iString, uString);
0140       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
0141       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
0142       if( uString!=uPattern ){
0143         return 0;
0144       }
0145       prevEscape = 0;
0146     }
0147   }
0148 
0149   return zString[iString]==0;
0150 }
0151 
0152 /*
0153 ** Implementation of the like() SQL function.  This function implements
0154 ** the build-in LIKE operator.  The first argument to the function is the
0155 ** pattern and the second argument is the string.  So, the SQL statements:
0156 **
0157 **       A LIKE B
0158 **
0159 ** is implemented as like(B, A). If there is an escape character E,
0160 **
0161 **       A LIKE B ESCAPE E
0162 **
0163 ** is mapped to like(B, A, E).
0164 */
0165 static void icuLikeFunc(
0166   sqlite3_context *context,
0167   int argc,
0168   sqlite3_value **argv
0169 ){
0170   const unsigned char *zA = sqlite3_value_text(argv[0]);
0171   const unsigned char *zB = sqlite3_value_text(argv[1]);
0172   UChar32 uEsc = 0;
0173 
0174   /* Limit the length of the LIKE or GLOB pattern to avoid problems
0175   ** of deep recursion and N*N behavior in patternCompare().
0176   */
0177   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
0178     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
0179     return;
0180   }
0181 
0182 
0183   if( argc==3 ){
0184     /* The escape character string must consist of a single UTF-8 character.
0185     ** Otherwise, return an error.
0186     */
0187     int nE= sqlite3_value_bytes(argv[2]);
0188     const unsigned char *zE = sqlite3_value_text(argv[2]);
0189     int i = 0;
0190     if( zE==nullptr ) return;
0191     U8_NEXT(zE, i, nE, uEsc);
0192     if( i!=nE){
0193       sqlite3_result_error(context,
0194           "ESCAPE expression must be a single character", -1);
0195       return;
0196     }
0197   }
0198 
0199   if( zA && zB ){
0200     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
0201   }
0202 }
0203 
0204 /*
0205 ** This function is called when an ICU function called from within
0206 ** the implementation of an SQL scalar function returns an error.
0207 **
0208 ** The scalar function context passed as the first argument is
0209 ** loaded with an error message based on the following two args.
0210 */
0211 static void icuFunctionError(
0212   sqlite3_context *pCtx,       /* SQLite scalar function context */
0213   const char *zName,           /* Name of ICU function that failed */
0214   UErrorCode e                 /* Error code returned by ICU function */
0215 ){
0216   char zBuf[128];
0217   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
0218   zBuf[127] = '\0';
0219   sqlite3_result_error(pCtx, zBuf, -1);
0220 }
0221 
0222 /*
0223 ** Function to delete compiled regexp objects. Registered as
0224 ** a destructor function with sqlite3_set_auxdata().
0225 */
0226 static void icuRegexpDelete(void *p){
0227   URegularExpression *pExpr = (URegularExpression *)p;
0228   uregex_close(pExpr);
0229 }
0230 
0231 /*
0232 ** Implementation of SQLite REGEXP operator. This scalar function takes
0233 ** two arguments. The first is a regular expression pattern to compile
0234 ** the second is a string to match against that pattern. If either
0235 ** argument is an SQL NULL, then NULL is returned. Otherwise, the result
0236 ** is 1 if the string matches the pattern, or 0 otherwise.
0237 **
0238 ** SQLite maps the regexp() function to the regexp() operator such
0239 ** that the following two are equivalent:
0240 **
0241 **     zString REGEXP zPattern
0242 **     regexp(zPattern, zString)
0243 **
0244 ** Uses the following ICU regexp APIs:
0245 **
0246 **     uregex_open()
0247 **     uregex_matches()
0248 **     uregex_close()
0249 */
0250 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
0251   UErrorCode status = U_ZERO_ERROR;
0252   URegularExpression *pExpr;
0253   UBool res;
0254   const UChar *zString = static_cast<const UChar *>(sqlite3_value_text16(apArg[1]));
0255 
0256   (void)nArg;  /* Unused parameter */
0257 
0258   /* If the left hand side of the regexp operator is NULL,
0259   ** then the result is also NULL.
0260   */
0261   if( !zString ){
0262     return;
0263   }
0264 
0265   pExpr = static_cast<URegularExpression*>(sqlite3_get_auxdata(p, 0));
0266   if( !pExpr ){
0267     const UChar *zPattern = static_cast<const UChar *>(sqlite3_value_text16(apArg[0]));
0268     if( !zPattern ){
0269       return;
0270     }
0271     pExpr = uregex_open(zPattern, -1, 0, nullptr, &status);
0272 
0273     if( U_SUCCESS(status) ){
0274       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
0275     }else{
0276       assert(!pExpr);
0277       icuFunctionError(p, "uregex_open", status);
0278       return;
0279     }
0280   }
0281 
0282   /* Configure the text that the regular expression operates on. */
0283   uregex_setText(pExpr, zString, -1, &status);
0284   if( !U_SUCCESS(status) ){
0285     icuFunctionError(p, "uregex_setText", status);
0286     return;
0287   }
0288 
0289   /* Attempt the match */
0290   res = uregex_matches(pExpr, 0, &status);
0291   if( !U_SUCCESS(status) ){
0292     icuFunctionError(p, "uregex_matches", status);
0293     return;
0294   }
0295 
0296   /* Set the text that the regular expression operates on to a NULL
0297   ** pointer. This is not really necessary, but it is tidier than
0298   ** leaving the regular expression object configured with an invalid
0299   ** pointer after this function returns.
0300   */
0301   uregex_setText(pExpr, nullptr, 0, &status);
0302 
0303   /* Return 1 or 0. */
0304   sqlite3_result_int(p, res ? 1 : 0);
0305 }
0306 
0307 /*
0308 ** Implementations of scalar functions for case mapping - upper() and
0309 ** lower(). Function upper() converts its input to upper-case (ABC).
0310 ** Function lower() converts to lower-case (abc).
0311 **
0312 ** ICU provides two types of case mapping, "general" case mapping and
0313 ** "language specific". Refer to ICU documentation for the differences
0314 ** between the two.
0315 **
0316 ** To utilise "general" case mapping, the upper() or lower() scalar
0317 ** functions are invoked with one argument:
0318 **
0319 **     upper('ABC') -> 'abc'
0320 **     lower('abc') -> 'ABC'
0321 **
0322 ** To access ICU "language specific" case mapping, upper() or lower()
0323 ** should be invoked with two arguments. The second argument is the name
0324 ** of the locale to use. Passing an empty string ("") or SQL NULL value
0325 ** as the second argument is the same as invoking the 1 argument version
0326 ** of upper() or lower().
0327 **
0328 **     lower('I', 'en_us') -> 'i'
0329 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
0330 **
0331 ** https://www.icu-project.org/userguide/posix.html#case_mappings
0332 */
0333 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
0334   const UChar *zInput;
0335   UChar *zOutput;
0336   int nInput;
0337   int nOutput;
0338 
0339   UErrorCode status = U_ZERO_ERROR;
0340   const unsigned char *zLocale = nullptr;
0341 
0342   assert(nArg==1 || nArg==2);
0343   if( nArg==2 ){
0344     zLocale = static_cast<const unsigned char *>(sqlite3_value_text(apArg[1]));
0345   }
0346 
0347   zInput = static_cast<const UChar *>(sqlite3_value_text16(apArg[0]));
0348   if( !zInput ){
0349     return;
0350   }
0351   nInput = sqlite3_value_bytes16(apArg[0]);
0352 
0353   nOutput = nInput * 2 + 2;
0354   zOutput = static_cast<UChar *>(sqlite3_malloc(nOutput));
0355   if( !zOutput ){
0356     return;
0357   }
0358 
0359   if( sqlite3_user_data(p) ){
0360     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, reinterpret_cast<const char*>(zLocale), &status);
0361   }else{
0362     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, reinterpret_cast<const char*>(zLocale), &status);
0363   }
0364 
0365   if( !U_SUCCESS(status) ){
0366     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
0367     return;
0368   }
0369 
0370   sqlite3_result_text16(p, zOutput, -1, xFree);
0371 }
0372 
0373 /*
0374 ** Collation sequence destructor function. The pCtx argument points to
0375 ** a UCollator structure previously allocated using ucol_open().
0376 */
0377 static void icuCollationDel(void *pCtx){
0378   UCollator *p = (UCollator *)pCtx;
0379   ucol_close(p);
0380 }
0381 
0382 /*
0383 ** Collation sequence comparison function. The pCtx argument points to
0384 ** a UCollator structure previously allocated using ucol_open().
0385 */
0386 static int icuCollationColl(
0387   void *pCtx,
0388   int nLeft,
0389   const void *zLeft,
0390   int nRight,
0391   const void *zRight
0392 ){
0393   UCollationResult res;
0394   UCollator *p = (UCollator *)pCtx;
0395   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
0396   switch( res ){
0397     case UCOL_LESS:    return -1;
0398     case UCOL_GREATER: return +1;
0399     case UCOL_EQUAL:   return 0;
0400   }
0401   assert(!"Unexpected return value from ucol_strcoll()");
0402   return 0;
0403 }
0404 
0405 /*
0406 ** Implementation of the scalar function icu_load_collation().
0407 **
0408 ** This scalar function is used to add ICU collation based collation
0409 ** types to an SQLite database connection. It is intended to be called
0410 ** as follows:
0411 **
0412 **     SELECT icu_load_collation(<locale>, <collation-name>);
0413 **
0414 ** Where <locale> is a string containing an ICU locale identifier (i.e.
0415 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
0416 ** collation sequence to create.
0417 */
0418 static void icuLoadCollation(
0419   sqlite3_context *p,
0420   int nArg,
0421   sqlite3_value **apArg
0422 ){
0423   (void)nArg;  /* Unused parameter */
0424 
0425   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
0426   UErrorCode status = U_ZERO_ERROR;
0427   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
0428   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
0429   UCollator *pUCollator;    /* ICU library collation object */
0430   int rc;                   /* Return code from sqlite3_create_collation_x() */
0431 
0432   assert(nArg==2);
0433   zLocale = (const char *)sqlite3_value_text(apArg[0]);
0434   zName = (const char *)sqlite3_value_text(apArg[1]);
0435 
0436   if( !zLocale || !zName ){
0437     return;
0438   }
0439 
0440   pUCollator = ucol_open(zLocale, &status);
0441   if( !U_SUCCESS(status) ){
0442     icuFunctionError(p, "ucol_open", status);
0443     return;
0444   }
0445   assert(p);
0446 
0447   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
0448       icuCollationColl, icuCollationDel
0449   );
0450   if( rc!=SQLITE_OK ){
0451     ucol_close(pUCollator);
0452     sqlite3_result_error(p, "Error registering collation function", -1);
0453   }
0454 }
0455 
0456 /*
0457 ** Register the ICU extension functions with database db.
0458 */
0459 KDB_SQLITE_ICU_EXPORT int sqlite3IcuInit(sqlite3 *db){
0460   struct IcuScalar {
0461     const char *zName;                        /* Function name */
0462     int nArg;                                 /* Number of arguments */
0463     int enc;                                  /* Optimal text encoding */
0464     void *pContext;                           /* sqlite3_user_data() context */
0465     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
0466   } scalars[] = {
0467     {"regexp", 2, SQLITE_ANY,          nullptr, icuRegexpFunc},
0468 
0469     {"lower",  1, SQLITE_UTF16,        nullptr, icuCaseFunc16},
0470     {"lower",  2, SQLITE_UTF16,        nullptr, icuCaseFunc16},
0471     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
0472     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
0473 
0474     {"lower",  1, SQLITE_UTF8,         nullptr, icuCaseFunc16},
0475     {"lower",  2, SQLITE_UTF8,         nullptr, icuCaseFunc16},
0476     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
0477     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
0478 
0479     {"like",   2, SQLITE_UTF8,         nullptr, icuLikeFunc},
0480     {"like",   3, SQLITE_UTF8,         nullptr, icuLikeFunc},
0481 
0482     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
0483   };
0484 
0485   int rc = SQLITE_OK;
0486   int i;
0487 
0488   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
0489     struct IcuScalar *p = &scalars[i];
0490     rc = sqlite3_create_function(
0491         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, nullptr, nullptr
0492     );
0493   }
0494 
0495   return rc;
0496 }
0497 
0498 #if !defined SQLITE_CORE || !SQLITE_CORE
0499 KDB_SQLITE_ICU_EXPORT int sqlite3_extension_init(
0500   sqlite3 *db,
0501   char **pzErrMsg,
0502   const struct sqlite3_api_routines *pApi
0503 ){
0504   (void)pzErrMsg;  /* Unused parameter */
0505   SQLITE_EXTENSION_INIT2(pApi)
0506   return sqlite3IcuInit(db);
0507 }
0508 #endif
0509 
0510 #endif