icu.cpp 18 KB

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