build.c 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886
  1. /*
  2. ** 2001 September 15
  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. ** This file contains C code routines that are called by the SQLite parser
  13. ** when syntax rules are reduced. The routines in this file handle the
  14. ** following kinds of SQL syntax:
  15. **
  16. ** CREATE TABLE
  17. ** DROP TABLE
  18. ** CREATE INDEX
  19. ** DROP INDEX
  20. ** creating ID lists
  21. ** BEGIN TRANSACTION
  22. ** COMMIT
  23. ** ROLLBACK
  24. */
  25. #include "sqliteInt.h"
  26. /*
  27. ** This routine is called when a new SQL statement is beginning to
  28. ** be parsed. Initialize the pParse structure as needed.
  29. */
  30. void sqlite3BeginParse(Parse *pParse, int explainFlag){
  31. pParse->explain = (u8)explainFlag;
  32. pParse->nVar = 0;
  33. }
  34. #ifndef SQLITE_OMIT_SHARED_CACHE
  35. /*
  36. ** The TableLock structure is only used by the sqlite3TableLock() and
  37. ** codeTableLocks() functions.
  38. */
  39. struct TableLock {
  40. int iDb; /* The database containing the table to be locked */
  41. int iTab; /* The root page of the table to be locked */
  42. u8 isWriteLock; /* True for write lock. False for a read lock */
  43. const char *zName; /* Name of the table */
  44. };
  45. /*
  46. ** Record the fact that we want to lock a table at run-time.
  47. **
  48. ** The table to be locked has root page iTab and is found in database iDb.
  49. ** A read or a write lock can be taken depending on isWritelock.
  50. **
  51. ** This routine just records the fact that the lock is desired. The
  52. ** code to make the lock occur is generated by a later call to
  53. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  54. */
  55. void sqlite3TableLock(
  56. Parse *pParse, /* Parsing context */
  57. int iDb, /* Index of the database containing the table to lock */
  58. int iTab, /* Root page number of the table to be locked */
  59. u8 isWriteLock, /* True for a write lock */
  60. const char *zName /* Name of the table to be locked */
  61. ){
  62. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  63. int i;
  64. int nBytes;
  65. TableLock *p;
  66. assert( iDb>=0 );
  67. for(i=0; i<pToplevel->nTableLock; i++){
  68. p = &pToplevel->aTableLock[i];
  69. if( p->iDb==iDb && p->iTab==iTab ){
  70. p->isWriteLock = (p->isWriteLock || isWriteLock);
  71. return;
  72. }
  73. }
  74. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  75. pToplevel->aTableLock =
  76. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  77. if( pToplevel->aTableLock ){
  78. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  79. p->iDb = iDb;
  80. p->iTab = iTab;
  81. p->isWriteLock = isWriteLock;
  82. p->zName = zName;
  83. }else{
  84. pToplevel->nTableLock = 0;
  85. pToplevel->db->mallocFailed = 1;
  86. }
  87. }
  88. /*
  89. ** Code an OP_TableLock instruction for each table locked by the
  90. ** statement (configured by calls to sqlite3TableLock()).
  91. */
  92. static void codeTableLocks(Parse *pParse){
  93. int i;
  94. Vdbe *pVdbe;
  95. pVdbe = sqlite3GetVdbe(pParse);
  96. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  97. for(i=0; i<pParse->nTableLock; i++){
  98. TableLock *p = &pParse->aTableLock[i];
  99. int p1 = p->iDb;
  100. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  101. p->zName, P4_STATIC);
  102. }
  103. }
  104. #else
  105. #define codeTableLocks(x)
  106. #endif
  107. /*
  108. ** This routine is called after a single SQL statement has been
  109. ** parsed and a VDBE program to execute that statement has been
  110. ** prepared. This routine puts the finishing touches on the
  111. ** VDBE program and resets the pParse structure for the next
  112. ** parse.
  113. **
  114. ** Note that if an error occurred, it might be the case that
  115. ** no VDBE code was generated.
  116. */
  117. void sqlite3FinishCoding(Parse *pParse){
  118. sqlite3 *db;
  119. Vdbe *v;
  120. assert( pParse->pToplevel==0 );
  121. db = pParse->db;
  122. if( db->mallocFailed ) return;
  123. if( pParse->nested ) return;
  124. if( pParse->nErr ) return;
  125. /* Begin by generating some termination code at the end of the
  126. ** vdbe program
  127. */
  128. v = sqlite3GetVdbe(pParse);
  129. assert( !pParse->isMultiWrite
  130. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  131. if( v ){
  132. sqlite3VdbeAddOp0(v, OP_Halt);
  133. /* The cookie mask contains one bit for each database file open.
  134. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  135. ** set for each database that is used. Generate code to start a
  136. ** transaction on each used database and to verify the schema cookie
  137. ** on each used database.
  138. */
  139. if( pParse->cookieGoto>0 ){
  140. yDbMask mask;
  141. int iDb;
  142. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  143. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  144. if( (mask & pParse->cookieMask)==0 ) continue;
  145. sqlite3VdbeUsesBtree(v, iDb);
  146. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  147. if( db->init.busy==0 ){
  148. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  149. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  150. iDb, pParse->cookieValue[iDb],
  151. db->aDb[iDb].pSchema->iGeneration);
  152. }
  153. }
  154. #ifndef SQLITE_OMIT_VIRTUALTABLE
  155. {
  156. int i;
  157. for(i=0; i<pParse->nVtabLock; i++){
  158. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  159. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  160. }
  161. pParse->nVtabLock = 0;
  162. }
  163. #endif
  164. /* Once all the cookies have been verified and transactions opened,
  165. ** obtain the required table-locks. This is a no-op unless the
  166. ** shared-cache feature is enabled.
  167. */
  168. codeTableLocks(pParse);
  169. /* Initialize any AUTOINCREMENT data structures required.
  170. */
  171. sqlite3AutoincrementBegin(pParse);
  172. /* Finally, jump back to the beginning of the executable code. */
  173. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  174. }
  175. }
  176. /* Get the VDBE program ready for execution
  177. */
  178. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  179. #ifdef SQLITE_DEBUG
  180. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  181. sqlite3VdbeTrace(v, trace);
  182. #endif
  183. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  184. /* A minimum of one cursor is required if autoincrement is used
  185. * See ticket [a696379c1f08866] */
  186. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  187. sqlite3VdbeMakeReady(v, pParse);
  188. pParse->rc = SQLITE_DONE;
  189. pParse->colNamesSet = 0;
  190. }else{
  191. pParse->rc = SQLITE_ERROR;
  192. }
  193. pParse->nTab = 0;
  194. pParse->nMem = 0;
  195. pParse->nSet = 0;
  196. pParse->nVar = 0;
  197. pParse->cookieMask = 0;
  198. pParse->cookieGoto = 0;
  199. }
  200. /*
  201. ** Run the parser and code generator recursively in order to generate
  202. ** code for the SQL statement given onto the end of the pParse context
  203. ** currently under construction. When the parser is run recursively
  204. ** this way, the final OP_Halt is not appended and other initialization
  205. ** and finalization steps are omitted because those are handling by the
  206. ** outermost parser.
  207. **
  208. ** Not everything is nestable. This facility is designed to permit
  209. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  210. ** care if you decide to try to use this routine for some other purposes.
  211. */
  212. void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  213. va_list ap;
  214. char *zSql;
  215. char *zErrMsg = 0;
  216. sqlite3 *db = pParse->db;
  217. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  218. char saveBuf[SAVE_SZ];
  219. if( pParse->nErr ) return;
  220. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  221. va_start(ap, zFormat);
  222. zSql = sqlite3VMPrintf(db, zFormat, ap);
  223. va_end(ap);
  224. if( zSql==0 ){
  225. return; /* A malloc must have failed */
  226. }
  227. pParse->nested++;
  228. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  229. memset(&pParse->nVar, 0, SAVE_SZ);
  230. sqlite3RunParser(pParse, zSql, &zErrMsg);
  231. sqlite3DbFree(db, zErrMsg);
  232. sqlite3DbFree(db, zSql);
  233. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  234. pParse->nested--;
  235. }
  236. /*
  237. ** Locate the in-memory structure that describes a particular database
  238. ** table given the name of that table and (optionally) the name of the
  239. ** database containing the table. Return NULL if not found.
  240. **
  241. ** If zDatabase is 0, all databases are searched for the table and the
  242. ** first matching table is returned. (No checking for duplicate table
  243. ** names is done.) The search order is TEMP first, then MAIN, then any
  244. ** auxiliary databases added using the ATTACH command.
  245. **
  246. ** See also sqlite3LocateTable().
  247. */
  248. Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  249. Table *p = 0;
  250. int i;
  251. int nName;
  252. assert( zName!=0 );
  253. nName = sqlite3Strlen30(zName);
  254. /* All mutexes are required for schema access. Make sure we hold them. */
  255. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  256. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  257. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  258. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  259. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  260. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  261. if( p ) break;
  262. }
  263. return p;
  264. }
  265. /*
  266. ** Locate the in-memory structure that describes a particular database
  267. ** table given the name of that table and (optionally) the name of the
  268. ** database containing the table. Return NULL if not found. Also leave an
  269. ** error message in pParse->zErrMsg.
  270. **
  271. ** The difference between this routine and sqlite3FindTable() is that this
  272. ** routine leaves an error message in pParse->zErrMsg where
  273. ** sqlite3FindTable() does not.
  274. */
  275. Table *sqlite3LocateTable(
  276. Parse *pParse, /* context in which to report errors */
  277. int isView, /* True if looking for a VIEW rather than a TABLE */
  278. const char *zName, /* Name of the table we are looking for */
  279. const char *zDbase /* Name of the database. Might be NULL */
  280. ){
  281. Table *p;
  282. /* Read the database schema. If an error occurs, leave an error message
  283. ** and code in pParse and return NULL. */
  284. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  285. return 0;
  286. }
  287. p = sqlite3FindTable(pParse->db, zName, zDbase);
  288. if( p==0 ){
  289. const char *zMsg = isView ? "no such view" : "no such table";
  290. if( zDbase ){
  291. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  292. }else{
  293. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  294. }
  295. pParse->checkSchema = 1;
  296. }
  297. return p;
  298. }
  299. /*
  300. ** Locate the table identified by *p.
  301. **
  302. ** This is a wrapper around sqlite3LocateTable(). The difference between
  303. ** sqlite3LocateTable() and this function is that this function restricts
  304. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  305. ** non-NULL if it is part of a view or trigger program definition. See
  306. ** sqlite3FixSrcList() for details.
  307. */
  308. Table *sqlite3LocateTableItem(
  309. Parse *pParse,
  310. int isView,
  311. struct SrcList_item *p
  312. ){
  313. const char *zDb;
  314. assert( p->pSchema==0 || p->zDatabase==0 );
  315. if( p->pSchema ){
  316. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  317. zDb = pParse->db->aDb[iDb].zName;
  318. }else{
  319. zDb = p->zDatabase;
  320. }
  321. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  322. }
  323. /*
  324. ** Locate the in-memory structure that describes
  325. ** a particular index given the name of that index
  326. ** and the name of the database that contains the index.
  327. ** Return NULL if not found.
  328. **
  329. ** If zDatabase is 0, all databases are searched for the
  330. ** table and the first matching index is returned. (No checking
  331. ** for duplicate index names is done.) The search order is
  332. ** TEMP first, then MAIN, then any auxiliary databases added
  333. ** using the ATTACH command.
  334. */
  335. Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  336. Index *p = 0;
  337. int i;
  338. int nName = sqlite3Strlen30(zName);
  339. /* All mutexes are required for schema access. Make sure we hold them. */
  340. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  341. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  342. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  343. Schema *pSchema = db->aDb[j].pSchema;
  344. assert( pSchema );
  345. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  346. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  347. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  348. if( p ) break;
  349. }
  350. return p;
  351. }
  352. /*
  353. ** Reclaim the memory used by an index
  354. */
  355. static void freeIndex(sqlite3 *db, Index *p){
  356. #ifndef SQLITE_OMIT_ANALYZE
  357. sqlite3DeleteIndexSamples(db, p);
  358. #endif
  359. sqlite3ExprDelete(db, p->pPartIdxWhere);
  360. sqlite3DbFree(db, p->zColAff);
  361. sqlite3DbFree(db, p);
  362. }
  363. /*
  364. ** For the index called zIdxName which is found in the database iDb,
  365. ** unlike that index from its Table then remove the index from
  366. ** the index hash table and free all memory structures associated
  367. ** with the index.
  368. */
  369. void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  370. Index *pIndex;
  371. int len;
  372. Hash *pHash;
  373. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  374. pHash = &db->aDb[iDb].pSchema->idxHash;
  375. len = sqlite3Strlen30(zIdxName);
  376. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  377. if( ALWAYS(pIndex) ){
  378. if( pIndex->pTable->pIndex==pIndex ){
  379. pIndex->pTable->pIndex = pIndex->pNext;
  380. }else{
  381. Index *p;
  382. /* Justification of ALWAYS(); The index must be on the list of
  383. ** indices. */
  384. p = pIndex->pTable->pIndex;
  385. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  386. if( ALWAYS(p && p->pNext==pIndex) ){
  387. p->pNext = pIndex->pNext;
  388. }
  389. }
  390. freeIndex(db, pIndex);
  391. }
  392. db->flags |= SQLITE_InternChanges;
  393. }
  394. /*
  395. ** Look through the list of open database files in db->aDb[] and if
  396. ** any have been closed, remove them from the list. Reallocate the
  397. ** db->aDb[] structure to a smaller size, if possible.
  398. **
  399. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  400. ** are never candidates for being collapsed.
  401. */
  402. void sqlite3CollapseDatabaseArray(sqlite3 *db){
  403. int i, j;
  404. for(i=j=2; i<db->nDb; i++){
  405. struct Db *pDb = &db->aDb[i];
  406. if( pDb->pBt==0 ){
  407. sqlite3DbFree(db, pDb->zName);
  408. pDb->zName = 0;
  409. continue;
  410. }
  411. if( j<i ){
  412. db->aDb[j] = db->aDb[i];
  413. }
  414. j++;
  415. }
  416. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  417. db->nDb = j;
  418. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  419. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  420. sqlite3DbFree(db, db->aDb);
  421. db->aDb = db->aDbStatic;
  422. }
  423. }
  424. /*
  425. ** Reset the schema for the database at index iDb. Also reset the
  426. ** TEMP schema.
  427. */
  428. void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  429. Db *pDb;
  430. assert( iDb<db->nDb );
  431. /* Case 1: Reset the single schema identified by iDb */
  432. pDb = &db->aDb[iDb];
  433. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  434. assert( pDb->pSchema!=0 );
  435. sqlite3SchemaClear(pDb->pSchema);
  436. /* If any database other than TEMP is reset, then also reset TEMP
  437. ** since TEMP might be holding triggers that reference tables in the
  438. ** other database.
  439. */
  440. if( iDb!=1 ){
  441. pDb = &db->aDb[1];
  442. assert( pDb->pSchema!=0 );
  443. sqlite3SchemaClear(pDb->pSchema);
  444. }
  445. return;
  446. }
  447. /*
  448. ** Erase all schema information from all attached databases (including
  449. ** "main" and "temp") for a single database connection.
  450. */
  451. void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  452. int i;
  453. sqlite3BtreeEnterAll(db);
  454. for(i=0; i<db->nDb; i++){
  455. Db *pDb = &db->aDb[i];
  456. if( pDb->pSchema ){
  457. sqlite3SchemaClear(pDb->pSchema);
  458. }
  459. }
  460. db->flags &= ~SQLITE_InternChanges;
  461. sqlite3VtabUnlockList(db);
  462. sqlite3BtreeLeaveAll(db);
  463. sqlite3CollapseDatabaseArray(db);
  464. }
  465. /*
  466. ** This routine is called when a commit occurs.
  467. */
  468. void sqlite3CommitInternalChanges(sqlite3 *db){
  469. db->flags &= ~SQLITE_InternChanges;
  470. }
  471. /*
  472. ** Delete memory allocated for the column names of a table or view (the
  473. ** Table.aCol[] array).
  474. */
  475. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  476. int i;
  477. Column *pCol;
  478. assert( pTable!=0 );
  479. if( (pCol = pTable->aCol)!=0 ){
  480. for(i=0; i<pTable->nCol; i++, pCol++){
  481. sqlite3DbFree(db, pCol->zName);
  482. sqlite3ExprDelete(db, pCol->pDflt);
  483. sqlite3DbFree(db, pCol->zDflt);
  484. sqlite3DbFree(db, pCol->zType);
  485. sqlite3DbFree(db, pCol->zColl);
  486. }
  487. sqlite3DbFree(db, pTable->aCol);
  488. }
  489. }
  490. /*
  491. ** Remove the memory data structures associated with the given
  492. ** Table. No changes are made to disk by this routine.
  493. **
  494. ** This routine just deletes the data structure. It does not unlink
  495. ** the table data structure from the hash table. But it does destroy
  496. ** memory structures of the indices and foreign keys associated with
  497. ** the table.
  498. **
  499. ** The db parameter is optional. It is needed if the Table object
  500. ** contains lookaside memory. (Table objects in the schema do not use
  501. ** lookaside memory, but some ephemeral Table objects do.) Or the
  502. ** db parameter can be used with db->pnBytesFreed to measure the memory
  503. ** used by the Table object.
  504. */
  505. void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  506. Index *pIndex, *pNext;
  507. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  508. assert( !pTable || pTable->nRef>0 );
  509. /* Do not delete the table until the reference count reaches zero. */
  510. if( !pTable ) return;
  511. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  512. /* Record the number of outstanding lookaside allocations in schema Tables
  513. ** prior to doing any free() operations. Since schema Tables do not use
  514. ** lookaside, this number should not change. */
  515. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  516. db->lookaside.nOut : 0 );
  517. /* Delete all indices associated with this table. */
  518. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  519. pNext = pIndex->pNext;
  520. assert( pIndex->pSchema==pTable->pSchema );
  521. if( !db || db->pnBytesFreed==0 ){
  522. char *zName = pIndex->zName;
  523. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  524. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  525. );
  526. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  527. assert( pOld==pIndex || pOld==0 );
  528. }
  529. freeIndex(db, pIndex);
  530. }
  531. /* Delete any foreign keys attached to this table. */
  532. sqlite3FkDelete(db, pTable);
  533. /* Delete the Table structure itself.
  534. */
  535. sqliteDeleteColumnNames(db, pTable);
  536. sqlite3DbFree(db, pTable->zName);
  537. sqlite3DbFree(db, pTable->zColAff);
  538. sqlite3SelectDelete(db, pTable->pSelect);
  539. #ifndef SQLITE_OMIT_CHECK
  540. sqlite3ExprListDelete(db, pTable->pCheck);
  541. #endif
  542. #ifndef SQLITE_OMIT_VIRTUALTABLE
  543. sqlite3VtabClear(db, pTable);
  544. #endif
  545. sqlite3DbFree(db, pTable);
  546. /* Verify that no lookaside memory was used by schema tables */
  547. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  548. }
  549. /*
  550. ** Unlink the given table from the hash tables and the delete the
  551. ** table structure with all its indices and foreign keys.
  552. */
  553. void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  554. Table *p;
  555. Db *pDb;
  556. assert( db!=0 );
  557. assert( iDb>=0 && iDb<db->nDb );
  558. assert( zTabName );
  559. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  560. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  561. pDb = &db->aDb[iDb];
  562. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  563. sqlite3Strlen30(zTabName),0);
  564. sqlite3DeleteTable(db, p);
  565. db->flags |= SQLITE_InternChanges;
  566. }
  567. /*
  568. ** Given a token, return a string that consists of the text of that
  569. ** token. Space to hold the returned string
  570. ** is obtained from sqliteMalloc() and must be freed by the calling
  571. ** function.
  572. **
  573. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  574. ** surround the body of the token are removed.
  575. **
  576. ** Tokens are often just pointers into the original SQL text and so
  577. ** are not \000 terminated and are not persistent. The returned string
  578. ** is \000 terminated and is persistent.
  579. */
  580. char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  581. char *zName;
  582. if( pName ){
  583. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  584. sqlite3Dequote(zName);
  585. }else{
  586. zName = 0;
  587. }
  588. return zName;
  589. }
  590. /*
  591. ** Open the sqlite_master table stored in database number iDb for
  592. ** writing. The table is opened using cursor 0.
  593. */
  594. void sqlite3OpenMasterTable(Parse *p, int iDb){
  595. Vdbe *v = sqlite3GetVdbe(p);
  596. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  597. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  598. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  599. if( p->nTab==0 ){
  600. p->nTab = 1;
  601. }
  602. }
  603. /*
  604. ** Parameter zName points to a nul-terminated buffer containing the name
  605. ** of a database ("main", "temp" or the name of an attached db). This
  606. ** function returns the index of the named database in db->aDb[], or
  607. ** -1 if the named db cannot be found.
  608. */
  609. int sqlite3FindDbName(sqlite3 *db, const char *zName){
  610. int i = -1; /* Database number */
  611. if( zName ){
  612. Db *pDb;
  613. int n = sqlite3Strlen30(zName);
  614. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  615. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  616. 0==sqlite3StrICmp(pDb->zName, zName) ){
  617. break;
  618. }
  619. }
  620. }
  621. return i;
  622. }
  623. /*
  624. ** The token *pName contains the name of a database (either "main" or
  625. ** "temp" or the name of an attached db). This routine returns the
  626. ** index of the named database in db->aDb[], or -1 if the named db
  627. ** does not exist.
  628. */
  629. int sqlite3FindDb(sqlite3 *db, Token *pName){
  630. int i; /* Database number */
  631. char *zName; /* Name we are searching for */
  632. zName = sqlite3NameFromToken(db, pName);
  633. i = sqlite3FindDbName(db, zName);
  634. sqlite3DbFree(db, zName);
  635. return i;
  636. }
  637. /* The table or view or trigger name is passed to this routine via tokens
  638. ** pName1 and pName2. If the table name was fully qualified, for example:
  639. **
  640. ** CREATE TABLE xxx.yyy (...);
  641. **
  642. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  643. ** the table name is not fully qualified, i.e.:
  644. **
  645. ** CREATE TABLE yyy(...);
  646. **
  647. ** Then pName1 is set to "yyy" and pName2 is "".
  648. **
  649. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  650. ** pName2) that stores the unqualified table name. The index of the
  651. ** database "xxx" is returned.
  652. */
  653. int sqlite3TwoPartName(
  654. Parse *pParse, /* Parsing and code generating context */
  655. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  656. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  657. Token **pUnqual /* Write the unqualified object name here */
  658. ){
  659. int iDb; /* Database holding the object */
  660. sqlite3 *db = pParse->db;
  661. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  662. if( db->init.busy ) {
  663. sqlite3ErrorMsg(pParse, "corrupt database");
  664. pParse->nErr++;
  665. return -1;
  666. }
  667. *pUnqual = pName2;
  668. iDb = sqlite3FindDb(db, pName1);
  669. if( iDb<0 ){
  670. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  671. pParse->nErr++;
  672. return -1;
  673. }
  674. }else{
  675. assert( db->init.iDb==0 || db->init.busy );
  676. iDb = db->init.iDb;
  677. *pUnqual = pName1;
  678. }
  679. return iDb;
  680. }
  681. /*
  682. ** This routine is used to check if the UTF-8 string zName is a legal
  683. ** unqualified name for a new schema object (table, index, view or
  684. ** trigger). All names are legal except those that begin with the string
  685. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  686. ** is reserved for internal use.
  687. */
  688. int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  689. if( !pParse->db->init.busy && pParse->nested==0
  690. && (pParse->db->flags & SQLITE_WriteSchema)==0
  691. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  692. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  693. return SQLITE_ERROR;
  694. }
  695. return SQLITE_OK;
  696. }
  697. /*
  698. ** Begin constructing a new table representation in memory. This is
  699. ** the first of several action routines that get called in response
  700. ** to a CREATE TABLE statement. In particular, this routine is called
  701. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  702. ** flag is true if the table should be stored in the auxiliary database
  703. ** file instead of in the main database file. This is normally the case
  704. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  705. ** CREATE and TABLE.
  706. **
  707. ** The new table record is initialized and put in pParse->pNewTable.
  708. ** As more of the CREATE TABLE statement is parsed, additional action
  709. ** routines will be called to add more information to this record.
  710. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  711. ** is called to complete the construction of the new table record.
  712. */
  713. void sqlite3StartTable(
  714. Parse *pParse, /* Parser context */
  715. Token *pName1, /* First part of the name of the table or view */
  716. Token *pName2, /* Second part of the name of the table or view */
  717. int isTemp, /* True if this is a TEMP table */
  718. int isView, /* True if this is a VIEW */
  719. int isVirtual, /* True if this is a VIRTUAL table */
  720. int noErr /* Do nothing if table already exists */
  721. ){
  722. Table *pTable;
  723. char *zName = 0; /* The name of the new table */
  724. sqlite3 *db = pParse->db;
  725. Vdbe *v;
  726. int iDb; /* Database number to create the table in */
  727. Token *pName; /* Unqualified name of the table to create */
  728. /* The table or view name to create is passed to this routine via tokens
  729. ** pName1 and pName2. If the table name was fully qualified, for example:
  730. **
  731. ** CREATE TABLE xxx.yyy (...);
  732. **
  733. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  734. ** the table name is not fully qualified, i.e.:
  735. **
  736. ** CREATE TABLE yyy(...);
  737. **
  738. ** Then pName1 is set to "yyy" and pName2 is "".
  739. **
  740. ** The call below sets the pName pointer to point at the token (pName1 or
  741. ** pName2) that stores the unqualified table name. The variable iDb is
  742. ** set to the index of the database that the table or view is to be
  743. ** created in.
  744. */
  745. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  746. if( iDb<0 ) return;
  747. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  748. /* If creating a temp table, the name may not be qualified. Unless
  749. ** the database name is "temp" anyway. */
  750. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  751. return;
  752. }
  753. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  754. pParse->sNameToken = *pName;
  755. zName = sqlite3NameFromToken(db, pName);
  756. if( zName==0 ) return;
  757. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  758. goto begin_table_error;
  759. }
  760. if( db->init.iDb==1 ) isTemp = 1;
  761. #ifndef SQLITE_OMIT_AUTHORIZATION
  762. assert( (isTemp & 1)==isTemp );
  763. {
  764. int code;
  765. char *zDb = db->aDb[iDb].zName;
  766. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  767. goto begin_table_error;
  768. }
  769. if( isView ){
  770. if( !OMIT_TEMPDB && isTemp ){
  771. code = SQLITE_CREATE_TEMP_VIEW;
  772. }else{
  773. code = SQLITE_CREATE_VIEW;
  774. }
  775. }else{
  776. if( !OMIT_TEMPDB && isTemp ){
  777. code = SQLITE_CREATE_TEMP_TABLE;
  778. }else{
  779. code = SQLITE_CREATE_TABLE;
  780. }
  781. }
  782. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  783. goto begin_table_error;
  784. }
  785. }
  786. #endif
  787. /* Make sure the new table name does not collide with an existing
  788. ** index or table name in the same database. Issue an error message if
  789. ** it does. The exception is if the statement being parsed was passed
  790. ** to an sqlite3_declare_vtab() call. In that case only the column names
  791. ** and types will be used, so there is no need to test for namespace
  792. ** collisions.
  793. */
  794. if( !IN_DECLARE_VTAB ){
  795. char *zDb = db->aDb[iDb].zName;
  796. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  797. goto begin_table_error;
  798. }
  799. pTable = sqlite3FindTable(db, zName, zDb);
  800. if( pTable ){
  801. if( !noErr ){
  802. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  803. }else{
  804. assert( !db->init.busy );
  805. sqlite3CodeVerifySchema(pParse, iDb);
  806. }
  807. goto begin_table_error;
  808. }
  809. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  810. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  811. goto begin_table_error;
  812. }
  813. }
  814. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  815. if( pTable==0 ){
  816. db->mallocFailed = 1;
  817. pParse->rc = SQLITE_NOMEM;
  818. pParse->nErr++;
  819. goto begin_table_error;
  820. }
  821. pTable->zName = zName;
  822. pTable->iPKey = -1;
  823. pTable->pSchema = db->aDb[iDb].pSchema;
  824. pTable->nRef = 1;
  825. pTable->nRowEst = 1048576;
  826. assert( pParse->pNewTable==0 );
  827. pParse->pNewTable = pTable;
  828. /* If this is the magic sqlite_sequence table used by autoincrement,
  829. ** then record a pointer to this table in the main database structure
  830. ** so that INSERT can find the table easily.
  831. */
  832. #ifndef SQLITE_OMIT_AUTOINCREMENT
  833. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  834. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  835. pTable->pSchema->pSeqTab = pTable;
  836. }
  837. #endif
  838. /* Begin generating the code that will insert the table record into
  839. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  840. ** and allocate the record number for the table entry now. Before any
  841. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  842. ** indices to be created and the table record must come before the
  843. ** indices. Hence, the record number for the table must be allocated
  844. ** now.
  845. */
  846. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  847. int j1;
  848. int fileFormat;
  849. int reg1, reg2, reg3;
  850. sqlite3BeginWriteOperation(pParse, 0, iDb);
  851. #ifndef SQLITE_OMIT_VIRTUALTABLE
  852. if( isVirtual ){
  853. sqlite3VdbeAddOp0(v, OP_VBegin);
  854. }
  855. #endif
  856. /* If the file format and encoding in the database have not been set,
  857. ** set them now.
  858. */
  859. reg1 = pParse->regRowid = ++pParse->nMem;
  860. reg2 = pParse->regRoot = ++pParse->nMem;
  861. reg3 = ++pParse->nMem;
  862. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  863. sqlite3VdbeUsesBtree(v, iDb);
  864. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  865. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  866. 1 : SQLITE_MAX_FILE_FORMAT;
  867. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  868. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  869. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  870. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  871. sqlite3VdbeJumpHere(v, j1);
  872. /* This just creates a place-holder record in the sqlite_master table.
  873. ** The record created does not contain anything yet. It will be replaced
  874. ** by the real entry in code generated at sqlite3EndTable().
  875. **
  876. ** The rowid for the new entry is left in register pParse->regRowid.
  877. ** The root page number of the new table is left in reg pParse->regRoot.
  878. ** The rowid and root page number values are needed by the code that
  879. ** sqlite3EndTable will generate.
  880. */
  881. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  882. if( isView || isVirtual ){
  883. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  884. }else
  885. #endif
  886. {
  887. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  888. }
  889. sqlite3OpenMasterTable(pParse, iDb);
  890. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  891. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  892. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  893. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  894. sqlite3VdbeAddOp0(v, OP_Close);
  895. }
  896. /* Normal (non-error) return. */
  897. return;
  898. /* If an error occurs, we jump here */
  899. begin_table_error:
  900. sqlite3DbFree(db, zName);
  901. return;
  902. }
  903. /*
  904. ** This macro is used to compare two strings in a case-insensitive manner.
  905. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  906. ** produces larger code.
  907. **
  908. ** WARNING: This macro is not compatible with the strcmp() family. It
  909. ** returns true if the two strings are equal, otherwise false.
  910. */
  911. #define STRICMP(x, y) (\
  912. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  913. sqlite3UpperToLower[*(unsigned char *)(y)] \
  914. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  915. /*
  916. ** Add a new column to the table currently being constructed.
  917. **
  918. ** The parser calls this routine once for each column declaration
  919. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  920. ** first to get things going. Then this routine is called for each
  921. ** column.
  922. */
  923. void sqlite3AddColumn(Parse *pParse, Token *pName){
  924. Table *p;
  925. int i;
  926. char *z;
  927. Column *pCol;
  928. sqlite3 *db = pParse->db;
  929. if( (p = pParse->pNewTable)==0 ) return;
  930. #if SQLITE_MAX_COLUMN
  931. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  932. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  933. return;
  934. }
  935. #endif
  936. z = sqlite3NameFromToken(db, pName);
  937. if( z==0 ) return;
  938. for(i=0; i<p->nCol; i++){
  939. if( STRICMP(z, p->aCol[i].zName) ){
  940. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  941. sqlite3DbFree(db, z);
  942. return;
  943. }
  944. }
  945. if( (p->nCol & 0x7)==0 ){
  946. Column *aNew;
  947. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  948. if( aNew==0 ){
  949. sqlite3DbFree(db, z);
  950. return;
  951. }
  952. p->aCol = aNew;
  953. }
  954. pCol = &p->aCol[p->nCol];
  955. memset(pCol, 0, sizeof(p->aCol[0]));
  956. pCol->zName = z;
  957. /* If there is no type specified, columns have the default affinity
  958. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  959. ** be called next to set pCol->affinity correctly.
  960. */
  961. pCol->affinity = SQLITE_AFF_NONE;
  962. pCol->szEst = 1;
  963. p->nCol++;
  964. }
  965. /*
  966. ** This routine is called by the parser while in the middle of
  967. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  968. ** been seen on a column. This routine sets the notNull flag on
  969. ** the column currently under construction.
  970. */
  971. void sqlite3AddNotNull(Parse *pParse, int onError){
  972. Table *p;
  973. p = pParse->pNewTable;
  974. if( p==0 || NEVER(p->nCol<1) ) return;
  975. p->aCol[p->nCol-1].notNull = (u8)onError;
  976. }
  977. /*
  978. ** Scan the column type name zType (length nType) and return the
  979. ** associated affinity type.
  980. **
  981. ** This routine does a case-independent search of zType for the
  982. ** substrings in the following table. If one of the substrings is
  983. ** found, the corresponding affinity is returned. If zType contains
  984. ** more than one of the substrings, entries toward the top of
  985. ** the table take priority. For example, if zType is 'BLOBINT',
  986. ** SQLITE_AFF_INTEGER is returned.
  987. **
  988. ** Substring | Affinity
  989. ** --------------------------------
  990. ** 'INT' | SQLITE_AFF_INTEGER
  991. ** 'CHAR' | SQLITE_AFF_TEXT
  992. ** 'CLOB' | SQLITE_AFF_TEXT
  993. ** 'TEXT' | SQLITE_AFF_TEXT
  994. ** 'BLOB' | SQLITE_AFF_NONE
  995. ** 'REAL' | SQLITE_AFF_REAL
  996. ** 'FLOA' | SQLITE_AFF_REAL
  997. ** 'DOUB' | SQLITE_AFF_REAL
  998. **
  999. ** If none of the substrings in the above table are found,
  1000. ** SQLITE_AFF_NUMERIC is returned.
  1001. */
  1002. char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  1003. u32 h = 0;
  1004. char aff = SQLITE_AFF_NUMERIC;
  1005. const char *zChar = 0;
  1006. if( zIn==0 ) return aff;
  1007. while( zIn[0] ){
  1008. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  1009. zIn++;
  1010. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  1011. aff = SQLITE_AFF_TEXT;
  1012. zChar = zIn;
  1013. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  1014. aff = SQLITE_AFF_TEXT;
  1015. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  1016. aff = SQLITE_AFF_TEXT;
  1017. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  1018. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  1019. aff = SQLITE_AFF_NONE;
  1020. if( zIn[0]=='(' ) zChar = zIn;
  1021. #ifndef SQLITE_OMIT_FLOATING_POINT
  1022. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  1023. && aff==SQLITE_AFF_NUMERIC ){
  1024. aff = SQLITE_AFF_REAL;
  1025. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  1026. && aff==SQLITE_AFF_NUMERIC ){
  1027. aff = SQLITE_AFF_REAL;
  1028. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  1029. && aff==SQLITE_AFF_NUMERIC ){
  1030. aff = SQLITE_AFF_REAL;
  1031. #endif
  1032. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  1033. aff = SQLITE_AFF_INTEGER;
  1034. break;
  1035. }
  1036. }
  1037. /* If pszEst is not NULL, store an estimate of the field size. The
  1038. ** estimate is scaled so that the size of an integer is 1. */
  1039. if( pszEst ){
  1040. *pszEst = 1; /* default size is approx 4 bytes */
  1041. if( aff<=SQLITE_AFF_NONE ){
  1042. if( zChar ){
  1043. while( zChar[0] ){
  1044. if( sqlite3Isdigit(zChar[0]) ){
  1045. int v = 0;
  1046. sqlite3GetInt32(zChar, &v);
  1047. v = v/4 + 1;
  1048. if( v>255 ) v = 255;
  1049. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  1050. break;
  1051. }
  1052. zChar++;
  1053. }
  1054. }else{
  1055. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  1056. }
  1057. }
  1058. }
  1059. return aff;
  1060. }
  1061. /*
  1062. ** This routine is called by the parser while in the middle of
  1063. ** parsing a CREATE TABLE statement. The pFirst token is the first
  1064. ** token in the sequence of tokens that describe the type of the
  1065. ** column currently under construction. pLast is the last token
  1066. ** in the sequence. Use this information to construct a string
  1067. ** that contains the typename of the column and store that string
  1068. ** in zType.
  1069. */
  1070. void sqlite3AddColumnType(Parse *pParse, Token *pType){
  1071. Table *p;
  1072. Column *pCol;
  1073. p = pParse->pNewTable;
  1074. if( p==0 || NEVER(p->nCol<1) ) return;
  1075. pCol = &p->aCol[p->nCol-1];
  1076. assert( pCol->zType==0 );
  1077. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  1078. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  1079. }
  1080. /*
  1081. ** The expression is the default value for the most recently added column
  1082. ** of the table currently under construction.
  1083. **
  1084. ** Default value expressions must be constant. Raise an exception if this
  1085. ** is not the case.
  1086. **
  1087. ** This routine is called by the parser while in the middle of
  1088. ** parsing a CREATE TABLE statement.
  1089. */
  1090. void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  1091. Table *p;
  1092. Column *pCol;
  1093. sqlite3 *db = pParse->db;
  1094. p = pParse->pNewTable;
  1095. if( p!=0 ){
  1096. pCol = &(p->aCol[p->nCol-1]);
  1097. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  1098. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  1099. pCol->zName);
  1100. }else{
  1101. /* A copy of pExpr is used instead of the original, as pExpr contains
  1102. ** tokens that point to volatile memory. The 'span' of the expression
  1103. ** is required by pragma table_info.
  1104. */
  1105. sqlite3ExprDelete(db, pCol->pDflt);
  1106. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  1107. sqlite3DbFree(db, pCol->zDflt);
  1108. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  1109. (int)(pSpan->zEnd - pSpan->zStart));
  1110. }
  1111. }
  1112. sqlite3ExprDelete(db, pSpan->pExpr);
  1113. }
  1114. /*
  1115. ** Designate the PRIMARY KEY for the table. pList is a list of names
  1116. ** of columns that form the primary key. If pList is NULL, then the
  1117. ** most recently added column of the table is the primary key.
  1118. **
  1119. ** A table can have at most one primary key. If the table already has
  1120. ** a primary key (and this is the second primary key) then create an
  1121. ** error.
  1122. **
  1123. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  1124. ** then we will try to use that column as the rowid. Set the Table.iPKey
  1125. ** field of the table under construction to be the index of the
  1126. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  1127. ** no INTEGER PRIMARY KEY.
  1128. **
  1129. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  1130. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  1131. */
  1132. void sqlite3AddPrimaryKey(
  1133. Parse *pParse, /* Parsing context */
  1134. ExprList *pList, /* List of field names to be indexed */
  1135. int onError, /* What to do with a uniqueness conflict */
  1136. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  1137. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  1138. ){
  1139. Table *pTab = pParse->pNewTable;
  1140. char *zType = 0;
  1141. int iCol = -1, i;
  1142. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  1143. if( pTab->tabFlags & TF_HasPrimaryKey ){
  1144. sqlite3ErrorMsg(pParse,
  1145. "table \"%s\" has more than one primary key", pTab->zName);
  1146. goto primary_key_exit;
  1147. }
  1148. pTab->tabFlags |= TF_HasPrimaryKey;
  1149. if( pList==0 ){
  1150. iCol = pTab->nCol - 1;
  1151. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  1152. }else{
  1153. for(i=0; i<pList->nExpr; i++){
  1154. for(iCol=0; iCol<pTab->nCol; iCol++){
  1155. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  1156. break;
  1157. }
  1158. }
  1159. if( iCol<pTab->nCol ){
  1160. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  1161. }
  1162. }
  1163. if( pList->nExpr>1 ) iCol = -1;
  1164. }
  1165. if( iCol>=0 && iCol<pTab->nCol ){
  1166. zType = pTab->aCol[iCol].zType;
  1167. }
  1168. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  1169. && sortOrder==SQLITE_SO_ASC ){
  1170. pTab->iPKey = iCol;
  1171. pTab->keyConf = (u8)onError;
  1172. assert( autoInc==0 || autoInc==1 );
  1173. pTab->tabFlags |= autoInc*TF_Autoincrement;
  1174. }else if( autoInc ){
  1175. #ifndef SQLITE_OMIT_AUTOINCREMENT
  1176. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  1177. "INTEGER PRIMARY KEY");
  1178. #endif
  1179. }else{
  1180. Index *p;
  1181. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  1182. 0, sortOrder, 0);
  1183. if( p ){
  1184. p->autoIndex = 2;
  1185. }
  1186. pList = 0;
  1187. }
  1188. primary_key_exit:
  1189. sqlite3ExprListDelete(pParse->db, pList);
  1190. return;
  1191. }
  1192. /*
  1193. ** Add a new CHECK constraint to the table currently under construction.
  1194. */
  1195. void sqlite3AddCheckConstraint(
  1196. Parse *pParse, /* Parsing context */
  1197. Expr *pCheckExpr /* The check expression */
  1198. ){
  1199. #ifndef SQLITE_OMIT_CHECK
  1200. Table *pTab = pParse->pNewTable;
  1201. if( pTab && !IN_DECLARE_VTAB ){
  1202. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  1203. if( pParse->constraintName.n ){
  1204. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  1205. }
  1206. }else
  1207. #endif
  1208. {
  1209. sqlite3ExprDelete(pParse->db, pCheckExpr);
  1210. }
  1211. }
  1212. /*
  1213. ** Set the collation function of the most recently parsed table column
  1214. ** to the CollSeq given.
  1215. */
  1216. void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  1217. Table *p;
  1218. int i;
  1219. char *zColl; /* Dequoted name of collation sequence */
  1220. sqlite3 *db;
  1221. if( (p = pParse->pNewTable)==0 ) return;
  1222. i = p->nCol-1;
  1223. db = pParse->db;
  1224. zColl = sqlite3NameFromToken(db, pToken);
  1225. if( !zColl ) return;
  1226. if( sqlite3LocateCollSeq(pParse, zColl) ){
  1227. Index *pIdx;
  1228. sqlite3DbFree(db, p->aCol[i].zColl);
  1229. p->aCol[i].zColl = zColl;
  1230. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  1231. ** then an index may have been created on this column before the
  1232. ** collation type was added. Correct this if it is the case.
  1233. */
  1234. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  1235. assert( pIdx->nColumn==1 );
  1236. if( pIdx->aiColumn[0]==i ){
  1237. pIdx->azColl[0] = p->aCol[i].zColl;
  1238. }
  1239. }
  1240. }else{
  1241. sqlite3DbFree(db, zColl);
  1242. }
  1243. }
  1244. /*
  1245. ** This function returns the collation sequence for database native text
  1246. ** encoding identified by the string zName, length nName.
  1247. **
  1248. ** If the requested collation sequence is not available, or not available
  1249. ** in the database native encoding, the collation factory is invoked to
  1250. ** request it. If the collation factory does not supply such a sequence,
  1251. ** and the sequence is available in another text encoding, then that is
  1252. ** returned instead.
  1253. **
  1254. ** If no versions of the requested collations sequence are available, or
  1255. ** another error occurs, NULL is returned and an error message written into
  1256. ** pParse.
  1257. **
  1258. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  1259. ** invokes the collation factory if the named collation cannot be found
  1260. ** and generates an error message.
  1261. **
  1262. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  1263. */
  1264. CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  1265. sqlite3 *db = pParse->db;
  1266. u8 enc = ENC(db);
  1267. u8 initbusy = db->init.busy;
  1268. CollSeq *pColl;
  1269. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  1270. if( !initbusy && (!pColl || !pColl->xCmp) ){
  1271. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  1272. }
  1273. return pColl;
  1274. }
  1275. /*
  1276. ** Generate code that will increment the schema cookie.
  1277. **
  1278. ** The schema cookie is used to determine when the schema for the
  1279. ** database changes. After each schema change, the cookie value
  1280. ** changes. When a process first reads the schema it records the
  1281. ** cookie. Thereafter, whenever it goes to access the database,
  1282. ** it checks the cookie to make sure the schema has not changed
  1283. ** since it was last read.
  1284. **
  1285. ** This plan is not completely bullet-proof. It is possible for
  1286. ** the schema to change multiple times and for the cookie to be
  1287. ** set back to prior value. But schema changes are infrequent
  1288. ** and the probability of hitting the same cookie value is only
  1289. ** 1 chance in 2^32. So we're safe enough.
  1290. */
  1291. void sqlite3ChangeCookie(Parse *pParse, int iDb){
  1292. int r1 = sqlite3GetTempReg(pParse);
  1293. sqlite3 *db = pParse->db;
  1294. Vdbe *v = pParse->pVdbe;
  1295. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1296. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  1297. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  1298. sqlite3ReleaseTempReg(pParse, r1);
  1299. }
  1300. /*
  1301. ** Measure the number of characters needed to output the given
  1302. ** identifier. The number returned includes any quotes used
  1303. ** but does not include the null terminator.
  1304. **
  1305. ** The estimate is conservative. It might be larger that what is
  1306. ** really needed.
  1307. */
  1308. static int identLength(const char *z){
  1309. int n;
  1310. for(n=0; *z; n++, z++){
  1311. if( *z=='"' ){ n++; }
  1312. }
  1313. return n + 2;
  1314. }
  1315. /*
  1316. ** The first parameter is a pointer to an output buffer. The second
  1317. ** parameter is a pointer to an integer that contains the offset at
  1318. ** which to write into the output buffer. This function copies the
  1319. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  1320. ** to the specified offset in the buffer and updates *pIdx to refer
  1321. ** to the first byte after the last byte written before returning.
  1322. **
  1323. ** If the string zSignedIdent consists entirely of alpha-numeric
  1324. ** characters, does not begin with a digit and is not an SQL keyword,
  1325. ** then it is copied to the output buffer exactly as it is. Otherwise,
  1326. ** it is quoted using double-quotes.
  1327. */
  1328. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  1329. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  1330. int i, j, needQuote;
  1331. i = *pIdx;
  1332. for(j=0; zIdent[j]; j++){
  1333. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  1334. }
  1335. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  1336. if( !needQuote ){
  1337. needQuote = zIdent[j];
  1338. }
  1339. if( needQuote ) z[i++] = '"';
  1340. for(j=0; zIdent[j]; j++){
  1341. z[i++] = zIdent[j];
  1342. if( zIdent[j]=='"' ) z[i++] = '"';
  1343. }
  1344. if( needQuote ) z[i++] = '"';
  1345. z[i] = 0;
  1346. *pIdx = i;
  1347. }
  1348. /*
  1349. ** Generate a CREATE TABLE statement appropriate for the given
  1350. ** table. Memory to hold the text of the statement is obtained
  1351. ** from sqliteMalloc() and must be freed by the calling function.
  1352. */
  1353. static char *createTableStmt(sqlite3 *db, Table *p){
  1354. int i, k, n;
  1355. char *zStmt;
  1356. char *zSep, *zSep2, *zEnd;
  1357. Column *pCol;
  1358. n = 0;
  1359. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  1360. n += identLength(pCol->zName) + 5;
  1361. }
  1362. n += identLength(p->zName);
  1363. if( n<50 ){
  1364. zSep = "";
  1365. zSep2 = ",";
  1366. zEnd = ")";
  1367. }else{
  1368. zSep = "\n ";
  1369. zSep2 = ",\n ";
  1370. zEnd = "\n)";
  1371. }
  1372. n += 35 + 6*p->nCol;
  1373. zStmt = sqlite3DbMallocRaw(0, n);
  1374. if( zStmt==0 ){
  1375. db->mallocFailed = 1;
  1376. return 0;
  1377. }
  1378. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  1379. k = sqlite3Strlen30(zStmt);
  1380. identPut(zStmt, &k, p->zName);
  1381. zStmt[k++] = '(';
  1382. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  1383. static const char * const azType[] = {
  1384. /* SQLITE_AFF_TEXT */ " TEXT",
  1385. /* SQLITE_AFF_NONE */ "",
  1386. /* SQLITE_AFF_NUMERIC */ " NUM",
  1387. /* SQLITE_AFF_INTEGER */ " INT",
  1388. /* SQLITE_AFF_REAL */ " REAL"
  1389. };
  1390. int len;
  1391. const char *zType;
  1392. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  1393. k += sqlite3Strlen30(&zStmt[k]);
  1394. zSep = zSep2;
  1395. identPut(zStmt, &k, pCol->zName);
  1396. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  1397. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  1398. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  1399. testcase( pCol->affinity==SQLITE_AFF_NONE );
  1400. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  1401. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  1402. testcase( pCol->affinity==SQLITE_AFF_REAL );
  1403. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  1404. len = sqlite3Strlen30(zType);
  1405. assert( pCol->affinity==SQLITE_AFF_NONE
  1406. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  1407. memcpy(&zStmt[k], zType, len);
  1408. k += len;
  1409. assert( k<=n );
  1410. }
  1411. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  1412. return zStmt;
  1413. }
  1414. /*
  1415. ** Estimate the total row width for a table.
  1416. */
  1417. static void estimateTableWidth(Table *pTab){
  1418. unsigned wTable = 0;
  1419. const Column *pTabCol;
  1420. int i;
  1421. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  1422. wTable += pTabCol->szEst;
  1423. }
  1424. if( pTab->iPKey<0 ) wTable++;
  1425. pTab->szTabRow = sqlite3LogEst(wTable*4);
  1426. }
  1427. /*
  1428. ** Estimate the average size of a row for an index.
  1429. */
  1430. static void estimateIndexWidth(Index *pIdx){
  1431. unsigned wIndex = 1;
  1432. int i;
  1433. const Column *aCol = pIdx->pTable->aCol;
  1434. for(i=0; i<pIdx->nColumn; i++){
  1435. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  1436. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  1437. }
  1438. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  1439. }
  1440. /*
  1441. ** This routine is called to report the final ")" that terminates
  1442. ** a CREATE TABLE statement.
  1443. **
  1444. ** The table structure that other action routines have been building
  1445. ** is added to the internal hash tables, assuming no errors have
  1446. ** occurred.
  1447. **
  1448. ** An entry for the table is made in the master table on disk, unless
  1449. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  1450. ** it means we are reading the sqlite_master table because we just
  1451. ** connected to the database or because the sqlite_master table has
  1452. ** recently changed, so the entry for this table already exists in
  1453. ** the sqlite_master table. We do not want to create it again.
  1454. **
  1455. ** If the pSelect argument is not NULL, it means that this routine
  1456. ** was called to create a table generated from a
  1457. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  1458. ** the new table will match the result set of the SELECT.
  1459. */
  1460. void sqlite3EndTable(
  1461. Parse *pParse, /* Parse context */
  1462. Token *pCons, /* The ',' token after the last column defn. */
  1463. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  1464. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  1465. ){
  1466. Table *p; /* The new table */
  1467. sqlite3 *db = pParse->db; /* The database connection */
  1468. int iDb; /* Database in which the table lives */
  1469. Index *pIdx; /* An implied index of the table */
  1470. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  1471. return;
  1472. }
  1473. p = pParse->pNewTable;
  1474. if( p==0 ) return;
  1475. assert( !db->init.busy || !pSelect );
  1476. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1477. #ifndef SQLITE_OMIT_CHECK
  1478. /* Resolve names in all CHECK constraint expressions.
  1479. */
  1480. if( p->pCheck ){
  1481. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  1482. }
  1483. #endif /* !defined(SQLITE_OMIT_CHECK) */
  1484. /* Estimate the average row size for the table and for all implied indices */
  1485. estimateTableWidth(p);
  1486. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  1487. estimateIndexWidth(pIdx);
  1488. }
  1489. /* If the db->init.busy is 1 it means we are reading the SQL off the
  1490. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1491. ** So do not write to the disk again. Extract the root page number
  1492. ** for the table from the db->init.newTnum field. (The page number
  1493. ** should have been put there by the sqliteOpenCb routine.)
  1494. */
  1495. if( db->init.busy ){
  1496. p->tnum = db->init.newTnum;
  1497. }
  1498. /* If not initializing, then create a record for the new table
  1499. ** in the SQLITE_MASTER table of the database.
  1500. **
  1501. ** If this is a TEMPORARY table, write the entry into the auxiliary
  1502. ** file instead of into the main database file.
  1503. */
  1504. if( !db->init.busy ){
  1505. int n;
  1506. Vdbe *v;
  1507. char *zType; /* "view" or "table" */
  1508. char *zType2; /* "VIEW" or "TABLE" */
  1509. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  1510. v = sqlite3GetVdbe(pParse);
  1511. if( NEVER(v==0) ) return;
  1512. sqlite3VdbeAddOp1(v, OP_Close, 0);
  1513. /*
  1514. ** Initialize zType for the new view or table.
  1515. */
  1516. if( p->pSelect==0 ){
  1517. /* A regular table */
  1518. zType = "table";
  1519. zType2 = "TABLE";
  1520. #ifndef SQLITE_OMIT_VIEW
  1521. }else{
  1522. /* A view */
  1523. zType = "view";
  1524. zType2 = "VIEW";
  1525. #endif
  1526. }
  1527. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  1528. ** statement to populate the new table. The root-page number for the
  1529. ** new table is in register pParse->regRoot.
  1530. **
  1531. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  1532. ** suitable state to query for the column names and types to be used
  1533. ** by the new table.
  1534. **
  1535. ** A shared-cache write-lock is not required to write to the new table,
  1536. ** as a schema-lock must have already been obtained to create it. Since
  1537. ** a schema-lock excludes all other database users, the write-lock would
  1538. ** be redundant.
  1539. */
  1540. if( pSelect ){
  1541. SelectDest dest;
  1542. Table *pSelTab;
  1543. assert(pParse->nTab==1);
  1544. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  1545. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  1546. pParse->nTab = 2;
  1547. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  1548. sqlite3Select(pParse, pSelect, &dest);
  1549. sqlite3VdbeAddOp1(v, OP_Close, 1);
  1550. if( pParse->nErr==0 ){
  1551. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  1552. if( pSelTab==0 ) return;
  1553. assert( p->aCol==0 );
  1554. p->nCol = pSelTab->nCol;
  1555. p->aCol = pSelTab->aCol;
  1556. pSelTab->nCol = 0;
  1557. pSelTab->aCol = 0;
  1558. sqlite3DeleteTable(db, pSelTab);
  1559. }
  1560. }
  1561. /* Compute the complete text of the CREATE statement */
  1562. if( pSelect ){
  1563. zStmt = createTableStmt(db, p);
  1564. }else{
  1565. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  1566. zStmt = sqlite3MPrintf(db,
  1567. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  1568. );
  1569. }
  1570. /* A slot for the record has already been allocated in the
  1571. ** SQLITE_MASTER table. We just need to update that slot with all
  1572. ** the information we've collected.
  1573. */
  1574. sqlite3NestedParse(pParse,
  1575. "UPDATE %Q.%s "
  1576. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  1577. "WHERE rowid=#%d",
  1578. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1579. zType,
  1580. p->zName,
  1581. p->zName,
  1582. pParse->regRoot,
  1583. zStmt,
  1584. pParse->regRowid
  1585. );
  1586. sqlite3DbFree(db, zStmt);
  1587. sqlite3ChangeCookie(pParse, iDb);
  1588. #ifndef SQLITE_OMIT_AUTOINCREMENT
  1589. /* Check to see if we need to create an sqlite_sequence table for
  1590. ** keeping track of autoincrement keys.
  1591. */
  1592. if( p->tabFlags & TF_Autoincrement ){
  1593. Db *pDb = &db->aDb[iDb];
  1594. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1595. if( pDb->pSchema->pSeqTab==0 ){
  1596. sqlite3NestedParse(pParse,
  1597. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  1598. pDb->zName
  1599. );
  1600. }
  1601. }
  1602. #endif
  1603. /* Reparse everything to update our internal data structures */
  1604. sqlite3VdbeAddParseSchemaOp(v, iDb,
  1605. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  1606. }
  1607. /* Add the table to the in-memory representation of the database.
  1608. */
  1609. if( db->init.busy ){
  1610. Table *pOld;
  1611. Schema *pSchema = p->pSchema;
  1612. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1613. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  1614. sqlite3Strlen30(p->zName),p);
  1615. if( pOld ){
  1616. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  1617. db->mallocFailed = 1;
  1618. return;
  1619. }
  1620. pParse->pNewTable = 0;
  1621. db->flags |= SQLITE_InternChanges;
  1622. #ifndef SQLITE_OMIT_ALTERTABLE
  1623. if( !p->pSelect ){
  1624. const char *zName = (const char *)pParse->sNameToken.z;
  1625. int nName;
  1626. assert( !pSelect && pCons && pEnd );
  1627. if( pCons->z==0 ){
  1628. pCons = pEnd;
  1629. }
  1630. nName = (int)((const char *)pCons->z - zName);
  1631. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  1632. }
  1633. #endif
  1634. }
  1635. }
  1636. #ifndef SQLITE_OMIT_VIEW
  1637. /*
  1638. ** The parser calls this routine in order to create a new VIEW
  1639. */
  1640. void sqlite3CreateView(
  1641. Parse *pParse, /* The parsing context */
  1642. Token *pBegin, /* The CREATE token that begins the statement */
  1643. Token *pName1, /* The token that holds the name of the view */
  1644. Token *pName2, /* The token that holds the name of the view */
  1645. Select *pSelect, /* A SELECT statement that will become the new view */
  1646. int isTemp, /* TRUE for a TEMPORARY view */
  1647. int noErr /* Suppress error messages if VIEW already exists */
  1648. ){
  1649. Table *p;
  1650. int n;
  1651. const char *z;
  1652. Token sEnd;
  1653. DbFixer sFix;
  1654. Token *pName = 0;
  1655. int iDb;
  1656. sqlite3 *db = pParse->db;
  1657. if( pParse->nVar>0 ){
  1658. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  1659. sqlite3SelectDelete(db, pSelect);
  1660. return;
  1661. }
  1662. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  1663. p = pParse->pNewTable;
  1664. if( p==0 || pParse->nErr ){
  1665. sqlite3SelectDelete(db, pSelect);
  1666. return;
  1667. }
  1668. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  1669. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1670. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  1671. if( sqlite3FixSelect(&sFix, pSelect) ){
  1672. sqlite3SelectDelete(db, pSelect);
  1673. return;
  1674. }
  1675. /* Make a copy of the entire SELECT statement that defines the view.
  1676. ** This will force all the Expr.token.z values to be dynamically
  1677. ** allocated rather than point to the input string - which means that
  1678. ** they will persist after the current sqlite3_exec() call returns.
  1679. */
  1680. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  1681. sqlite3SelectDelete(db, pSelect);
  1682. if( db->mallocFailed ){
  1683. return;
  1684. }
  1685. if( !db->init.busy ){
  1686. sqlite3ViewGetColumnNames(pParse, p);
  1687. }
  1688. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  1689. ** the end.
  1690. */
  1691. sEnd = pParse->sLastToken;
  1692. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  1693. sEnd.z += sEnd.n;
  1694. }
  1695. sEnd.n = 0;
  1696. n = (int)(sEnd.z - pBegin->z);
  1697. z = pBegin->z;
  1698. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  1699. sEnd.z = &z[n-1];
  1700. sEnd.n = 1;
  1701. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  1702. sqlite3EndTable(pParse, 0, &sEnd, 0);
  1703. return;
  1704. }
  1705. #endif /* SQLITE_OMIT_VIEW */
  1706. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  1707. /*
  1708. ** The Table structure pTable is really a VIEW. Fill in the names of
  1709. ** the columns of the view in the pTable structure. Return the number
  1710. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  1711. */
  1712. int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  1713. Table *pSelTab; /* A fake table from which we get the result set */
  1714. Select *pSel; /* Copy of the SELECT that implements the view */
  1715. int nErr = 0; /* Number of errors encountered */
  1716. int n; /* Temporarily holds the number of cursors assigned */
  1717. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  1718. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  1719. assert( pTable );
  1720. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1721. if( sqlite3VtabCallConnect(pParse, pTable) ){
  1722. return SQLITE_ERROR;
  1723. }
  1724. if( IsVirtual(pTable) ) return 0;
  1725. #endif
  1726. #ifndef SQLITE_OMIT_VIEW
  1727. /* A positive nCol means the columns names for this view are
  1728. ** already known.
  1729. */
  1730. if( pTable->nCol>0 ) return 0;
  1731. /* A negative nCol is a special marker meaning that we are currently
  1732. ** trying to compute the column names. If we enter this routine with
  1733. ** a negative nCol, it means two or more views form a loop, like this:
  1734. **
  1735. ** CREATE VIEW one AS SELECT * FROM two;
  1736. ** CREATE VIEW two AS SELECT * FROM one;
  1737. **
  1738. ** Actually, the error above is now caught prior to reaching this point.
  1739. ** But the following test is still important as it does come up
  1740. ** in the following:
  1741. **
  1742. ** CREATE TABLE main.ex1(a);
  1743. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  1744. ** SELECT * FROM temp.ex1;
  1745. */
  1746. if( pTable->nCol<0 ){
  1747. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  1748. return 1;
  1749. }
  1750. assert( pTable->nCol>=0 );
  1751. /* If we get this far, it means we need to compute the table names.
  1752. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  1753. ** "*" elements in the results set of the view and will assign cursors
  1754. ** to the elements of the FROM clause. But we do not want these changes
  1755. ** to be permanent. So the computation is done on a copy of the SELECT
  1756. ** statement that defines the view.
  1757. */
  1758. assert( pTable->pSelect );
  1759. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  1760. if( pSel ){
  1761. u8 enableLookaside = db->lookaside.bEnabled;
  1762. n = pParse->nTab;
  1763. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  1764. pTable->nCol = -1;
  1765. db->lookaside.bEnabled = 0;
  1766. #ifndef SQLITE_OMIT_AUTHORIZATION
  1767. xAuth = db->xAuth;
  1768. db->xAuth = 0;
  1769. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  1770. db->xAuth = xAuth;
  1771. #else
  1772. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  1773. #endif
  1774. db->lookaside.bEnabled = enableLookaside;
  1775. pParse->nTab = n;
  1776. if( pSelTab ){
  1777. assert( pTable->aCol==0 );
  1778. pTable->nCol = pSelTab->nCol;
  1779. pTable->aCol = pSelTab->aCol;
  1780. pSelTab->nCol = 0;
  1781. pSelTab->aCol = 0;
  1782. sqlite3DeleteTable(db, pSelTab);
  1783. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  1784. pTable->pSchema->flags |= DB_UnresetViews;
  1785. }else{
  1786. pTable->nCol = 0;
  1787. nErr++;
  1788. }
  1789. sqlite3SelectDelete(db, pSel);
  1790. } else {
  1791. nErr++;
  1792. }
  1793. #endif /* SQLITE_OMIT_VIEW */
  1794. return nErr;
  1795. }
  1796. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  1797. #ifndef SQLITE_OMIT_VIEW
  1798. /*
  1799. ** Clear the column names from every VIEW in database idx.
  1800. */
  1801. static void sqliteViewResetAll(sqlite3 *db, int idx){
  1802. HashElem *i;
  1803. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  1804. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  1805. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  1806. Table *pTab = sqliteHashData(i);
  1807. if( pTab->pSelect ){
  1808. sqliteDeleteColumnNames(db, pTab);
  1809. pTab->aCol = 0;
  1810. pTab->nCol = 0;
  1811. }
  1812. }
  1813. DbClearProperty(db, idx, DB_UnresetViews);
  1814. }
  1815. #else
  1816. # define sqliteViewResetAll(A,B)
  1817. #endif /* SQLITE_OMIT_VIEW */
  1818. /*
  1819. ** This function is called by the VDBE to adjust the internal schema
  1820. ** used by SQLite when the btree layer moves a table root page. The
  1821. ** root-page of a table or index in database iDb has changed from iFrom
  1822. ** to iTo.
  1823. **
  1824. ** Ticket #1728: The symbol table might still contain information
  1825. ** on tables and/or indices that are the process of being deleted.
  1826. ** If you are unlucky, one of those deleted indices or tables might
  1827. ** have the same rootpage number as the real table or index that is
  1828. ** being moved. So we cannot stop searching after the first match
  1829. ** because the first match might be for one of the deleted indices
  1830. ** or tables and not the table/index that is actually being moved.
  1831. ** We must continue looping until all tables and indices with
  1832. ** rootpage==iFrom have been converted to have a rootpage of iTo
  1833. ** in order to be certain that we got the right one.
  1834. */
  1835. #ifndef SQLITE_OMIT_AUTOVACUUM
  1836. void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  1837. HashElem *pElem;
  1838. Hash *pHash;
  1839. Db *pDb;
  1840. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1841. pDb = &db->aDb[iDb];
  1842. pHash = &pDb->pSchema->tblHash;
  1843. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1844. Table *pTab = sqliteHashData(pElem);
  1845. if( pTab->tnum==iFrom ){
  1846. pTab->tnum = iTo;
  1847. }
  1848. }
  1849. pHash = &pDb->pSchema->idxHash;
  1850. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1851. Index *pIdx = sqliteHashData(pElem);
  1852. if( pIdx->tnum==iFrom ){
  1853. pIdx->tnum = iTo;
  1854. }
  1855. }
  1856. }
  1857. #endif
  1858. /*
  1859. ** Write code to erase the table with root-page iTable from database iDb.
  1860. ** Also write code to modify the sqlite_master table and internal schema
  1861. ** if a root-page of another table is moved by the btree-layer whilst
  1862. ** erasing iTable (this can happen with an auto-vacuum database).
  1863. */
  1864. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  1865. Vdbe *v = sqlite3GetVdbe(pParse);
  1866. int r1 = sqlite3GetTempReg(pParse);
  1867. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  1868. sqlite3MayAbort(pParse);
  1869. #ifndef SQLITE_OMIT_AUTOVACUUM
  1870. /* OP_Destroy stores an in integer r1. If this integer
  1871. ** is non-zero, then it is the root page number of a table moved to
  1872. ** location iTable. The following code modifies the sqlite_master table to
  1873. ** reflect this.
  1874. **
  1875. ** The "#NNN" in the SQL is a special constant that means whatever value
  1876. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  1877. ** token for additional information.
  1878. */
  1879. sqlite3NestedParse(pParse,
  1880. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  1881. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  1882. #endif
  1883. sqlite3ReleaseTempReg(pParse, r1);
  1884. }
  1885. /*
  1886. ** Write VDBE code to erase table pTab and all associated indices on disk.
  1887. ** Code to update the sqlite_master tables and internal schema definitions
  1888. ** in case a root-page belonging to another table is moved by the btree layer
  1889. ** is also added (this can happen with an auto-vacuum database).
  1890. */
  1891. static void destroyTable(Parse *pParse, Table *pTab){
  1892. #ifdef SQLITE_OMIT_AUTOVACUUM
  1893. Index *pIdx;
  1894. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1895. destroyRootPage(pParse, pTab->tnum, iDb);
  1896. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1897. destroyRootPage(pParse, pIdx->tnum, iDb);
  1898. }
  1899. #else
  1900. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  1901. ** is not defined), then it is important to call OP_Destroy on the
  1902. ** table and index root-pages in order, starting with the numerically
  1903. ** largest root-page number. This guarantees that none of the root-pages
  1904. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  1905. ** following were coded:
  1906. **
  1907. ** OP_Destroy 4 0
  1908. ** ...
  1909. ** OP_Destroy 5 0
  1910. **
  1911. ** and root page 5 happened to be the largest root-page number in the
  1912. ** database, then root page 5 would be moved to page 4 by the
  1913. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  1914. ** a free-list page.
  1915. */
  1916. int iTab = pTab->tnum;
  1917. int iDestroyed = 0;
  1918. while( 1 ){
  1919. Index *pIdx;
  1920. int iLargest = 0;
  1921. if( iDestroyed==0 || iTab<iDestroyed ){
  1922. iLargest = iTab;
  1923. }
  1924. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1925. int iIdx = pIdx->tnum;
  1926. assert( pIdx->pSchema==pTab->pSchema );
  1927. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  1928. iLargest = iIdx;
  1929. }
  1930. }
  1931. if( iLargest==0 ){
  1932. return;
  1933. }else{
  1934. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1935. assert( iDb>=0 && iDb<pParse->db->nDb );
  1936. destroyRootPage(pParse, iLargest, iDb);
  1937. iDestroyed = iLargest;
  1938. }
  1939. }
  1940. #endif
  1941. }
  1942. /*
  1943. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  1944. ** after a DROP INDEX or DROP TABLE command.
  1945. */
  1946. static void sqlite3ClearStatTables(
  1947. Parse *pParse, /* The parsing context */
  1948. int iDb, /* The database number */
  1949. const char *zType, /* "idx" or "tbl" */
  1950. const char *zName /* Name of index or table */
  1951. ){
  1952. int i;
  1953. const char *zDbName = pParse->db->aDb[iDb].zName;
  1954. for(i=1; i<=4; i++){
  1955. char zTab[24];
  1956. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  1957. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  1958. sqlite3NestedParse(pParse,
  1959. "DELETE FROM %Q.%s WHERE %s=%Q",
  1960. zDbName, zTab, zType, zName
  1961. );
  1962. }
  1963. }
  1964. }
  1965. /*
  1966. ** Generate code to drop a table.
  1967. */
  1968. void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  1969. Vdbe *v;
  1970. sqlite3 *db = pParse->db;
  1971. Trigger *pTrigger;
  1972. Db *pDb = &db->aDb[iDb];
  1973. v = sqlite3GetVdbe(pParse);
  1974. assert( v!=0 );
  1975. sqlite3BeginWriteOperation(pParse, 1, iDb);
  1976. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1977. if( IsVirtual(pTab) ){
  1978. sqlite3VdbeAddOp0(v, OP_VBegin);
  1979. }
  1980. #endif
  1981. /* Drop all triggers associated with the table being dropped. Code
  1982. ** is generated to remove entries from sqlite_master and/or
  1983. ** sqlite_temp_master if required.
  1984. */
  1985. pTrigger = sqlite3TriggerList(pParse, pTab);
  1986. while( pTrigger ){
  1987. assert( pTrigger->pSchema==pTab->pSchema ||
  1988. pTrigger->pSchema==db->aDb[1].pSchema );
  1989. sqlite3DropTriggerPtr(pParse, pTrigger);
  1990. pTrigger = pTrigger->pNext;
  1991. }
  1992. #ifndef SQLITE_OMIT_AUTOINCREMENT
  1993. /* Remove any entries of the sqlite_sequence table associated with
  1994. ** the table being dropped. This is done before the table is dropped
  1995. ** at the btree level, in case the sqlite_sequence table needs to
  1996. ** move as a result of the drop (can happen in auto-vacuum mode).
  1997. */
  1998. if( pTab->tabFlags & TF_Autoincrement ){
  1999. sqlite3NestedParse(pParse,
  2000. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  2001. pDb->zName, pTab->zName
  2002. );
  2003. }
  2004. #endif
  2005. /* Drop all SQLITE_MASTER table and index entries that refer to the
  2006. ** table. The program name loops through the master table and deletes
  2007. ** every row that refers to a table of the same name as the one being
  2008. ** dropped. Triggers are handled separately because a trigger can be
  2009. ** created in the temp database that refers to a table in another
  2010. ** database.
  2011. */
  2012. sqlite3NestedParse(pParse,
  2013. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  2014. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  2015. if( !isView && !IsVirtual(pTab) ){
  2016. destroyTable(pParse, pTab);
  2017. }
  2018. /* Remove the table entry from SQLite's internal schema and modify
  2019. ** the schema cookie.
  2020. */
  2021. if( IsVirtual(pTab) ){
  2022. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  2023. }
  2024. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  2025. sqlite3ChangeCookie(pParse, iDb);
  2026. sqliteViewResetAll(db, iDb);
  2027. }
  2028. /*
  2029. ** This routine is called to do the work of a DROP TABLE statement.
  2030. ** pName is the name of the table to be dropped.
  2031. */
  2032. void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  2033. Table *pTab;
  2034. Vdbe *v;
  2035. sqlite3 *db = pParse->db;
  2036. int iDb;
  2037. if( db->mallocFailed ){
  2038. goto exit_drop_table;
  2039. }
  2040. assert( pParse->nErr==0 );
  2041. assert( pName->nSrc==1 );
  2042. if( noErr ) db->suppressErr++;
  2043. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  2044. if( noErr ) db->suppressErr--;
  2045. if( pTab==0 ){
  2046. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  2047. goto exit_drop_table;
  2048. }
  2049. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2050. assert( iDb>=0 && iDb<db->nDb );
  2051. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  2052. ** it is initialized.
  2053. */
  2054. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  2055. goto exit_drop_table;
  2056. }
  2057. #ifndef SQLITE_OMIT_AUTHORIZATION
  2058. {
  2059. int code;
  2060. const char *zTab = SCHEMA_TABLE(iDb);
  2061. const char *zDb = db->aDb[iDb].zName;
  2062. const char *zArg2 = 0;
  2063. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  2064. goto exit_drop_table;
  2065. }
  2066. if( isView ){
  2067. if( !OMIT_TEMPDB && iDb==1 ){
  2068. code = SQLITE_DROP_TEMP_VIEW;
  2069. }else{
  2070. code = SQLITE_DROP_VIEW;
  2071. }
  2072. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2073. }else if( IsVirtual(pTab) ){
  2074. code = SQLITE_DROP_VTABLE;
  2075. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  2076. #endif
  2077. }else{
  2078. if( !OMIT_TEMPDB && iDb==1 ){
  2079. code = SQLITE_DROP_TEMP_TABLE;
  2080. }else{
  2081. code = SQLITE_DROP_TABLE;
  2082. }
  2083. }
  2084. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  2085. goto exit_drop_table;
  2086. }
  2087. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  2088. goto exit_drop_table;
  2089. }
  2090. }
  2091. #endif
  2092. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  2093. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  2094. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  2095. goto exit_drop_table;
  2096. }
  2097. #ifndef SQLITE_OMIT_VIEW
  2098. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  2099. ** on a table.
  2100. */
  2101. if( isView && pTab->pSelect==0 ){
  2102. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  2103. goto exit_drop_table;
  2104. }
  2105. if( !isView && pTab->pSelect ){
  2106. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  2107. goto exit_drop_table;
  2108. }
  2109. #endif
  2110. /* Generate code to remove the table from the master table
  2111. ** on disk.
  2112. */
  2113. v = sqlite3GetVdbe(pParse);
  2114. if( v ){
  2115. sqlite3BeginWriteOperation(pParse, 1, iDb);
  2116. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  2117. sqlite3FkDropTable(pParse, pName, pTab);
  2118. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  2119. }
  2120. exit_drop_table:
  2121. sqlite3SrcListDelete(db, pName);
  2122. }
  2123. /*
  2124. ** This routine is called to create a new foreign key on the table
  2125. ** currently under construction. pFromCol determines which columns
  2126. ** in the current table point to the foreign key. If pFromCol==0 then
  2127. ** connect the key to the last column inserted. pTo is the name of
  2128. ** the table referred to. pToCol is a list of tables in the other
  2129. ** pTo table that the foreign key points to. flags contains all
  2130. ** information about the conflict resolution algorithms specified
  2131. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  2132. **
  2133. ** An FKey structure is created and added to the table currently
  2134. ** under construction in the pParse->pNewTable field.
  2135. **
  2136. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  2137. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  2138. */
  2139. void sqlite3CreateForeignKey(
  2140. Parse *pParse, /* Parsing context */
  2141. ExprList *pFromCol, /* Columns in this table that point to other table */
  2142. Token *pTo, /* Name of the other table */
  2143. ExprList *pToCol, /* Columns in the other table */
  2144. int flags /* Conflict resolution algorithms. */
  2145. ){
  2146. sqlite3 *db = pParse->db;
  2147. #ifndef SQLITE_OMIT_FOREIGN_KEY
  2148. FKey *pFKey = 0;
  2149. FKey *pNextTo;
  2150. Table *p = pParse->pNewTable;
  2151. int nByte;
  2152. int i;
  2153. int nCol;
  2154. char *z;
  2155. assert( pTo!=0 );
  2156. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  2157. if( pFromCol==0 ){
  2158. int iCol = p->nCol-1;
  2159. if( NEVER(iCol<0) ) goto fk_end;
  2160. if( pToCol && pToCol->nExpr!=1 ){
  2161. sqlite3ErrorMsg(pParse, "foreign key on %s"
  2162. " should reference only one column of table %T",
  2163. p->aCol[iCol].zName, pTo);
  2164. goto fk_end;
  2165. }
  2166. nCol = 1;
  2167. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  2168. sqlite3ErrorMsg(pParse,
  2169. "number of columns in foreign key does not match the number of "
  2170. "columns in the referenced table");
  2171. goto fk_end;
  2172. }else{
  2173. nCol = pFromCol->nExpr;
  2174. }
  2175. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  2176. if( pToCol ){
  2177. for(i=0; i<pToCol->nExpr; i++){
  2178. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  2179. }
  2180. }
  2181. pFKey = sqlite3DbMallocZero(db, nByte );
  2182. if( pFKey==0 ){
  2183. goto fk_end;
  2184. }
  2185. pFKey->pFrom = p;
  2186. pFKey->pNextFrom = p->pFKey;
  2187. z = (char*)&pFKey->aCol[nCol];
  2188. pFKey->zTo = z;
  2189. memcpy(z, pTo->z, pTo->n);
  2190. z[pTo->n] = 0;
  2191. sqlite3Dequote(z);
  2192. z += pTo->n+1;
  2193. pFKey->nCol = nCol;
  2194. if( pFromCol==0 ){
  2195. pFKey->aCol[0].iFrom = p->nCol-1;
  2196. }else{
  2197. for(i=0; i<nCol; i++){
  2198. int j;
  2199. for(j=0; j<p->nCol; j++){
  2200. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  2201. pFKey->aCol[i].iFrom = j;
  2202. break;
  2203. }
  2204. }
  2205. if( j>=p->nCol ){
  2206. sqlite3ErrorMsg(pParse,
  2207. "unknown column \"%s\" in foreign key definition",
  2208. pFromCol->a[i].zName);
  2209. goto fk_end;
  2210. }
  2211. }
  2212. }
  2213. if( pToCol ){
  2214. for(i=0; i<nCol; i++){
  2215. int n = sqlite3Strlen30(pToCol->a[i].zName);
  2216. pFKey->aCol[i].zCol = z;
  2217. memcpy(z, pToCol->a[i].zName, n);
  2218. z[n] = 0;
  2219. z += n+1;
  2220. }
  2221. }
  2222. pFKey->isDeferred = 0;
  2223. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  2224. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  2225. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  2226. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  2227. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  2228. );
  2229. if( pNextTo==pFKey ){
  2230. db->mallocFailed = 1;
  2231. goto fk_end;
  2232. }
  2233. if( pNextTo ){
  2234. assert( pNextTo->pPrevTo==0 );
  2235. pFKey->pNextTo = pNextTo;
  2236. pNextTo->pPrevTo = pFKey;
  2237. }
  2238. /* Link the foreign key to the table as the last step.
  2239. */
  2240. p->pFKey = pFKey;
  2241. pFKey = 0;
  2242. fk_end:
  2243. sqlite3DbFree(db, pFKey);
  2244. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  2245. sqlite3ExprListDelete(db, pFromCol);
  2246. sqlite3ExprListDelete(db, pToCol);
  2247. }
  2248. /*
  2249. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  2250. ** clause is seen as part of a foreign key definition. The isDeferred
  2251. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  2252. ** The behavior of the most recently created foreign key is adjusted
  2253. ** accordingly.
  2254. */
  2255. void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  2256. #ifndef SQLITE_OMIT_FOREIGN_KEY
  2257. Table *pTab;
  2258. FKey *pFKey;
  2259. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  2260. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  2261. pFKey->isDeferred = (u8)isDeferred;
  2262. #endif
  2263. }
  2264. /*
  2265. ** Generate code that will erase and refill index *pIdx. This is
  2266. ** used to initialize a newly created index or to recompute the
  2267. ** content of an index in response to a REINDEX command.
  2268. **
  2269. ** if memRootPage is not negative, it means that the index is newly
  2270. ** created. The register specified by memRootPage contains the
  2271. ** root page number of the index. If memRootPage is negative, then
  2272. ** the index already exists and must be cleared before being refilled and
  2273. ** the root page number of the index is taken from pIndex->tnum.
  2274. */
  2275. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  2276. Table *pTab = pIndex->pTable; /* The table that is indexed */
  2277. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  2278. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  2279. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  2280. int addr1; /* Address of top of loop */
  2281. int addr2; /* Address to jump to for next iteration */
  2282. int tnum; /* Root page of index */
  2283. int iPartIdxLabel; /* Jump to this label to skip a row */
  2284. Vdbe *v; /* Generate code into this virtual machine */
  2285. KeyInfo *pKey; /* KeyInfo for index */
  2286. int regRecord; /* Register holding assemblied index record */
  2287. sqlite3 *db = pParse->db; /* The database connection */
  2288. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2289. #ifndef SQLITE_OMIT_AUTHORIZATION
  2290. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  2291. db->aDb[iDb].zName ) ){
  2292. return;
  2293. }
  2294. #endif
  2295. /* Require a write-lock on the table to perform this operation */
  2296. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  2297. v = sqlite3GetVdbe(pParse);
  2298. if( v==0 ) return;
  2299. if( memRootPage>=0 ){
  2300. tnum = memRootPage;
  2301. }else{
  2302. tnum = pIndex->tnum;
  2303. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  2304. }
  2305. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  2306. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  2307. (char *)pKey, P4_KEYINFO_HANDOFF);
  2308. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  2309. /* Open the sorter cursor if we are to use one. */
  2310. iSorter = pParse->nTab++;
  2311. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  2312. /* Open the table. Loop through all rows of the table, inserting index
  2313. ** records into the sorter. */
  2314. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  2315. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  2316. regRecord = sqlite3GetTempReg(pParse);
  2317. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  2318. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  2319. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  2320. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  2321. sqlite3VdbeJumpHere(v, addr1);
  2322. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  2323. if( pIndex->onError!=OE_None ){
  2324. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  2325. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  2326. addr2 = sqlite3VdbeCurrentAddr(v);
  2327. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  2328. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  2329. OE_Abort, "indexed columns are not unique", P4_STATIC
  2330. );
  2331. }else{
  2332. addr2 = sqlite3VdbeCurrentAddr(v);
  2333. }
  2334. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  2335. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  2336. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  2337. sqlite3ReleaseTempReg(pParse, regRecord);
  2338. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  2339. sqlite3VdbeJumpHere(v, addr1);
  2340. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  2341. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  2342. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  2343. }
  2344. /*
  2345. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  2346. ** and pTblList is the name of the table that is to be indexed. Both will
  2347. ** be NULL for a primary key or an index that is created to satisfy a
  2348. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  2349. ** as the table to be indexed. pParse->pNewTable is a table that is
  2350. ** currently being constructed by a CREATE TABLE statement.
  2351. **
  2352. ** pList is a list of columns to be indexed. pList will be NULL if this
  2353. ** is a primary key or unique-constraint on the most recent column added
  2354. ** to the table currently under construction.
  2355. **
  2356. ** If the index is created successfully, return a pointer to the new Index
  2357. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  2358. ** as the tables primary key (Index.autoIndex==2).
  2359. */
  2360. Index *sqlite3CreateIndex(
  2361. Parse *pParse, /* All information about this parse */
  2362. Token *pName1, /* First part of index name. May be NULL */
  2363. Token *pName2, /* Second part of index name. May be NULL */
  2364. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  2365. ExprList *pList, /* A list of columns to be indexed */
  2366. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  2367. Token *pStart, /* The CREATE token that begins this statement */
  2368. Expr *pPIWhere, /* WHERE clause for partial indices */
  2369. int sortOrder, /* Sort order of primary key when pList==NULL */
  2370. int ifNotExist /* Omit error if index already exists */
  2371. ){
  2372. Index *pRet = 0; /* Pointer to return */
  2373. Table *pTab = 0; /* Table to be indexed */
  2374. Index *pIndex = 0; /* The index to be created */
  2375. char *zName = 0; /* Name of the index */
  2376. int nName; /* Number of characters in zName */
  2377. int i, j;
  2378. Token nullId; /* Fake token for an empty ID list */
  2379. DbFixer sFix; /* For assigning database names to pTable */
  2380. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  2381. sqlite3 *db = pParse->db;
  2382. Db *pDb; /* The specific table containing the indexed database */
  2383. int iDb; /* Index of the database that is being written */
  2384. Token *pName = 0; /* Unqualified name of the index to create */
  2385. struct ExprList_item *pListItem; /* For looping over pList */
  2386. const Column *pTabCol; /* A column in the table */
  2387. int nCol; /* Number of columns */
  2388. int nExtra = 0; /* Space allocated for zExtra[] */
  2389. char *zExtra; /* Extra space after the Index object */
  2390. assert( pParse->nErr==0 ); /* Never called with prior errors */
  2391. if( db->mallocFailed || IN_DECLARE_VTAB ){
  2392. goto exit_create_index;
  2393. }
  2394. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2395. goto exit_create_index;
  2396. }
  2397. /*
  2398. ** Find the table that is to be indexed. Return early if not found.
  2399. */
  2400. if( pTblName!=0 ){
  2401. /* Use the two-part index name to determine the database
  2402. ** to search for the table. 'Fix' the table name to this db
  2403. ** before looking up the table.
  2404. */
  2405. assert( pName1 && pName2 );
  2406. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  2407. if( iDb<0 ) goto exit_create_index;
  2408. assert( pName && pName->z );
  2409. #ifndef SQLITE_OMIT_TEMPDB
  2410. /* If the index name was unqualified, check if the table
  2411. ** is a temp table. If so, set the database to 1. Do not do this
  2412. ** if initialising a database schema.
  2413. */
  2414. if( !db->init.busy ){
  2415. pTab = sqlite3SrcListLookup(pParse, pTblName);
  2416. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  2417. iDb = 1;
  2418. }
  2419. }
  2420. #endif
  2421. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  2422. if( sqlite3FixSrcList(&sFix, pTblName) ){
  2423. /* Because the parser constructs pTblName from a single identifier,
  2424. ** sqlite3FixSrcList can never fail. */
  2425. assert(0);
  2426. }
  2427. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  2428. assert( db->mallocFailed==0 || pTab==0 );
  2429. if( pTab==0 ) goto exit_create_index;
  2430. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  2431. sqlite3ErrorMsg(pParse,
  2432. "cannot create a TEMP index on non-TEMP table \"%s\"",
  2433. pTab->zName);
  2434. goto exit_create_index;
  2435. }
  2436. }else{
  2437. assert( pName==0 );
  2438. assert( pStart==0 );
  2439. pTab = pParse->pNewTable;
  2440. if( !pTab ) goto exit_create_index;
  2441. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2442. }
  2443. pDb = &db->aDb[iDb];
  2444. assert( pTab!=0 );
  2445. assert( pParse->nErr==0 );
  2446. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  2447. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  2448. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  2449. goto exit_create_index;
  2450. }
  2451. #ifndef SQLITE_OMIT_VIEW
  2452. if( pTab->pSelect ){
  2453. sqlite3ErrorMsg(pParse, "views may not be indexed");
  2454. goto exit_create_index;
  2455. }
  2456. #endif
  2457. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2458. if( IsVirtual(pTab) ){
  2459. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  2460. goto exit_create_index;
  2461. }
  2462. #endif
  2463. /*
  2464. ** Find the name of the index. Make sure there is not already another
  2465. ** index or table with the same name.
  2466. **
  2467. ** Exception: If we are reading the names of permanent indices from the
  2468. ** sqlite_master table (because some other process changed the schema) and
  2469. ** one of the index names collides with the name of a temporary table or
  2470. ** index, then we will continue to process this index.
  2471. **
  2472. ** If pName==0 it means that we are
  2473. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  2474. ** own name.
  2475. */
  2476. if( pName ){
  2477. zName = sqlite3NameFromToken(db, pName);
  2478. if( zName==0 ) goto exit_create_index;
  2479. assert( pName->z!=0 );
  2480. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  2481. goto exit_create_index;
  2482. }
  2483. if( !db->init.busy ){
  2484. if( sqlite3FindTable(db, zName, 0)!=0 ){
  2485. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  2486. goto exit_create_index;
  2487. }
  2488. }
  2489. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  2490. if( !ifNotExist ){
  2491. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  2492. }else{
  2493. assert( !db->init.busy );
  2494. sqlite3CodeVerifySchema(pParse, iDb);
  2495. }
  2496. goto exit_create_index;
  2497. }
  2498. }else{
  2499. int n;
  2500. Index *pLoop;
  2501. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  2502. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  2503. if( zName==0 ){
  2504. goto exit_create_index;
  2505. }
  2506. }
  2507. /* Check for authorization to create an index.
  2508. */
  2509. #ifndef SQLITE_OMIT_AUTHORIZATION
  2510. {
  2511. const char *zDb = pDb->zName;
  2512. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  2513. goto exit_create_index;
  2514. }
  2515. i = SQLITE_CREATE_INDEX;
  2516. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  2517. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  2518. goto exit_create_index;
  2519. }
  2520. }
  2521. #endif
  2522. /* If pList==0, it means this routine was called to make a primary
  2523. ** key out of the last column added to the table under construction.
  2524. ** So create a fake list to simulate this.
  2525. */
  2526. if( pList==0 ){
  2527. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  2528. nullId.n = sqlite3Strlen30((char*)nullId.z);
  2529. pList = sqlite3ExprListAppend(pParse, 0, 0);
  2530. if( pList==0 ) goto exit_create_index;
  2531. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  2532. pList->a[0].sortOrder = (u8)sortOrder;
  2533. }
  2534. /* Figure out how many bytes of space are required to store explicitly
  2535. ** specified collation sequence names.
  2536. */
  2537. for(i=0; i<pList->nExpr; i++){
  2538. Expr *pExpr = pList->a[i].pExpr;
  2539. if( pExpr ){
  2540. assert( pExpr->op==TK_COLLATE );
  2541. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  2542. }
  2543. }
  2544. /*
  2545. ** Allocate the index structure.
  2546. */
  2547. nName = sqlite3Strlen30(zName);
  2548. nCol = pList->nExpr;
  2549. pIndex = sqlite3DbMallocZero(db,
  2550. ROUND8(sizeof(Index)) + /* Index structure */
  2551. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  2552. sizeof(char *)*nCol + /* Index.azColl */
  2553. sizeof(int)*nCol + /* Index.aiColumn */
  2554. sizeof(u8)*nCol + /* Index.aSortOrder */
  2555. nName + 1 + /* Index.zName */
  2556. nExtra /* Collation sequence names */
  2557. );
  2558. if( db->mallocFailed ){
  2559. goto exit_create_index;
  2560. }
  2561. zExtra = (char*)pIndex;
  2562. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  2563. pIndex->azColl = (char**)
  2564. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  2565. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  2566. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  2567. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  2568. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  2569. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  2570. zExtra = (char *)(&pIndex->zName[nName+1]);
  2571. memcpy(pIndex->zName, zName, nName+1);
  2572. pIndex->pTable = pTab;
  2573. pIndex->nColumn = pList->nExpr;
  2574. pIndex->onError = (u8)onError;
  2575. pIndex->uniqNotNull = onError==OE_Abort;
  2576. pIndex->autoIndex = (u8)(pName==0);
  2577. pIndex->pSchema = db->aDb[iDb].pSchema;
  2578. if( pPIWhere ){
  2579. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  2580. pIndex->pPartIdxWhere = pPIWhere;
  2581. pPIWhere = 0;
  2582. }
  2583. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  2584. /* Check to see if we should honor DESC requests on index columns
  2585. */
  2586. if( pDb->pSchema->file_format>=4 ){
  2587. sortOrderMask = -1; /* Honor DESC */
  2588. }else{
  2589. sortOrderMask = 0; /* Ignore DESC */
  2590. }
  2591. /* Scan the names of the columns of the table to be indexed and
  2592. ** load the column indices into the Index structure. Report an error
  2593. ** if any column is not found.
  2594. **
  2595. ** TODO: Add a test to make sure that the same column is not named
  2596. ** more than once within the same index. Only the first instance of
  2597. ** the column will ever be used by the optimizer. Note that using the
  2598. ** same column more than once cannot be an error because that would
  2599. ** break backwards compatibility - it needs to be a warning.
  2600. */
  2601. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  2602. const char *zColName = pListItem->zName;
  2603. int requestedSortOrder;
  2604. char *zColl; /* Collation sequence name */
  2605. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  2606. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  2607. }
  2608. if( j>=pTab->nCol ){
  2609. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  2610. pTab->zName, zColName);
  2611. pParse->checkSchema = 1;
  2612. goto exit_create_index;
  2613. }
  2614. pIndex->aiColumn[i] = j;
  2615. if( pListItem->pExpr ){
  2616. int nColl;
  2617. assert( pListItem->pExpr->op==TK_COLLATE );
  2618. zColl = pListItem->pExpr->u.zToken;
  2619. nColl = sqlite3Strlen30(zColl) + 1;
  2620. assert( nExtra>=nColl );
  2621. memcpy(zExtra, zColl, nColl);
  2622. zColl = zExtra;
  2623. zExtra += nColl;
  2624. nExtra -= nColl;
  2625. }else{
  2626. zColl = pTab->aCol[j].zColl;
  2627. if( !zColl ) zColl = "BINARY";
  2628. }
  2629. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  2630. goto exit_create_index;
  2631. }
  2632. pIndex->azColl[i] = zColl;
  2633. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  2634. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  2635. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  2636. }
  2637. sqlite3DefaultRowEst(pIndex);
  2638. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  2639. if( pTab==pParse->pNewTable ){
  2640. /* This routine has been called to create an automatic index as a
  2641. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  2642. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  2643. ** i.e. one of:
  2644. **
  2645. ** CREATE TABLE t(x PRIMARY KEY, y);
  2646. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  2647. **
  2648. ** Either way, check to see if the table already has such an index. If
  2649. ** so, don't bother creating this one. This only applies to
  2650. ** automatically created indices. Users can do as they wish with
  2651. ** explicit indices.
  2652. **
  2653. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  2654. ** (and thus suppressing the second one) even if they have different
  2655. ** sort orders.
  2656. **
  2657. ** If there are different collating sequences or if the columns of
  2658. ** the constraint occur in different orders, then the constraints are
  2659. ** considered distinct and both result in separate indices.
  2660. */
  2661. Index *pIdx;
  2662. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  2663. int k;
  2664. assert( pIdx->onError!=OE_None );
  2665. assert( pIdx->autoIndex );
  2666. assert( pIndex->onError!=OE_None );
  2667. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  2668. for(k=0; k<pIdx->nColumn; k++){
  2669. const char *z1;
  2670. const char *z2;
  2671. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  2672. z1 = pIdx->azColl[k];
  2673. z2 = pIndex->azColl[k];
  2674. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  2675. }
  2676. if( k==pIdx->nColumn ){
  2677. if( pIdx->onError!=pIndex->onError ){
  2678. /* This constraint creates the same index as a previous
  2679. ** constraint specified somewhere in the CREATE TABLE statement.
  2680. ** However the ON CONFLICT clauses are different. If both this
  2681. ** constraint and the previous equivalent constraint have explicit
  2682. ** ON CONFLICT clauses this is an error. Otherwise, use the
  2683. ** explicitly specified behavior for the index.
  2684. */
  2685. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  2686. sqlite3ErrorMsg(pParse,
  2687. "conflicting ON CONFLICT clauses specified", 0);
  2688. }
  2689. if( pIdx->onError==OE_Default ){
  2690. pIdx->onError = pIndex->onError;
  2691. }
  2692. }
  2693. goto exit_create_index;
  2694. }
  2695. }
  2696. }
  2697. /* Link the new Index structure to its table and to the other
  2698. ** in-memory database structures.
  2699. */
  2700. if( db->init.busy ){
  2701. Index *p;
  2702. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  2703. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  2704. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  2705. pIndex);
  2706. if( p ){
  2707. assert( p==pIndex ); /* Malloc must have failed */
  2708. db->mallocFailed = 1;
  2709. goto exit_create_index;
  2710. }
  2711. db->flags |= SQLITE_InternChanges;
  2712. if( pTblName!=0 ){
  2713. pIndex->tnum = db->init.newTnum;
  2714. }
  2715. }
  2716. /* If the db->init.busy is 0 then create the index on disk. This
  2717. ** involves writing the index into the master table and filling in the
  2718. ** index with the current table contents.
  2719. **
  2720. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  2721. ** command. db->init.busy is 1 when a database is opened and
  2722. ** CREATE INDEX statements are read out of the master table. In
  2723. ** the latter case the index already exists on disk, which is why
  2724. ** we don't want to recreate it.
  2725. **
  2726. ** If pTblName==0 it means this index is generated as a primary key
  2727. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  2728. ** has just been created, it contains no data and the index initialization
  2729. ** step can be skipped.
  2730. */
  2731. else if( pParse->nErr==0 ){
  2732. Vdbe *v;
  2733. char *zStmt;
  2734. int iMem = ++pParse->nMem;
  2735. v = sqlite3GetVdbe(pParse);
  2736. if( v==0 ) goto exit_create_index;
  2737. /* Create the rootpage for the index
  2738. */
  2739. sqlite3BeginWriteOperation(pParse, 1, iDb);
  2740. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  2741. /* Gather the complete text of the CREATE INDEX statement into
  2742. ** the zStmt variable
  2743. */
  2744. if( pStart ){
  2745. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  2746. if( pName->z[n-1]==';' ) n--;
  2747. /* A named index with an explicit CREATE INDEX statement */
  2748. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  2749. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  2750. }else{
  2751. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  2752. /* zStmt = sqlite3MPrintf(""); */
  2753. zStmt = 0;
  2754. }
  2755. /* Add an entry in sqlite_master for this index
  2756. */
  2757. sqlite3NestedParse(pParse,
  2758. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  2759. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  2760. pIndex->zName,
  2761. pTab->zName,
  2762. iMem,
  2763. zStmt
  2764. );
  2765. sqlite3DbFree(db, zStmt);
  2766. /* Fill the index with data and reparse the schema. Code an OP_Expire
  2767. ** to invalidate all pre-compiled statements.
  2768. */
  2769. if( pTblName ){
  2770. sqlite3RefillIndex(pParse, pIndex, iMem);
  2771. sqlite3ChangeCookie(pParse, iDb);
  2772. sqlite3VdbeAddParseSchemaOp(v, iDb,
  2773. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  2774. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  2775. }
  2776. }
  2777. /* When adding an index to the list of indices for a table, make
  2778. ** sure all indices labeled OE_Replace come after all those labeled
  2779. ** OE_Ignore. This is necessary for the correct constraint check
  2780. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  2781. ** UPDATE and INSERT statements.
  2782. */
  2783. if( db->init.busy || pTblName==0 ){
  2784. if( onError!=OE_Replace || pTab->pIndex==0
  2785. || pTab->pIndex->onError==OE_Replace){
  2786. pIndex->pNext = pTab->pIndex;
  2787. pTab->pIndex = pIndex;
  2788. }else{
  2789. Index *pOther = pTab->pIndex;
  2790. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  2791. pOther = pOther->pNext;
  2792. }
  2793. pIndex->pNext = pOther->pNext;
  2794. pOther->pNext = pIndex;
  2795. }
  2796. pRet = pIndex;
  2797. pIndex = 0;
  2798. }
  2799. /* Clean up before exiting */
  2800. exit_create_index:
  2801. if( pIndex ) freeIndex(db, pIndex);
  2802. sqlite3ExprDelete(db, pPIWhere);
  2803. sqlite3ExprListDelete(db, pList);
  2804. sqlite3SrcListDelete(db, pTblName);
  2805. sqlite3DbFree(db, zName);
  2806. return pRet;
  2807. }
  2808. /*
  2809. ** Fill the Index.aiRowEst[] array with default information - information
  2810. ** to be used when we have not run the ANALYZE command.
  2811. **
  2812. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  2813. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  2814. ** number of rows in the table that match any particular value of the
  2815. ** first column of the index. aiRowEst[2] is an estimate of the number
  2816. ** of rows that match any particular combiniation of the first 2 columns
  2817. ** of the index. And so forth. It must always be the case that
  2818. *
  2819. ** aiRowEst[N]<=aiRowEst[N-1]
  2820. ** aiRowEst[N]>=1
  2821. **
  2822. ** Apart from that, we have little to go on besides intuition as to
  2823. ** how aiRowEst[] should be initialized. The numbers generated here
  2824. ** are based on typical values found in actual indices.
  2825. */
  2826. void sqlite3DefaultRowEst(Index *pIdx){
  2827. tRowcnt *a = pIdx->aiRowEst;
  2828. int i;
  2829. tRowcnt n;
  2830. assert( a!=0 );
  2831. a[0] = pIdx->pTable->nRowEst;
  2832. if( a[0]<10 ) a[0] = 10;
  2833. n = 10;
  2834. for(i=1; i<=pIdx->nColumn; i++){
  2835. a[i] = n;
  2836. if( n>5 ) n--;
  2837. }
  2838. if( pIdx->onError!=OE_None ){
  2839. a[pIdx->nColumn] = 1;
  2840. }
  2841. }
  2842. /*
  2843. ** This routine will drop an existing named index. This routine
  2844. ** implements the DROP INDEX statement.
  2845. */
  2846. void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  2847. Index *pIndex;
  2848. Vdbe *v;
  2849. sqlite3 *db = pParse->db;
  2850. int iDb;
  2851. assert( pParse->nErr==0 ); /* Never called with prior errors */
  2852. if( db->mallocFailed ){
  2853. goto exit_drop_index;
  2854. }
  2855. assert( pName->nSrc==1 );
  2856. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2857. goto exit_drop_index;
  2858. }
  2859. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  2860. if( pIndex==0 ){
  2861. if( !ifExists ){
  2862. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  2863. }else{
  2864. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  2865. }
  2866. pParse->checkSchema = 1;
  2867. goto exit_drop_index;
  2868. }
  2869. if( pIndex->autoIndex ){
  2870. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  2871. "or PRIMARY KEY constraint cannot be dropped", 0);
  2872. goto exit_drop_index;
  2873. }
  2874. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2875. #ifndef SQLITE_OMIT_AUTHORIZATION
  2876. {
  2877. int code = SQLITE_DROP_INDEX;
  2878. Table *pTab = pIndex->pTable;
  2879. const char *zDb = db->aDb[iDb].zName;
  2880. const char *zTab = SCHEMA_TABLE(iDb);
  2881. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  2882. goto exit_drop_index;
  2883. }
  2884. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  2885. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  2886. goto exit_drop_index;
  2887. }
  2888. }
  2889. #endif
  2890. /* Generate code to remove the index and from the master table */
  2891. v = sqlite3GetVdbe(pParse);
  2892. if( v ){
  2893. sqlite3BeginWriteOperation(pParse, 1, iDb);
  2894. sqlite3NestedParse(pParse,
  2895. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  2896. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  2897. );
  2898. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  2899. sqlite3ChangeCookie(pParse, iDb);
  2900. destroyRootPage(pParse, pIndex->tnum, iDb);
  2901. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  2902. }
  2903. exit_drop_index:
  2904. sqlite3SrcListDelete(db, pName);
  2905. }
  2906. /*
  2907. ** pArray is a pointer to an array of objects. Each object in the
  2908. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  2909. ** to extend the array so that there is space for a new object at the end.
  2910. **
  2911. ** When this function is called, *pnEntry contains the current size of
  2912. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  2913. ** in total).
  2914. **
  2915. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  2916. ** space allocated for the new object is zeroed, *pnEntry updated to
  2917. ** reflect the new size of the array and a pointer to the new allocation
  2918. ** returned. *pIdx is set to the index of the new array entry in this case.
  2919. **
  2920. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  2921. ** unchanged and a copy of pArray returned.
  2922. */
  2923. void *sqlite3ArrayAllocate(
  2924. sqlite3 *db, /* Connection to notify of malloc failures */
  2925. void *pArray, /* Array of objects. Might be reallocated */
  2926. int szEntry, /* Size of each object in the array */
  2927. int *pnEntry, /* Number of objects currently in use */
  2928. int *pIdx /* Write the index of a new slot here */
  2929. ){
  2930. char *z;
  2931. int n = *pnEntry;
  2932. if( (n & (n-1))==0 ){
  2933. int sz = (n==0) ? 1 : 2*n;
  2934. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  2935. if( pNew==0 ){
  2936. *pIdx = -1;
  2937. return pArray;
  2938. }
  2939. pArray = pNew;
  2940. }
  2941. z = (char*)pArray;
  2942. memset(&z[n * szEntry], 0, szEntry);
  2943. *pIdx = n;
  2944. ++*pnEntry;
  2945. return pArray;
  2946. }
  2947. /*
  2948. ** Append a new element to the given IdList. Create a new IdList if
  2949. ** need be.
  2950. **
  2951. ** A new IdList is returned, or NULL if malloc() fails.
  2952. */
  2953. IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  2954. int i;
  2955. if( pList==0 ){
  2956. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  2957. if( pList==0 ) return 0;
  2958. }
  2959. pList->a = sqlite3ArrayAllocate(
  2960. db,
  2961. pList->a,
  2962. sizeof(pList->a[0]),
  2963. &pList->nId,
  2964. &i
  2965. );
  2966. if( i<0 ){
  2967. sqlite3IdListDelete(db, pList);
  2968. return 0;
  2969. }
  2970. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  2971. return pList;
  2972. }
  2973. /*
  2974. ** Delete an IdList.
  2975. */
  2976. void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  2977. int i;
  2978. if( pList==0 ) return;
  2979. for(i=0; i<pList->nId; i++){
  2980. sqlite3DbFree(db, pList->a[i].zName);
  2981. }
  2982. sqlite3DbFree(db, pList->a);
  2983. sqlite3DbFree(db, pList);
  2984. }
  2985. /*
  2986. ** Return the index in pList of the identifier named zId. Return -1
  2987. ** if not found.
  2988. */
  2989. int sqlite3IdListIndex(IdList *pList, const char *zName){
  2990. int i;
  2991. if( pList==0 ) return -1;
  2992. for(i=0; i<pList->nId; i++){
  2993. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  2994. }
  2995. return -1;
  2996. }
  2997. /*
  2998. ** Expand the space allocated for the given SrcList object by
  2999. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  3000. ** New slots are zeroed.
  3001. **
  3002. ** For example, suppose a SrcList initially contains two entries: A,B.
  3003. ** To append 3 new entries onto the end, do this:
  3004. **
  3005. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  3006. **
  3007. ** After the call above it would contain: A, B, nil, nil, nil.
  3008. ** If the iStart argument had been 1 instead of 2, then the result
  3009. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  3010. ** the iStart value would be 0. The result then would
  3011. ** be: nil, nil, nil, A, B.
  3012. **
  3013. ** If a memory allocation fails the SrcList is unchanged. The
  3014. ** db->mallocFailed flag will be set to true.
  3015. */
  3016. SrcList *sqlite3SrcListEnlarge(
  3017. sqlite3 *db, /* Database connection to notify of OOM errors */
  3018. SrcList *pSrc, /* The SrcList to be enlarged */
  3019. int nExtra, /* Number of new slots to add to pSrc->a[] */
  3020. int iStart /* Index in pSrc->a[] of first new slot */
  3021. ){
  3022. int i;
  3023. /* Sanity checking on calling parameters */
  3024. assert( iStart>=0 );
  3025. assert( nExtra>=1 );
  3026. assert( pSrc!=0 );
  3027. assert( iStart<=pSrc->nSrc );
  3028. /* Allocate additional space if needed */
  3029. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  3030. SrcList *pNew;
  3031. int nAlloc = pSrc->nSrc+nExtra;
  3032. int nGot;
  3033. pNew = sqlite3DbRealloc(db, pSrc,
  3034. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  3035. if( pNew==0 ){
  3036. assert( db->mallocFailed );
  3037. return pSrc;
  3038. }
  3039. pSrc = pNew;
  3040. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  3041. pSrc->nAlloc = (u8)nGot;
  3042. }
  3043. /* Move existing slots that come after the newly inserted slots
  3044. ** out of the way */
  3045. for(i=pSrc->nSrc-1; i>=iStart; i--){
  3046. pSrc->a[i+nExtra] = pSrc->a[i];
  3047. }
  3048. pSrc->nSrc += (i8)nExtra;
  3049. /* Zero the newly allocated slots */
  3050. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  3051. for(i=iStart; i<iStart+nExtra; i++){
  3052. pSrc->a[i].iCursor = -1;
  3053. }
  3054. /* Return a pointer to the enlarged SrcList */
  3055. return pSrc;
  3056. }
  3057. /*
  3058. ** Append a new table name to the given SrcList. Create a new SrcList if
  3059. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  3060. **
  3061. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  3062. ** SrcList might be the same as the SrcList that was input or it might be
  3063. ** a new one. If an OOM error does occurs, then the prior value of pList
  3064. ** that is input to this routine is automatically freed.
  3065. **
  3066. ** If pDatabase is not null, it means that the table has an optional
  3067. ** database name prefix. Like this: "database.table". The pDatabase
  3068. ** points to the table name and the pTable points to the database name.
  3069. ** The SrcList.a[].zName field is filled with the table name which might
  3070. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  3071. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  3072. ** or with NULL if no database is specified.
  3073. **
  3074. ** In other words, if call like this:
  3075. **
  3076. ** sqlite3SrcListAppend(D,A,B,0);
  3077. **
  3078. ** Then B is a table name and the database name is unspecified. If called
  3079. ** like this:
  3080. **
  3081. ** sqlite3SrcListAppend(D,A,B,C);
  3082. **
  3083. ** Then C is the table name and B is the database name. If C is defined
  3084. ** then so is B. In other words, we never have a case where:
  3085. **
  3086. ** sqlite3SrcListAppend(D,A,0,C);
  3087. **
  3088. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  3089. ** before being added to the SrcList.
  3090. */
  3091. SrcList *sqlite3SrcListAppend(
  3092. sqlite3 *db, /* Connection to notify of malloc failures */
  3093. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  3094. Token *pTable, /* Table to append */
  3095. Token *pDatabase /* Database of the table */
  3096. ){
  3097. struct SrcList_item *pItem;
  3098. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  3099. if( pList==0 ){
  3100. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  3101. if( pList==0 ) return 0;
  3102. pList->nAlloc = 1;
  3103. }
  3104. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  3105. if( db->mallocFailed ){
  3106. sqlite3SrcListDelete(db, pList);
  3107. return 0;
  3108. }
  3109. pItem = &pList->a[pList->nSrc-1];
  3110. if( pDatabase && pDatabase->z==0 ){
  3111. pDatabase = 0;
  3112. }
  3113. if( pDatabase ){
  3114. Token *pTemp = pDatabase;
  3115. pDatabase = pTable;
  3116. pTable = pTemp;
  3117. }
  3118. pItem->zName = sqlite3NameFromToken(db, pTable);
  3119. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  3120. return pList;
  3121. }
  3122. /*
  3123. ** Assign VdbeCursor index numbers to all tables in a SrcList
  3124. */
  3125. void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  3126. int i;
  3127. struct SrcList_item *pItem;
  3128. assert(pList || pParse->db->mallocFailed );
  3129. if( pList ){
  3130. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  3131. if( pItem->iCursor>=0 ) break;
  3132. pItem->iCursor = pParse->nTab++;
  3133. if( pItem->pSelect ){
  3134. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  3135. }
  3136. }
  3137. }
  3138. }
  3139. /*
  3140. ** Delete an entire SrcList including all its substructure.
  3141. */
  3142. void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  3143. int i;
  3144. struct SrcList_item *pItem;
  3145. if( pList==0 ) return;
  3146. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  3147. sqlite3DbFree(db, pItem->zDatabase);
  3148. sqlite3DbFree(db, pItem->zName);
  3149. sqlite3DbFree(db, pItem->zAlias);
  3150. sqlite3DbFree(db, pItem->zIndex);
  3151. sqlite3DeleteTable(db, pItem->pTab);
  3152. sqlite3SelectDelete(db, pItem->pSelect);
  3153. sqlite3ExprDelete(db, pItem->pOn);
  3154. sqlite3IdListDelete(db, pItem->pUsing);
  3155. }
  3156. sqlite3DbFree(db, pList);
  3157. }
  3158. /*
  3159. ** This routine is called by the parser to add a new term to the
  3160. ** end of a growing FROM clause. The "p" parameter is the part of
  3161. ** the FROM clause that has already been constructed. "p" is NULL
  3162. ** if this is the first term of the FROM clause. pTable and pDatabase
  3163. ** are the name of the table and database named in the FROM clause term.
  3164. ** pDatabase is NULL if the database name qualifier is missing - the
  3165. ** usual case. If the term has a alias, then pAlias points to the
  3166. ** alias token. If the term is a subquery, then pSubquery is the
  3167. ** SELECT statement that the subquery encodes. The pTable and
  3168. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  3169. ** parameters are the content of the ON and USING clauses.
  3170. **
  3171. ** Return a new SrcList which encodes is the FROM with the new
  3172. ** term added.
  3173. */
  3174. SrcList *sqlite3SrcListAppendFromTerm(
  3175. Parse *pParse, /* Parsing context */
  3176. SrcList *p, /* The left part of the FROM clause already seen */
  3177. Token *pTable, /* Name of the table to add to the FROM clause */
  3178. Token *pDatabase, /* Name of the database containing pTable */
  3179. Token *pAlias, /* The right-hand side of the AS subexpression */
  3180. Select *pSubquery, /* A subquery used in place of a table name */
  3181. Expr *pOn, /* The ON clause of a join */
  3182. IdList *pUsing /* The USING clause of a join */
  3183. ){
  3184. struct SrcList_item *pItem;
  3185. sqlite3 *db = pParse->db;
  3186. if( !p && (pOn || pUsing) ){
  3187. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  3188. (pOn ? "ON" : "USING")
  3189. );
  3190. goto append_from_error;
  3191. }
  3192. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  3193. if( p==0 || NEVER(p->nSrc==0) ){
  3194. goto append_from_error;
  3195. }
  3196. pItem = &p->a[p->nSrc-1];
  3197. assert( pAlias!=0 );
  3198. if( pAlias->n ){
  3199. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  3200. }
  3201. pItem->pSelect = pSubquery;
  3202. pItem->pOn = pOn;
  3203. pItem->pUsing = pUsing;
  3204. return p;
  3205. append_from_error:
  3206. assert( p==0 );
  3207. sqlite3ExprDelete(db, pOn);
  3208. sqlite3IdListDelete(db, pUsing);
  3209. sqlite3SelectDelete(db, pSubquery);
  3210. return 0;
  3211. }
  3212. /*
  3213. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  3214. ** element of the source-list passed as the second argument.
  3215. */
  3216. void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  3217. assert( pIndexedBy!=0 );
  3218. if( p && ALWAYS(p->nSrc>0) ){
  3219. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  3220. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  3221. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  3222. /* A "NOT INDEXED" clause was supplied. See parse.y
  3223. ** construct "indexed_opt" for details. */
  3224. pItem->notIndexed = 1;
  3225. }else{
  3226. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  3227. }
  3228. }
  3229. }
  3230. /*
  3231. ** When building up a FROM clause in the parser, the join operator
  3232. ** is initially attached to the left operand. But the code generator
  3233. ** expects the join operator to be on the right operand. This routine
  3234. ** Shifts all join operators from left to right for an entire FROM
  3235. ** clause.
  3236. **
  3237. ** Example: Suppose the join is like this:
  3238. **
  3239. ** A natural cross join B
  3240. **
  3241. ** The operator is "natural cross join". The A and B operands are stored
  3242. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  3243. ** operator with A. This routine shifts that operator over to B.
  3244. */
  3245. void sqlite3SrcListShiftJoinType(SrcList *p){
  3246. if( p ){
  3247. int i;
  3248. assert( p->a || p->nSrc==0 );
  3249. for(i=p->nSrc-1; i>0; i--){
  3250. p->a[i].jointype = p->a[i-1].jointype;
  3251. }
  3252. p->a[0].jointype = 0;
  3253. }
  3254. }
  3255. /*
  3256. ** Begin a transaction
  3257. */
  3258. void sqlite3BeginTransaction(Parse *pParse, int type){
  3259. sqlite3 *db;
  3260. Vdbe *v;
  3261. int i;
  3262. assert( pParse!=0 );
  3263. db = pParse->db;
  3264. assert( db!=0 );
  3265. /* if( db->aDb[0].pBt==0 ) return; */
  3266. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  3267. return;
  3268. }
  3269. v = sqlite3GetVdbe(pParse);
  3270. if( !v ) return;
  3271. if( type!=TK_DEFERRED ){
  3272. for(i=0; i<db->nDb; i++){
  3273. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  3274. sqlite3VdbeUsesBtree(v, i);
  3275. }
  3276. }
  3277. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  3278. }
  3279. /*
  3280. ** Commit a transaction
  3281. */
  3282. void sqlite3CommitTransaction(Parse *pParse){
  3283. Vdbe *v;
  3284. assert( pParse!=0 );
  3285. assert( pParse->db!=0 );
  3286. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  3287. return;
  3288. }
  3289. v = sqlite3GetVdbe(pParse);
  3290. if( v ){
  3291. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  3292. }
  3293. }
  3294. /*
  3295. ** Rollback a transaction
  3296. */
  3297. void sqlite3RollbackTransaction(Parse *pParse){
  3298. Vdbe *v;
  3299. assert( pParse!=0 );
  3300. assert( pParse->db!=0 );
  3301. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  3302. return;
  3303. }
  3304. v = sqlite3GetVdbe(pParse);
  3305. if( v ){
  3306. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  3307. }
  3308. }
  3309. /*
  3310. ** This function is called by the parser when it parses a command to create,
  3311. ** release or rollback an SQL savepoint.
  3312. */
  3313. void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  3314. char *zName = sqlite3NameFromToken(pParse->db, pName);
  3315. if( zName ){
  3316. Vdbe *v = sqlite3GetVdbe(pParse);
  3317. #ifndef SQLITE_OMIT_AUTHORIZATION
  3318. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  3319. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  3320. #endif
  3321. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  3322. sqlite3DbFree(pParse->db, zName);
  3323. return;
  3324. }
  3325. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  3326. }
  3327. }
  3328. /*
  3329. ** Make sure the TEMP database is open and available for use. Return
  3330. ** the number of errors. Leave any error messages in the pParse structure.
  3331. */
  3332. int sqlite3OpenTempDatabase(Parse *pParse){
  3333. sqlite3 *db = pParse->db;
  3334. if( db->aDb[1].pBt==0 && !pParse->explain ){
  3335. int rc;
  3336. Btree *pBt;
  3337. static const int flags =
  3338. SQLITE_OPEN_READWRITE |
  3339. SQLITE_OPEN_CREATE |
  3340. SQLITE_OPEN_EXCLUSIVE |
  3341. SQLITE_OPEN_DELETEONCLOSE |
  3342. SQLITE_OPEN_TEMP_DB;
  3343. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  3344. if( rc!=SQLITE_OK ){
  3345. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  3346. "file for storing temporary tables");
  3347. pParse->rc = rc;
  3348. return 1;
  3349. }
  3350. db->aDb[1].pBt = pBt;
  3351. assert( db->aDb[1].pSchema );
  3352. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  3353. db->mallocFailed = 1;
  3354. return 1;
  3355. }
  3356. }
  3357. return 0;
  3358. }
  3359. /*
  3360. ** Generate VDBE code that will verify the schema cookie and start
  3361. ** a read-transaction for all named database files.
  3362. **
  3363. ** It is important that all schema cookies be verified and all
  3364. ** read transactions be started before anything else happens in
  3365. ** the VDBE program. But this routine can be called after much other
  3366. ** code has been generated. So here is what we do:
  3367. **
  3368. ** The first time this routine is called, we code an OP_Goto that
  3369. ** will jump to a subroutine at the end of the program. Then we
  3370. ** record every database that needs its schema verified in the
  3371. ** pParse->cookieMask field. Later, after all other code has been
  3372. ** generated, the subroutine that does the cookie verifications and
  3373. ** starts the transactions will be coded and the OP_Goto P2 value
  3374. ** will be made to point to that subroutine. The generation of the
  3375. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  3376. **
  3377. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  3378. ** schema on any databases. This can be used to position the OP_Goto
  3379. ** early in the code, before we know if any database tables will be used.
  3380. */
  3381. void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  3382. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3383. #ifndef SQLITE_OMIT_TRIGGER
  3384. if( pToplevel!=pParse ){
  3385. /* This branch is taken if a trigger is currently being coded. In this
  3386. ** case, set cookieGoto to a non-zero value to show that this function
  3387. ** has been called. This is used by the sqlite3ExprCodeConstants()
  3388. ** function. */
  3389. pParse->cookieGoto = -1;
  3390. }
  3391. #endif
  3392. if( pToplevel->cookieGoto==0 ){
  3393. Vdbe *v = sqlite3GetVdbe(pToplevel);
  3394. if( v==0 ) return; /* This only happens if there was a prior error */
  3395. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  3396. }
  3397. if( iDb>=0 ){
  3398. sqlite3 *db = pToplevel->db;
  3399. yDbMask mask;
  3400. assert( iDb<db->nDb );
  3401. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  3402. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  3403. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  3404. mask = ((yDbMask)1)<<iDb;
  3405. if( (pToplevel->cookieMask & mask)==0 ){
  3406. pToplevel->cookieMask |= mask;
  3407. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  3408. if( !OMIT_TEMPDB && iDb==1 ){
  3409. sqlite3OpenTempDatabase(pToplevel);
  3410. }
  3411. }
  3412. }
  3413. }
  3414. /*
  3415. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  3416. ** attached database. Otherwise, invoke it for the database named zDb only.
  3417. */
  3418. void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  3419. sqlite3 *db = pParse->db;
  3420. int i;
  3421. for(i=0; i<db->nDb; i++){
  3422. Db *pDb = &db->aDb[i];
  3423. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  3424. sqlite3CodeVerifySchema(pParse, i);
  3425. }
  3426. }
  3427. }
  3428. /*
  3429. ** Generate VDBE code that prepares for doing an operation that
  3430. ** might change the database.
  3431. **
  3432. ** This routine starts a new transaction if we are not already within
  3433. ** a transaction. If we are already within a transaction, then a checkpoint
  3434. ** is set if the setStatement parameter is true. A checkpoint should
  3435. ** be set for operations that might fail (due to a constraint) part of
  3436. ** the way through and which will need to undo some writes without having to
  3437. ** rollback the whole transaction. For operations where all constraints
  3438. ** can be checked before any changes are made to the database, it is never
  3439. ** necessary to undo a write and the checkpoint should not be set.
  3440. */
  3441. void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  3442. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3443. sqlite3CodeVerifySchema(pParse, iDb);
  3444. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  3445. pToplevel->isMultiWrite |= setStatement;
  3446. }
  3447. /*
  3448. ** Indicate that the statement currently under construction might write
  3449. ** more than one entry (example: deleting one row then inserting another,
  3450. ** inserting multiple rows in a table, or inserting a row and index entries.)
  3451. ** If an abort occurs after some of these writes have completed, then it will
  3452. ** be necessary to undo the completed writes.
  3453. */
  3454. void sqlite3MultiWrite(Parse *pParse){
  3455. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3456. pToplevel->isMultiWrite = 1;
  3457. }
  3458. /*
  3459. ** The code generator calls this routine if is discovers that it is
  3460. ** possible to abort a statement prior to completion. In order to
  3461. ** perform this abort without corrupting the database, we need to make
  3462. ** sure that the statement is protected by a statement transaction.
  3463. **
  3464. ** Technically, we only need to set the mayAbort flag if the
  3465. ** isMultiWrite flag was previously set. There is a time dependency
  3466. ** such that the abort must occur after the multiwrite. This makes
  3467. ** some statements involving the REPLACE conflict resolution algorithm
  3468. ** go a little faster. But taking advantage of this time dependency
  3469. ** makes it more difficult to prove that the code is correct (in
  3470. ** particular, it prevents us from writing an effective
  3471. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  3472. ** to take the safe route and skip the optimization.
  3473. */
  3474. void sqlite3MayAbort(Parse *pParse){
  3475. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3476. pToplevel->mayAbort = 1;
  3477. }
  3478. /*
  3479. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  3480. ** error. The onError parameter determines which (if any) of the statement
  3481. ** and/or current transaction is rolled back.
  3482. */
  3483. void sqlite3HaltConstraint(
  3484. Parse *pParse, /* Parsing context */
  3485. int errCode, /* extended error code */
  3486. int onError, /* Constraint type */
  3487. char *p4, /* Error message */
  3488. int p4type /* P4_STATIC or P4_TRANSIENT */
  3489. ){
  3490. Vdbe *v = sqlite3GetVdbe(pParse);
  3491. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  3492. if( onError==OE_Abort ){
  3493. sqlite3MayAbort(pParse);
  3494. }
  3495. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  3496. }
  3497. /*
  3498. ** Check to see if pIndex uses the collating sequence pColl. Return
  3499. ** true if it does and false if it does not.
  3500. */
  3501. #ifndef SQLITE_OMIT_REINDEX
  3502. static int collationMatch(const char *zColl, Index *pIndex){
  3503. int i;
  3504. assert( zColl!=0 );
  3505. for(i=0; i<pIndex->nColumn; i++){
  3506. const char *z = pIndex->azColl[i];
  3507. assert( z!=0 );
  3508. if( 0==sqlite3StrICmp(z, zColl) ){
  3509. return 1;
  3510. }
  3511. }
  3512. return 0;
  3513. }
  3514. #endif
  3515. /*
  3516. ** Recompute all indices of pTab that use the collating sequence pColl.
  3517. ** If pColl==0 then recompute all indices of pTab.
  3518. */
  3519. #ifndef SQLITE_OMIT_REINDEX
  3520. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  3521. Index *pIndex; /* An index associated with pTab */
  3522. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  3523. if( zColl==0 || collationMatch(zColl, pIndex) ){
  3524. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  3525. sqlite3BeginWriteOperation(pParse, 0, iDb);
  3526. sqlite3RefillIndex(pParse, pIndex, -1);
  3527. }
  3528. }
  3529. }
  3530. #endif
  3531. /*
  3532. ** Recompute all indices of all tables in all databases where the
  3533. ** indices use the collating sequence pColl. If pColl==0 then recompute
  3534. ** all indices everywhere.
  3535. */
  3536. #ifndef SQLITE_OMIT_REINDEX
  3537. static void reindexDatabases(Parse *pParse, char const *zColl){
  3538. Db *pDb; /* A single database */
  3539. int iDb; /* The database index number */
  3540. sqlite3 *db = pParse->db; /* The database connection */
  3541. HashElem *k; /* For looping over tables in pDb */
  3542. Table *pTab; /* A table in the database */
  3543. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  3544. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  3545. assert( pDb!=0 );
  3546. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  3547. pTab = (Table*)sqliteHashData(k);
  3548. reindexTable(pParse, pTab, zColl);
  3549. }
  3550. }
  3551. }
  3552. #endif
  3553. /*
  3554. ** Generate code for the REINDEX command.
  3555. **
  3556. ** REINDEX -- 1
  3557. ** REINDEX <collation> -- 2
  3558. ** REINDEX ?<database>.?<tablename> -- 3
  3559. ** REINDEX ?<database>.?<indexname> -- 4
  3560. **
  3561. ** Form 1 causes all indices in all attached databases to be rebuilt.
  3562. ** Form 2 rebuilds all indices in all databases that use the named
  3563. ** collating function. Forms 3 and 4 rebuild the named index or all
  3564. ** indices associated with the named table.
  3565. */
  3566. #ifndef SQLITE_OMIT_REINDEX
  3567. void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  3568. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  3569. char *z; /* Name of a table or index */
  3570. const char *zDb; /* Name of the database */
  3571. Table *pTab; /* A table in the database */
  3572. Index *pIndex; /* An index associated with pTab */
  3573. int iDb; /* The database index number */
  3574. sqlite3 *db = pParse->db; /* The database connection */
  3575. Token *pObjName; /* Name of the table or index to be reindexed */
  3576. /* Read the database schema. If an error occurs, leave an error message
  3577. ** and code in pParse and return NULL. */
  3578. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  3579. return;
  3580. }
  3581. if( pName1==0 ){
  3582. reindexDatabases(pParse, 0);
  3583. return;
  3584. }else if( NEVER(pName2==0) || pName2->z==0 ){
  3585. char *zColl;
  3586. assert( pName1->z );
  3587. zColl = sqlite3NameFromToken(pParse->db, pName1);
  3588. if( !zColl ) return;
  3589. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  3590. if( pColl ){
  3591. reindexDatabases(pParse, zColl);
  3592. sqlite3DbFree(db, zColl);
  3593. return;
  3594. }
  3595. sqlite3DbFree(db, zColl);
  3596. }
  3597. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  3598. if( iDb<0 ) return;
  3599. z = sqlite3NameFromToken(db, pObjName);
  3600. if( z==0 ) return;
  3601. zDb = db->aDb[iDb].zName;
  3602. pTab = sqlite3FindTable(db, z, zDb);
  3603. if( pTab ){
  3604. reindexTable(pParse, pTab, 0);
  3605. sqlite3DbFree(db, z);
  3606. return;
  3607. }
  3608. pIndex = sqlite3FindIndex(db, z, zDb);
  3609. sqlite3DbFree(db, z);
  3610. if( pIndex ){
  3611. sqlite3BeginWriteOperation(pParse, 0, iDb);
  3612. sqlite3RefillIndex(pParse, pIndex, -1);
  3613. return;
  3614. }
  3615. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  3616. }
  3617. #endif
  3618. /*
  3619. ** Return a dynamicly allocated KeyInfo structure that can be used
  3620. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  3621. **
  3622. ** If successful, a pointer to the new structure is returned. In this case
  3623. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  3624. ** pointer. If an error occurs (out of memory or missing collation
  3625. ** sequence), NULL is returned and the state of pParse updated to reflect
  3626. ** the error.
  3627. */
  3628. KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  3629. int i;
  3630. int nCol = pIdx->nColumn;
  3631. KeyInfo *pKey;
  3632. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  3633. if( pKey ){
  3634. for(i=0; i<nCol; i++){
  3635. char *zColl = pIdx->azColl[i];
  3636. assert( zColl );
  3637. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  3638. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  3639. }
  3640. }
  3641. if( pParse->nErr ){
  3642. sqlite3DbFree(pParse->db, pKey);
  3643. pKey = 0;
  3644. }
  3645. return pKey;
  3646. }