icu.cpp 18 KB

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