icu.c 14 KB

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