callback.c

Go to the documentation of this file.
00001 /*
00002 ** 2005 May 23 
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 **
00013 ** This file contains functions used to access the internal hash tables
00014 ** of user defined functions and collation sequences.
00015 **
00016 ** $Id: callback.c,v 1.32 2008/10/10 17:41:29 drh Exp $
00017 */
00018 
00019 #include "sqliteInt.h"
00020 
00021 /*
00022 ** Invoke the 'collation needed' callback to request a collation sequence
00023 ** in the database text encoding of name zName, length nName.
00024 ** If the collation sequence
00025 */
00026 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
00027   assert( !db->xCollNeeded || !db->xCollNeeded16 );
00028   if( nName<0 ) nName = sqlite3Strlen(db, zName);
00029   if( db->xCollNeeded ){
00030     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
00031     if( !zExternal ) return;
00032     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
00033     sqlite3DbFree(db, zExternal);
00034   }
00035 #ifndef SQLITE_OMIT_UTF16
00036   if( db->xCollNeeded16 ){
00037     char const *zExternal;
00038     sqlite3_value *pTmp = sqlite3ValueNew(db);
00039     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
00040     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
00041     if( zExternal ){
00042       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
00043     }
00044     sqlite3ValueFree(pTmp);
00045   }
00046 #endif
00047 }
00048 
00049 /*
00050 ** This routine is called if the collation factory fails to deliver a
00051 ** collation function in the best encoding but there may be other versions
00052 ** of this collation function (for other text encodings) available. Use one
00053 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
00054 ** possible.
00055 */
00056 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
00057   CollSeq *pColl2;
00058   char *z = pColl->zName;
00059   int n = strlen(z);
00060   int i;
00061   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
00062   for(i=0; i<3; i++){
00063     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
00064     if( pColl2->xCmp!=0 ){
00065       memcpy(pColl, pColl2, sizeof(CollSeq));
00066       pColl->xDel = 0;         /* Do not copy the destructor */
00067       return SQLITE_OK;
00068     }
00069   }
00070   return SQLITE_ERROR;
00071 }
00072 
00073 /*
00074 ** This function is responsible for invoking the collation factory callback
00075 ** or substituting a collation sequence of a different encoding when the
00076 ** requested collation sequence is not available in the database native
00077 ** encoding.
00078 ** 
00079 ** If it is not NULL, then pColl must point to the database native encoding 
00080 ** collation sequence with name zName, length nName.
00081 **
00082 ** The return value is either the collation sequence to be used in database
00083 ** db for collation type name zName, length nName, or NULL, if no collation
00084 ** sequence can be found.
00085 */
00086 CollSeq *sqlite3GetCollSeq(
00087   sqlite3* db, 
00088   CollSeq *pColl, 
00089   const char *zName, 
00090   int nName
00091 ){
00092   CollSeq *p;
00093 
00094   p = pColl;
00095   if( !p ){
00096     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
00097   }
00098   if( !p || !p->xCmp ){
00099     /* No collation sequence of this type for this encoding is registered.
00100     ** Call the collation factory to see if it can supply us with one.
00101     */
00102     callCollNeeded(db, zName, nName);
00103     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
00104   }
00105   if( p && !p->xCmp && synthCollSeq(db, p) ){
00106     p = 0;
00107   }
00108   assert( !p || p->xCmp );
00109   return p;
00110 }
00111 
00112 /*
00113 ** This routine is called on a collation sequence before it is used to
00114 ** check that it is defined. An undefined collation sequence exists when
00115 ** a database is loaded that contains references to collation sequences
00116 ** that have not been defined by sqlite3_create_collation() etc.
00117 **
00118 ** If required, this routine calls the 'collation needed' callback to
00119 ** request a definition of the collating sequence. If this doesn't work, 
00120 ** an equivalent collating sequence that uses a text encoding different
00121 ** from the main database is substituted, if one is available.
00122 */
00123 int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
00124   if( pColl ){
00125     const char *zName = pColl->zName;
00126     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
00127     if( !p ){
00128       if( pParse->nErr==0 ){
00129         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
00130       }
00131       pParse->nErr++;
00132       return SQLITE_ERROR;
00133     }
00134     assert( p==pColl );
00135   }
00136   return SQLITE_OK;
00137 }
00138 
00139 
00140 
00141 /*
00142 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
00143 ** specified by zName and nName is not found and parameter 'create' is
00144 ** true, then create a new entry. Otherwise return NULL.
00145 **
00146 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
00147 ** array of three CollSeq structures. The first is the collation sequence
00148 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
00149 **
00150 ** Stored immediately after the three collation sequences is a copy of
00151 ** the collation sequence name. A pointer to this string is stored in
00152 ** each collation sequence structure.
00153 */
00154 static CollSeq *findCollSeqEntry(
00155   sqlite3 *db,
00156   const char *zName,
00157   int nName,
00158   int create
00159 ){
00160   CollSeq *pColl;
00161   if( nName<0 ) nName = sqlite3Strlen(db, zName);
00162   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
00163 
00164   if( 0==pColl && create ){
00165     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
00166     if( pColl ){
00167       CollSeq *pDel = 0;
00168       pColl[0].zName = (char*)&pColl[3];
00169       pColl[0].enc = SQLITE_UTF8;
00170       pColl[1].zName = (char*)&pColl[3];
00171       pColl[1].enc = SQLITE_UTF16LE;
00172       pColl[2].zName = (char*)&pColl[3];
00173       pColl[2].enc = SQLITE_UTF16BE;
00174       memcpy(pColl[0].zName, zName, nName);
00175       pColl[0].zName[nName] = 0;
00176       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
00177 
00178       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
00179       ** return the pColl pointer to be deleted (because it wasn't added
00180       ** to the hash table).
00181       */
00182       assert( pDel==0 || pDel==pColl );
00183       if( pDel!=0 ){
00184         db->mallocFailed = 1;
00185         sqlite3DbFree(db, pDel);
00186         pColl = 0;
00187       }
00188     }
00189   }
00190   return pColl;
00191 }
00192 
00193 /*
00194 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
00195 ** Return the CollSeq* pointer for the collation sequence named zName
00196 ** for the encoding 'enc' from the database 'db'.
00197 **
00198 ** If the entry specified is not found and 'create' is true, then create a
00199 ** new entry.  Otherwise return NULL.
00200 **
00201 ** A separate function sqlite3LocateCollSeq() is a wrapper around
00202 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
00203 ** if necessary and generates an error message if the collating sequence
00204 ** cannot be found.
00205 */
00206 CollSeq *sqlite3FindCollSeq(
00207   sqlite3 *db,
00208   u8 enc,
00209   const char *zName,
00210   int nName,
00211   int create
00212 ){
00213   CollSeq *pColl;
00214   if( zName ){
00215     pColl = findCollSeqEntry(db, zName, nName, create);
00216   }else{
00217     pColl = db->pDfltColl;
00218   }
00219   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
00220   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
00221   if( pColl ) pColl += enc-1;
00222   return pColl;
00223 }
00224 
00225 /* During the search for the best function definition, this procedure
00226 ** is called to test how well the function passed as the first argument
00227 ** matches the request for a function with nArg arguments in a system
00228 ** that uses encoding enc. The value returned indicates how well the
00229 ** request is matched. A higher value indicates a better match.
00230 **
00231 ** The returned value is always between 1 and 6, as follows:
00232 **
00233 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
00234 **    encoding is requested, or vice versa.
00235 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
00236 **    requested, or vice versa.
00237 ** 3: A variable arguments function using the same text encoding.
00238 ** 4: A function with the exact number of arguments requested that
00239 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
00240 ** 5: A function with the exact number of arguments requested that
00241 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
00242 ** 6: An exact match.
00243 **
00244 */
00245 static int matchQuality(FuncDef *p, int nArg, u8 enc){
00246   int match = 0;
00247   if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
00248     match = 1;
00249     if( p->nArg==nArg || nArg==-1 ){
00250       match = 4;
00251     }
00252     if( enc==p->iPrefEnc ){
00253       match += 2;
00254     }
00255     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
00256              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
00257       match += 1;
00258     }
00259   }
00260   return match;
00261 }
00262 
00263 /*
00264 ** Search a FuncDefHash for a function with the given name.  Return
00265 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
00266 */
00267 static FuncDef *functionSearch(
00268   FuncDefHash *pHash,  /* Hash table to search */
00269   int h,               /* Hash of the name */
00270   const char *zFunc,   /* Name of function */
00271   int nFunc            /* Number of bytes in zFunc */
00272 ){
00273   FuncDef *p;
00274   for(p=pHash->a[h]; p; p=p->pHash){
00275     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
00276       return p;
00277     }
00278   }
00279   return 0;
00280 }
00281 
00282 /*
00283 ** Insert a new FuncDef into a FuncDefHash hash table.
00284 */
00285 void sqlite3FuncDefInsert(
00286   FuncDefHash *pHash,  /* The hash table into which to insert */
00287   FuncDef *pDef        /* The function definition to insert */
00288 ){
00289   FuncDef *pOther;
00290   int nName = strlen(pDef->zName);
00291   u8 c1 = (u8)pDef->zName[0];
00292   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
00293   pOther = functionSearch(pHash, h, pDef->zName, nName);
00294   if( pOther ){
00295     pDef->pNext = pOther->pNext;
00296     pOther->pNext = pDef;
00297   }else{
00298     pDef->pNext = 0;
00299     pDef->pHash = pHash->a[h];
00300     pHash->a[h] = pDef;
00301   }
00302 }
00303   
00304   
00305 
00306 /*
00307 ** Locate a user function given a name, a number of arguments and a flag
00308 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
00309 ** pointer to the FuncDef structure that defines that function, or return
00310 ** NULL if the function does not exist.
00311 **
00312 ** If the createFlag argument is true, then a new (blank) FuncDef
00313 ** structure is created and liked into the "db" structure if a
00314 ** no matching function previously existed.  When createFlag is true
00315 ** and the nArg parameter is -1, then only a function that accepts
00316 ** any number of arguments will be returned.
00317 **
00318 ** If createFlag is false and nArg is -1, then the first valid
00319 ** function found is returned.  A function is valid if either xFunc
00320 ** or xStep is non-zero.
00321 **
00322 ** If createFlag is false, then a function with the required name and
00323 ** number of arguments may be returned even if the eTextRep flag does not
00324 ** match that requested.
00325 */
00326 FuncDef *sqlite3FindFunction(
00327   sqlite3 *db,       /* An open database */
00328   const char *zName, /* Name of the function.  Not null-terminated */
00329   int nName,         /* Number of characters in the name */
00330   int nArg,          /* Number of arguments.  -1 means any number */
00331   u8 enc,            /* Preferred text encoding */
00332   int createFlag     /* Create new entry if true and does not otherwise exist */
00333 ){
00334   FuncDef *p;         /* Iterator variable */
00335   FuncDef *pBest = 0; /* Best match found so far */
00336   int bestScore = 0;  /* Score of best match */
00337   int h;              /* Hash value */
00338 
00339 
00340   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
00341   if( nArg<-1 ) nArg = -1;
00342   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
00343 
00344   /* First search for a match amongst the application-defined functions.
00345   */
00346   p = functionSearch(&db->aFunc, h, zName, nName);
00347   while( p ){
00348     int score = matchQuality(p, nArg, enc);
00349     if( score>bestScore ){
00350       pBest = p;
00351       bestScore = score;
00352     }
00353     p = p->pNext;
00354   }
00355 
00356   /* If no match is found, search the built-in functions.
00357   **
00358   ** Except, if createFlag is true, that means that we are trying to
00359   ** install a new function.  Whatever FuncDef structure is returned will
00360   ** have fields overwritten with new information appropriate for the
00361   ** new function.  But the FuncDefs for built-in functions are read-only.
00362   ** So we must not search for built-ins when creating a new function.
00363   */ 
00364   if( !createFlag && !pBest ){
00365     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
00366     p = functionSearch(pHash, h, zName, nName);
00367     while( p ){
00368       int score = matchQuality(p, nArg, enc);
00369       if( score>bestScore ){
00370         pBest = p;
00371         bestScore = score;
00372       }
00373       p = p->pNext;
00374     }
00375   }
00376 
00377   /* If the createFlag parameter is true and the search did not reveal an
00378   ** exact match for the name, number of arguments and encoding, then add a
00379   ** new entry to the hash table and return it.
00380   */
00381   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
00382       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
00383     pBest->zName = (char *)&pBest[1];
00384     pBest->nArg = nArg;
00385     pBest->iPrefEnc = enc;
00386     memcpy(pBest->zName, zName, nName);
00387     pBest->zName[nName] = 0;
00388     sqlite3FuncDefInsert(&db->aFunc, pBest);
00389   }
00390 
00391   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
00392     return pBest;
00393   }
00394   return 0;
00395 }
00396 
00397 /*
00398 ** Free all resources held by the schema structure. The void* argument points
00399 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
00400 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
00401 ** of the schema hash tables).
00402 **
00403 ** The Schema.cache_size variable is not cleared.
00404 */
00405 void sqlite3SchemaFree(void *p){
00406   Hash temp1;
00407   Hash temp2;
00408   HashElem *pElem;
00409   Schema *pSchema = (Schema *)p;
00410 
00411   temp1 = pSchema->tblHash;
00412   temp2 = pSchema->trigHash;
00413   sqlite3HashInit(&pSchema->trigHash, 0);
00414   sqlite3HashClear(&pSchema->aFKey);
00415   sqlite3HashClear(&pSchema->idxHash);
00416   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
00417     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
00418   }
00419   sqlite3HashClear(&temp2);
00420   sqlite3HashInit(&pSchema->tblHash, 0);
00421   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
00422     Table *pTab = sqliteHashData(pElem);
00423     sqlite3DeleteTable(pTab);
00424   }
00425   sqlite3HashClear(&temp1);
00426   pSchema->pSeqTab = 0;
00427   pSchema->flags &= ~DB_SchemaLoaded;
00428 }
00429 
00430 /*
00431 ** Find and return the schema associated with a BTree.  Create
00432 ** a new one if necessary.
00433 */
00434 Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
00435   Schema * p;
00436   if( pBt ){
00437     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
00438   }else{
00439     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
00440   }
00441   if( !p ){
00442     db->mallocFailed = 1;
00443   }else if ( 0==p->file_format ){
00444     sqlite3HashInit(&p->tblHash, 0);
00445     sqlite3HashInit(&p->idxHash, 0);
00446     sqlite3HashInit(&p->trigHash, 0);
00447     sqlite3HashInit(&p->aFKey, 1);
00448     p->enc = SQLITE_UTF8;
00449   }
00450   return p;
00451 }

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:52 2011 by Doxygen 1.6.1