callback.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. ** 2005 May 23
  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 functions used to access the internal hash tables
  14. ** of user defined functions and collation sequences.
  15. */
  16. #include "sqliteInt.h"
  17. /*
  18. ** Invoke the 'collation needed' callback to request a collation sequence
  19. ** in the encoding enc of name zName, length nName.
  20. */
  21. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  22. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  23. if( db->xCollNeeded ){
  24. char *zExternal = sqlite3DbStrDup(db, zName);
  25. if( !zExternal ) return;
  26. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  27. sqlite3DbFree(db, zExternal);
  28. }
  29. #ifndef SQLITE_OMIT_UTF16
  30. if( db->xCollNeeded16 ){
  31. char const *zExternal;
  32. sqlite3_value *pTmp = sqlite3ValueNew(db);
  33. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  34. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  35. if( zExternal ){
  36. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  37. }
  38. sqlite3ValueFree(pTmp);
  39. }
  40. #endif
  41. }
  42. /*
  43. ** This routine is called if the collation factory fails to deliver a
  44. ** collation function in the best encoding but there may be other versions
  45. ** of this collation function (for other text encodings) available. Use one
  46. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  47. ** possible.
  48. */
  49. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  50. CollSeq *pColl2;
  51. char *z = pColl->zName;
  52. int i;
  53. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  54. for(i=0; i<3; i++){
  55. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  56. if( pColl2->xCmp!=0 ){
  57. memcpy(pColl, pColl2, sizeof(CollSeq));
  58. pColl->xDel = 0; /* Do not copy the destructor */
  59. return SQLITE_OK;
  60. }
  61. }
  62. return SQLITE_ERROR;
  63. }
  64. /*
  65. ** This function is responsible for invoking the collation factory callback
  66. ** or substituting a collation sequence of a different encoding when the
  67. ** requested collation sequence is not available in the desired encoding.
  68. **
  69. ** If it is not NULL, then pColl must point to the database native encoding
  70. ** collation sequence with name zName, length nName.
  71. **
  72. ** The return value is either the collation sequence to be used in database
  73. ** db for collation type name zName, length nName, or NULL, if no collation
  74. ** sequence can be found. If no collation is found, leave an error message.
  75. **
  76. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  77. */
  78. CollSeq *sqlite3GetCollSeq(
  79. Parse *pParse, /* Parsing context */
  80. u8 enc, /* The desired encoding for the collating sequence */
  81. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  82. const char *zName /* Collating sequence name */
  83. ){
  84. CollSeq *p;
  85. sqlite3 *db = pParse->db;
  86. p = pColl;
  87. if( !p ){
  88. p = sqlite3FindCollSeq(db, enc, zName, 0);
  89. }
  90. if( !p || !p->xCmp ){
  91. /* No collation sequence of this type for this encoding is registered.
  92. ** Call the collation factory to see if it can supply us with one.
  93. */
  94. callCollNeeded(db, enc, zName);
  95. p = sqlite3FindCollSeq(db, enc, zName, 0);
  96. }
  97. if( p && !p->xCmp && synthCollSeq(db, p) ){
  98. p = 0;
  99. }
  100. assert( !p || p->xCmp );
  101. if( p==0 ){
  102. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  103. }
  104. return p;
  105. }
  106. /*
  107. ** This routine is called on a collation sequence before it is used to
  108. ** check that it is defined. An undefined collation sequence exists when
  109. ** a database is loaded that contains references to collation sequences
  110. ** that have not been defined by sqlite3_create_collation() etc.
  111. **
  112. ** If required, this routine calls the 'collation needed' callback to
  113. ** request a definition of the collating sequence. If this doesn't work,
  114. ** an equivalent collating sequence that uses a text encoding different
  115. ** from the main database is substituted, if one is available.
  116. */
  117. int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  118. if( pColl ){
  119. const char *zName = pColl->zName;
  120. sqlite3 *db = pParse->db;
  121. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  122. if( !p ){
  123. return SQLITE_ERROR;
  124. }
  125. assert( p==pColl );
  126. }
  127. return SQLITE_OK;
  128. }
  129. /*
  130. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  131. ** specified by zName and nName is not found and parameter 'create' is
  132. ** true, then create a new entry. Otherwise return NULL.
  133. **
  134. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  135. ** array of three CollSeq structures. The first is the collation sequence
  136. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  137. **
  138. ** Stored immediately after the three collation sequences is a copy of
  139. ** the collation sequence name. A pointer to this string is stored in
  140. ** each collation sequence structure.
  141. */
  142. static CollSeq *findCollSeqEntry(
  143. sqlite3 *db, /* Database connection */
  144. const char *zName, /* Name of the collating sequence */
  145. int create /* Create a new entry if true */
  146. ){
  147. CollSeq *pColl;
  148. int nName = sqlite3Strlen30(zName);
  149. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  150. if( 0==pColl && create ){
  151. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  152. if( pColl ){
  153. CollSeq *pDel = 0;
  154. pColl[0].zName = (char*)&pColl[3];
  155. pColl[0].enc = SQLITE_UTF8;
  156. pColl[1].zName = (char*)&pColl[3];
  157. pColl[1].enc = SQLITE_UTF16LE;
  158. pColl[2].zName = (char*)&pColl[3];
  159. pColl[2].enc = SQLITE_UTF16BE;
  160. memcpy(pColl[0].zName, zName, nName);
  161. pColl[0].zName[nName] = 0;
  162. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  163. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  164. ** return the pColl pointer to be deleted (because it wasn't added
  165. ** to the hash table).
  166. */
  167. assert( pDel==0 || pDel==pColl );
  168. if( pDel!=0 ){
  169. db->mallocFailed = 1;
  170. sqlite3DbFree(db, pDel);
  171. pColl = 0;
  172. }
  173. }
  174. }
  175. return pColl;
  176. }
  177. /*
  178. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  179. ** Return the CollSeq* pointer for the collation sequence named zName
  180. ** for the encoding 'enc' from the database 'db'.
  181. **
  182. ** If the entry specified is not found and 'create' is true, then create a
  183. ** new entry. Otherwise return NULL.
  184. **
  185. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  186. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  187. ** if necessary and generates an error message if the collating sequence
  188. ** cannot be found.
  189. **
  190. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  191. */
  192. CollSeq *sqlite3FindCollSeq(
  193. sqlite3 *db,
  194. u8 enc,
  195. const char *zName,
  196. int create
  197. ){
  198. CollSeq *pColl;
  199. if( zName ){
  200. pColl = findCollSeqEntry(db, zName, create);
  201. }else{
  202. pColl = db->pDfltColl;
  203. }
  204. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  205. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  206. if( pColl ) pColl += enc-1;
  207. return pColl;
  208. }
  209. /* During the search for the best function definition, this procedure
  210. ** is called to test how well the function passed as the first argument
  211. ** matches the request for a function with nArg arguments in a system
  212. ** that uses encoding enc. The value returned indicates how well the
  213. ** request is matched. A higher value indicates a better match.
  214. **
  215. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  216. ** is also -1. In other words, we are searching for a function that
  217. ** takes a variable number of arguments.
  218. **
  219. ** If nArg is -2 that means that we are searching for any function
  220. ** regardless of the number of arguments it uses, so return a positive
  221. ** match score for any
  222. **
  223. ** The returned value is always between 0 and 6, as follows:
  224. **
  225. ** 0: Not a match.
  226. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  227. ** 2: UTF16 byte order change required and function takes any number of args.
  228. ** 3: encoding matches and function takes any number of arguments
  229. ** 4: UTF8/16 conversion required - argument count matches exactly
  230. ** 5: UTF16 byte order conversion required - argument count matches exactly
  231. ** 6: Perfect match: encoding and argument count match exactly.
  232. **
  233. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  234. ** a perfect match and any function with both xStep and xFunc NULL is
  235. ** a non-match.
  236. */
  237. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  238. static int matchQuality(
  239. FuncDef *p, /* The function we are evaluating for match quality */
  240. int nArg, /* Desired number of arguments. (-1)==any */
  241. u8 enc /* Desired text encoding */
  242. ){
  243. int match;
  244. /* nArg of -2 is a special case */
  245. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  246. /* Wrong number of arguments means "no match" */
  247. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  248. /* Give a better score to a function with a specific number of arguments
  249. ** than to function that accepts any number of arguments. */
  250. if( p->nArg==nArg ){
  251. match = 4;
  252. }else{
  253. match = 1;
  254. }
  255. /* Bonus points if the text encoding matches */
  256. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  257. match += 2; /* Exact encoding match */
  258. }else if( (enc & p->funcFlags & 2)!=0 ){
  259. match += 1; /* Both are UTF16, but with different byte orders */
  260. }
  261. return match;
  262. }
  263. /*
  264. ** Search a FuncDefHash for a function with the given name. Return
  265. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  266. */
  267. static FuncDef *functionSearch(
  268. FuncDefHash *pHash, /* Hash table to search */
  269. int h, /* Hash of the name */
  270. const char *zFunc, /* Name of function */
  271. int nFunc /* Number of bytes in zFunc */
  272. ){
  273. FuncDef *p;
  274. for(p=pHash->a[h]; p; p=p->pHash){
  275. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  276. return p;
  277. }
  278. }
  279. return 0;
  280. }
  281. /*
  282. ** Insert a new FuncDef into a FuncDefHash hash table.
  283. */
  284. void sqlite3FuncDefInsert(
  285. FuncDefHash *pHash, /* The hash table into which to insert */
  286. FuncDef *pDef /* The function definition to insert */
  287. ){
  288. FuncDef *pOther;
  289. int nName = sqlite3Strlen30(pDef->zName);
  290. u8 c1 = (u8)pDef->zName[0];
  291. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  292. pOther = functionSearch(pHash, h, pDef->zName, nName);
  293. if( pOther ){
  294. assert( pOther!=pDef && pOther->pNext!=pDef );
  295. pDef->pNext = pOther->pNext;
  296. pOther->pNext = pDef;
  297. }else{
  298. pDef->pNext = 0;
  299. pDef->pHash = pHash->a[h];
  300. pHash->a[h] = pDef;
  301. }
  302. }
  303. /*
  304. ** Locate a user function given a name, a number of arguments and a flag
  305. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  306. ** pointer to the FuncDef structure that defines that function, or return
  307. ** NULL if the function does not exist.
  308. **
  309. ** If the createFlag argument is true, then a new (blank) FuncDef
  310. ** structure is created and liked into the "db" structure if a
  311. ** no matching function previously existed.
  312. **
  313. ** If nArg is -2, then the first valid function found is returned. A
  314. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  315. ** case is used to see if zName is a valid function name for some number
  316. ** of arguments. If nArg is -2, then createFlag must be 0.
  317. **
  318. ** If createFlag is false, then a function with the required name and
  319. ** number of arguments may be returned even if the eTextRep flag does not
  320. ** match that requested.
  321. */
  322. FuncDef *sqlite3FindFunction(
  323. sqlite3 *db, /* An open database */
  324. const char *zName, /* Name of the function. Not null-terminated */
  325. int nName, /* Number of characters in the name */
  326. int nArg, /* Number of arguments. -1 means any number */
  327. u8 enc, /* Preferred text encoding */
  328. u8 createFlag /* Create new entry if true and does not otherwise exist */
  329. ){
  330. FuncDef *p; /* Iterator variable */
  331. FuncDef *pBest = 0; /* Best match found so far */
  332. int bestScore = 0; /* Score of best match */
  333. int h; /* Hash value */
  334. assert( nArg>=(-2) );
  335. assert( nArg>=(-1) || createFlag==0 );
  336. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  337. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  338. /* First search for a match amongst the application-defined functions.
  339. */
  340. p = functionSearch(&db->aFunc, h, zName, nName);
  341. while( p ){
  342. int score = matchQuality(p, nArg, enc);
  343. if( score>bestScore ){
  344. pBest = p;
  345. bestScore = score;
  346. }
  347. p = p->pNext;
  348. }
  349. /* If no match is found, search the built-in functions.
  350. **
  351. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  352. ** functions even if a prior app-defined function was found. And give
  353. ** priority to built-in functions.
  354. **
  355. ** Except, if createFlag is true, that means that we are trying to
  356. ** install a new function. Whatever FuncDef structure is returned it will
  357. ** have fields overwritten with new information appropriate for the
  358. ** new function. But the FuncDefs for built-in functions are read-only.
  359. ** So we must not search for built-ins when creating a new function.
  360. */
  361. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  362. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  363. bestScore = 0;
  364. p = functionSearch(pHash, h, zName, nName);
  365. while( p ){
  366. int score = matchQuality(p, nArg, enc);
  367. if( score>bestScore ){
  368. pBest = p;
  369. bestScore = score;
  370. }
  371. p = p->pNext;
  372. }
  373. }
  374. /* If the createFlag parameter is true and the search did not reveal an
  375. ** exact match for the name, number of arguments and encoding, then add a
  376. ** new entry to the hash table and return it.
  377. */
  378. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  379. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  380. pBest->zName = (char *)&pBest[1];
  381. pBest->nArg = (u16)nArg;
  382. pBest->funcFlags = enc;
  383. memcpy(pBest->zName, zName, nName);
  384. pBest->zName[nName] = 0;
  385. sqlite3FuncDefInsert(&db->aFunc, pBest);
  386. }
  387. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  388. return pBest;
  389. }
  390. return 0;
  391. }
  392. /*
  393. ** Free all resources held by the schema structure. The void* argument points
  394. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  395. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  396. ** of the schema hash tables).
  397. **
  398. ** The Schema.cache_size variable is not cleared.
  399. */
  400. void sqlite3SchemaClear(void *p){
  401. Hash temp1;
  402. Hash temp2;
  403. HashElem *pElem;
  404. Schema *pSchema = (Schema *)p;
  405. temp1 = pSchema->tblHash;
  406. temp2 = pSchema->trigHash;
  407. sqlite3HashInit(&pSchema->trigHash);
  408. sqlite3HashClear(&pSchema->idxHash);
  409. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  410. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  411. }
  412. sqlite3HashClear(&temp2);
  413. sqlite3HashInit(&pSchema->tblHash);
  414. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  415. Table *pTab = sqliteHashData(pElem);
  416. sqlite3DeleteTable(0, pTab);
  417. }
  418. sqlite3HashClear(&temp1);
  419. sqlite3HashClear(&pSchema->fkeyHash);
  420. pSchema->pSeqTab = 0;
  421. if( pSchema->flags & DB_SchemaLoaded ){
  422. pSchema->iGeneration++;
  423. pSchema->flags &= ~DB_SchemaLoaded;
  424. }
  425. }
  426. /*
  427. ** Find and return the schema associated with a BTree. Create
  428. ** a new one if necessary.
  429. */
  430. Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  431. Schema * p;
  432. if( pBt ){
  433. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  434. }else{
  435. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  436. }
  437. if( !p ){
  438. db->mallocFailed = 1;
  439. }else if ( 0==p->file_format ){
  440. sqlite3HashInit(&p->tblHash);
  441. sqlite3HashInit(&p->idxHash);
  442. sqlite3HashInit(&p->trigHash);
  443. sqlite3HashInit(&p->fkeyHash);
  444. p->enc = SQLITE_UTF8;
  445. }
  446. return p;
  447. }