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 / misc / nextchar.c

357 lines · 10758 bytes Raw Blame History
1/*
2** 2013-02-28
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**
13** This file contains code to implement the next_char(A,T,F,W,C) SQL function.
14**
15** The next_char(A,T,F,W,C) function finds all valid "next" characters for
16** string A given the vocabulary in T.F. If the W value exists and is a
17** non-empty string, then it is an SQL expression that limits the entries
18** in T.F that will be considered. If C exists and is a non-empty string,
19** then it is the name of the collating sequence to use for comparison. If
20**
21** Only the first three arguments are required. If the C parameter is
22** omitted or is NULL or is an empty string, then the default collating
23** sequence of T.F is used for comparision. If the W parameter is omitted
24** or is NULL or is an empty string, then no filtering of the output is
25** done.
26**
27** The T.F column should be indexed using collation C or else this routine
28** will be quite slow.
29**
30** For example, suppose an application has a dictionary like this:
31**
32** CREATE TABLE dictionary(word TEXT UNIQUE);
33**
34** Further suppose that for user keypad entry, it is desired to disable
35** (gray out) keys that are not valid as the next character. If the
36** the user has previously entered (say) 'cha' then to find all allowed
37** next characters (and thereby determine when keys should not be grayed
38** out) run the following query:
39**
40** SELECT next_char('cha','dictionary','word');
41**
42** IMPLEMENTATION NOTES:
43**
44** The next_char function is implemented using recursive SQL that makes
45** use of the table name and column name as part of a query. If either
46** the table name or column name are keywords or contain special characters,
47** then they should be escaped. For example:
48**
49** SELECT next_char('cha','[dictionary]','[word]');
50**
51** This also means that the table name can be a subquery:
52**
53** SELECT next_char('cha','(SELECT word AS w FROM dictionary)','w');
54*/
55#include "sqlite3ext.h"
56SQLITE_EXTENSION_INIT1
57#include <string.h>
58
59/*
60** A structure to hold context of the next_char() computation across
61** nested function calls.
62*/
63typedef struct nextCharContext nextCharContext;
64struct nextCharContext {
65 sqlite3 *db; /* Database connection */
66 sqlite3_stmt *pStmt; /* Prepared statement used to query */
67 const unsigned char *zPrefix; /* Prefix to scan */
68 int nPrefix; /* Size of zPrefix in bytes */
69 int nAlloc; /* Space allocated to aResult */
70 int nUsed; /* Space used in aResult */
71 unsigned int *aResult; /* Array of next characters */
72 int mallocFailed; /* True if malloc fails */
73 int otherError; /* True for any other failure */
74};
75
76/*
77** Append a result character if the character is not already in the
78** result.
79*/
80static void nextCharAppend(nextCharContext *p, unsigned c){
81 int i;
82 for(i=0; i<p->nUsed; i++){
83 if( p->aResult[i]==c ) return;
84 }
85 if( p->nUsed+1 > p->nAlloc ){
86 unsigned int *aNew;
87 int n = p->nAlloc*2 + 30;
88 aNew = sqlite3_realloc64(p->aResult, n*sizeof(unsigned int));
89 if( aNew==0 ){
90 p->mallocFailed = 1;
91 return;
92 }else{
93 p->aResult = aNew;
94 p->nAlloc = n;
95 }
96 }
97 p->aResult[p->nUsed++] = c;
98}
99
100/*
101** Write a character into z[] as UTF8. Return the number of bytes needed
102** to hold the character
103*/
104static int writeUtf8(unsigned char *z, unsigned c){
105 if( c<0x00080 ){
106 z[0] = (unsigned char)(c&0xff);
107 return 1;
108 }
109 if( c<0x00800 ){
110 z[0] = 0xC0 + (unsigned char)((c>>6)&0x1F);
111 z[1] = 0x80 + (unsigned char)(c & 0x3F);
112 return 2;
113 }
114 if( c<0x10000 ){
115 z[0] = 0xE0 + (unsigned char)((c>>12)&0x0F);
116 z[1] = 0x80 + (unsigned char)((c>>6) & 0x3F);
117 z[2] = 0x80 + (unsigned char)(c & 0x3F);
118 return 3;
119 }
120 z[0] = 0xF0 + (unsigned char)((c>>18) & 0x07);
121 z[1] = 0x80 + (unsigned char)((c>>12) & 0x3F);
122 z[2] = 0x80 + (unsigned char)((c>>6) & 0x3F);
123 z[3] = 0x80 + (unsigned char)(c & 0x3F);
124 return 4;
125}
126
127/*
128** Read a UTF8 character out of z[] and write it into *pOut. Return
129** the number of bytes in z[] that were used to construct the character.
130*/
131static int readUtf8(const unsigned char *z, unsigned *pOut){
132 static const unsigned char validBits[] = {
133 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
134 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
135 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
136 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
137 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
138 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
139 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
140 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
141 };
142 unsigned c = z[0];
143 if( c<0xc0 ){
144 *pOut = c;
145 return 1;
146 }else{
147 int n = 1;
148 c = validBits[c-0xc0];
149 while( (z[n] & 0xc0)==0x80 ){
150 c = (c<<6) + (0x3f & z[n++]);
151 }
152 if( c<0x80 || (c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){
153 c = 0xFFFD;
154 }
155 *pOut = c;
156 return n;
157 }
158}
159
160/*
161** The nextCharContext structure has been set up. Add all "next" characters
162** to the result set.
163**
164** Each step of the loop finds the smallest entry, in collation order, that
165** is greater than both:
166**
167** ?1 || ?2 where ?2 is c||char(0x10ffff) and c is the most recent
168** next character found. This skips over all other entries
169** that continue with c.
170**
171** ?3 the entry found by the previous step.
172**
173** The ?3 constraint guarantees forward progress, even for collating
174** sequences, such as NOCASE, in which ?1||?2 might sort before entries
175** that have already been visited.
176*/
177static void findNextChars(nextCharContext *p){
178 unsigned char zPrev[8];
179 int nPrev = 0;
180 unsigned char *zLast = 0;
181 int nLast = 0;
182 int rc;
183
184 for(;;){
185 sqlite3_bind_text(p->pStmt, 1, (char*)p->zPrefix, p->nPrefix,
186 SQLITE_STATIC);
187 sqlite3_bind_text(p->pStmt, 2, (char*)zPrev, nPrev, SQLITE_STATIC);
188 if( zLast ){
189 sqlite3_bind_text(p->pStmt, 3, (char*)zLast, nLast, SQLITE_STATIC);
190 }else{
191 sqlite3_bind_text(p->pStmt, 3, (char*)p->zPrefix, p->nPrefix,
192 SQLITE_STATIC);
193 }
194 rc = sqlite3_step(p->pStmt);
195 if( rc==SQLITE_DONE ){
196 break;
197 }else if( rc!=SQLITE_ROW ){
198 p->otherError = rc;
199 break;
200 }else{
201 const unsigned char *zOut = sqlite3_column_text(p->pStmt, 0);
202 int nOut = sqlite3_column_bytes(p->pStmt, 0);
203 unsigned char *zNew;
204 if( zOut==0 ){
205 p->mallocFailed = 1;
206 break;
207 }
208 zNew = sqlite3_realloc64(zLast, nOut+1);
209 if( zNew==0 ){
210 p->mallocFailed = 1;
211 break;
212 }
213 zLast = zNew;
214 nLast = nOut;
215 memcpy(zLast, zOut, nOut+1);
216 sqlite3_reset(p->pStmt);
217 if( nLast>p->nPrefix ){
218 unsigned cNext;
219 readUtf8(zLast+p->nPrefix, &cNext);
220 nextCharAppend(p, cNext);
221 if( p->mallocFailed ) break;
222 nPrev = writeUtf8(zPrev, cNext);
223 nPrev += writeUtf8(zPrev+nPrev, 0x10ffff);
224 }
225 }
226 }
227 sqlite3_reset(p->pStmt);
228 sqlite3_free(zLast);
229}
230
231
232/*
233** next_character(A,T,F,W[,C])
234**
235** Return a string composted of all next possible characters after
236** A for elements of T.F. If W is supplied, then it is an SQL expression
237** that limits the elements in T.F that are considered. Optional argument
238** is a collation sequence name.
239*/
240static void nextCharFunc(
241 sqlite3_context *context,
242 int argc,
243 sqlite3_value **argv
244){
245 nextCharContext c;
246 const unsigned char *zTable = sqlite3_value_text(argv[1]);
247 const unsigned char *zField = sqlite3_value_text(argv[2]);
248 const unsigned char *zWhere;
249 const unsigned char *zCollName;
250 char *zWhereClause = 0;
251 char *zColl = 0;
252 char *zSql;
253 int rc;
254
255 memset(&c, 0, sizeof(c));
256 c.db = sqlite3_context_db_handle(context);
257 c.zPrefix = sqlite3_value_text(argv[0]);
258 c.nPrefix = sqlite3_value_bytes(argv[0]);
259 if( zTable==0 || zField==0 || c.zPrefix==0 ) return;
260 if( argc>=4
261 && (zWhere = sqlite3_value_text(argv[3]))!=0
262 && zWhere[0]!=0
263 ){
264 zWhereClause = sqlite3_mprintf("AND (%s)", zWhere);
265 if( zWhereClause==0 ){
266 sqlite3_result_error_nomem(context);
267 return;
268 }
269 }else{
270 zWhereClause = "";
271 }
272 if( argc>=5
273 && (zCollName = sqlite3_value_text(argv[4]))!=0
274 && zCollName[0]!=0
275 ){
276 zColl = sqlite3_mprintf("collate \"%w\"", zCollName);
277 if( zColl==0 ){
278 sqlite3_result_error_nomem(context);
279 if( zWhereClause[0] ) sqlite3_free(zWhereClause);
280 return;
281 }
282 }else{
283 zColl = "";
284 }
285 zSql = sqlite3_mprintf(
286 "SELECT %s FROM %s"
287 " WHERE %s>(?1 || ?2) %s"
288 " AND +%s>?3 %s"
289 " AND %s<=(?1 || char(1114111)) %s" /* 1114111 == 0x10ffff */
290 " %s"
291 " ORDER BY 1 %s ASC LIMIT 1",
292 zField, zTable, zField, zColl, zField, zColl, zField, zColl,
293 zWhereClause, zColl
294 );
295 if( zWhereClause[0] ) sqlite3_free(zWhereClause);
296 if( zColl[0] ) sqlite3_free(zColl);
297 if( zSql==0 ){
298 sqlite3_result_error_nomem(context);
299 return;
300 }
301
302 rc = sqlite3_prepare_v2(c.db, zSql, -1, &c.pStmt, 0);
303 sqlite3_free(zSql);
304 if( rc ){
305 sqlite3_result_error(context, sqlite3_errmsg(c.db), -1);
306 return;
307 }
308 findNextChars(&c);
309 if( c.mallocFailed ){
310 sqlite3_result_error_nomem(context);
311 }else{
312 unsigned char *pRes;
313 pRes = sqlite3_malloc64( c.nUsed*4 + 1 );
314 if( pRes==0 ){
315 sqlite3_result_error_nomem(context);
316 }else{
317 int i;
318 int n = 0;
319 for(i=0; i<c.nUsed; i++){
320 n += writeUtf8(pRes+n, c.aResult[i]);
321 }
322 pRes[n] = 0;
323 sqlite3_result_text(context, (const char*)pRes, n, sqlite3_free);
324 }
325 }
326 sqlite3_finalize(c.pStmt);
327 sqlite3_free(c.aResult);
328}
329
330#ifdef _WIN32
331__declspec(dllexport)
332#endif
333int sqlite3_nextchar_init(
334 sqlite3 *db,
335 char **pzErrMsg,
336 const sqlite3_api_routines *pApi
337){
338 int rc = SQLITE_OK;
339 int nArg;
340
341 /* Normally, this function should not be marked as innocuous, because
342 ** it is vulnerable to SQL injection attacks. */
343#ifdef SQLITE_NEXT_CHAR_INNOCUOUS
344 const int flags = SQLITE_UTF8|SQLITE_INNOCUOUS;
345#else
346 const int flags = SQLITE_UTF8;
347#endif
348
349 SQLITE_EXTENSION_INIT2(pApi);
350
351 (void)pzErrMsg; /* Unused parameter */
352 for(nArg=3; rc==SQLITE_OK && nArg<=5; nArg++){
353 rc = sqlite3_create_function(
354 db, "next_char", nArg, flags, 0, nextCharFunc, 0, 0);
355 }
356 return rc;
357}