build.c 109 KB

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