sqlite3expert.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235
  1. /*
  2. ** 2017 April 09
  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. #include "sqlite3expert.h"
  14. #include <assert.h>
  15. #include <string.h>
  16. #include <stdio.h>
  17. #if !defined(SQLITE_AMALGAMATION)
  18. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  19. # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
  20. #endif
  21. #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
  22. # define ALWAYS(X) (1)
  23. # define NEVER(X) (0)
  24. #elif !defined(NDEBUG)
  25. # define ALWAYS(X) ((X)?1:(assert(0),0))
  26. # define NEVER(X) ((X)?(assert(0),1):0)
  27. #else
  28. # define ALWAYS(X) (X)
  29. # define NEVER(X) (X)
  30. #endif
  31. #endif /* !defined(SQLITE_AMALGAMATION) */
  32. #ifndef SQLITE_OMIT_VIRTUALTABLE
  33. typedef sqlite3_int64 i64;
  34. typedef sqlite3_uint64 u64;
  35. typedef struct IdxColumn IdxColumn;
  36. typedef struct IdxConstraint IdxConstraint;
  37. typedef struct IdxScan IdxScan;
  38. typedef struct IdxStatement IdxStatement;
  39. typedef struct IdxTable IdxTable;
  40. typedef struct IdxWrite IdxWrite;
  41. #define STRLEN (int)strlen
  42. /*
  43. ** A temp table name that we assume no user database will actually use.
  44. ** If this assumption proves incorrect triggers on the table with the
  45. ** conflicting name will be ignored.
  46. */
  47. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  48. /*
  49. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  50. ** any other type of single-ended range constraint on a column).
  51. **
  52. ** pLink:
  53. ** Used to temporarily link IdxConstraint objects into lists while
  54. ** creating candidate indexes.
  55. */
  56. struct IdxConstraint {
  57. char *zColl; /* Collation sequence */
  58. int bRange; /* True for range, false for eq */
  59. int iCol; /* Constrained table column */
  60. int bFlag; /* Used by idxFindCompatible() */
  61. int bDesc; /* True if ORDER BY <expr> DESC */
  62. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  63. IdxConstraint *pLink; /* See above */
  64. };
  65. /*
  66. ** A single scan of a single table.
  67. */
  68. struct IdxScan {
  69. IdxTable *pTab; /* Associated table object */
  70. int iDb; /* Database containing table zTable */
  71. i64 covering; /* Mask of columns required for cov. index */
  72. IdxConstraint *pOrder; /* ORDER BY columns */
  73. IdxConstraint *pEq; /* List of == constraints */
  74. IdxConstraint *pRange; /* List of < constraints */
  75. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  76. };
  77. /*
  78. ** Information regarding a single database table. Extracted from
  79. ** "PRAGMA table_info" by function idxGetTableInfo().
  80. */
  81. struct IdxColumn {
  82. char *zName;
  83. char *zColl;
  84. int iPk;
  85. };
  86. struct IdxTable {
  87. int nCol;
  88. char *zName; /* Table name */
  89. IdxColumn *aCol;
  90. IdxTable *pNext; /* Next table in linked list of all tables */
  91. };
  92. /*
  93. ** An object of the following type is created for each unique table/write-op
  94. ** seen. The objects are stored in a singly-linked list beginning at
  95. ** sqlite3expert.pWrite.
  96. */
  97. struct IdxWrite {
  98. IdxTable *pTab;
  99. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  100. IdxWrite *pNext;
  101. };
  102. /*
  103. ** Each statement being analyzed is represented by an instance of this
  104. ** structure.
  105. */
  106. struct IdxStatement {
  107. int iId; /* Statement number */
  108. char *zSql; /* SQL statement */
  109. char *zIdx; /* Indexes */
  110. char *zEQP; /* Plan */
  111. IdxStatement *pNext;
  112. };
  113. /*
  114. ** A hash table for storing strings. With space for a payload string
  115. ** with each entry. Methods are:
  116. **
  117. ** idxHashInit()
  118. ** idxHashClear()
  119. ** idxHashAdd()
  120. ** idxHashSearch()
  121. */
  122. #define IDX_HASH_SIZE 1023
  123. typedef struct IdxHashEntry IdxHashEntry;
  124. typedef struct IdxHash IdxHash;
  125. struct IdxHashEntry {
  126. char *zKey; /* nul-terminated key */
  127. char *zVal; /* nul-terminated value string */
  128. char *zVal2; /* nul-terminated value string 2 */
  129. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  130. IdxHashEntry *pNext; /* Next entry in hash */
  131. };
  132. struct IdxHash {
  133. IdxHashEntry *pFirst;
  134. IdxHashEntry *aHash[IDX_HASH_SIZE];
  135. };
  136. /*
  137. ** sqlite3expert object.
  138. */
  139. struct sqlite3expert {
  140. int iSample; /* Percentage of tables to sample for stat1 */
  141. sqlite3 *db; /* User database */
  142. sqlite3 *dbm; /* In-memory db for this analysis */
  143. sqlite3 *dbv; /* Vtab schema for this analysis */
  144. IdxTable *pTable; /* List of all IdxTable objects */
  145. IdxScan *pScan; /* List of scan objects */
  146. IdxWrite *pWrite; /* List of write objects */
  147. IdxStatement *pStatement; /* List of IdxStatement objects */
  148. int bRun; /* True once analysis has run */
  149. char **pzErrmsg;
  150. int rc; /* Error code from whereinfo hook */
  151. IdxHash hIdx; /* Hash containing all candidate indexes */
  152. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  153. };
  154. /*
  155. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  156. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  157. */
  158. static void *idxMalloc(int *pRc, int nByte){
  159. void *pRet;
  160. assert( *pRc==SQLITE_OK );
  161. assert( nByte>0 );
  162. pRet = sqlite3_malloc(nByte);
  163. if( pRet ){
  164. memset(pRet, 0, nByte);
  165. }else{
  166. *pRc = SQLITE_NOMEM;
  167. }
  168. return pRet;
  169. }
  170. /*
  171. ** Initialize an IdxHash hash table.
  172. */
  173. static void idxHashInit(IdxHash *pHash){
  174. memset(pHash, 0, sizeof(IdxHash));
  175. }
  176. /*
  177. ** Reset an IdxHash hash table.
  178. */
  179. static void idxHashClear(IdxHash *pHash){
  180. int i;
  181. for(i=0; i<IDX_HASH_SIZE; i++){
  182. IdxHashEntry *pEntry;
  183. IdxHashEntry *pNext;
  184. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  185. pNext = pEntry->pHashNext;
  186. sqlite3_free(pEntry->zVal2);
  187. sqlite3_free(pEntry);
  188. }
  189. }
  190. memset(pHash, 0, sizeof(IdxHash));
  191. }
  192. /*
  193. ** Return the index of the hash bucket that the string specified by the
  194. ** arguments to this function belongs.
  195. */
  196. static int idxHashString(const char *z, int n){
  197. unsigned int ret = 0;
  198. int i;
  199. for(i=0; i<n; i++){
  200. ret += (ret<<3) + (unsigned char)(z[i]);
  201. }
  202. return (int)(ret % IDX_HASH_SIZE);
  203. }
  204. /*
  205. ** If zKey is already present in the hash table, return non-zero and do
  206. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  207. ** the hash table passed as the second argument.
  208. */
  209. static int idxHashAdd(
  210. int *pRc,
  211. IdxHash *pHash,
  212. const char *zKey,
  213. const char *zVal
  214. ){
  215. int nKey = STRLEN(zKey);
  216. int iHash = idxHashString(zKey, nKey);
  217. int nVal = (zVal ? STRLEN(zVal) : 0);
  218. IdxHashEntry *pEntry;
  219. assert( iHash>=0 );
  220. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  221. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  222. return 1;
  223. }
  224. }
  225. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  226. if( pEntry ){
  227. pEntry->zKey = (char*)&pEntry[1];
  228. memcpy(pEntry->zKey, zKey, nKey);
  229. if( zVal ){
  230. pEntry->zVal = &pEntry->zKey[nKey+1];
  231. memcpy(pEntry->zVal, zVal, nVal);
  232. }
  233. pEntry->pHashNext = pHash->aHash[iHash];
  234. pHash->aHash[iHash] = pEntry;
  235. pEntry->pNext = pHash->pFirst;
  236. pHash->pFirst = pEntry;
  237. }
  238. return 0;
  239. }
  240. /*
  241. ** If zKey/nKey is present in the hash table, return a pointer to the
  242. ** hash-entry object.
  243. */
  244. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  245. int iHash;
  246. IdxHashEntry *pEntry;
  247. if( nKey<0 ) nKey = STRLEN(zKey);
  248. iHash = idxHashString(zKey, nKey);
  249. assert( iHash>=0 );
  250. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  251. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  252. return pEntry;
  253. }
  254. }
  255. return 0;
  256. }
  257. /*
  258. ** If the hash table contains an entry with a key equal to the string
  259. ** passed as the final two arguments to this function, return a pointer
  260. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  261. ** hash table, return NULL.
  262. */
  263. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  264. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  265. if( pEntry ) return pEntry->zVal;
  266. return 0;
  267. }
  268. /*
  269. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  270. ** variable to point to a copy of nul-terminated string zColl.
  271. */
  272. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  273. IdxConstraint *pNew;
  274. int nColl = STRLEN(zColl);
  275. assert( *pRc==SQLITE_OK );
  276. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  277. if( pNew ){
  278. pNew->zColl = (char*)&pNew[1];
  279. memcpy(pNew->zColl, zColl, nColl+1);
  280. }
  281. return pNew;
  282. }
  283. /*
  284. ** An error associated with database handle db has just occurred. Pass
  285. ** the error message to callback function xOut.
  286. */
  287. static void idxDatabaseError(
  288. sqlite3 *db, /* Database handle */
  289. char **pzErrmsg /* Write error here */
  290. ){
  291. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  292. }
  293. /*
  294. ** Prepare an SQL statement.
  295. */
  296. static int idxPrepareStmt(
  297. sqlite3 *db, /* Database handle to compile against */
  298. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  299. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  300. const char *zSql /* SQL statement to compile */
  301. ){
  302. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  303. if( rc!=SQLITE_OK ){
  304. *ppStmt = 0;
  305. idxDatabaseError(db, pzErrmsg);
  306. }
  307. return rc;
  308. }
  309. /*
  310. ** Prepare an SQL statement using the results of a printf() formatting.
  311. */
  312. static int idxPrintfPrepareStmt(
  313. sqlite3 *db, /* Database handle to compile against */
  314. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  315. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  316. const char *zFmt, /* printf() format of SQL statement */
  317. ... /* Trailing printf() arguments */
  318. ){
  319. va_list ap;
  320. int rc;
  321. char *zSql;
  322. va_start(ap, zFmt);
  323. zSql = sqlite3_vmprintf(zFmt, ap);
  324. if( zSql==0 ){
  325. rc = SQLITE_NOMEM;
  326. }else{
  327. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  328. sqlite3_free(zSql);
  329. }
  330. va_end(ap);
  331. return rc;
  332. }
  333. /*************************************************************************
  334. ** Beginning of virtual table implementation.
  335. */
  336. typedef struct ExpertVtab ExpertVtab;
  337. struct ExpertVtab {
  338. sqlite3_vtab base;
  339. IdxTable *pTab;
  340. sqlite3expert *pExpert;
  341. };
  342. typedef struct ExpertCsr ExpertCsr;
  343. struct ExpertCsr {
  344. sqlite3_vtab_cursor base;
  345. sqlite3_stmt *pData;
  346. };
  347. static char *expertDequote(const char *zIn){
  348. int n = STRLEN(zIn);
  349. char *zRet = sqlite3_malloc(n);
  350. assert( zIn[0]=='\'' );
  351. assert( zIn[n-1]=='\'' );
  352. if( zRet ){
  353. int iOut = 0;
  354. int iIn = 0;
  355. for(iIn=1; iIn<(n-1); iIn++){
  356. if( zIn[iIn]=='\'' ){
  357. assert( zIn[iIn+1]=='\'' );
  358. iIn++;
  359. }
  360. zRet[iOut++] = zIn[iIn];
  361. }
  362. zRet[iOut] = '\0';
  363. }
  364. return zRet;
  365. }
  366. /*
  367. ** This function is the implementation of both the xConnect and xCreate
  368. ** methods of the r-tree virtual table.
  369. **
  370. ** argv[0] -> module name
  371. ** argv[1] -> database name
  372. ** argv[2] -> table name
  373. ** argv[...] -> column names...
  374. */
  375. static int expertConnect(
  376. sqlite3 *db,
  377. void *pAux,
  378. int argc, const char *const*argv,
  379. sqlite3_vtab **ppVtab,
  380. char **pzErr
  381. ){
  382. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  383. ExpertVtab *p = 0;
  384. int rc;
  385. if( argc!=4 ){
  386. *pzErr = sqlite3_mprintf("internal error!");
  387. rc = SQLITE_ERROR;
  388. }else{
  389. char *zCreateTable = expertDequote(argv[3]);
  390. if( zCreateTable ){
  391. rc = sqlite3_declare_vtab(db, zCreateTable);
  392. if( rc==SQLITE_OK ){
  393. p = idxMalloc(&rc, sizeof(ExpertVtab));
  394. }
  395. if( rc==SQLITE_OK ){
  396. p->pExpert = pExpert;
  397. p->pTab = pExpert->pTable;
  398. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  399. }
  400. sqlite3_free(zCreateTable);
  401. }else{
  402. rc = SQLITE_NOMEM;
  403. }
  404. }
  405. *ppVtab = (sqlite3_vtab*)p;
  406. return rc;
  407. }
  408. static int expertDisconnect(sqlite3_vtab *pVtab){
  409. ExpertVtab *p = (ExpertVtab*)pVtab;
  410. sqlite3_free(p);
  411. return SQLITE_OK;
  412. }
  413. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  414. ExpertVtab *p = (ExpertVtab*)pVtab;
  415. int rc = SQLITE_OK;
  416. int n = 0;
  417. IdxScan *pScan;
  418. const int opmask =
  419. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  420. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  421. SQLITE_INDEX_CONSTRAINT_LE;
  422. pScan = idxMalloc(&rc, sizeof(IdxScan));
  423. if( pScan ){
  424. int i;
  425. /* Link the new scan object into the list */
  426. pScan->pTab = p->pTab;
  427. pScan->pNextScan = p->pExpert->pScan;
  428. p->pExpert->pScan = pScan;
  429. /* Add the constraints to the IdxScan object */
  430. for(i=0; i<pIdxInfo->nConstraint; i++){
  431. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  432. if( pCons->usable
  433. && pCons->iColumn>=0
  434. && p->pTab->aCol[pCons->iColumn].iPk==0
  435. && (pCons->op & opmask)
  436. ){
  437. IdxConstraint *pNew;
  438. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  439. pNew = idxNewConstraint(&rc, zColl);
  440. if( pNew ){
  441. pNew->iCol = pCons->iColumn;
  442. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  443. pNew->pNext = pScan->pEq;
  444. pScan->pEq = pNew;
  445. }else{
  446. pNew->bRange = 1;
  447. pNew->pNext = pScan->pRange;
  448. pScan->pRange = pNew;
  449. }
  450. }
  451. n++;
  452. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  453. }
  454. }
  455. /* Add the ORDER BY to the IdxScan object */
  456. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  457. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  458. if( iCol>=0 ){
  459. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  460. if( pNew ){
  461. pNew->iCol = iCol;
  462. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  463. pNew->pNext = pScan->pOrder;
  464. pNew->pLink = pScan->pOrder;
  465. pScan->pOrder = pNew;
  466. n++;
  467. }
  468. }
  469. }
  470. }
  471. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  472. return rc;
  473. }
  474. static int expertUpdate(
  475. sqlite3_vtab *pVtab,
  476. int nData,
  477. sqlite3_value **azData,
  478. sqlite_int64 *pRowid
  479. ){
  480. (void)pVtab;
  481. (void)nData;
  482. (void)azData;
  483. (void)pRowid;
  484. return SQLITE_OK;
  485. }
  486. /*
  487. ** Virtual table module xOpen method.
  488. */
  489. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  490. int rc = SQLITE_OK;
  491. ExpertCsr *pCsr;
  492. (void)pVTab;
  493. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  494. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  495. return rc;
  496. }
  497. /*
  498. ** Virtual table module xClose method.
  499. */
  500. static int expertClose(sqlite3_vtab_cursor *cur){
  501. ExpertCsr *pCsr = (ExpertCsr*)cur;
  502. sqlite3_finalize(pCsr->pData);
  503. sqlite3_free(pCsr);
  504. return SQLITE_OK;
  505. }
  506. /*
  507. ** Virtual table module xEof method.
  508. **
  509. ** Return non-zero if the cursor does not currently point to a valid
  510. ** record (i.e if the scan has finished), or zero otherwise.
  511. */
  512. static int expertEof(sqlite3_vtab_cursor *cur){
  513. ExpertCsr *pCsr = (ExpertCsr*)cur;
  514. return pCsr->pData==0;
  515. }
  516. /*
  517. ** Virtual table module xNext method.
  518. */
  519. static int expertNext(sqlite3_vtab_cursor *cur){
  520. ExpertCsr *pCsr = (ExpertCsr*)cur;
  521. int rc = SQLITE_OK;
  522. assert( pCsr->pData );
  523. rc = sqlite3_step(pCsr->pData);
  524. if( rc!=SQLITE_ROW ){
  525. rc = sqlite3_finalize(pCsr->pData);
  526. pCsr->pData = 0;
  527. }else{
  528. rc = SQLITE_OK;
  529. }
  530. return rc;
  531. }
  532. /*
  533. ** Virtual table module xRowid method.
  534. */
  535. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  536. (void)cur;
  537. *pRowid = 0;
  538. return SQLITE_OK;
  539. }
  540. /*
  541. ** Virtual table module xColumn method.
  542. */
  543. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  544. ExpertCsr *pCsr = (ExpertCsr*)cur;
  545. sqlite3_value *pVal;
  546. pVal = sqlite3_column_value(pCsr->pData, i);
  547. if( pVal ){
  548. sqlite3_result_value(ctx, pVal);
  549. }
  550. return SQLITE_OK;
  551. }
  552. /*
  553. ** Virtual table module xFilter method.
  554. */
  555. static int expertFilter(
  556. sqlite3_vtab_cursor *cur,
  557. int idxNum, const char *idxStr,
  558. int argc, sqlite3_value **argv
  559. ){
  560. ExpertCsr *pCsr = (ExpertCsr*)cur;
  561. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  562. sqlite3expert *pExpert = pVtab->pExpert;
  563. int rc;
  564. (void)idxNum;
  565. (void)idxStr;
  566. (void)argc;
  567. (void)argv;
  568. rc = sqlite3_finalize(pCsr->pData);
  569. pCsr->pData = 0;
  570. if( rc==SQLITE_OK ){
  571. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  572. "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName
  573. );
  574. }
  575. if( rc==SQLITE_OK ){
  576. rc = expertNext(cur);
  577. }
  578. return rc;
  579. }
  580. static int idxRegisterVtab(sqlite3expert *p){
  581. static sqlite3_module expertModule = {
  582. 2, /* iVersion */
  583. expertConnect, /* xCreate - create a table */
  584. expertConnect, /* xConnect - connect to an existing table */
  585. expertBestIndex, /* xBestIndex - Determine search strategy */
  586. expertDisconnect, /* xDisconnect - Disconnect from a table */
  587. expertDisconnect, /* xDestroy - Drop a table */
  588. expertOpen, /* xOpen - open a cursor */
  589. expertClose, /* xClose - close a cursor */
  590. expertFilter, /* xFilter - configure scan constraints */
  591. expertNext, /* xNext - advance a cursor */
  592. expertEof, /* xEof */
  593. expertColumn, /* xColumn - read data */
  594. expertRowid, /* xRowid - read data */
  595. expertUpdate, /* xUpdate - write data */
  596. 0, /* xBegin - begin transaction */
  597. 0, /* xSync - sync transaction */
  598. 0, /* xCommit - commit transaction */
  599. 0, /* xRollback - rollback transaction */
  600. 0, /* xFindFunction - function overloading */
  601. 0, /* xRename - rename the table */
  602. 0, /* xSavepoint */
  603. 0, /* xRelease */
  604. 0, /* xRollbackTo */
  605. 0, /* xShadowName */
  606. 0, /* xIntegrity */
  607. };
  608. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  609. }
  610. /*
  611. ** End of virtual table implementation.
  612. *************************************************************************/
  613. /*
  614. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  615. ** is called, set it to the return value of sqlite3_finalize() before
  616. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  617. */
  618. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  619. int rc = sqlite3_finalize(pStmt);
  620. if( *pRc==SQLITE_OK ) *pRc = rc;
  621. }
  622. /*
  623. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  624. ** in the main database of connection db. If successful, set (*ppOut) to
  625. ** point to the new object and return SQLITE_OK. Otherwise, return an
  626. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  627. ** set to point to an error string.
  628. **
  629. ** It is the responsibility of the caller to eventually free either the
  630. ** IdxTable object or error message using sqlite3_free().
  631. */
  632. static int idxGetTableInfo(
  633. sqlite3 *db, /* Database connection to read details from */
  634. const char *zTab, /* Table name */
  635. IdxTable **ppOut, /* OUT: New object (if successful) */
  636. char **pzErrmsg /* OUT: Error message (if not) */
  637. ){
  638. sqlite3_stmt *p1 = 0;
  639. int nCol = 0;
  640. int nTab;
  641. int nByte;
  642. IdxTable *pNew = 0;
  643. int rc, rc2;
  644. char *pCsr = 0;
  645. int nPk = 0;
  646. *ppOut = 0;
  647. if( zTab==0 ) return SQLITE_ERROR;
  648. nTab = STRLEN(zTab);
  649. nByte = sizeof(IdxTable) + nTab + 1;
  650. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
  651. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  652. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  653. const char *zColSeq = 0;
  654. if( zCol==0 ){
  655. rc = SQLITE_ERROR;
  656. break;
  657. }
  658. nByte += 1 + STRLEN(zCol);
  659. rc = sqlite3_table_column_metadata(
  660. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  661. );
  662. if( zColSeq==0 ) zColSeq = "binary";
  663. nByte += 1 + STRLEN(zColSeq);
  664. nCol++;
  665. nPk += (sqlite3_column_int(p1, 5)>0);
  666. }
  667. rc2 = sqlite3_reset(p1);
  668. if( rc==SQLITE_OK ) rc = rc2;
  669. nByte += sizeof(IdxColumn) * nCol;
  670. if( rc==SQLITE_OK ){
  671. pNew = idxMalloc(&rc, nByte);
  672. }
  673. if( rc==SQLITE_OK ){
  674. pNew->aCol = (IdxColumn*)&pNew[1];
  675. pNew->nCol = nCol;
  676. pCsr = (char*)&pNew->aCol[nCol];
  677. }
  678. nCol = 0;
  679. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  680. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  681. const char *zColSeq = 0;
  682. int nCopy;
  683. if( zCol==0 ) continue;
  684. nCopy = STRLEN(zCol) + 1;
  685. pNew->aCol[nCol].zName = pCsr;
  686. pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
  687. memcpy(pCsr, zCol, nCopy);
  688. pCsr += nCopy;
  689. rc = sqlite3_table_column_metadata(
  690. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  691. );
  692. if( rc==SQLITE_OK ){
  693. if( zColSeq==0 ) zColSeq = "binary";
  694. nCopy = STRLEN(zColSeq) + 1;
  695. pNew->aCol[nCol].zColl = pCsr;
  696. memcpy(pCsr, zColSeq, nCopy);
  697. pCsr += nCopy;
  698. }
  699. nCol++;
  700. }
  701. idxFinalize(&rc, p1);
  702. if( rc!=SQLITE_OK ){
  703. sqlite3_free(pNew);
  704. pNew = 0;
  705. }else if( ALWAYS(pNew!=0) ){
  706. pNew->zName = pCsr;
  707. if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
  708. }
  709. *ppOut = pNew;
  710. return rc;
  711. }
  712. /*
  713. ** This function is a no-op if *pRc is set to anything other than
  714. ** SQLITE_OK when it is called.
  715. **
  716. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  717. ** the printf() style arguments is appended to zIn and the result returned
  718. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  719. ** zIn before returning.
  720. */
  721. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  722. va_list ap;
  723. char *zAppend = 0;
  724. char *zRet = 0;
  725. int nIn = zIn ? STRLEN(zIn) : 0;
  726. int nAppend = 0;
  727. va_start(ap, zFmt);
  728. if( *pRc==SQLITE_OK ){
  729. zAppend = sqlite3_vmprintf(zFmt, ap);
  730. if( zAppend ){
  731. nAppend = STRLEN(zAppend);
  732. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  733. }
  734. if( zAppend && zRet ){
  735. if( nIn ) memcpy(zRet, zIn, nIn);
  736. memcpy(&zRet[nIn], zAppend, nAppend+1);
  737. }else{
  738. sqlite3_free(zRet);
  739. zRet = 0;
  740. *pRc = SQLITE_NOMEM;
  741. }
  742. sqlite3_free(zAppend);
  743. sqlite3_free(zIn);
  744. }
  745. va_end(ap);
  746. return zRet;
  747. }
  748. /*
  749. ** Return true if zId must be quoted in order to use it as an SQL
  750. ** identifier, or false otherwise.
  751. */
  752. static int idxIdentifierRequiresQuotes(const char *zId){
  753. int i;
  754. int nId = STRLEN(zId);
  755. if( sqlite3_keyword_check(zId, nId) ) return 1;
  756. for(i=0; zId[i]; i++){
  757. if( !(zId[i]=='_')
  758. && !(zId[i]>='0' && zId[i]<='9')
  759. && !(zId[i]>='a' && zId[i]<='z')
  760. && !(zId[i]>='A' && zId[i]<='Z')
  761. ){
  762. return 1;
  763. }
  764. }
  765. return 0;
  766. }
  767. /*
  768. ** This function appends an index column definition suitable for constraint
  769. ** pCons to the string passed as zIn and returns the result.
  770. */
  771. static char *idxAppendColDefn(
  772. int *pRc, /* IN/OUT: Error code */
  773. char *zIn, /* Column defn accumulated so far */
  774. IdxTable *pTab, /* Table index will be created on */
  775. IdxConstraint *pCons
  776. ){
  777. char *zRet = zIn;
  778. IdxColumn *p = &pTab->aCol[pCons->iCol];
  779. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  780. if( idxIdentifierRequiresQuotes(p->zName) ){
  781. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  782. }else{
  783. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  784. }
  785. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  786. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  787. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  788. }else{
  789. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  790. }
  791. }
  792. if( pCons->bDesc ){
  793. zRet = idxAppendText(pRc, zRet, " DESC");
  794. }
  795. return zRet;
  796. }
  797. /*
  798. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  799. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  800. ** such an index is found, return non-zero. Or, if no such index is found,
  801. ** return zero.
  802. **
  803. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  804. */
  805. static int idxFindCompatible(
  806. int *pRc, /* OUT: Error code */
  807. sqlite3* dbm, /* Database to search */
  808. IdxScan *pScan, /* Scan for table to search for index on */
  809. IdxConstraint *pEq, /* List of == constraints */
  810. IdxConstraint *pTail /* List of range constraints */
  811. ){
  812. const char *zTbl = pScan->pTab->zName;
  813. sqlite3_stmt *pIdxList = 0;
  814. IdxConstraint *pIter;
  815. int nEq = 0; /* Number of elements in pEq */
  816. int rc;
  817. /* Count the elements in list pEq */
  818. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  819. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  820. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  821. int bMatch = 1;
  822. IdxConstraint *pT = pTail;
  823. sqlite3_stmt *pInfo = 0;
  824. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  825. if( zIdx==0 ) continue;
  826. /* Zero the IdxConstraint.bFlag values in the pEq list */
  827. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  828. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  829. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  830. int iIdx = sqlite3_column_int(pInfo, 0);
  831. int iCol = sqlite3_column_int(pInfo, 1);
  832. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  833. if( iIdx<nEq ){
  834. for(pIter=pEq; pIter; pIter=pIter->pLink){
  835. if( pIter->bFlag ) continue;
  836. if( pIter->iCol!=iCol ) continue;
  837. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  838. pIter->bFlag = 1;
  839. break;
  840. }
  841. if( pIter==0 ){
  842. bMatch = 0;
  843. break;
  844. }
  845. }else{
  846. if( pT ){
  847. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  848. bMatch = 0;
  849. break;
  850. }
  851. pT = pT->pLink;
  852. }
  853. }
  854. }
  855. idxFinalize(&rc, pInfo);
  856. if( rc==SQLITE_OK && bMatch ){
  857. sqlite3_finalize(pIdxList);
  858. return 1;
  859. }
  860. }
  861. idxFinalize(&rc, pIdxList);
  862. *pRc = rc;
  863. return 0;
  864. }
  865. /* Callback for sqlite3_exec() with query with leading count(*) column.
  866. * The first argument is expected to be an int*, referent to be incremented
  867. * if that leading column is not exactly '0'.
  868. */
  869. static int countNonzeros(void* pCount, int nc,
  870. char* azResults[], char* azColumns[]){
  871. (void)azColumns; /* Suppress unused parameter warning */
  872. if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
  873. *((int *)pCount) += 1;
  874. }
  875. return 0;
  876. }
  877. static int idxCreateFromCons(
  878. sqlite3expert *p,
  879. IdxScan *pScan,
  880. IdxConstraint *pEq,
  881. IdxConstraint *pTail
  882. ){
  883. sqlite3 *dbm = p->dbm;
  884. int rc = SQLITE_OK;
  885. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  886. IdxTable *pTab = pScan->pTab;
  887. char *zCols = 0;
  888. char *zIdx = 0;
  889. IdxConstraint *pCons;
  890. unsigned int h = 0;
  891. const char *zFmt;
  892. for(pCons=pEq; pCons; pCons=pCons->pLink){
  893. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  894. }
  895. for(pCons=pTail; pCons; pCons=pCons->pLink){
  896. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  897. }
  898. if( rc==SQLITE_OK ){
  899. /* Hash the list of columns to come up with a name for the index */
  900. const char *zTable = pScan->pTab->zName;
  901. int quoteTable = idxIdentifierRequiresQuotes(zTable);
  902. char *zName = 0; /* Index name */
  903. int collisions = 0;
  904. do{
  905. int i;
  906. char *zFind;
  907. for(i=0; zCols[i]; i++){
  908. h += ((h<<3) + zCols[i]);
  909. }
  910. sqlite3_free(zName);
  911. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  912. if( zName==0 ) break;
  913. /* Is is unique among table, view and index names? */
  914. zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
  915. " AND type in ('index','table','view')";
  916. zFind = sqlite3_mprintf(zFmt, zName);
  917. i = 0;
  918. rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
  919. assert(rc==SQLITE_OK);
  920. sqlite3_free(zFind);
  921. if( i==0 ){
  922. collisions = 0;
  923. break;
  924. }
  925. ++collisions;
  926. }while( collisions<50 && zName!=0 );
  927. if( collisions ){
  928. /* This return means "Gave up trying to find a unique index name." */
  929. rc = SQLITE_BUSY_TIMEOUT;
  930. }else if( zName==0 ){
  931. rc = SQLITE_NOMEM;
  932. }else{
  933. if( quoteTable ){
  934. zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
  935. }else{
  936. zFmt = "CREATE INDEX %s ON %s(%s)";
  937. }
  938. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  939. if( !zIdx ){
  940. rc = SQLITE_NOMEM;
  941. }else{
  942. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  943. if( rc!=SQLITE_OK ){
  944. rc = SQLITE_BUSY_TIMEOUT;
  945. }else{
  946. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  947. }
  948. }
  949. sqlite3_free(zName);
  950. sqlite3_free(zIdx);
  951. }
  952. }
  953. sqlite3_free(zCols);
  954. }
  955. return rc;
  956. }
  957. /*
  958. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  959. ** a constraint compatible with *p. Otherwise return false.
  960. */
  961. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  962. IdxConstraint *pCmp;
  963. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  964. if( p->iCol==pCmp->iCol ) return 1;
  965. }
  966. return 0;
  967. }
  968. static int idxCreateFromWhere(
  969. sqlite3expert *p,
  970. IdxScan *pScan, /* Create indexes for this scan */
  971. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  972. ){
  973. IdxConstraint *p1 = 0;
  974. IdxConstraint *pCon;
  975. int rc;
  976. /* Gather up all the == constraints. */
  977. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  978. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  979. pCon->pLink = p1;
  980. p1 = pCon;
  981. }
  982. }
  983. /* Create an index using the == constraints collected above. And the
  984. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  985. rc = idxCreateFromCons(p, pScan, p1, pTail);
  986. /* If no range/ORDER BY passed by the caller, create a version of the
  987. ** index for each range constraint. */
  988. if( pTail==0 ){
  989. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  990. assert( pCon->pLink==0 );
  991. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  992. rc = idxCreateFromCons(p, pScan, p1, pCon);
  993. }
  994. }
  995. }
  996. return rc;
  997. }
  998. /*
  999. ** Create candidate indexes in database [dbm] based on the data in
  1000. ** linked-list pScan.
  1001. */
  1002. static int idxCreateCandidates(sqlite3expert *p){
  1003. int rc = SQLITE_OK;
  1004. IdxScan *pIter;
  1005. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  1006. rc = idxCreateFromWhere(p, pIter, 0);
  1007. if( rc==SQLITE_OK && pIter->pOrder ){
  1008. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  1009. }
  1010. }
  1011. return rc;
  1012. }
  1013. /*
  1014. ** Free all elements of the linked list starting at pConstraint.
  1015. */
  1016. static void idxConstraintFree(IdxConstraint *pConstraint){
  1017. IdxConstraint *pNext;
  1018. IdxConstraint *p;
  1019. for(p=pConstraint; p; p=pNext){
  1020. pNext = p->pNext;
  1021. sqlite3_free(p);
  1022. }
  1023. }
  1024. /*
  1025. ** Free all elements of the linked list starting from pScan up until pLast
  1026. ** (pLast is not freed).
  1027. */
  1028. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  1029. IdxScan *p;
  1030. IdxScan *pNext;
  1031. for(p=pScan; p!=pLast; p=pNext){
  1032. pNext = p->pNextScan;
  1033. idxConstraintFree(p->pOrder);
  1034. idxConstraintFree(p->pEq);
  1035. idxConstraintFree(p->pRange);
  1036. sqlite3_free(p);
  1037. }
  1038. }
  1039. /*
  1040. ** Free all elements of the linked list starting from pStatement up
  1041. ** until pLast (pLast is not freed).
  1042. */
  1043. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  1044. IdxStatement *p;
  1045. IdxStatement *pNext;
  1046. for(p=pStatement; p!=pLast; p=pNext){
  1047. pNext = p->pNext;
  1048. sqlite3_free(p->zEQP);
  1049. sqlite3_free(p->zIdx);
  1050. sqlite3_free(p);
  1051. }
  1052. }
  1053. /*
  1054. ** Free the linked list of IdxTable objects starting at pTab.
  1055. */
  1056. static void idxTableFree(IdxTable *pTab){
  1057. IdxTable *pIter;
  1058. IdxTable *pNext;
  1059. for(pIter=pTab; pIter; pIter=pNext){
  1060. pNext = pIter->pNext;
  1061. sqlite3_free(pIter);
  1062. }
  1063. }
  1064. /*
  1065. ** Free the linked list of IdxWrite objects starting at pTab.
  1066. */
  1067. static void idxWriteFree(IdxWrite *pTab){
  1068. IdxWrite *pIter;
  1069. IdxWrite *pNext;
  1070. for(pIter=pTab; pIter; pIter=pNext){
  1071. pNext = pIter->pNext;
  1072. sqlite3_free(pIter);
  1073. }
  1074. }
  1075. /*
  1076. ** This function is called after candidate indexes have been created. It
  1077. ** runs all the queries to see which indexes they prefer, and populates
  1078. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  1079. */
  1080. static int idxFindIndexes(
  1081. sqlite3expert *p,
  1082. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  1083. ){
  1084. IdxStatement *pStmt;
  1085. sqlite3 *dbm = p->dbm;
  1086. int rc = SQLITE_OK;
  1087. IdxHash hIdx;
  1088. idxHashInit(&hIdx);
  1089. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  1090. IdxHashEntry *pEntry;
  1091. sqlite3_stmt *pExplain = 0;
  1092. idxHashClear(&hIdx);
  1093. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  1094. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  1095. );
  1096. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  1097. /* int iId = sqlite3_column_int(pExplain, 0); */
  1098. /* int iParent = sqlite3_column_int(pExplain, 1); */
  1099. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  1100. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  1101. int nDetail;
  1102. int i;
  1103. if( !zDetail ) continue;
  1104. nDetail = STRLEN(zDetail);
  1105. for(i=0; i<nDetail; i++){
  1106. const char *zIdx = 0;
  1107. if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  1108. zIdx = &zDetail[i+13];
  1109. }else if( i+22<nDetail
  1110. && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
  1111. ){
  1112. zIdx = &zDetail[i+22];
  1113. }
  1114. if( zIdx ){
  1115. const char *zSql;
  1116. int nIdx = 0;
  1117. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  1118. nIdx++;
  1119. }
  1120. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  1121. if( zSql ){
  1122. idxHashAdd(&rc, &hIdx, zSql, 0);
  1123. if( rc ) goto find_indexes_out;
  1124. }
  1125. break;
  1126. }
  1127. }
  1128. if( zDetail[0]!='-' ){
  1129. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  1130. }
  1131. }
  1132. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  1133. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  1134. }
  1135. idxFinalize(&rc, pExplain);
  1136. }
  1137. find_indexes_out:
  1138. idxHashClear(&hIdx);
  1139. return rc;
  1140. }
  1141. static int idxAuthCallback(
  1142. void *pCtx,
  1143. int eOp,
  1144. const char *z3,
  1145. const char *z4,
  1146. const char *zDb,
  1147. const char *zTrigger
  1148. ){
  1149. int rc = SQLITE_OK;
  1150. (void)z4;
  1151. (void)zTrigger;
  1152. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  1153. if( sqlite3_stricmp(zDb, "main")==0 ){
  1154. sqlite3expert *p = (sqlite3expert*)pCtx;
  1155. IdxTable *pTab;
  1156. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  1157. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  1158. }
  1159. if( pTab ){
  1160. IdxWrite *pWrite;
  1161. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  1162. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  1163. }
  1164. if( pWrite==0 ){
  1165. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  1166. if( rc==SQLITE_OK ){
  1167. pWrite->pTab = pTab;
  1168. pWrite->eOp = eOp;
  1169. pWrite->pNext = p->pWrite;
  1170. p->pWrite = pWrite;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. return rc;
  1177. }
  1178. static int idxProcessOneTrigger(
  1179. sqlite3expert *p,
  1180. IdxWrite *pWrite,
  1181. char **pzErr
  1182. ){
  1183. static const char *zInt = UNIQUE_TABLE_NAME;
  1184. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  1185. IdxTable *pTab = pWrite->pTab;
  1186. const char *zTab = pTab->zName;
  1187. const char *zSql =
  1188. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
  1189. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  1190. "ORDER BY type;";
  1191. sqlite3_stmt *pSelect = 0;
  1192. int rc = SQLITE_OK;
  1193. char *zWrite = 0;
  1194. /* Create the table and its triggers in the temp schema */
  1195. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  1196. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  1197. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  1198. if( zCreate==0 ) continue;
  1199. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  1200. }
  1201. idxFinalize(&rc, pSelect);
  1202. /* Rename the table in the temp schema to zInt */
  1203. if( rc==SQLITE_OK ){
  1204. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  1205. if( z==0 ){
  1206. rc = SQLITE_NOMEM;
  1207. }else{
  1208. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  1209. sqlite3_free(z);
  1210. }
  1211. }
  1212. switch( pWrite->eOp ){
  1213. case SQLITE_INSERT: {
  1214. int i;
  1215. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  1216. for(i=0; i<pTab->nCol; i++){
  1217. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  1218. }
  1219. zWrite = idxAppendText(&rc, zWrite, ")");
  1220. break;
  1221. }
  1222. case SQLITE_UPDATE: {
  1223. int i;
  1224. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  1225. for(i=0; i<pTab->nCol; i++){
  1226. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  1227. pTab->aCol[i].zName
  1228. );
  1229. }
  1230. break;
  1231. }
  1232. default: {
  1233. assert( pWrite->eOp==SQLITE_DELETE );
  1234. if( rc==SQLITE_OK ){
  1235. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  1236. if( zWrite==0 ) rc = SQLITE_NOMEM;
  1237. }
  1238. }
  1239. }
  1240. if( rc==SQLITE_OK ){
  1241. sqlite3_stmt *pX = 0;
  1242. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  1243. idxFinalize(&rc, pX);
  1244. if( rc!=SQLITE_OK ){
  1245. idxDatabaseError(p->dbv, pzErr);
  1246. }
  1247. }
  1248. sqlite3_free(zWrite);
  1249. if( rc==SQLITE_OK ){
  1250. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  1251. }
  1252. return rc;
  1253. }
  1254. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  1255. int rc = SQLITE_OK;
  1256. IdxWrite *pEnd = 0;
  1257. IdxWrite *pFirst = p->pWrite;
  1258. while( rc==SQLITE_OK && pFirst!=pEnd ){
  1259. IdxWrite *pIter;
  1260. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  1261. rc = idxProcessOneTrigger(p, pIter, pzErr);
  1262. }
  1263. pEnd = pFirst;
  1264. pFirst = p->pWrite;
  1265. }
  1266. return rc;
  1267. }
  1268. /*
  1269. ** This function tests if the schema of the main database of database handle
  1270. ** db contains an object named zTab. Assuming no error occurs, output parameter
  1271. ** (*pbContains) is set to true if zTab exists, or false if it does not.
  1272. **
  1273. ** Or, if an error occurs, an SQLite error code is returned. The final value
  1274. ** of (*pbContains) is undefined in this case.
  1275. */
  1276. static int expertDbContainsObject(
  1277. sqlite3 *db,
  1278. const char *zTab,
  1279. int *pbContains /* OUT: True if object exists */
  1280. ){
  1281. const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?";
  1282. sqlite3_stmt *pSql = 0;
  1283. int rc = SQLITE_OK;
  1284. int ret = 0;
  1285. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  1286. if( rc==SQLITE_OK ){
  1287. sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC);
  1288. if( SQLITE_ROW==sqlite3_step(pSql) ){
  1289. ret = 1;
  1290. }
  1291. rc = sqlite3_finalize(pSql);
  1292. }
  1293. *pbContains = ret;
  1294. return rc;
  1295. }
  1296. /*
  1297. ** Execute SQL command zSql using database handle db. If no error occurs,
  1298. ** set (*pzErr) to NULL and return SQLITE_OK.
  1299. **
  1300. ** If an error does occur, return an SQLite error code and set (*pzErr) to
  1301. ** point to a buffer containing an English language error message. Except,
  1302. ** if the error message begins with "no such module:", then ignore the
  1303. ** error and return as if the SQL statement had succeeded.
  1304. **
  1305. ** This is used to copy as much of the database schema as possible while
  1306. ** ignoring any errors related to missing virtual table modules.
  1307. */
  1308. static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){
  1309. int rc = SQLITE_OK;
  1310. char *zErr = 0;
  1311. rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
  1312. if( rc!=SQLITE_OK && zErr ){
  1313. int nErr = STRLEN(zErr);
  1314. if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){
  1315. sqlite3_free(zErr);
  1316. rc = SQLITE_OK;
  1317. zErr = 0;
  1318. }
  1319. }
  1320. *pzErr = zErr;
  1321. return rc;
  1322. }
  1323. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  1324. int rc = idxRegisterVtab(p);
  1325. sqlite3_stmt *pSchema = 0;
  1326. /* For each table in the main db schema:
  1327. **
  1328. ** 1) Add an entry to the p->pTable list, and
  1329. ** 2) Create the equivalent virtual table in dbv.
  1330. */
  1331. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  1332. "SELECT type, name, sql, 1, "
  1333. " substr(sql,1,14)=='create virtual' COLLATE nocase "
  1334. "FROM sqlite_schema "
  1335. "WHERE type IN ('table','view') AND "
  1336. " substr(name,1,7)!='sqlite_' COLLATE nocase "
  1337. " UNION ALL "
  1338. "SELECT type, name, sql, 2, 0 FROM sqlite_schema "
  1339. "WHERE type = 'trigger'"
  1340. " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
  1341. "ORDER BY 4, 5 DESC, 1"
  1342. );
  1343. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  1344. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  1345. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  1346. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  1347. int bVirtual = sqlite3_column_int(pSchema, 4);
  1348. int bExists = 0;
  1349. if( zType==0 || zName==0 ) continue;
  1350. rc = expertDbContainsObject(p->dbv, zName, &bExists);
  1351. if( rc || bExists ) continue;
  1352. if( zType[0]=='v' || zType[1]=='r' || bVirtual ){
  1353. /* A view. Or a trigger on a view. */
  1354. if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg);
  1355. }else{
  1356. IdxTable *pTab;
  1357. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  1358. if( rc==SQLITE_OK && ALWAYS(pTab!=0) ){
  1359. int i;
  1360. char *zInner = 0;
  1361. char *zOuter = 0;
  1362. pTab->pNext = p->pTable;
  1363. p->pTable = pTab;
  1364. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  1365. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  1366. for(i=0; i<pTab->nCol; i++){
  1367. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  1368. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  1369. );
  1370. }
  1371. zInner = idxAppendText(&rc, zInner, ")");
  1372. /* The CVT statement to create the vtab */
  1373. zOuter = idxAppendText(&rc, 0,
  1374. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  1375. );
  1376. if( rc==SQLITE_OK ){
  1377. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  1378. }
  1379. sqlite3_free(zInner);
  1380. sqlite3_free(zOuter);
  1381. }
  1382. }
  1383. }
  1384. idxFinalize(&rc, pSchema);
  1385. return rc;
  1386. }
  1387. struct IdxSampleCtx {
  1388. int iTarget;
  1389. double target; /* Target nRet/nRow value */
  1390. double nRow; /* Number of rows seen */
  1391. double nRet; /* Number of rows returned */
  1392. };
  1393. static void idxSampleFunc(
  1394. sqlite3_context *pCtx,
  1395. int argc,
  1396. sqlite3_value **argv
  1397. ){
  1398. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  1399. int bRet;
  1400. (void)argv;
  1401. assert( argc==0 );
  1402. if( p->nRow==0.0 ){
  1403. bRet = 1;
  1404. }else{
  1405. bRet = (p->nRet / p->nRow) <= p->target;
  1406. if( bRet==0 ){
  1407. unsigned short rnd;
  1408. sqlite3_randomness(2, (void*)&rnd);
  1409. bRet = ((int)rnd % 100) <= p->iTarget;
  1410. }
  1411. }
  1412. sqlite3_result_int(pCtx, bRet);
  1413. p->nRow += 1.0;
  1414. p->nRet += (double)bRet;
  1415. }
  1416. struct IdxRemCtx {
  1417. int nSlot;
  1418. struct IdxRemSlot {
  1419. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  1420. i64 iVal; /* SQLITE_INTEGER value */
  1421. double rVal; /* SQLITE_FLOAT value */
  1422. int nByte; /* Bytes of space allocated at z */
  1423. int n; /* Size of buffer z */
  1424. char *z; /* SQLITE_TEXT/BLOB value */
  1425. } aSlot[1];
  1426. };
  1427. /*
  1428. ** Implementation of scalar function sqlite_expert_rem().
  1429. */
  1430. static void idxRemFunc(
  1431. sqlite3_context *pCtx,
  1432. int argc,
  1433. sqlite3_value **argv
  1434. ){
  1435. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  1436. struct IdxRemSlot *pSlot;
  1437. int iSlot;
  1438. assert( argc==2 );
  1439. iSlot = sqlite3_value_int(argv[0]);
  1440. assert( iSlot<p->nSlot );
  1441. pSlot = &p->aSlot[iSlot];
  1442. switch( pSlot->eType ){
  1443. case SQLITE_NULL:
  1444. /* no-op */
  1445. break;
  1446. case SQLITE_INTEGER:
  1447. sqlite3_result_int64(pCtx, pSlot->iVal);
  1448. break;
  1449. case SQLITE_FLOAT:
  1450. sqlite3_result_double(pCtx, pSlot->rVal);
  1451. break;
  1452. case SQLITE_BLOB:
  1453. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  1454. break;
  1455. case SQLITE_TEXT:
  1456. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  1457. break;
  1458. }
  1459. pSlot->eType = sqlite3_value_type(argv[1]);
  1460. switch( pSlot->eType ){
  1461. case SQLITE_NULL:
  1462. /* no-op */
  1463. break;
  1464. case SQLITE_INTEGER:
  1465. pSlot->iVal = sqlite3_value_int64(argv[1]);
  1466. break;
  1467. case SQLITE_FLOAT:
  1468. pSlot->rVal = sqlite3_value_double(argv[1]);
  1469. break;
  1470. case SQLITE_BLOB:
  1471. case SQLITE_TEXT: {
  1472. int nByte = sqlite3_value_bytes(argv[1]);
  1473. const void *pData = 0;
  1474. if( nByte>pSlot->nByte ){
  1475. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  1476. if( zNew==0 ){
  1477. sqlite3_result_error_nomem(pCtx);
  1478. return;
  1479. }
  1480. pSlot->nByte = nByte*2;
  1481. pSlot->z = zNew;
  1482. }
  1483. pSlot->n = nByte;
  1484. if( pSlot->eType==SQLITE_BLOB ){
  1485. pData = sqlite3_value_blob(argv[1]);
  1486. if( pData ) memcpy(pSlot->z, pData, nByte);
  1487. }else{
  1488. pData = sqlite3_value_text(argv[1]);
  1489. memcpy(pSlot->z, pData, nByte);
  1490. }
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  1496. int rc = SQLITE_OK;
  1497. const char *zMax =
  1498. "SELECT max(i.seqno) FROM "
  1499. " sqlite_schema AS s, "
  1500. " pragma_index_list(s.name) AS l, "
  1501. " pragma_index_info(l.name) AS i "
  1502. "WHERE s.type = 'table'";
  1503. sqlite3_stmt *pMax = 0;
  1504. *pnMax = 0;
  1505. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  1506. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  1507. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  1508. }
  1509. idxFinalize(&rc, pMax);
  1510. return rc;
  1511. }
  1512. static int idxPopulateOneStat1(
  1513. sqlite3expert *p,
  1514. sqlite3_stmt *pIndexXInfo,
  1515. sqlite3_stmt *pWriteStat,
  1516. const char *zTab,
  1517. const char *zIdx,
  1518. char **pzErr
  1519. ){
  1520. char *zCols = 0;
  1521. char *zOrder = 0;
  1522. char *zQuery = 0;
  1523. int nCol = 0;
  1524. int i;
  1525. sqlite3_stmt *pQuery = 0;
  1526. int *aStat = 0;
  1527. int rc = SQLITE_OK;
  1528. assert( p->iSample>0 );
  1529. /* Formulate the query text */
  1530. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  1531. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  1532. const char *zComma = zCols==0 ? "" : ", ";
  1533. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  1534. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  1535. if( zName==0 ){
  1536. /* This index contains an expression. Ignore it. */
  1537. sqlite3_free(zCols);
  1538. sqlite3_free(zOrder);
  1539. return sqlite3_reset(pIndexXInfo);
  1540. }
  1541. zCols = idxAppendText(&rc, zCols,
  1542. "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
  1543. zComma, zName, nCol, zName, zColl
  1544. );
  1545. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  1546. }
  1547. sqlite3_reset(pIndexXInfo);
  1548. if( rc==SQLITE_OK ){
  1549. if( p->iSample==100 ){
  1550. zQuery = sqlite3_mprintf(
  1551. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  1552. );
  1553. }else{
  1554. zQuery = sqlite3_mprintf(
  1555. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  1556. );
  1557. }
  1558. }
  1559. sqlite3_free(zCols);
  1560. sqlite3_free(zOrder);
  1561. /* Formulate the query text */
  1562. if( rc==SQLITE_OK ){
  1563. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  1564. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  1565. }
  1566. sqlite3_free(zQuery);
  1567. if( rc==SQLITE_OK ){
  1568. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  1569. }
  1570. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  1571. IdxHashEntry *pEntry;
  1572. char *zStat = 0;
  1573. for(i=0; i<=nCol; i++) aStat[i] = 1;
  1574. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  1575. aStat[0]++;
  1576. for(i=0; i<nCol; i++){
  1577. if( sqlite3_column_int(pQuery, i)==0 ) break;
  1578. }
  1579. for(/*no-op*/; i<nCol; i++){
  1580. aStat[i+1]++;
  1581. }
  1582. }
  1583. if( rc==SQLITE_OK ){
  1584. int s0 = aStat[0];
  1585. zStat = sqlite3_mprintf("%d", s0);
  1586. if( zStat==0 ) rc = SQLITE_NOMEM;
  1587. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  1588. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  1589. }
  1590. }
  1591. if( rc==SQLITE_OK ){
  1592. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  1593. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  1594. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  1595. sqlite3_step(pWriteStat);
  1596. rc = sqlite3_reset(pWriteStat);
  1597. }
  1598. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  1599. if( pEntry ){
  1600. assert( pEntry->zVal2==0 );
  1601. pEntry->zVal2 = zStat;
  1602. }else{
  1603. sqlite3_free(zStat);
  1604. }
  1605. }
  1606. sqlite3_free(aStat);
  1607. idxFinalize(&rc, pQuery);
  1608. return rc;
  1609. }
  1610. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  1611. int rc;
  1612. char *zSql;
  1613. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  1614. if( rc!=SQLITE_OK ) return rc;
  1615. zSql = sqlite3_mprintf(
  1616. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  1617. );
  1618. if( zSql==0 ) return SQLITE_NOMEM;
  1619. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  1620. sqlite3_free(zSql);
  1621. return rc;
  1622. }
  1623. /*
  1624. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  1625. ** indexes have already been created in database sqlite3expert.dbm, this
  1626. ** function populates sqlite_stat1 table in the same database.
  1627. **
  1628. ** The stat1 data is generated by querying the
  1629. */
  1630. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  1631. int rc = SQLITE_OK;
  1632. int nMax =0;
  1633. struct IdxRemCtx *pCtx = 0;
  1634. struct IdxSampleCtx samplectx;
  1635. int i;
  1636. i64 iPrev = -100000;
  1637. sqlite3_stmt *pAllIndex = 0;
  1638. sqlite3_stmt *pIndexXInfo = 0;
  1639. sqlite3_stmt *pWrite = 0;
  1640. const char *zAllIndex =
  1641. "SELECT s.rowid, s.name, l.name FROM "
  1642. " sqlite_schema AS s, "
  1643. " pragma_index_list(s.name) AS l "
  1644. "WHERE s.type = 'table'";
  1645. const char *zIndexXInfo =
  1646. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  1647. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  1648. /* If iSample==0, no sqlite_stat1 data is required. */
  1649. if( p->iSample==0 ) return SQLITE_OK;
  1650. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  1651. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  1652. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  1653. if( rc==SQLITE_OK ){
  1654. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  1655. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  1656. }
  1657. if( rc==SQLITE_OK ){
  1658. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  1659. rc = sqlite3_create_function(dbrem, "sqlite_expert_rem",
  1660. 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  1661. );
  1662. }
  1663. if( rc==SQLITE_OK ){
  1664. rc = sqlite3_create_function(p->db, "sqlite_expert_sample",
  1665. 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  1666. );
  1667. }
  1668. if( rc==SQLITE_OK ){
  1669. pCtx->nSlot = nMax+1;
  1670. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  1671. }
  1672. if( rc==SQLITE_OK ){
  1673. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  1674. }
  1675. if( rc==SQLITE_OK ){
  1676. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  1677. }
  1678. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  1679. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  1680. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  1681. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  1682. if( zTab==0 || zIdx==0 ) continue;
  1683. if( p->iSample<100 && iPrev!=iRowid ){
  1684. samplectx.target = (double)p->iSample / 100.0;
  1685. samplectx.iTarget = p->iSample;
  1686. samplectx.nRow = 0.0;
  1687. samplectx.nRet = 0.0;
  1688. rc = idxBuildSampleTable(p, zTab);
  1689. if( rc!=SQLITE_OK ) break;
  1690. }
  1691. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  1692. iPrev = iRowid;
  1693. }
  1694. if( rc==SQLITE_OK && p->iSample<100 ){
  1695. rc = sqlite3_exec(p->dbv,
  1696. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  1697. );
  1698. }
  1699. idxFinalize(&rc, pAllIndex);
  1700. idxFinalize(&rc, pIndexXInfo);
  1701. idxFinalize(&rc, pWrite);
  1702. if( pCtx ){
  1703. for(i=0; i<pCtx->nSlot; i++){
  1704. sqlite3_free(pCtx->aSlot[i].z);
  1705. }
  1706. sqlite3_free(pCtx);
  1707. }
  1708. if( rc==SQLITE_OK ){
  1709. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
  1710. }
  1711. sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0);
  1712. sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0);
  1713. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  1714. return rc;
  1715. }
  1716. /*
  1717. ** Define and possibly pretend to use a useless collation sequence.
  1718. ** This pretense allows expert to accept SQL using custom collations.
  1719. */
  1720. int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
  1721. (void)up1;
  1722. (void)up2;
  1723. (void)up3;
  1724. (void)up4;
  1725. (void)up5;
  1726. assert(0); /* VDBE should never be run. */
  1727. return 0;
  1728. }
  1729. /* And a callback to register above upon actual need */
  1730. void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
  1731. (void)up1;
  1732. sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
  1733. }
  1734. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
  1735. && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
  1736. /*
  1737. ** dummy functions for no-op implementation of UDFs during expert's work
  1738. */
  1739. void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
  1740. (void)up1;
  1741. (void)up2;
  1742. (void)up3;
  1743. assert(0); /* VDBE should never be run. */
  1744. }
  1745. void dummyUDFvalue(sqlite3_context *up1){
  1746. (void)up1;
  1747. assert(0); /* VDBE should never be run. */
  1748. }
  1749. /*
  1750. ** Register UDFs from user database with another.
  1751. */
  1752. int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
  1753. sqlite3_stmt *pStmt;
  1754. int rc = sqlite3_prepare_v2(dbSrc,
  1755. "SELECT name,type,enc,narg,flags "
  1756. "FROM pragma_function_list() "
  1757. "WHERE builtin==0", -1, &pStmt, 0);
  1758. if( rc==SQLITE_OK ){
  1759. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  1760. int nargs = sqlite3_column_int(pStmt,3);
  1761. int flags = sqlite3_column_int(pStmt,4);
  1762. const char *name = (char*)sqlite3_column_text(pStmt,0);
  1763. const char *type = (char*)sqlite3_column_text(pStmt,1);
  1764. const char *enc = (char*)sqlite3_column_text(pStmt,2);
  1765. if( name==0 || type==0 || enc==0 ){
  1766. /* no-op. Only happens on OOM */
  1767. }else{
  1768. int ienc = SQLITE_UTF8;
  1769. int rcf = SQLITE_ERROR;
  1770. if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
  1771. else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
  1772. ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
  1773. if( strcmp(type,"w")==0 ){
  1774. rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
  1775. dummyUDF,dummyUDFvalue,0,0,0);
  1776. }else if( strcmp(type,"a")==0 ){
  1777. rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
  1778. 0,dummyUDF,dummyUDFvalue);
  1779. }else if( strcmp(type,"s")==0 ){
  1780. rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
  1781. dummyUDF,0,0);
  1782. }
  1783. if( rcf!=SQLITE_OK ){
  1784. rc = rcf;
  1785. break;
  1786. }
  1787. }
  1788. }
  1789. sqlite3_finalize(pStmt);
  1790. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  1791. }
  1792. return rc;
  1793. }
  1794. #endif
  1795. /*
  1796. ** Allocate a new sqlite3expert object.
  1797. */
  1798. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  1799. int rc = SQLITE_OK;
  1800. sqlite3expert *pNew;
  1801. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  1802. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  1803. ** will contain a virtual table corresponding to each real table in
  1804. ** the user database schema, and a copy of each view. It is used to
  1805. ** collect information regarding the WHERE, ORDER BY and other clauses
  1806. ** of the user's query.
  1807. */
  1808. if( rc==SQLITE_OK ){
  1809. pNew->db = db;
  1810. pNew->iSample = 100;
  1811. rc = sqlite3_open(":memory:", &pNew->dbv);
  1812. }
  1813. if( rc==SQLITE_OK ){
  1814. rc = sqlite3_open(":memory:", &pNew->dbm);
  1815. if( rc==SQLITE_OK ){
  1816. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  1817. }
  1818. }
  1819. /* Allow custom collations to be dealt with through prepare. */
  1820. if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
  1821. if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
  1822. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
  1823. && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
  1824. /* Register UDFs from database [db] with [dbm] and [dbv]. */
  1825. if( rc==SQLITE_OK ){
  1826. rc = registerUDFs(pNew->db, pNew->dbm);
  1827. }
  1828. if( rc==SQLITE_OK ){
  1829. rc = registerUDFs(pNew->db, pNew->dbv);
  1830. }
  1831. #endif
  1832. /* Copy the entire schema of database [db] into [dbm]. */
  1833. if( rc==SQLITE_OK ){
  1834. sqlite3_stmt *pSql = 0;
  1835. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  1836. "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase"
  1837. " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase"
  1838. " ORDER BY 3 DESC, rowid"
  1839. );
  1840. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  1841. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  1842. const char *zName = (const char*)sqlite3_column_text(pSql, 1);
  1843. int bExists = 0;
  1844. rc = expertDbContainsObject(pNew->dbm, zName, &bExists);
  1845. if( rc==SQLITE_OK && zSql && bExists==0 ){
  1846. rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg);
  1847. }
  1848. }
  1849. idxFinalize(&rc, pSql);
  1850. }
  1851. /* Create the vtab schema */
  1852. if( rc==SQLITE_OK ){
  1853. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  1854. }
  1855. /* Register the auth callback with dbv */
  1856. if( rc==SQLITE_OK ){
  1857. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  1858. }
  1859. /* If an error has occurred, free the new object and return NULL. Otherwise,
  1860. ** return the new sqlite3expert handle. */
  1861. if( rc!=SQLITE_OK ){
  1862. sqlite3_expert_destroy(pNew);
  1863. pNew = 0;
  1864. }
  1865. return pNew;
  1866. }
  1867. /*
  1868. ** Configure an sqlite3expert object.
  1869. */
  1870. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  1871. int rc = SQLITE_OK;
  1872. va_list ap;
  1873. va_start(ap, op);
  1874. switch( op ){
  1875. case EXPERT_CONFIG_SAMPLE: {
  1876. int iVal = va_arg(ap, int);
  1877. if( iVal<0 ) iVal = 0;
  1878. if( iVal>100 ) iVal = 100;
  1879. p->iSample = iVal;
  1880. break;
  1881. }
  1882. default:
  1883. rc = SQLITE_NOTFOUND;
  1884. break;
  1885. }
  1886. va_end(ap);
  1887. return rc;
  1888. }
  1889. /*
  1890. ** Add an SQL statement to the analysis.
  1891. */
  1892. int sqlite3_expert_sql(
  1893. sqlite3expert *p, /* From sqlite3_expert_new() */
  1894. const char *zSql, /* SQL statement to add */
  1895. char **pzErr /* OUT: Error message (if any) */
  1896. ){
  1897. IdxScan *pScanOrig = p->pScan;
  1898. IdxStatement *pStmtOrig = p->pStatement;
  1899. int rc = SQLITE_OK;
  1900. const char *zStmt = zSql;
  1901. if( p->bRun ) return SQLITE_MISUSE;
  1902. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  1903. sqlite3_stmt *pStmt = 0;
  1904. /* Ensure that the provided statement compiles against user's DB. */
  1905. rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
  1906. if( rc!=SQLITE_OK ) break;
  1907. sqlite3_finalize(pStmt);
  1908. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  1909. if( rc==SQLITE_OK ){
  1910. if( pStmt ){
  1911. IdxStatement *pNew;
  1912. const char *z = sqlite3_sql(pStmt);
  1913. int n = STRLEN(z);
  1914. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  1915. if( rc==SQLITE_OK ){
  1916. pNew->zSql = (char*)&pNew[1];
  1917. memcpy(pNew->zSql, z, n+1);
  1918. pNew->pNext = p->pStatement;
  1919. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  1920. p->pStatement = pNew;
  1921. }
  1922. sqlite3_finalize(pStmt);
  1923. }
  1924. }else{
  1925. idxDatabaseError(p->dbv, pzErr);
  1926. }
  1927. }
  1928. if( rc!=SQLITE_OK ){
  1929. idxScanFree(p->pScan, pScanOrig);
  1930. idxStatementFree(p->pStatement, pStmtOrig);
  1931. p->pScan = pScanOrig;
  1932. p->pStatement = pStmtOrig;
  1933. }
  1934. return rc;
  1935. }
  1936. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  1937. int rc;
  1938. IdxHashEntry *pEntry;
  1939. /* Do trigger processing to collect any extra IdxScan structures */
  1940. rc = idxProcessTriggers(p, pzErr);
  1941. /* Create candidate indexes within the in-memory database file */
  1942. if( rc==SQLITE_OK ){
  1943. rc = idxCreateCandidates(p);
  1944. }else if ( rc==SQLITE_BUSY_TIMEOUT ){
  1945. if( pzErr )
  1946. *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
  1947. return rc;
  1948. }
  1949. /* Generate the stat1 data */
  1950. if( rc==SQLITE_OK ){
  1951. rc = idxPopulateStat1(p, pzErr);
  1952. }
  1953. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  1954. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  1955. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  1956. "%s;%s%s\n", pEntry->zVal,
  1957. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  1958. );
  1959. }
  1960. /* Figure out which of the candidate indexes are preferred by the query
  1961. ** planner and report the results to the user. */
  1962. if( rc==SQLITE_OK ){
  1963. rc = idxFindIndexes(p, pzErr);
  1964. }
  1965. if( rc==SQLITE_OK ){
  1966. p->bRun = 1;
  1967. }
  1968. return rc;
  1969. }
  1970. /*
  1971. ** Return the total number of statements that have been added to this
  1972. ** sqlite3expert using sqlite3_expert_sql().
  1973. */
  1974. int sqlite3_expert_count(sqlite3expert *p){
  1975. int nRet = 0;
  1976. if( p->pStatement ) nRet = p->pStatement->iId+1;
  1977. return nRet;
  1978. }
  1979. /*
  1980. ** Return a component of the report.
  1981. */
  1982. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  1983. const char *zRet = 0;
  1984. IdxStatement *pStmt;
  1985. if( p->bRun==0 ) return 0;
  1986. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  1987. switch( eReport ){
  1988. case EXPERT_REPORT_SQL:
  1989. if( pStmt ) zRet = pStmt->zSql;
  1990. break;
  1991. case EXPERT_REPORT_INDEXES:
  1992. if( pStmt ) zRet = pStmt->zIdx;
  1993. break;
  1994. case EXPERT_REPORT_PLAN:
  1995. if( pStmt ) zRet = pStmt->zEQP;
  1996. break;
  1997. case EXPERT_REPORT_CANDIDATES:
  1998. zRet = p->zCandidates;
  1999. break;
  2000. }
  2001. return zRet;
  2002. }
  2003. /*
  2004. ** Free an sqlite3expert object.
  2005. */
  2006. void sqlite3_expert_destroy(sqlite3expert *p){
  2007. if( p ){
  2008. sqlite3_close(p->dbm);
  2009. sqlite3_close(p->dbv);
  2010. idxScanFree(p->pScan, 0);
  2011. idxStatementFree(p->pStatement, 0);
  2012. idxTableFree(p->pTable);
  2013. idxWriteFree(p->pWrite);
  2014. idxHashClear(&p->hIdx);
  2015. sqlite3_free(p->zCandidates);
  2016. sqlite3_free(p);
  2017. }
  2018. }
  2019. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */