shell.c 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259
  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 code to implement the "sqlite" command line
  13. ** utility for accessing SQLite databases.
  14. */
  15. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  16. /* This needs to come before any includes for MSVC compiler */
  17. #define _CRT_SECURE_NO_WARNINGS
  18. #endif
  19. /*
  20. ** Enable large-file support for fopen() and friends on unix.
  21. */
  22. #ifndef SQLITE_DISABLE_LFS
  23. # define _LARGE_FILE 1
  24. # ifndef _FILE_OFFSET_BITS
  25. # define _FILE_OFFSET_BITS 64
  26. # endif
  27. # define _LARGEFILE_SOURCE 1
  28. #endif
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <assert.h>
  33. #include "sqlite3.h"
  34. #if SQLITE_USER_AUTHENTICATION
  35. # include "sqlite3userauth.h"
  36. #endif
  37. #include <ctype.h>
  38. #include <stdarg.h>
  39. #if !defined(_WIN32) && !defined(WIN32)
  40. # include <signal.h>
  41. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  42. # include <pwd.h>
  43. # endif
  44. # include <unistd.h>
  45. # include <sys/types.h>
  46. #endif
  47. #if defined(HAVE_READLINE) && HAVE_READLINE!=0
  48. # include <readline/readline.h>
  49. # include <readline/history.h>
  50. #else
  51. # undef HAVE_READLINE
  52. #endif
  53. #if defined(HAVE_EDITLINE) && !defined(HAVE_READLINE)
  54. # define HAVE_READLINE 1
  55. # include <editline/readline.h>
  56. #endif
  57. #if !defined(HAVE_READLINE)
  58. # define add_history(X)
  59. # define read_history(X)
  60. # define write_history(X)
  61. # define stifle_history(X)
  62. #endif
  63. #if defined(_WIN32) || defined(WIN32)
  64. # include <io.h>
  65. # include <fcntl.h>
  66. #define isatty(h) _isatty(h)
  67. #ifndef access
  68. # define access(f,m) _access((f),(m))
  69. #endif
  70. #undef popen
  71. #define popen _popen
  72. #undef pclose
  73. #define pclose _pclose
  74. #else
  75. /* Make sure isatty() has a prototype.
  76. */
  77. extern int isatty(int);
  78. /* popen and pclose are not C89 functions and so are sometimes omitted from
  79. ** the <stdio.h> header */
  80. extern FILE *popen(const char*,const char*);
  81. extern int pclose(FILE*);
  82. #endif
  83. #if defined(_WIN32_WCE)
  84. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  85. * thus we always assume that we have a console. That can be
  86. * overridden with the -batch command line option.
  87. */
  88. #define isatty(x) 1
  89. #endif
  90. /* ctype macros that work with signed characters */
  91. #define IsSpace(X) isspace((unsigned char)X)
  92. #define IsDigit(X) isdigit((unsigned char)X)
  93. #define ToLower(X) (char)tolower((unsigned char)X)
  94. /* True if the timer is enabled */
  95. static int enableTimer = 0;
  96. /* Return the current wall-clock time */
  97. static sqlite3_int64 timeOfDay(void){
  98. static sqlite3_vfs *clockVfs = 0;
  99. sqlite3_int64 t;
  100. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  101. if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
  102. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  103. }else{
  104. double r;
  105. clockVfs->xCurrentTime(clockVfs, &r);
  106. t = (sqlite3_int64)(r*86400000.0);
  107. }
  108. return t;
  109. }
  110. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \
  111. && !defined(__minux)
  112. #include <sys/time.h>
  113. #include <sys/resource.h>
  114. /* Saved resource information for the beginning of an operation */
  115. static struct rusage sBegin; /* CPU time at start */
  116. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  117. /*
  118. ** Begin timing an operation
  119. */
  120. static void beginTimer(void){
  121. if( enableTimer ){
  122. getrusage(RUSAGE_SELF, &sBegin);
  123. iBegin = timeOfDay();
  124. }
  125. }
  126. /* Return the difference of two time_structs in seconds */
  127. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  128. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  129. (double)(pEnd->tv_sec - pStart->tv_sec);
  130. }
  131. /*
  132. ** Print the timing results.
  133. */
  134. static void endTimer(void){
  135. if( enableTimer ){
  136. struct rusage sEnd;
  137. sqlite3_int64 iEnd = timeOfDay();
  138. getrusage(RUSAGE_SELF, &sEnd);
  139. printf("Run Time: real %.3f user %f sys %f\n",
  140. (iEnd - iBegin)*0.001,
  141. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  142. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  143. }
  144. }
  145. #define BEGIN_TIMER beginTimer()
  146. #define END_TIMER endTimer()
  147. #define HAS_TIMER 1
  148. #elif (defined(_WIN32) || defined(WIN32))
  149. #include <windows.h>
  150. /* Saved resource information for the beginning of an operation */
  151. static HANDLE hProcess;
  152. static FILETIME ftKernelBegin;
  153. static FILETIME ftUserBegin;
  154. static sqlite3_int64 ftWallBegin;
  155. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
  156. static GETPROCTIMES getProcessTimesAddr = NULL;
  157. /*
  158. ** Check to see if we have timer support. Return 1 if necessary
  159. ** support found (or found previously).
  160. */
  161. static int hasTimer(void){
  162. if( getProcessTimesAddr ){
  163. return 1;
  164. } else {
  165. /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
  166. ** See if the version we are running on has it, and if it does, save off
  167. ** a pointer to it and the current process handle.
  168. */
  169. hProcess = GetCurrentProcess();
  170. if( hProcess ){
  171. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  172. if( NULL != hinstLib ){
  173. getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  174. if( NULL != getProcessTimesAddr ){
  175. return 1;
  176. }
  177. FreeLibrary(hinstLib);
  178. }
  179. }
  180. }
  181. return 0;
  182. }
  183. /*
  184. ** Begin timing an operation
  185. */
  186. static void beginTimer(void){
  187. if( enableTimer && getProcessTimesAddr ){
  188. FILETIME ftCreation, ftExit;
  189. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
  190. ftWallBegin = timeOfDay();
  191. }
  192. }
  193. /* Return the difference of two FILETIME structs in seconds */
  194. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  195. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  196. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  197. return (double) ((i64End - i64Start) / 10000000.0);
  198. }
  199. /*
  200. ** Print the timing results.
  201. */
  202. static void endTimer(void){
  203. if( enableTimer && getProcessTimesAddr){
  204. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  205. sqlite3_int64 ftWallEnd = timeOfDay();
  206. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
  207. printf("Run Time: real %.3f user %f sys %f\n",
  208. (ftWallEnd - ftWallBegin)*0.001,
  209. timeDiff(&ftUserBegin, &ftUserEnd),
  210. timeDiff(&ftKernelBegin, &ftKernelEnd));
  211. }
  212. }
  213. #define BEGIN_TIMER beginTimer()
  214. #define END_TIMER endTimer()
  215. #define HAS_TIMER hasTimer()
  216. #else
  217. #define BEGIN_TIMER
  218. #define END_TIMER
  219. #define HAS_TIMER 0
  220. #endif
  221. /*
  222. ** Used to prevent warnings about unused parameters
  223. */
  224. #define UNUSED_PARAMETER(x) (void)(x)
  225. /*
  226. ** If the following flag is set, then command execution stops
  227. ** at an error if we are not interactive.
  228. */
  229. static int bail_on_error = 0;
  230. /*
  231. ** Threat stdin as an interactive input if the following variable
  232. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  233. */
  234. static int stdin_is_interactive = 1;
  235. /*
  236. ** The following is the open SQLite database. We make a pointer
  237. ** to this database a static variable so that it can be accessed
  238. ** by the SIGINT handler to interrupt database processing.
  239. */
  240. static sqlite3 *db = 0;
  241. /*
  242. ** True if an interrupt (Control-C) has been received.
  243. */
  244. static volatile int seenInterrupt = 0;
  245. /*
  246. ** This is the name of our program. It is set in main(), used
  247. ** in a number of other places, mostly for error messages.
  248. */
  249. static char *Argv0;
  250. /*
  251. ** Prompt strings. Initialized in main. Settable with
  252. ** .prompt main continue
  253. */
  254. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  255. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  256. /*
  257. ** Write I/O traces to the following stream.
  258. */
  259. #ifdef SQLITE_ENABLE_IOTRACE
  260. static FILE *iotrace = 0;
  261. #endif
  262. /*
  263. ** This routine works like printf in that its first argument is a
  264. ** format string and subsequent arguments are values to be substituted
  265. ** in place of % fields. The result of formatting this string
  266. ** is written to iotrace.
  267. */
  268. #ifdef SQLITE_ENABLE_IOTRACE
  269. static void iotracePrintf(const char *zFormat, ...){
  270. va_list ap;
  271. char *z;
  272. if( iotrace==0 ) return;
  273. va_start(ap, zFormat);
  274. z = sqlite3_vmprintf(zFormat, ap);
  275. va_end(ap);
  276. fprintf(iotrace, "%s", z);
  277. sqlite3_free(z);
  278. }
  279. #endif
  280. /*
  281. ** Determines if a string is a number of not.
  282. */
  283. static int isNumber(const char *z, int *realnum){
  284. if( *z=='-' || *z=='+' ) z++;
  285. if( !IsDigit(*z) ){
  286. return 0;
  287. }
  288. z++;
  289. if( realnum ) *realnum = 0;
  290. while( IsDigit(*z) ){ z++; }
  291. if( *z=='.' ){
  292. z++;
  293. if( !IsDigit(*z) ) return 0;
  294. while( IsDigit(*z) ){ z++; }
  295. if( realnum ) *realnum = 1;
  296. }
  297. if( *z=='e' || *z=='E' ){
  298. z++;
  299. if( *z=='+' || *z=='-' ) z++;
  300. if( !IsDigit(*z) ) return 0;
  301. while( IsDigit(*z) ){ z++; }
  302. if( realnum ) *realnum = 1;
  303. }
  304. return *z==0;
  305. }
  306. /*
  307. ** A global char* and an SQL function to access its current value
  308. ** from within an SQL statement. This program used to use the
  309. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  310. ** The correct way to do this with sqlite3 is to use the bind API, but
  311. ** since the shell is built around the callback paradigm it would be a lot
  312. ** of work. Instead just use this hack, which is quite harmless.
  313. */
  314. static const char *zShellStatic = 0;
  315. static void shellstaticFunc(
  316. sqlite3_context *context,
  317. int argc,
  318. sqlite3_value **argv
  319. ){
  320. assert( 0==argc );
  321. assert( zShellStatic );
  322. UNUSED_PARAMETER(argc);
  323. UNUSED_PARAMETER(argv);
  324. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  325. }
  326. /*
  327. ** This routine reads a line of text from FILE in, stores
  328. ** the text in memory obtained from malloc() and returns a pointer
  329. ** to the text. NULL is returned at end of file, or if malloc()
  330. ** fails.
  331. **
  332. ** If zLine is not NULL then it is a malloced buffer returned from
  333. ** a previous call to this routine that may be reused.
  334. */
  335. static char *local_getline(char *zLine, FILE *in){
  336. int nLine = zLine==0 ? 0 : 100;
  337. int n = 0;
  338. while( 1 ){
  339. if( n+100>nLine ){
  340. nLine = nLine*2 + 100;
  341. zLine = realloc(zLine, nLine);
  342. if( zLine==0 ) return 0;
  343. }
  344. if( fgets(&zLine[n], nLine - n, in)==0 ){
  345. if( n==0 ){
  346. free(zLine);
  347. return 0;
  348. }
  349. zLine[n] = 0;
  350. break;
  351. }
  352. while( zLine[n] ) n++;
  353. if( n>0 && zLine[n-1]=='\n' ){
  354. n--;
  355. if( n>0 && zLine[n-1]=='\r' ) n--;
  356. zLine[n] = 0;
  357. break;
  358. }
  359. }
  360. return zLine;
  361. }
  362. /*
  363. ** Retrieve a single line of input text.
  364. **
  365. ** If in==0 then read from standard input and prompt before each line.
  366. ** If isContinuation is true, then a continuation prompt is appropriate.
  367. ** If isContinuation is zero, then the main prompt should be used.
  368. **
  369. ** If zPrior is not NULL then it is a buffer from a prior call to this
  370. ** routine that can be reused.
  371. **
  372. ** The result is stored in space obtained from malloc() and must either
  373. ** be freed by the caller or else passed back into this routine via the
  374. ** zPrior argument for reuse.
  375. */
  376. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  377. char *zPrompt;
  378. char *zResult;
  379. if( in!=0 ){
  380. zResult = local_getline(zPrior, in);
  381. }else{
  382. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  383. #if defined(HAVE_READLINE)
  384. free(zPrior);
  385. zResult = readline(zPrompt);
  386. if( zResult && *zResult ) add_history(zResult);
  387. #else
  388. printf("%s", zPrompt);
  389. fflush(stdout);
  390. zResult = local_getline(zPrior, stdin);
  391. #endif
  392. }
  393. return zResult;
  394. }
  395. /*
  396. ** Shell output mode information from before ".explain on",
  397. ** saved so that it can be restored by ".explain off"
  398. */
  399. typedef struct SavedModeInfo SavedModeInfo;
  400. struct SavedModeInfo {
  401. int valid; /* Is there legit data in here? */
  402. int mode; /* Mode prior to ".explain on" */
  403. int showHeader; /* The ".header" setting prior to ".explain on" */
  404. int colWidth[100]; /* Column widths prior to ".explain on" */
  405. };
  406. /*
  407. ** State information about the database connection is contained in an
  408. ** instance of the following structure.
  409. */
  410. typedef struct ShellState ShellState;
  411. struct ShellState {
  412. sqlite3 *db; /* The database */
  413. int echoOn; /* True to echo input commands */
  414. int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  415. int statsOn; /* True to display memory stats before each finalize */
  416. int outCount; /* Revert to stdout when reaching zero */
  417. int cnt; /* Number of records displayed so far */
  418. FILE *out; /* Write results here */
  419. FILE *traceOut; /* Output for sqlite3_trace() */
  420. int nErr; /* Number of errors seen */
  421. int mode; /* An output mode setting */
  422. int writableSchema; /* True if PRAGMA writable_schema=ON */
  423. int showHeader; /* True to show column names in List or Column mode */
  424. unsigned shellFlgs; /* Various flags */
  425. char *zDestTable; /* Name of destination table when MODE_Insert */
  426. char separator[20]; /* Separator character for MODE_List */
  427. char newline[20]; /* Record separator in MODE_Csv */
  428. int colWidth[100]; /* Requested width of each column when in column mode*/
  429. int actualWidth[100]; /* Actual width of each column */
  430. char nullvalue[20]; /* The text to print when a NULL comes back from
  431. ** the database */
  432. SavedModeInfo normalMode;/* Holds the mode just before .explain ON */
  433. char outfile[FILENAME_MAX]; /* Filename for *out */
  434. const char *zDbFilename; /* name of the database file */
  435. char *zFreeOnClose; /* Filename to free when closing */
  436. const char *zVfs; /* Name of VFS to use */
  437. sqlite3_stmt *pStmt; /* Current statement if any. */
  438. FILE *pLog; /* Write log output here */
  439. int *aiIndent; /* Array of indents used in MODE_Explain */
  440. int nIndent; /* Size of array aiIndent[] */
  441. int iIndent; /* Index of current op in aiIndent[] */
  442. };
  443. /*
  444. ** These are the allowed shellFlgs values
  445. */
  446. #define SHFLG_Scratch 0x00001 /* The --scratch option is used */
  447. #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
  448. #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
  449. /*
  450. ** These are the allowed modes.
  451. */
  452. #define MODE_Line 0 /* One column per line. Blank line between records */
  453. #define MODE_Column 1 /* One record per line in neat columns */
  454. #define MODE_List 2 /* One record per line with a separator */
  455. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  456. #define MODE_Html 4 /* Generate an XHTML table */
  457. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  458. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  459. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  460. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  461. static const char *modeDescr[] = {
  462. "line",
  463. "column",
  464. "list",
  465. "semi",
  466. "html",
  467. "insert",
  468. "tcl",
  469. "csv",
  470. "explain",
  471. };
  472. /*
  473. ** Number of elements in an array
  474. */
  475. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  476. /*
  477. ** Compute a string length that is limited to what can be stored in
  478. ** lower 30 bits of a 32-bit signed integer.
  479. */
  480. static int strlen30(const char *z){
  481. const char *z2 = z;
  482. while( *z2 ){ z2++; }
  483. return 0x3fffffff & (int)(z2 - z);
  484. }
  485. /*
  486. ** A callback for the sqlite3_log() interface.
  487. */
  488. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  489. ShellState *p = (ShellState*)pArg;
  490. if( p->pLog==0 ) return;
  491. fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  492. fflush(p->pLog);
  493. }
  494. /*
  495. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  496. */
  497. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  498. int i;
  499. char *zBlob = (char *)pBlob;
  500. fprintf(out,"X'");
  501. for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); }
  502. fprintf(out,"'");
  503. }
  504. /*
  505. ** Output the given string as a quoted string using SQL quoting conventions.
  506. */
  507. static void output_quoted_string(FILE *out, const char *z){
  508. int i;
  509. int nSingle = 0;
  510. for(i=0; z[i]; i++){
  511. if( z[i]=='\'' ) nSingle++;
  512. }
  513. if( nSingle==0 ){
  514. fprintf(out,"'%s'",z);
  515. }else{
  516. fprintf(out,"'");
  517. while( *z ){
  518. for(i=0; z[i] && z[i]!='\''; i++){}
  519. if( i==0 ){
  520. fprintf(out,"''");
  521. z++;
  522. }else if( z[i]=='\'' ){
  523. fprintf(out,"%.*s''",i,z);
  524. z += i+1;
  525. }else{
  526. fprintf(out,"%s",z);
  527. break;
  528. }
  529. }
  530. fprintf(out,"'");
  531. }
  532. }
  533. /*
  534. ** Output the given string as a quoted according to C or TCL quoting rules.
  535. */
  536. static void output_c_string(FILE *out, const char *z){
  537. unsigned int c;
  538. fputc('"', out);
  539. while( (c = *(z++))!=0 ){
  540. if( c=='\\' ){
  541. fputc(c, out);
  542. fputc(c, out);
  543. }else if( c=='"' ){
  544. fputc('\\', out);
  545. fputc('"', out);
  546. }else if( c=='\t' ){
  547. fputc('\\', out);
  548. fputc('t', out);
  549. }else if( c=='\n' ){
  550. fputc('\\', out);
  551. fputc('n', out);
  552. }else if( c=='\r' ){
  553. fputc('\\', out);
  554. fputc('r', out);
  555. }else if( !isprint(c&0xff) ){
  556. fprintf(out, "\\%03o", c&0xff);
  557. }else{
  558. fputc(c, out);
  559. }
  560. }
  561. fputc('"', out);
  562. }
  563. /*
  564. ** Output the given string with characters that are special to
  565. ** HTML escaped.
  566. */
  567. static void output_html_string(FILE *out, const char *z){
  568. int i;
  569. if( z==0 ) z = "";
  570. while( *z ){
  571. for(i=0; z[i]
  572. && z[i]!='<'
  573. && z[i]!='&'
  574. && z[i]!='>'
  575. && z[i]!='\"'
  576. && z[i]!='\'';
  577. i++){}
  578. if( i>0 ){
  579. fprintf(out,"%.*s",i,z);
  580. }
  581. if( z[i]=='<' ){
  582. fprintf(out,"&lt;");
  583. }else if( z[i]=='&' ){
  584. fprintf(out,"&amp;");
  585. }else if( z[i]=='>' ){
  586. fprintf(out,"&gt;");
  587. }else if( z[i]=='\"' ){
  588. fprintf(out,"&quot;");
  589. }else if( z[i]=='\'' ){
  590. fprintf(out,"&#39;");
  591. }else{
  592. break;
  593. }
  594. z += i + 1;
  595. }
  596. }
  597. /*
  598. ** If a field contains any character identified by a 1 in the following
  599. ** array, then the string must be quoted for CSV.
  600. */
  601. static const char needCsvQuote[] = {
  602. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  603. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  604. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  610. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  611. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  612. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  613. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  614. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  615. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  616. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  617. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  618. };
  619. /*
  620. ** Output a single term of CSV. Actually, p->separator is used for
  621. ** the separator, which may or may not be a comma. p->nullvalue is
  622. ** the null value. Strings are quoted if necessary. The separator
  623. ** is only issued if bSep is true.
  624. */
  625. static void output_csv(ShellState *p, const char *z, int bSep){
  626. FILE *out = p->out;
  627. if( z==0 ){
  628. fprintf(out,"%s",p->nullvalue);
  629. }else{
  630. int i;
  631. int nSep = strlen30(p->separator);
  632. for(i=0; z[i]; i++){
  633. if( needCsvQuote[((unsigned char*)z)[i]]
  634. || (z[i]==p->separator[0] &&
  635. (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  636. i = 0;
  637. break;
  638. }
  639. }
  640. if( i==0 ){
  641. putc('"', out);
  642. for(i=0; z[i]; i++){
  643. if( z[i]=='"' ) putc('"', out);
  644. putc(z[i], out);
  645. }
  646. putc('"', out);
  647. }else{
  648. fprintf(out, "%s", z);
  649. }
  650. }
  651. if( bSep ){
  652. fprintf(p->out, "%s", p->separator);
  653. }
  654. }
  655. #ifdef SIGINT
  656. /*
  657. ** This routine runs when the user presses Ctrl-C
  658. */
  659. static void interrupt_handler(int NotUsed){
  660. UNUSED_PARAMETER(NotUsed);
  661. seenInterrupt++;
  662. if( seenInterrupt>2 ) exit(1);
  663. if( db ) sqlite3_interrupt(db);
  664. }
  665. #endif
  666. /*
  667. ** This is the callback routine that the shell
  668. ** invokes for each row of a query result.
  669. */
  670. static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  671. int i;
  672. ShellState *p = (ShellState*)pArg;
  673. switch( p->mode ){
  674. case MODE_Line: {
  675. int w = 5;
  676. if( azArg==0 ) break;
  677. for(i=0; i<nArg; i++){
  678. int len = strlen30(azCol[i] ? azCol[i] : "");
  679. if( len>w ) w = len;
  680. }
  681. if( p->cnt++>0 ) fprintf(p->out,"\n");
  682. for(i=0; i<nArg; i++){
  683. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  684. azArg[i] ? azArg[i] : p->nullvalue);
  685. }
  686. break;
  687. }
  688. case MODE_Explain:
  689. case MODE_Column: {
  690. if( p->cnt++==0 ){
  691. for(i=0; i<nArg; i++){
  692. int w, n;
  693. if( i<ArraySize(p->colWidth) ){
  694. w = p->colWidth[i];
  695. }else{
  696. w = 0;
  697. }
  698. if( w==0 ){
  699. w = strlen30(azCol[i] ? azCol[i] : "");
  700. if( w<10 ) w = 10;
  701. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  702. if( w<n ) w = n;
  703. }
  704. if( i<ArraySize(p->actualWidth) ){
  705. p->actualWidth[i] = w;
  706. }
  707. if( p->showHeader ){
  708. if( w<0 ){
  709. fprintf(p->out,"%*.*s%s",-w,-w,azCol[i], i==nArg-1 ? "\n": " ");
  710. }else{
  711. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  712. }
  713. }
  714. }
  715. if( p->showHeader ){
  716. for(i=0; i<nArg; i++){
  717. int w;
  718. if( i<ArraySize(p->actualWidth) ){
  719. w = p->actualWidth[i];
  720. if( w<0 ) w = -w;
  721. }else{
  722. w = 10;
  723. }
  724. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  725. "----------------------------------------------------------",
  726. i==nArg-1 ? "\n": " ");
  727. }
  728. }
  729. }
  730. if( azArg==0 ) break;
  731. for(i=0; i<nArg; i++){
  732. int w;
  733. if( i<ArraySize(p->actualWidth) ){
  734. w = p->actualWidth[i];
  735. }else{
  736. w = 10;
  737. }
  738. if( p->mode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
  739. w = strlen30(azArg[i]);
  740. }
  741. if( i==1 && p->aiIndent && p->pStmt ){
  742. if( p->iIndent<p->nIndent ){
  743. fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  744. }
  745. p->iIndent++;
  746. }
  747. if( w<0 ){
  748. fprintf(p->out,"%*.*s%s",-w,-w,
  749. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  750. }else{
  751. fprintf(p->out,"%-*.*s%s",w,w,
  752. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  753. }
  754. }
  755. break;
  756. }
  757. case MODE_Semi:
  758. case MODE_List: {
  759. if( p->cnt++==0 && p->showHeader ){
  760. for(i=0; i<nArg; i++){
  761. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  762. }
  763. }
  764. if( azArg==0 ) break;
  765. for(i=0; i<nArg; i++){
  766. char *z = azArg[i];
  767. if( z==0 ) z = p->nullvalue;
  768. fprintf(p->out, "%s", z);
  769. if( i<nArg-1 ){
  770. fprintf(p->out, "%s", p->separator);
  771. }else if( p->mode==MODE_Semi ){
  772. fprintf(p->out, ";\n");
  773. }else{
  774. fprintf(p->out, "\n");
  775. }
  776. }
  777. break;
  778. }
  779. case MODE_Html: {
  780. if( p->cnt++==0 && p->showHeader ){
  781. fprintf(p->out,"<TR>");
  782. for(i=0; i<nArg; i++){
  783. fprintf(p->out,"<TH>");
  784. output_html_string(p->out, azCol[i]);
  785. fprintf(p->out,"</TH>\n");
  786. }
  787. fprintf(p->out,"</TR>\n");
  788. }
  789. if( azArg==0 ) break;
  790. fprintf(p->out,"<TR>");
  791. for(i=0; i<nArg; i++){
  792. fprintf(p->out,"<TD>");
  793. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  794. fprintf(p->out,"</TD>\n");
  795. }
  796. fprintf(p->out,"</TR>\n");
  797. break;
  798. }
  799. case MODE_Tcl: {
  800. if( p->cnt++==0 && p->showHeader ){
  801. for(i=0; i<nArg; i++){
  802. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  803. if(i<nArg-1) fprintf(p->out, "%s", p->separator);
  804. }
  805. fprintf(p->out,"\n");
  806. }
  807. if( azArg==0 ) break;
  808. for(i=0; i<nArg; i++){
  809. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  810. if(i<nArg-1) fprintf(p->out, "%s", p->separator);
  811. }
  812. fprintf(p->out,"\n");
  813. break;
  814. }
  815. case MODE_Csv: {
  816. #if defined(WIN32) || defined(_WIN32)
  817. fflush(p->out);
  818. _setmode(_fileno(p->out), _O_BINARY);
  819. #endif
  820. if( p->cnt++==0 && p->showHeader ){
  821. for(i=0; i<nArg; i++){
  822. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  823. }
  824. fprintf(p->out,"%s",p->newline);
  825. }
  826. if( azArg>0 ){
  827. for(i=0; i<nArg; i++){
  828. output_csv(p, azArg[i], i<nArg-1);
  829. }
  830. fprintf(p->out,"%s",p->newline);
  831. }
  832. #if defined(WIN32) || defined(_WIN32)
  833. fflush(p->out);
  834. _setmode(_fileno(p->out), _O_TEXT);
  835. #endif
  836. break;
  837. }
  838. case MODE_Insert: {
  839. p->cnt++;
  840. if( azArg==0 ) break;
  841. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  842. for(i=0; i<nArg; i++){
  843. char *zSep = i>0 ? ",": "";
  844. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  845. fprintf(p->out,"%sNULL",zSep);
  846. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  847. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  848. output_quoted_string(p->out, azArg[i]);
  849. }else if( aiType && (aiType[i]==SQLITE_INTEGER
  850. || aiType[i]==SQLITE_FLOAT) ){
  851. fprintf(p->out,"%s%s",zSep, azArg[i]);
  852. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  853. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  854. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  855. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  856. output_hex_blob(p->out, pBlob, nBlob);
  857. }else if( isNumber(azArg[i], 0) ){
  858. fprintf(p->out,"%s%s",zSep, azArg[i]);
  859. }else{
  860. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  861. output_quoted_string(p->out, azArg[i]);
  862. }
  863. }
  864. fprintf(p->out,");\n");
  865. break;
  866. }
  867. }
  868. return 0;
  869. }
  870. /*
  871. ** This is the callback routine that the SQLite library
  872. ** invokes for each row of a query result.
  873. */
  874. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  875. /* since we don't have type info, call the shell_callback with a NULL value */
  876. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  877. }
  878. /*
  879. ** Set the destination table field of the ShellState structure to
  880. ** the name of the table given. Escape any quote characters in the
  881. ** table name.
  882. */
  883. static void set_table_name(ShellState *p, const char *zName){
  884. int i, n;
  885. int needQuote;
  886. char *z;
  887. if( p->zDestTable ){
  888. free(p->zDestTable);
  889. p->zDestTable = 0;
  890. }
  891. if( zName==0 ) return;
  892. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  893. for(i=n=0; zName[i]; i++, n++){
  894. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  895. needQuote = 1;
  896. if( zName[i]=='\'' ) n++;
  897. }
  898. }
  899. if( needQuote ) n += 2;
  900. z = p->zDestTable = malloc( n+1 );
  901. if( z==0 ){
  902. fprintf(stderr,"Error: out of memory\n");
  903. exit(1);
  904. }
  905. n = 0;
  906. if( needQuote ) z[n++] = '\'';
  907. for(i=0; zName[i]; i++){
  908. z[n++] = zName[i];
  909. if( zName[i]=='\'' ) z[n++] = '\'';
  910. }
  911. if( needQuote ) z[n++] = '\'';
  912. z[n] = 0;
  913. }
  914. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  915. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  916. ** added to zIn, and the result returned in memory obtained from malloc().
  917. ** zIn, if it was not NULL, is freed.
  918. **
  919. ** If the third argument, quote, is not '\0', then it is used as a
  920. ** quote character for zAppend.
  921. */
  922. static char *appendText(char *zIn, char const *zAppend, char quote){
  923. int len;
  924. int i;
  925. int nAppend = strlen30(zAppend);
  926. int nIn = (zIn?strlen30(zIn):0);
  927. len = nAppend+nIn+1;
  928. if( quote ){
  929. len += 2;
  930. for(i=0; i<nAppend; i++){
  931. if( zAppend[i]==quote ) len++;
  932. }
  933. }
  934. zIn = (char *)realloc(zIn, len);
  935. if( !zIn ){
  936. return 0;
  937. }
  938. if( quote ){
  939. char *zCsr = &zIn[nIn];
  940. *zCsr++ = quote;
  941. for(i=0; i<nAppend; i++){
  942. *zCsr++ = zAppend[i];
  943. if( zAppend[i]==quote ) *zCsr++ = quote;
  944. }
  945. *zCsr++ = quote;
  946. *zCsr++ = '\0';
  947. assert( (zCsr-zIn)==len );
  948. }else{
  949. memcpy(&zIn[nIn], zAppend, nAppend);
  950. zIn[len-1] = '\0';
  951. }
  952. return zIn;
  953. }
  954. /*
  955. ** Execute a query statement that will generate SQL output. Print
  956. ** the result columns, comma-separated, on a line and then add a
  957. ** semicolon terminator to the end of that line.
  958. **
  959. ** If the number of columns is 1 and that column contains text "--"
  960. ** then write the semicolon on a separate line. That way, if a
  961. ** "--" comment occurs at the end of the statement, the comment
  962. ** won't consume the semicolon terminator.
  963. */
  964. static int run_table_dump_query(
  965. ShellState *p, /* Query context */
  966. const char *zSelect, /* SELECT statement to extract content */
  967. const char *zFirstRow /* Print before first row, if not NULL */
  968. ){
  969. sqlite3_stmt *pSelect;
  970. int rc;
  971. int nResult;
  972. int i;
  973. const char *z;
  974. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  975. if( rc!=SQLITE_OK || !pSelect ){
  976. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  977. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  978. return rc;
  979. }
  980. rc = sqlite3_step(pSelect);
  981. nResult = sqlite3_column_count(pSelect);
  982. while( rc==SQLITE_ROW ){
  983. if( zFirstRow ){
  984. fprintf(p->out, "%s", zFirstRow);
  985. zFirstRow = 0;
  986. }
  987. z = (const char*)sqlite3_column_text(pSelect, 0);
  988. fprintf(p->out, "%s", z);
  989. for(i=1; i<nResult; i++){
  990. fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  991. }
  992. if( z==0 ) z = "";
  993. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  994. if( z[0] ){
  995. fprintf(p->out, "\n;\n");
  996. }else{
  997. fprintf(p->out, ";\n");
  998. }
  999. rc = sqlite3_step(pSelect);
  1000. }
  1001. rc = sqlite3_finalize(pSelect);
  1002. if( rc!=SQLITE_OK ){
  1003. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  1004. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1005. }
  1006. return rc;
  1007. }
  1008. /*
  1009. ** Allocate space and save off current error string.
  1010. */
  1011. static char *save_err_msg(
  1012. sqlite3 *db /* Database to query */
  1013. ){
  1014. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1015. char *zErrMsg = sqlite3_malloc(nErrMsg);
  1016. if( zErrMsg ){
  1017. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1018. }
  1019. return zErrMsg;
  1020. }
  1021. /*
  1022. ** Display memory stats.
  1023. */
  1024. static int display_stats(
  1025. sqlite3 *db, /* Database to query */
  1026. ShellState *pArg, /* Pointer to ShellState */
  1027. int bReset /* True to reset the stats */
  1028. ){
  1029. int iCur;
  1030. int iHiwtr;
  1031. if( pArg && pArg->out ){
  1032. iHiwtr = iCur = -1;
  1033. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  1034. fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr);
  1035. iHiwtr = iCur = -1;
  1036. sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  1037. fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr);
  1038. if( pArg->shellFlgs & SHFLG_Pagecache ){
  1039. iHiwtr = iCur = -1;
  1040. sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  1041. fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr);
  1042. }
  1043. iHiwtr = iCur = -1;
  1044. sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  1045. fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  1046. if( pArg->shellFlgs & SHFLG_Scratch ){
  1047. iHiwtr = iCur = -1;
  1048. sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  1049. fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr);
  1050. }
  1051. iHiwtr = iCur = -1;
  1052. sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  1053. fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  1054. iHiwtr = iCur = -1;
  1055. sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  1056. fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr);
  1057. iHiwtr = iCur = -1;
  1058. sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  1059. fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr);
  1060. iHiwtr = iCur = -1;
  1061. sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  1062. fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr);
  1063. #ifdef YYTRACKMAXSTACKDEPTH
  1064. iHiwtr = iCur = -1;
  1065. sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  1066. fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr);
  1067. #endif
  1068. }
  1069. if( pArg && pArg->out && db ){
  1070. if( pArg->shellFlgs & SHFLG_Lookaside ){
  1071. iHiwtr = iCur = -1;
  1072. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
  1073. fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
  1074. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset);
  1075. fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr);
  1076. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset);
  1077. fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr);
  1078. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset);
  1079. fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr);
  1080. }
  1081. iHiwtr = iCur = -1;
  1082. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1083. fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1;
  1084. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1085. fprintf(pArg->out, "Page cache hits: %d\n", iCur);
  1086. iHiwtr = iCur = -1;
  1087. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1088. fprintf(pArg->out, "Page cache misses: %d\n", iCur);
  1089. iHiwtr = iCur = -1;
  1090. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1091. fprintf(pArg->out, "Page cache writes: %d\n", iCur);
  1092. iHiwtr = iCur = -1;
  1093. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1094. fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur);
  1095. iHiwtr = iCur = -1;
  1096. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1097. fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur);
  1098. }
  1099. if( pArg && pArg->out && db && pArg->pStmt ){
  1100. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
  1101. fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
  1102. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1103. fprintf(pArg->out, "Sort Operations: %d\n", iCur);
  1104. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
  1105. fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  1106. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  1107. fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  1108. }
  1109. return 0;
  1110. }
  1111. /*
  1112. ** Parameter azArray points to a zero-terminated array of strings. zStr
  1113. ** points to a single nul-terminated string. Return non-zero if zStr
  1114. ** is equal, according to strcmp(), to any of the strings in the array.
  1115. ** Otherwise, return zero.
  1116. */
  1117. static int str_in_array(const char *zStr, const char **azArray){
  1118. int i;
  1119. for(i=0; azArray[i]; i++){
  1120. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  1121. }
  1122. return 0;
  1123. }
  1124. /*
  1125. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  1126. ** and populate the ShellState.aiIndent[] array with the number of
  1127. ** spaces each opcode should be indented before it is output.
  1128. **
  1129. ** The indenting rules are:
  1130. **
  1131. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  1132. ** all opcodes that occur between the p2 jump destination and the opcode
  1133. ** itself by 2 spaces.
  1134. **
  1135. ** * For each "Goto", if the jump destination is earlier in the program
  1136. ** and ends on one of:
  1137. ** Yield SeekGt SeekLt RowSetRead Rewind
  1138. ** or if the P1 parameter is one instead of zero,
  1139. ** then indent all opcodes between the earlier instruction
  1140. ** and "Goto" by 2 spaces.
  1141. */
  1142. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  1143. const char *zSql; /* The text of the SQL statement */
  1144. const char *z; /* Used to check if this is an EXPLAIN */
  1145. int *abYield = 0; /* True if op is an OP_Yield */
  1146. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  1147. int iOp; /* Index of operation in p->aiIndent[] */
  1148. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  1149. "NextIfOpen", "PrevIfOpen", 0 };
  1150. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", "Rewind", 0 };
  1151. const char *azGoto[] = { "Goto", 0 };
  1152. /* Try to figure out if this is really an EXPLAIN statement. If this
  1153. ** cannot be verified, return early. */
  1154. zSql = sqlite3_sql(pSql);
  1155. if( zSql==0 ) return;
  1156. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  1157. if( sqlite3_strnicmp(z, "explain", 7) ) return;
  1158. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  1159. int i;
  1160. int iAddr = sqlite3_column_int(pSql, 0);
  1161. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  1162. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  1163. ** p2 is an instruction address, set variable p2op to the index of that
  1164. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  1165. ** the current instruction is part of a sub-program generated by an
  1166. ** SQL trigger or foreign key. */
  1167. int p2 = sqlite3_column_int(pSql, 3);
  1168. int p2op = (p2 + (iOp-iAddr));
  1169. /* Grow the p->aiIndent array as required */
  1170. if( iOp>=nAlloc ){
  1171. nAlloc += 100;
  1172. p->aiIndent = (int*)sqlite3_realloc(p->aiIndent, nAlloc*sizeof(int));
  1173. abYield = (int*)sqlite3_realloc(abYield, nAlloc*sizeof(int));
  1174. }
  1175. abYield[iOp] = str_in_array(zOp, azYield);
  1176. p->aiIndent[iOp] = 0;
  1177. p->nIndent = iOp+1;
  1178. if( str_in_array(zOp, azNext) ){
  1179. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1180. }
  1181. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  1182. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  1183. ){
  1184. for(i=p2op+1; i<iOp; i++) p->aiIndent[i] += 2;
  1185. }
  1186. }
  1187. p->iIndent = 0;
  1188. sqlite3_free(abYield);
  1189. sqlite3_reset(pSql);
  1190. }
  1191. /*
  1192. ** Free the array allocated by explain_data_prepare().
  1193. */
  1194. static void explain_data_delete(ShellState *p){
  1195. sqlite3_free(p->aiIndent);
  1196. p->aiIndent = 0;
  1197. p->nIndent = 0;
  1198. p->iIndent = 0;
  1199. }
  1200. /*
  1201. ** Execute a statement or set of statements. Print
  1202. ** any result rows/columns depending on the current mode
  1203. ** set via the supplied callback.
  1204. **
  1205. ** This is very similar to SQLite's built-in sqlite3_exec()
  1206. ** function except it takes a slightly different callback
  1207. ** and callback data argument.
  1208. */
  1209. static int shell_exec(
  1210. sqlite3 *db, /* An open database */
  1211. const char *zSql, /* SQL to be evaluated */
  1212. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1213. /* (not the same as sqlite3_exec) */
  1214. ShellState *pArg, /* Pointer to ShellState */
  1215. char **pzErrMsg /* Error msg written here */
  1216. ){
  1217. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1218. int rc = SQLITE_OK; /* Return Code */
  1219. int rc2;
  1220. const char *zLeftover; /* Tail of unprocessed SQL */
  1221. if( pzErrMsg ){
  1222. *pzErrMsg = NULL;
  1223. }
  1224. while( zSql[0] && (SQLITE_OK == rc) ){
  1225. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1226. if( SQLITE_OK != rc ){
  1227. if( pzErrMsg ){
  1228. *pzErrMsg = save_err_msg(db);
  1229. }
  1230. }else{
  1231. if( !pStmt ){
  1232. /* this happens for a comment or white-space */
  1233. zSql = zLeftover;
  1234. while( IsSpace(zSql[0]) ) zSql++;
  1235. continue;
  1236. }
  1237. /* save off the prepared statment handle and reset row count */
  1238. if( pArg ){
  1239. pArg->pStmt = pStmt;
  1240. pArg->cnt = 0;
  1241. }
  1242. /* echo the sql statement if echo on */
  1243. if( pArg && pArg->echoOn ){
  1244. const char *zStmtSql = sqlite3_sql(pStmt);
  1245. fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1246. }
  1247. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  1248. if( pArg && pArg->autoEQP ){
  1249. sqlite3_stmt *pExplain;
  1250. char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", sqlite3_sql(pStmt));
  1251. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1252. if( rc==SQLITE_OK ){
  1253. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  1254. fprintf(pArg->out,"--EQP-- %d,", sqlite3_column_int(pExplain, 0));
  1255. fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
  1256. fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
  1257. fprintf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  1258. }
  1259. }
  1260. sqlite3_finalize(pExplain);
  1261. sqlite3_free(zEQP);
  1262. }
  1263. /* If the shell is currently in ".explain" mode, gather the extra
  1264. ** data required to add indents to the output.*/
  1265. if( pArg && pArg->mode==MODE_Explain ){
  1266. explain_data_prepare(pArg, pStmt);
  1267. }
  1268. /* perform the first step. this will tell us if we
  1269. ** have a result set or not and how wide it is.
  1270. */
  1271. rc = sqlite3_step(pStmt);
  1272. /* if we have a result set... */
  1273. if( SQLITE_ROW == rc ){
  1274. /* if we have a callback... */
  1275. if( xCallback ){
  1276. /* allocate space for col name ptr, value ptr, and type */
  1277. int nCol = sqlite3_column_count(pStmt);
  1278. void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1279. if( !pData ){
  1280. rc = SQLITE_NOMEM;
  1281. }else{
  1282. char **azCols = (char **)pData; /* Names of result columns */
  1283. char **azVals = &azCols[nCol]; /* Results */
  1284. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1285. int i, x;
  1286. assert(sizeof(int) <= sizeof(char *));
  1287. /* save off ptrs to column names */
  1288. for(i=0; i<nCol; i++){
  1289. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1290. }
  1291. do{
  1292. /* extract the data and data types */
  1293. for(i=0; i<nCol; i++){
  1294. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  1295. if( x==SQLITE_BLOB && pArg && pArg->mode==MODE_Insert ){
  1296. azVals[i] = "";
  1297. }else{
  1298. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  1299. }
  1300. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1301. rc = SQLITE_NOMEM;
  1302. break; /* from for */
  1303. }
  1304. } /* end for */
  1305. /* if data and types extracted successfully... */
  1306. if( SQLITE_ROW == rc ){
  1307. /* call the supplied callback with the result row data */
  1308. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1309. rc = SQLITE_ABORT;
  1310. }else{
  1311. rc = sqlite3_step(pStmt);
  1312. }
  1313. }
  1314. } while( SQLITE_ROW == rc );
  1315. sqlite3_free(pData);
  1316. }
  1317. }else{
  1318. do{
  1319. rc = sqlite3_step(pStmt);
  1320. } while( rc == SQLITE_ROW );
  1321. }
  1322. }
  1323. explain_data_delete(pArg);
  1324. /* print usage stats if stats on */
  1325. if( pArg && pArg->statsOn ){
  1326. display_stats(db, pArg, 0);
  1327. }
  1328. /* Finalize the statement just executed. If this fails, save a
  1329. ** copy of the error message. Otherwise, set zSql to point to the
  1330. ** next statement to execute. */
  1331. rc2 = sqlite3_finalize(pStmt);
  1332. if( rc!=SQLITE_NOMEM ) rc = rc2;
  1333. if( rc==SQLITE_OK ){
  1334. zSql = zLeftover;
  1335. while( IsSpace(zSql[0]) ) zSql++;
  1336. }else if( pzErrMsg ){
  1337. *pzErrMsg = save_err_msg(db);
  1338. }
  1339. /* clear saved stmt handle */
  1340. if( pArg ){
  1341. pArg->pStmt = NULL;
  1342. }
  1343. }
  1344. } /* end while */
  1345. return rc;
  1346. }
  1347. /*
  1348. ** This is a different callback routine used for dumping the database.
  1349. ** Each row received by this callback consists of a table name,
  1350. ** the table type ("index" or "table") and SQL to create the table.
  1351. ** This routine should print text sufficient to recreate the table.
  1352. */
  1353. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1354. int rc;
  1355. const char *zTable;
  1356. const char *zType;
  1357. const char *zSql;
  1358. const char *zPrepStmt = 0;
  1359. ShellState *p = (ShellState *)pArg;
  1360. UNUSED_PARAMETER(azCol);
  1361. if( nArg!=3 ) return 1;
  1362. zTable = azArg[0];
  1363. zType = azArg[1];
  1364. zSql = azArg[2];
  1365. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1366. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1367. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  1368. fprintf(p->out, "ANALYZE sqlite_master;\n");
  1369. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1370. return 0;
  1371. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1372. char *zIns;
  1373. if( !p->writableSchema ){
  1374. fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  1375. p->writableSchema = 1;
  1376. }
  1377. zIns = sqlite3_mprintf(
  1378. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1379. "VALUES('table','%q','%q',0,'%q');",
  1380. zTable, zTable, zSql);
  1381. fprintf(p->out, "%s\n", zIns);
  1382. sqlite3_free(zIns);
  1383. return 0;
  1384. }else{
  1385. fprintf(p->out, "%s;\n", zSql);
  1386. }
  1387. if( strcmp(zType, "table")==0 ){
  1388. sqlite3_stmt *pTableInfo = 0;
  1389. char *zSelect = 0;
  1390. char *zTableInfo = 0;
  1391. char *zTmp = 0;
  1392. int nRow = 0;
  1393. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1394. zTableInfo = appendText(zTableInfo, zTable, '"');
  1395. zTableInfo = appendText(zTableInfo, ");", 0);
  1396. rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
  1397. free(zTableInfo);
  1398. if( rc!=SQLITE_OK || !pTableInfo ){
  1399. return 1;
  1400. }
  1401. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1402. /* Always quote the table name, even if it appears to be pure ascii,
  1403. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  1404. zTmp = appendText(zTmp, zTable, '"');
  1405. if( zTmp ){
  1406. zSelect = appendText(zSelect, zTmp, '\'');
  1407. free(zTmp);
  1408. }
  1409. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1410. rc = sqlite3_step(pTableInfo);
  1411. while( rc==SQLITE_ROW ){
  1412. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1413. zSelect = appendText(zSelect, "quote(", 0);
  1414. zSelect = appendText(zSelect, zText, '"');
  1415. rc = sqlite3_step(pTableInfo);
  1416. if( rc==SQLITE_ROW ){
  1417. zSelect = appendText(zSelect, "), ", 0);
  1418. }else{
  1419. zSelect = appendText(zSelect, ") ", 0);
  1420. }
  1421. nRow++;
  1422. }
  1423. rc = sqlite3_finalize(pTableInfo);
  1424. if( rc!=SQLITE_OK || nRow==0 ){
  1425. free(zSelect);
  1426. return 1;
  1427. }
  1428. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1429. zSelect = appendText(zSelect, zTable, '"');
  1430. rc = run_table_dump_query(p, zSelect, zPrepStmt);
  1431. if( rc==SQLITE_CORRUPT ){
  1432. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1433. run_table_dump_query(p, zSelect, 0);
  1434. }
  1435. free(zSelect);
  1436. }
  1437. return 0;
  1438. }
  1439. /*
  1440. ** Run zQuery. Use dump_callback() as the callback routine so that
  1441. ** the contents of the query are output as SQL statements.
  1442. **
  1443. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1444. ** "ORDER BY rowid DESC" to the end.
  1445. */
  1446. static int run_schema_dump_query(
  1447. ShellState *p,
  1448. const char *zQuery
  1449. ){
  1450. int rc;
  1451. char *zErr = 0;
  1452. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  1453. if( rc==SQLITE_CORRUPT ){
  1454. char *zQ2;
  1455. int len = strlen30(zQuery);
  1456. fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
  1457. if( zErr ){
  1458. fprintf(p->out, "/****** %s ******/\n", zErr);
  1459. sqlite3_free(zErr);
  1460. zErr = 0;
  1461. }
  1462. zQ2 = malloc( len+100 );
  1463. if( zQ2==0 ) return rc;
  1464. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  1465. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  1466. if( rc ){
  1467. fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
  1468. }else{
  1469. rc = SQLITE_CORRUPT;
  1470. }
  1471. sqlite3_free(zErr);
  1472. free(zQ2);
  1473. }
  1474. return rc;
  1475. }
  1476. /*
  1477. ** Text of a help message
  1478. */
  1479. static char zHelp[] =
  1480. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  1481. ".bail on|off Stop after hitting an error. Default OFF\n"
  1482. ".clone NEWDB Clone data into NEWDB from the existing database\n"
  1483. ".databases List names and files of attached databases\n"
  1484. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  1485. " If TABLE specified, only dump tables matching\n"
  1486. " LIKE pattern TABLE.\n"
  1487. ".echo on|off Turn command echo on or off\n"
  1488. ".eqp on|off Enable or disable automatic EXPLAIN QUERY PLAN\n"
  1489. ".exit Exit this program\n"
  1490. ".explain ?on|off? Turn output mode suitable for EXPLAIN on or off.\n"
  1491. " With no args, it turns EXPLAIN on.\n"
  1492. ".fullschema Show schema and the content of sqlite_stat tables\n"
  1493. ".headers on|off Turn display of headers on or off\n"
  1494. ".help Show this message\n"
  1495. ".import FILE TABLE Import data from FILE into TABLE\n"
  1496. ".indices ?TABLE? Show names of all indices\n"
  1497. " If TABLE specified, only show indices for tables\n"
  1498. " matching LIKE pattern TABLE.\n"
  1499. #ifdef SQLITE_ENABLE_IOTRACE
  1500. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  1501. #endif
  1502. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1503. ".load FILE ?ENTRY? Load an extension library\n"
  1504. #endif
  1505. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  1506. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  1507. " csv Comma-separated values\n"
  1508. " column Left-aligned columns. (See .width)\n"
  1509. " html HTML <table> code\n"
  1510. " insert SQL insert statements for TABLE\n"
  1511. " line One value per line\n"
  1512. " list Values delimited by .separator string\n"
  1513. " tabs Tab-separated values\n"
  1514. " tcl TCL list elements\n"
  1515. ".nullvalue STRING Use STRING in place of NULL values\n"
  1516. ".once FILENAME Output for the next SQL command only to FILENAME\n"
  1517. ".open ?FILENAME? Close existing database and reopen FILENAME\n"
  1518. ".output ?FILENAME? Send output to FILENAME or stdout\n"
  1519. ".print STRING... Print literal STRING\n"
  1520. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  1521. ".quit Exit this program\n"
  1522. ".read FILENAME Execute SQL in FILENAME\n"
  1523. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  1524. ".save FILE Write in-memory database into FILE\n"
  1525. ".schema ?TABLE? Show the CREATE statements\n"
  1526. " If TABLE specified, only show tables matching\n"
  1527. " LIKE pattern TABLE.\n"
  1528. ".separator STRING ?NL? Change separator used by output mode and .import\n"
  1529. " NL is the end-of-line mark for CSV\n"
  1530. ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
  1531. ".show Show the current values for various settings\n"
  1532. ".stats on|off Turn stats on or off\n"
  1533. ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
  1534. ".tables ?TABLE? List names of tables\n"
  1535. " If TABLE specified, only list tables matching\n"
  1536. " LIKE pattern TABLE.\n"
  1537. ".timeout MS Try opening locked tables for MS milliseconds\n"
  1538. ".timer on|off Turn SQL timer on or off\n"
  1539. ".trace FILE|off Output each SQL statement as it is run\n"
  1540. ".vfsname ?AUX? Print the name of the VFS stack\n"
  1541. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  1542. " Negative values right-justify\n"
  1543. ;
  1544. /* Forward reference */
  1545. static int process_input(ShellState *p, FILE *in);
  1546. /*
  1547. ** Implementation of the "readfile(X)" SQL function. The entire content
  1548. ** of the file named X is read and returned as a BLOB. NULL is returned
  1549. ** if the file does not exist or is unreadable.
  1550. */
  1551. static void readfileFunc(
  1552. sqlite3_context *context,
  1553. int argc,
  1554. sqlite3_value **argv
  1555. ){
  1556. const char *zName;
  1557. FILE *in;
  1558. long nIn;
  1559. void *pBuf;
  1560. zName = (const char*)sqlite3_value_text(argv[0]);
  1561. if( zName==0 ) return;
  1562. in = fopen(zName, "rb");
  1563. if( in==0 ) return;
  1564. fseek(in, 0, SEEK_END);
  1565. nIn = ftell(in);
  1566. rewind(in);
  1567. pBuf = sqlite3_malloc( nIn );
  1568. if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
  1569. sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
  1570. }else{
  1571. sqlite3_free(pBuf);
  1572. }
  1573. fclose(in);
  1574. }
  1575. /*
  1576. ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
  1577. ** is written into file X. The number of bytes written is returned. Or
  1578. ** NULL is returned if something goes wrong, such as being unable to open
  1579. ** file X for writing.
  1580. */
  1581. static void writefileFunc(
  1582. sqlite3_context *context,
  1583. int argc,
  1584. sqlite3_value **argv
  1585. ){
  1586. FILE *out;
  1587. const char *z;
  1588. sqlite3_int64 rc;
  1589. const char *zFile;
  1590. zFile = (const char*)sqlite3_value_text(argv[0]);
  1591. if( zFile==0 ) return;
  1592. out = fopen(zFile, "wb");
  1593. if( out==0 ) return;
  1594. z = (const char*)sqlite3_value_blob(argv[1]);
  1595. if( z==0 ){
  1596. rc = 0;
  1597. }else{
  1598. rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  1599. }
  1600. fclose(out);
  1601. sqlite3_result_int64(context, rc);
  1602. }
  1603. /*
  1604. ** Make sure the database is open. If it is not, then open it. If
  1605. ** the database fails to open, print an error message and exit.
  1606. */
  1607. static void open_db(ShellState *p, int keepAlive){
  1608. if( p->db==0 ){
  1609. sqlite3_initialize();
  1610. sqlite3_open(p->zDbFilename, &p->db);
  1611. db = p->db;
  1612. if( db && sqlite3_errcode(db)==SQLITE_OK ){
  1613. sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  1614. shellstaticFunc, 0, 0);
  1615. }
  1616. if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  1617. fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
  1618. p->zDbFilename, sqlite3_errmsg(db));
  1619. if( keepAlive ) return;
  1620. exit(1);
  1621. }
  1622. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1623. sqlite3_enable_load_extension(p->db, 1);
  1624. #endif
  1625. sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
  1626. readfileFunc, 0, 0);
  1627. sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
  1628. writefileFunc, 0, 0);
  1629. }
  1630. }
  1631. /*
  1632. ** Do C-language style dequoting.
  1633. **
  1634. ** \t -> tab
  1635. ** \n -> newline
  1636. ** \r -> carriage return
  1637. ** \" -> "
  1638. ** \NNN -> ascii character NNN in octal
  1639. ** \\ -> backslash
  1640. */
  1641. static void resolve_backslashes(char *z){
  1642. int i, j;
  1643. char c;
  1644. while( *z && *z!='\\' ) z++;
  1645. for(i=j=0; (c = z[i])!=0; i++, j++){
  1646. if( c=='\\' ){
  1647. c = z[++i];
  1648. if( c=='n' ){
  1649. c = '\n';
  1650. }else if( c=='t' ){
  1651. c = '\t';
  1652. }else if( c=='r' ){
  1653. c = '\r';
  1654. }else if( c=='\\' ){
  1655. c = '\\';
  1656. }else if( c>='0' && c<='7' ){
  1657. c -= '0';
  1658. if( z[i+1]>='0' && z[i+1]<='7' ){
  1659. i++;
  1660. c = (c<<3) + z[i] - '0';
  1661. if( z[i+1]>='0' && z[i+1]<='7' ){
  1662. i++;
  1663. c = (c<<3) + z[i] - '0';
  1664. }
  1665. }
  1666. }
  1667. }
  1668. z[j] = c;
  1669. }
  1670. if( j<i ) z[j] = 0;
  1671. }
  1672. /*
  1673. ** Return the value of a hexadecimal digit. Return -1 if the input
  1674. ** is not a hex digit.
  1675. */
  1676. static int hexDigitValue(char c){
  1677. if( c>='0' && c<='9' ) return c - '0';
  1678. if( c>='a' && c<='f' ) return c - 'a' + 10;
  1679. if( c>='A' && c<='F' ) return c - 'A' + 10;
  1680. return -1;
  1681. }
  1682. /*
  1683. ** Interpret zArg as an integer value, possibly with suffixes.
  1684. */
  1685. static sqlite3_int64 integerValue(const char *zArg){
  1686. sqlite3_int64 v = 0;
  1687. static const struct { char *zSuffix; int iMult; } aMult[] = {
  1688. { "KiB", 1024 },
  1689. { "MiB", 1024*1024 },
  1690. { "GiB", 1024*1024*1024 },
  1691. { "KB", 1000 },
  1692. { "MB", 1000000 },
  1693. { "GB", 1000000000 },
  1694. { "K", 1000 },
  1695. { "M", 1000000 },
  1696. { "G", 1000000000 },
  1697. };
  1698. int i;
  1699. int isNeg = 0;
  1700. if( zArg[0]=='-' ){
  1701. isNeg = 1;
  1702. zArg++;
  1703. }else if( zArg[0]=='+' ){
  1704. zArg++;
  1705. }
  1706. if( zArg[0]=='0' && zArg[1]=='x' ){
  1707. int x;
  1708. zArg += 2;
  1709. while( (x = hexDigitValue(zArg[0]))>=0 ){
  1710. v = (v<<4) + x;
  1711. zArg++;
  1712. }
  1713. }else{
  1714. while( IsDigit(zArg[0]) ){
  1715. v = v*10 + zArg[0] - '0';
  1716. zArg++;
  1717. }
  1718. }
  1719. for(i=0; i<ArraySize(aMult); i++){
  1720. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  1721. v *= aMult[i].iMult;
  1722. break;
  1723. }
  1724. }
  1725. return isNeg? -v : v;
  1726. }
  1727. /*
  1728. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  1729. ** for TRUE and FALSE. Return the integer value if appropriate.
  1730. */
  1731. static int booleanValue(char *zArg){
  1732. int i;
  1733. if( zArg[0]=='0' && zArg[1]=='x' ){
  1734. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  1735. }else{
  1736. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  1737. }
  1738. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  1739. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  1740. return 1;
  1741. }
  1742. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  1743. return 0;
  1744. }
  1745. fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  1746. zArg);
  1747. return 0;
  1748. }
  1749. /*
  1750. ** Close an output file, assuming it is not stderr or stdout
  1751. */
  1752. static void output_file_close(FILE *f){
  1753. if( f && f!=stdout && f!=stderr ) fclose(f);
  1754. }
  1755. /*
  1756. ** Try to open an output file. The names "stdout" and "stderr" are
  1757. ** recognized and do the right thing. NULL is returned if the output
  1758. ** filename is "off".
  1759. */
  1760. static FILE *output_file_open(const char *zFile){
  1761. FILE *f;
  1762. if( strcmp(zFile,"stdout")==0 ){
  1763. f = stdout;
  1764. }else if( strcmp(zFile, "stderr")==0 ){
  1765. f = stderr;
  1766. }else if( strcmp(zFile, "off")==0 ){
  1767. f = 0;
  1768. }else{
  1769. f = fopen(zFile, "wb");
  1770. if( f==0 ){
  1771. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  1772. }
  1773. }
  1774. return f;
  1775. }
  1776. /*
  1777. ** A routine for handling output from sqlite3_trace().
  1778. */
  1779. static void sql_trace_callback(void *pArg, const char *z){
  1780. FILE *f = (FILE*)pArg;
  1781. if( f ){
  1782. int i = (int)strlen(z);
  1783. while( i>0 && z[i-1]==';' ){ i--; }
  1784. fprintf(f, "%.*s;\n", i, z);
  1785. }
  1786. }
  1787. /*
  1788. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  1789. ** a useful spot to set a debugger breakpoint.
  1790. */
  1791. static void test_breakpoint(void){
  1792. static int nCall = 0;
  1793. nCall++;
  1794. }
  1795. /*
  1796. ** An object used to read a CSV file
  1797. */
  1798. typedef struct CSVReader CSVReader;
  1799. struct CSVReader {
  1800. const char *zFile; /* Name of the input file */
  1801. FILE *in; /* Read the CSV text from this input stream */
  1802. char *z; /* Accumulated text for a field */
  1803. int n; /* Number of bytes in z */
  1804. int nAlloc; /* Space allocated for z[] */
  1805. int nLine; /* Current line number */
  1806. int cTerm; /* Character that terminated the most recent field */
  1807. int cSeparator; /* The separator character. (Usually ",") */
  1808. };
  1809. /* Append a single byte to z[] */
  1810. static void csv_append_char(CSVReader *p, int c){
  1811. if( p->n+1>=p->nAlloc ){
  1812. p->nAlloc += p->nAlloc + 100;
  1813. p->z = sqlite3_realloc(p->z, p->nAlloc);
  1814. if( p->z==0 ){
  1815. fprintf(stderr, "out of memory\n");
  1816. exit(1);
  1817. }
  1818. }
  1819. p->z[p->n++] = (char)c;
  1820. }
  1821. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  1822. ** with the option of having a separator other than ",".
  1823. **
  1824. ** + Input comes from p->in.
  1825. ** + Store results in p->z of length p->n. Space to hold p->z comes
  1826. ** from sqlite3_malloc().
  1827. ** + Use p->cSep as the separator. The default is ",".
  1828. ** + Keep track of the line number in p->nLine.
  1829. ** + Store the character that terminates the field in p->cTerm. Store
  1830. ** EOF on end-of-file.
  1831. ** + Report syntax errors on stderr
  1832. */
  1833. static char *csv_read_one_field(CSVReader *p){
  1834. int c, pc, ppc;
  1835. int cSep = p->cSeparator;
  1836. p->n = 0;
  1837. c = fgetc(p->in);
  1838. if( c==EOF || seenInterrupt ){
  1839. p->cTerm = EOF;
  1840. return 0;
  1841. }
  1842. if( c=='"' ){
  1843. int startLine = p->nLine;
  1844. int cQuote = c;
  1845. pc = ppc = 0;
  1846. while( 1 ){
  1847. c = fgetc(p->in);
  1848. if( c=='\n' ) p->nLine++;
  1849. if( c==cQuote ){
  1850. if( pc==cQuote ){
  1851. pc = 0;
  1852. continue;
  1853. }
  1854. }
  1855. if( (c==cSep && pc==cQuote)
  1856. || (c=='\n' && pc==cQuote)
  1857. || (c=='\n' && pc=='\r' && ppc==cQuote)
  1858. || (c==EOF && pc==cQuote)
  1859. ){
  1860. do{ p->n--; }while( p->z[p->n]!=cQuote );
  1861. p->cTerm = c;
  1862. break;
  1863. }
  1864. if( pc==cQuote && c!='\r' ){
  1865. fprintf(stderr, "%s:%d: unescaped %c character\n",
  1866. p->zFile, p->nLine, cQuote);
  1867. }
  1868. if( c==EOF ){
  1869. fprintf(stderr, "%s:%d: unterminated %c-quoted field\n",
  1870. p->zFile, startLine, cQuote);
  1871. p->cTerm = EOF;
  1872. break;
  1873. }
  1874. csv_append_char(p, c);
  1875. ppc = pc;
  1876. pc = c;
  1877. }
  1878. }else{
  1879. while( c!=EOF && c!=cSep && c!='\n' ){
  1880. csv_append_char(p, c);
  1881. c = fgetc(p->in);
  1882. }
  1883. if( c=='\n' ){
  1884. p->nLine++;
  1885. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  1886. }
  1887. p->cTerm = c;
  1888. }
  1889. if( p->z ) p->z[p->n] = 0;
  1890. return p->z;
  1891. }
  1892. /*
  1893. ** Try to transfer data for table zTable. If an error is seen while
  1894. ** moving forward, try to go backwards. The backwards movement won't
  1895. ** work for WITHOUT ROWID tables.
  1896. */
  1897. static void tryToCloneData(
  1898. ShellState *p,
  1899. sqlite3 *newDb,
  1900. const char *zTable
  1901. ){
  1902. sqlite3_stmt *pQuery = 0;
  1903. sqlite3_stmt *pInsert = 0;
  1904. char *zQuery = 0;
  1905. char *zInsert = 0;
  1906. int rc;
  1907. int i, j, n;
  1908. int nTable = (int)strlen(zTable);
  1909. int k = 0;
  1910. int cnt = 0;
  1911. const int spinRate = 10000;
  1912. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  1913. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  1914. if( rc ){
  1915. fprintf(stderr, "Error %d: %s on [%s]\n",
  1916. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  1917. zQuery);
  1918. goto end_data_xfer;
  1919. }
  1920. n = sqlite3_column_count(pQuery);
  1921. zInsert = sqlite3_malloc(200 + nTable + n*3);
  1922. if( zInsert==0 ){
  1923. fprintf(stderr, "out of memory\n");
  1924. goto end_data_xfer;
  1925. }
  1926. sqlite3_snprintf(200+nTable,zInsert,
  1927. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  1928. i = (int)strlen(zInsert);
  1929. for(j=1; j<n; j++){
  1930. memcpy(zInsert+i, ",?", 2);
  1931. i += 2;
  1932. }
  1933. memcpy(zInsert+i, ");", 3);
  1934. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  1935. if( rc ){
  1936. fprintf(stderr, "Error %d: %s on [%s]\n",
  1937. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  1938. zQuery);
  1939. goto end_data_xfer;
  1940. }
  1941. for(k=0; k<2; k++){
  1942. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  1943. for(i=0; i<n; i++){
  1944. switch( sqlite3_column_type(pQuery, i) ){
  1945. case SQLITE_NULL: {
  1946. sqlite3_bind_null(pInsert, i+1);
  1947. break;
  1948. }
  1949. case SQLITE_INTEGER: {
  1950. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  1951. break;
  1952. }
  1953. case SQLITE_FLOAT: {
  1954. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  1955. break;
  1956. }
  1957. case SQLITE_TEXT: {
  1958. sqlite3_bind_text(pInsert, i+1,
  1959. (const char*)sqlite3_column_text(pQuery,i),
  1960. -1, SQLITE_STATIC);
  1961. break;
  1962. }
  1963. case SQLITE_BLOB: {
  1964. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  1965. sqlite3_column_bytes(pQuery,i),
  1966. SQLITE_STATIC);
  1967. break;
  1968. }
  1969. }
  1970. } /* End for */
  1971. rc = sqlite3_step(pInsert);
  1972. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  1973. fprintf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  1974. sqlite3_errmsg(newDb));
  1975. }
  1976. sqlite3_reset(pInsert);
  1977. cnt++;
  1978. if( (cnt%spinRate)==0 ){
  1979. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  1980. fflush(stdout);
  1981. }
  1982. } /* End while */
  1983. if( rc==SQLITE_DONE ) break;
  1984. sqlite3_finalize(pQuery);
  1985. sqlite3_free(zQuery);
  1986. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  1987. zTable);
  1988. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  1989. if( rc ){
  1990. fprintf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  1991. break;
  1992. }
  1993. } /* End for(k=0...) */
  1994. end_data_xfer:
  1995. sqlite3_finalize(pQuery);
  1996. sqlite3_finalize(pInsert);
  1997. sqlite3_free(zQuery);
  1998. sqlite3_free(zInsert);
  1999. }
  2000. /*
  2001. ** Try to transfer all rows of the schema that match zWhere. For
  2002. ** each row, invoke xForEach() on the object defined by that row.
  2003. ** If an error is encountered while moving forward through the
  2004. ** sqlite_master table, try again moving backwards.
  2005. */
  2006. static void tryToCloneSchema(
  2007. ShellState *p,
  2008. sqlite3 *newDb,
  2009. const char *zWhere,
  2010. void (*xForEach)(ShellState*,sqlite3*,const char*)
  2011. ){
  2012. sqlite3_stmt *pQuery = 0;
  2013. char *zQuery = 0;
  2014. int rc;
  2015. const unsigned char *zName;
  2016. const unsigned char *zSql;
  2017. char *zErrMsg = 0;
  2018. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2019. " WHERE %s", zWhere);
  2020. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2021. if( rc ){
  2022. fprintf(stderr, "Error: (%d) %s on [%s]\n",
  2023. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2024. zQuery);
  2025. goto end_schema_xfer;
  2026. }
  2027. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2028. zName = sqlite3_column_text(pQuery, 0);
  2029. zSql = sqlite3_column_text(pQuery, 1);
  2030. printf("%s... ", zName); fflush(stdout);
  2031. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2032. if( zErrMsg ){
  2033. fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2034. sqlite3_free(zErrMsg);
  2035. zErrMsg = 0;
  2036. }
  2037. if( xForEach ){
  2038. xForEach(p, newDb, (const char*)zName);
  2039. }
  2040. printf("done\n");
  2041. }
  2042. if( rc!=SQLITE_DONE ){
  2043. sqlite3_finalize(pQuery);
  2044. sqlite3_free(zQuery);
  2045. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2046. " WHERE %s ORDER BY rowid DESC", zWhere);
  2047. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2048. if( rc ){
  2049. fprintf(stderr, "Error: (%d) %s on [%s]\n",
  2050. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2051. zQuery);
  2052. goto end_schema_xfer;
  2053. }
  2054. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2055. zName = sqlite3_column_text(pQuery, 0);
  2056. zSql = sqlite3_column_text(pQuery, 1);
  2057. printf("%s... ", zName); fflush(stdout);
  2058. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2059. if( zErrMsg ){
  2060. fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2061. sqlite3_free(zErrMsg);
  2062. zErrMsg = 0;
  2063. }
  2064. if( xForEach ){
  2065. xForEach(p, newDb, (const char*)zName);
  2066. }
  2067. printf("done\n");
  2068. }
  2069. }
  2070. end_schema_xfer:
  2071. sqlite3_finalize(pQuery);
  2072. sqlite3_free(zQuery);
  2073. }
  2074. /*
  2075. ** Open a new database file named "zNewDb". Try to recover as much information
  2076. ** as possible out of the main database (which might be corrupt) and write it
  2077. ** into zNewDb.
  2078. */
  2079. static void tryToClone(ShellState *p, const char *zNewDb){
  2080. int rc;
  2081. sqlite3 *newDb = 0;
  2082. if( access(zNewDb,0)==0 ){
  2083. fprintf(stderr, "File \"%s\" already exists.\n", zNewDb);
  2084. return;
  2085. }
  2086. rc = sqlite3_open(zNewDb, &newDb);
  2087. if( rc ){
  2088. fprintf(stderr, "Cannot create output database: %s\n",
  2089. sqlite3_errmsg(newDb));
  2090. }else{
  2091. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  2092. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  2093. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  2094. tryToCloneSchema(p, newDb, "type!='table'", 0);
  2095. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  2096. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2097. }
  2098. sqlite3_close(newDb);
  2099. }
  2100. /*
  2101. ** Change the output file back to stdout
  2102. */
  2103. static void output_reset(ShellState *p){
  2104. if( p->outfile[0]=='|' ){
  2105. pclose(p->out);
  2106. }else{
  2107. output_file_close(p->out);
  2108. }
  2109. p->outfile[0] = 0;
  2110. p->out = stdout;
  2111. }
  2112. /*
  2113. ** If an input line begins with "." then invoke this routine to
  2114. ** process that line.
  2115. **
  2116. ** Return 1 on error, 2 to exit, and 0 otherwise.
  2117. */
  2118. static int do_meta_command(char *zLine, ShellState *p){
  2119. int i = 1;
  2120. int nArg = 0;
  2121. int n, c;
  2122. int rc = 0;
  2123. char *azArg[50];
  2124. /* Parse the input line into tokens.
  2125. */
  2126. while( zLine[i] && nArg<ArraySize(azArg) ){
  2127. while( IsSpace(zLine[i]) ){ i++; }
  2128. if( zLine[i]==0 ) break;
  2129. if( zLine[i]=='\'' || zLine[i]=='"' ){
  2130. int delim = zLine[i++];
  2131. azArg[nArg++] = &zLine[i];
  2132. while( zLine[i] && zLine[i]!=delim ){
  2133. if( zLine[i]=='\\' && delim=='"' && zLine[i+1]!=0 ) i++;
  2134. i++;
  2135. }
  2136. if( zLine[i]==delim ){
  2137. zLine[i++] = 0;
  2138. }
  2139. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  2140. }else{
  2141. azArg[nArg++] = &zLine[i];
  2142. while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
  2143. if( zLine[i] ) zLine[i++] = 0;
  2144. resolve_backslashes(azArg[nArg-1]);
  2145. }
  2146. }
  2147. /* Process the input line.
  2148. */
  2149. if( nArg==0 ) return 0; /* no tokens, no error */
  2150. n = strlen30(azArg[0]);
  2151. c = azArg[0][0];
  2152. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  2153. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  2154. ){
  2155. const char *zDestFile = 0;
  2156. const char *zDb = 0;
  2157. sqlite3 *pDest;
  2158. sqlite3_backup *pBackup;
  2159. int j;
  2160. for(j=1; j<nArg; j++){
  2161. const char *z = azArg[j];
  2162. if( z[0]=='-' ){
  2163. while( z[0]=='-' ) z++;
  2164. /* No options to process at this time */
  2165. {
  2166. fprintf(stderr, "unknown option: %s\n", azArg[j]);
  2167. return 1;
  2168. }
  2169. }else if( zDestFile==0 ){
  2170. zDestFile = azArg[j];
  2171. }else if( zDb==0 ){
  2172. zDb = zDestFile;
  2173. zDestFile = azArg[j];
  2174. }else{
  2175. fprintf(stderr, "too many arguments to .backup\n");
  2176. return 1;
  2177. }
  2178. }
  2179. if( zDestFile==0 ){
  2180. fprintf(stderr, "missing FILENAME argument on .backup\n");
  2181. return 1;
  2182. }
  2183. if( zDb==0 ) zDb = "main";
  2184. rc = sqlite3_open(zDestFile, &pDest);
  2185. if( rc!=SQLITE_OK ){
  2186. fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  2187. sqlite3_close(pDest);
  2188. return 1;
  2189. }
  2190. open_db(p, 0);
  2191. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  2192. if( pBackup==0 ){
  2193. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2194. sqlite3_close(pDest);
  2195. return 1;
  2196. }
  2197. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  2198. sqlite3_backup_finish(pBackup);
  2199. if( rc==SQLITE_DONE ){
  2200. rc = 0;
  2201. }else{
  2202. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2203. rc = 1;
  2204. }
  2205. sqlite3_close(pDest);
  2206. }else
  2207. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  2208. if( nArg==2 ){
  2209. bail_on_error = booleanValue(azArg[1]);
  2210. }else{
  2211. fprintf(stderr, "Usage: .bail on|off\n");
  2212. rc = 1;
  2213. }
  2214. }else
  2215. /* The undocumented ".breakpoint" command causes a call to the no-op
  2216. ** routine named test_breakpoint().
  2217. */
  2218. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  2219. test_breakpoint();
  2220. }else
  2221. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  2222. if( nArg==2 ){
  2223. tryToClone(p, azArg[1]);
  2224. }else{
  2225. fprintf(stderr, "Usage: .clone FILENAME\n");
  2226. rc = 1;
  2227. }
  2228. }else
  2229. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  2230. ShellState data;
  2231. char *zErrMsg = 0;
  2232. open_db(p, 0);
  2233. memcpy(&data, p, sizeof(data));
  2234. data.showHeader = 1;
  2235. data.mode = MODE_Column;
  2236. data.colWidth[0] = 3;
  2237. data.colWidth[1] = 15;
  2238. data.colWidth[2] = 58;
  2239. data.cnt = 0;
  2240. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  2241. if( zErrMsg ){
  2242. fprintf(stderr,"Error: %s\n", zErrMsg);
  2243. sqlite3_free(zErrMsg);
  2244. rc = 1;
  2245. }
  2246. }else
  2247. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  2248. open_db(p, 0);
  2249. /* When playing back a "dump", the content might appear in an order
  2250. ** which causes immediate foreign key constraints to be violated.
  2251. ** So disable foreign-key constraint enforcement to prevent problems. */
  2252. if( nArg!=1 && nArg!=2 ){
  2253. fprintf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
  2254. rc = 1;
  2255. goto meta_command_exit;
  2256. }
  2257. fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
  2258. fprintf(p->out, "BEGIN TRANSACTION;\n");
  2259. p->writableSchema = 0;
  2260. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  2261. p->nErr = 0;
  2262. if( nArg==1 ){
  2263. run_schema_dump_query(p,
  2264. "SELECT name, type, sql FROM sqlite_master "
  2265. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  2266. );
  2267. run_schema_dump_query(p,
  2268. "SELECT name, type, sql FROM sqlite_master "
  2269. "WHERE name=='sqlite_sequence'"
  2270. );
  2271. run_table_dump_query(p,
  2272. "SELECT sql FROM sqlite_master "
  2273. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  2274. );
  2275. }else{
  2276. int i;
  2277. for(i=1; i<nArg; i++){
  2278. zShellStatic = azArg[i];
  2279. run_schema_dump_query(p,
  2280. "SELECT name, type, sql FROM sqlite_master "
  2281. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  2282. " AND sql NOT NULL");
  2283. run_table_dump_query(p,
  2284. "SELECT sql FROM sqlite_master "
  2285. "WHERE sql NOT NULL"
  2286. " AND type IN ('index','trigger','view')"
  2287. " AND tbl_name LIKE shellstatic()", 0
  2288. );
  2289. zShellStatic = 0;
  2290. }
  2291. }
  2292. if( p->writableSchema ){
  2293. fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
  2294. p->writableSchema = 0;
  2295. }
  2296. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2297. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  2298. fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  2299. }else
  2300. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  2301. if( nArg==2 ){
  2302. p->echoOn = booleanValue(azArg[1]);
  2303. }else{
  2304. fprintf(stderr, "Usage: .echo on|off\n");
  2305. rc = 1;
  2306. }
  2307. }else
  2308. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  2309. if( nArg==2 ){
  2310. p->autoEQP = booleanValue(azArg[1]);
  2311. }else{
  2312. fprintf(stderr, "Usage: .eqp on|off\n");
  2313. rc = 1;
  2314. }
  2315. }else
  2316. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  2317. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  2318. rc = 2;
  2319. }else
  2320. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  2321. int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
  2322. if(val == 1) {
  2323. if(!p->normalMode.valid) {
  2324. p->normalMode.valid = 1;
  2325. p->normalMode.mode = p->mode;
  2326. p->normalMode.showHeader = p->showHeader;
  2327. memcpy(p->normalMode.colWidth,p->colWidth,sizeof(p->colWidth));
  2328. }
  2329. /* We could put this code under the !p->explainValid
  2330. ** condition so that it does not execute if we are already in
  2331. ** explain mode. However, always executing it allows us an easy
  2332. ** was to reset to explain mode in case the user previously
  2333. ** did an .explain followed by a .width, .mode or .header
  2334. ** command.
  2335. */
  2336. p->mode = MODE_Explain;
  2337. p->showHeader = 1;
  2338. memset(p->colWidth,0,sizeof(p->colWidth));
  2339. p->colWidth[0] = 4; /* addr */
  2340. p->colWidth[1] = 13; /* opcode */
  2341. p->colWidth[2] = 4; /* P1 */
  2342. p->colWidth[3] = 4; /* P2 */
  2343. p->colWidth[4] = 4; /* P3 */
  2344. p->colWidth[5] = 13; /* P4 */
  2345. p->colWidth[6] = 2; /* P5 */
  2346. p->colWidth[7] = 13; /* Comment */
  2347. }else if (p->normalMode.valid) {
  2348. p->normalMode.valid = 0;
  2349. p->mode = p->normalMode.mode;
  2350. p->showHeader = p->normalMode.showHeader;
  2351. memcpy(p->colWidth,p->normalMode.colWidth,sizeof(p->colWidth));
  2352. }
  2353. }else
  2354. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  2355. ShellState data;
  2356. char *zErrMsg = 0;
  2357. int doStats = 0;
  2358. if( nArg!=1 ){
  2359. fprintf(stderr, "Usage: .fullschema\n");
  2360. rc = 1;
  2361. goto meta_command_exit;
  2362. }
  2363. open_db(p, 0);
  2364. memcpy(&data, p, sizeof(data));
  2365. data.showHeader = 0;
  2366. data.mode = MODE_Semi;
  2367. rc = sqlite3_exec(p->db,
  2368. "SELECT sql FROM"
  2369. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  2370. " FROM sqlite_master UNION ALL"
  2371. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  2372. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  2373. "ORDER BY rowid",
  2374. callback, &data, &zErrMsg
  2375. );
  2376. if( rc==SQLITE_OK ){
  2377. sqlite3_stmt *pStmt;
  2378. rc = sqlite3_prepare_v2(p->db,
  2379. "SELECT rowid FROM sqlite_master"
  2380. " WHERE name GLOB 'sqlite_stat[134]'",
  2381. -1, &pStmt, 0);
  2382. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  2383. sqlite3_finalize(pStmt);
  2384. }
  2385. if( doStats==0 ){
  2386. fprintf(p->out, "/* No STAT tables available */\n");
  2387. }else{
  2388. fprintf(p->out, "ANALYZE sqlite_master;\n");
  2389. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  2390. callback, &data, &zErrMsg);
  2391. data.mode = MODE_Insert;
  2392. data.zDestTable = "sqlite_stat1";
  2393. shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  2394. shell_callback, &data,&zErrMsg);
  2395. data.zDestTable = "sqlite_stat3";
  2396. shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  2397. shell_callback, &data,&zErrMsg);
  2398. data.zDestTable = "sqlite_stat4";
  2399. shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  2400. shell_callback, &data, &zErrMsg);
  2401. fprintf(p->out, "ANALYZE sqlite_master;\n");
  2402. }
  2403. }else
  2404. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  2405. if( nArg==2 ){
  2406. p->showHeader = booleanValue(azArg[1]);
  2407. }else{
  2408. fprintf(stderr, "Usage: .headers on|off\n");
  2409. rc = 1;
  2410. }
  2411. }else
  2412. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  2413. fprintf(p->out, "%s", zHelp);
  2414. }else
  2415. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  2416. char *zTable; /* Insert data into this table */
  2417. char *zFile; /* Name of file to extra content from */
  2418. sqlite3_stmt *pStmt = NULL; /* A statement */
  2419. int nCol; /* Number of columns in the table */
  2420. int nByte; /* Number of bytes in an SQL string */
  2421. int i, j; /* Loop counters */
  2422. int needCommit; /* True to COMMIT or ROLLBACK at end */
  2423. int nSep; /* Number of bytes in p->separator[] */
  2424. char *zSql; /* An SQL statement */
  2425. CSVReader sCsv; /* Reader context */
  2426. int (*xCloser)(FILE*); /* Procedure to close th3 connection */
  2427. if( nArg!=3 ){
  2428. fprintf(stderr, "Usage: .import FILE TABLE\n");
  2429. goto meta_command_exit;
  2430. }
  2431. zFile = azArg[1];
  2432. zTable = azArg[2];
  2433. seenInterrupt = 0;
  2434. memset(&sCsv, 0, sizeof(sCsv));
  2435. open_db(p, 0);
  2436. nSep = strlen30(p->separator);
  2437. if( nSep==0 ){
  2438. fprintf(stderr, "Error: non-null separator required for import\n");
  2439. return 1;
  2440. }
  2441. if( nSep>1 ){
  2442. fprintf(stderr, "Error: multi-character separators not allowed"
  2443. " for import\n");
  2444. return 1;
  2445. }
  2446. sCsv.zFile = zFile;
  2447. sCsv.nLine = 1;
  2448. if( sCsv.zFile[0]=='|' ){
  2449. sCsv.in = popen(sCsv.zFile+1, "r");
  2450. sCsv.zFile = "<pipe>";
  2451. xCloser = pclose;
  2452. }else{
  2453. sCsv.in = fopen(sCsv.zFile, "rb");
  2454. xCloser = fclose;
  2455. }
  2456. if( sCsv.in==0 ){
  2457. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2458. return 1;
  2459. }
  2460. sCsv.cSeparator = p->separator[0];
  2461. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  2462. if( zSql==0 ){
  2463. fprintf(stderr, "Error: out of memory\n");
  2464. xCloser(sCsv.in);
  2465. return 1;
  2466. }
  2467. nByte = strlen30(zSql);
  2468. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2469. csv_append_char(&sCsv, 0); /* To ensure sCsv.z is allocated */
  2470. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){
  2471. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  2472. char cSep = '(';
  2473. while( csv_read_one_field(&sCsv) ){
  2474. zCreate = sqlite3_mprintf("%z%c\n \"%s\" TEXT", zCreate, cSep, sCsv.z);
  2475. cSep = ',';
  2476. if( sCsv.cTerm!=sCsv.cSeparator ) break;
  2477. }
  2478. if( cSep=='(' ){
  2479. sqlite3_free(zCreate);
  2480. sqlite3_free(sCsv.z);
  2481. xCloser(sCsv.in);
  2482. fprintf(stderr,"%s: empty file\n", sCsv.zFile);
  2483. return 1;
  2484. }
  2485. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  2486. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  2487. sqlite3_free(zCreate);
  2488. if( rc ){
  2489. fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  2490. sqlite3_errmsg(db));
  2491. sqlite3_free(sCsv.z);
  2492. xCloser(sCsv.in);
  2493. return 1;
  2494. }
  2495. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2496. }
  2497. sqlite3_free(zSql);
  2498. if( rc ){
  2499. if (pStmt) sqlite3_finalize(pStmt);
  2500. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  2501. xCloser(sCsv.in);
  2502. return 1;
  2503. }
  2504. nCol = sqlite3_column_count(pStmt);
  2505. sqlite3_finalize(pStmt);
  2506. pStmt = 0;
  2507. if( nCol==0 ) return 0; /* no columns, no error */
  2508. zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 );
  2509. if( zSql==0 ){
  2510. fprintf(stderr, "Error: out of memory\n");
  2511. xCloser(sCsv.in);
  2512. return 1;
  2513. }
  2514. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  2515. j = strlen30(zSql);
  2516. for(i=1; i<nCol; i++){
  2517. zSql[j++] = ',';
  2518. zSql[j++] = '?';
  2519. }
  2520. zSql[j++] = ')';
  2521. zSql[j] = 0;
  2522. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2523. sqlite3_free(zSql);
  2524. if( rc ){
  2525. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  2526. if (pStmt) sqlite3_finalize(pStmt);
  2527. xCloser(sCsv.in);
  2528. return 1;
  2529. }
  2530. needCommit = sqlite3_get_autocommit(db);
  2531. if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0);
  2532. do{
  2533. int startLine = sCsv.nLine;
  2534. for(i=0; i<nCol; i++){
  2535. char *z = csv_read_one_field(&sCsv);
  2536. if( z==0 && i==0 ) break;
  2537. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  2538. if( i<nCol-1 && sCsv.cTerm!=sCsv.cSeparator ){
  2539. fprintf(stderr, "%s:%d: expected %d columns but found %d - "
  2540. "filling the rest with NULL\n",
  2541. sCsv.zFile, startLine, nCol, i+1);
  2542. i++;
  2543. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  2544. }
  2545. }
  2546. if( sCsv.cTerm==sCsv.cSeparator ){
  2547. do{
  2548. csv_read_one_field(&sCsv);
  2549. i++;
  2550. }while( sCsv.cTerm==sCsv.cSeparator );
  2551. fprintf(stderr, "%s:%d: expected %d columns but found %d - "
  2552. "extras ignored\n",
  2553. sCsv.zFile, startLine, nCol, i);
  2554. }
  2555. if( i>=nCol ){
  2556. sqlite3_step(pStmt);
  2557. rc = sqlite3_reset(pStmt);
  2558. if( rc!=SQLITE_OK ){
  2559. fprintf(stderr, "%s:%d: INSERT failed: %s\n", sCsv.zFile, startLine,
  2560. sqlite3_errmsg(db));
  2561. }
  2562. }
  2563. }while( sCsv.cTerm!=EOF );
  2564. xCloser(sCsv.in);
  2565. sqlite3_free(sCsv.z);
  2566. sqlite3_finalize(pStmt);
  2567. if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0);
  2568. }else
  2569. if( c=='i' && strncmp(azArg[0], "indices", n)==0 ){
  2570. ShellState data;
  2571. char *zErrMsg = 0;
  2572. open_db(p, 0);
  2573. memcpy(&data, p, sizeof(data));
  2574. data.showHeader = 0;
  2575. data.mode = MODE_List;
  2576. if( nArg==1 ){
  2577. rc = sqlite3_exec(p->db,
  2578. "SELECT name FROM sqlite_master "
  2579. "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  2580. "UNION ALL "
  2581. "SELECT name FROM sqlite_temp_master "
  2582. "WHERE type='index' "
  2583. "ORDER BY 1",
  2584. callback, &data, &zErrMsg
  2585. );
  2586. }else if( nArg==2 ){
  2587. zShellStatic = azArg[1];
  2588. rc = sqlite3_exec(p->db,
  2589. "SELECT name FROM sqlite_master "
  2590. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  2591. "UNION ALL "
  2592. "SELECT name FROM sqlite_temp_master "
  2593. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  2594. "ORDER BY 1",
  2595. callback, &data, &zErrMsg
  2596. );
  2597. zShellStatic = 0;
  2598. }else{
  2599. fprintf(stderr, "Usage: .indices ?LIKE-PATTERN?\n");
  2600. rc = 1;
  2601. goto meta_command_exit;
  2602. }
  2603. if( zErrMsg ){
  2604. fprintf(stderr,"Error: %s\n", zErrMsg);
  2605. sqlite3_free(zErrMsg);
  2606. rc = 1;
  2607. }else if( rc != SQLITE_OK ){
  2608. fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  2609. rc = 1;
  2610. }
  2611. }else
  2612. #ifdef SQLITE_ENABLE_IOTRACE
  2613. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  2614. extern void (*sqlite3IoTrace)(const char*, ...);
  2615. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  2616. iotrace = 0;
  2617. if( nArg<2 ){
  2618. sqlite3IoTrace = 0;
  2619. }else if( strcmp(azArg[1], "-")==0 ){
  2620. sqlite3IoTrace = iotracePrintf;
  2621. iotrace = stdout;
  2622. }else{
  2623. iotrace = fopen(azArg[1], "w");
  2624. if( iotrace==0 ){
  2625. fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  2626. sqlite3IoTrace = 0;
  2627. rc = 1;
  2628. }else{
  2629. sqlite3IoTrace = iotracePrintf;
  2630. }
  2631. }
  2632. }else
  2633. #endif
  2634. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2635. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  2636. const char *zFile, *zProc;
  2637. char *zErrMsg = 0;
  2638. if( nArg<2 ){
  2639. fprintf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  2640. rc = 1;
  2641. goto meta_command_exit;
  2642. }
  2643. zFile = azArg[1];
  2644. zProc = nArg>=3 ? azArg[2] : 0;
  2645. open_db(p, 0);
  2646. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  2647. if( rc!=SQLITE_OK ){
  2648. fprintf(stderr, "Error: %s\n", zErrMsg);
  2649. sqlite3_free(zErrMsg);
  2650. rc = 1;
  2651. }
  2652. }else
  2653. #endif
  2654. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  2655. if( nArg!=2 ){
  2656. fprintf(stderr, "Usage: .log FILENAME\n");
  2657. rc = 1;
  2658. }else{
  2659. const char *zFile = azArg[1];
  2660. output_file_close(p->pLog);
  2661. p->pLog = output_file_open(zFile);
  2662. }
  2663. }else
  2664. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  2665. const char *zMode = nArg>=2 ? azArg[1] : "";
  2666. int n2 = (int)strlen(zMode);
  2667. int c2 = zMode[0];
  2668. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  2669. p->mode = MODE_Line;
  2670. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  2671. p->mode = MODE_Column;
  2672. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  2673. p->mode = MODE_List;
  2674. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  2675. p->mode = MODE_Html;
  2676. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  2677. p->mode = MODE_Tcl;
  2678. sqlite3_snprintf(sizeof(p->separator), p->separator, " ");
  2679. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  2680. p->mode = MODE_Csv;
  2681. sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
  2682. sqlite3_snprintf(sizeof(p->newline), p->newline, "\r\n");
  2683. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  2684. p->mode = MODE_List;
  2685. sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
  2686. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  2687. p->mode = MODE_Insert;
  2688. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  2689. }else {
  2690. fprintf(stderr,"Error: mode should be one of: "
  2691. "column csv html insert line list tabs tcl\n");
  2692. rc = 1;
  2693. }
  2694. }else
  2695. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  2696. if( nArg==2 ){
  2697. sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  2698. "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  2699. }else{
  2700. fprintf(stderr, "Usage: .nullvalue STRING\n");
  2701. rc = 1;
  2702. }
  2703. }else
  2704. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  2705. sqlite3 *savedDb = p->db;
  2706. const char *zSavedFilename = p->zDbFilename;
  2707. char *zNewFilename = 0;
  2708. p->db = 0;
  2709. if( nArg>=2 ){
  2710. p->zDbFilename = zNewFilename = sqlite3_mprintf("%s", azArg[1]);
  2711. }
  2712. open_db(p, 1);
  2713. if( p->db!=0 ){
  2714. sqlite3_close(savedDb);
  2715. sqlite3_free(p->zFreeOnClose);
  2716. p->zFreeOnClose = zNewFilename;
  2717. }else{
  2718. sqlite3_free(zNewFilename);
  2719. p->db = savedDb;
  2720. p->zDbFilename = zSavedFilename;
  2721. }
  2722. }else
  2723. if( c=='o'
  2724. && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  2725. ){
  2726. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  2727. if( nArg>2 ){
  2728. fprintf(stderr, "Usage: .%s FILE\n", azArg[0]);
  2729. rc = 1;
  2730. goto meta_command_exit;
  2731. }
  2732. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  2733. if( nArg<2 ){
  2734. fprintf(stderr, "Usage: .once FILE\n");
  2735. rc = 1;
  2736. goto meta_command_exit;
  2737. }
  2738. p->outCount = 2;
  2739. }else{
  2740. p->outCount = 0;
  2741. }
  2742. output_reset(p);
  2743. if( zFile[0]=='|' ){
  2744. p->out = popen(zFile + 1, "w");
  2745. if( p->out==0 ){
  2746. fprintf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  2747. p->out = stdout;
  2748. rc = 1;
  2749. }else{
  2750. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  2751. }
  2752. }else{
  2753. p->out = output_file_open(zFile);
  2754. if( p->out==0 ){
  2755. if( strcmp(zFile,"off")!=0 ){
  2756. fprintf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  2757. }
  2758. p->out = stdout;
  2759. rc = 1;
  2760. } else {
  2761. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  2762. }
  2763. }
  2764. }else
  2765. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  2766. int i;
  2767. for(i=1; i<nArg; i++){
  2768. if( i>1 ) fprintf(p->out, " ");
  2769. fprintf(p->out, "%s", azArg[i]);
  2770. }
  2771. fprintf(p->out, "\n");
  2772. }else
  2773. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  2774. if( nArg >= 2) {
  2775. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  2776. }
  2777. if( nArg >= 3) {
  2778. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  2779. }
  2780. }else
  2781. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  2782. rc = 2;
  2783. }else
  2784. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  2785. FILE *alt;
  2786. if( nArg!=2 ){
  2787. fprintf(stderr, "Usage: .read FILE\n");
  2788. rc = 1;
  2789. goto meta_command_exit;
  2790. }
  2791. alt = fopen(azArg[1], "rb");
  2792. if( alt==0 ){
  2793. fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  2794. rc = 1;
  2795. }else{
  2796. rc = process_input(p, alt);
  2797. fclose(alt);
  2798. }
  2799. }else
  2800. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  2801. const char *zSrcFile;
  2802. const char *zDb;
  2803. sqlite3 *pSrc;
  2804. sqlite3_backup *pBackup;
  2805. int nTimeout = 0;
  2806. if( nArg==2 ){
  2807. zSrcFile = azArg[1];
  2808. zDb = "main";
  2809. }else if( nArg==3 ){
  2810. zSrcFile = azArg[2];
  2811. zDb = azArg[1];
  2812. }else{
  2813. fprintf(stderr, "Usage: .restore ?DB? FILE\n");
  2814. rc = 1;
  2815. goto meta_command_exit;
  2816. }
  2817. rc = sqlite3_open(zSrcFile, &pSrc);
  2818. if( rc!=SQLITE_OK ){
  2819. fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  2820. sqlite3_close(pSrc);
  2821. return 1;
  2822. }
  2823. open_db(p, 0);
  2824. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  2825. if( pBackup==0 ){
  2826. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  2827. sqlite3_close(pSrc);
  2828. return 1;
  2829. }
  2830. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  2831. || rc==SQLITE_BUSY ){
  2832. if( rc==SQLITE_BUSY ){
  2833. if( nTimeout++ >= 3 ) break;
  2834. sqlite3_sleep(100);
  2835. }
  2836. }
  2837. sqlite3_backup_finish(pBackup);
  2838. if( rc==SQLITE_DONE ){
  2839. rc = 0;
  2840. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  2841. fprintf(stderr, "Error: source database is busy\n");
  2842. rc = 1;
  2843. }else{
  2844. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  2845. rc = 1;
  2846. }
  2847. sqlite3_close(pSrc);
  2848. }else
  2849. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  2850. ShellState data;
  2851. char *zErrMsg = 0;
  2852. open_db(p, 0);
  2853. memcpy(&data, p, sizeof(data));
  2854. data.showHeader = 0;
  2855. data.mode = MODE_Semi;
  2856. if( nArg==2 ){
  2857. int i;
  2858. for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  2859. if( strcmp(azArg[1],"sqlite_master")==0 ){
  2860. char *new_argv[2], *new_colv[2];
  2861. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  2862. " type text,\n"
  2863. " name text,\n"
  2864. " tbl_name text,\n"
  2865. " rootpage integer,\n"
  2866. " sql text\n"
  2867. ")";
  2868. new_argv[1] = 0;
  2869. new_colv[0] = "sql";
  2870. new_colv[1] = 0;
  2871. callback(&data, 1, new_argv, new_colv);
  2872. rc = SQLITE_OK;
  2873. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  2874. char *new_argv[2], *new_colv[2];
  2875. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  2876. " type text,\n"
  2877. " name text,\n"
  2878. " tbl_name text,\n"
  2879. " rootpage integer,\n"
  2880. " sql text\n"
  2881. ")";
  2882. new_argv[1] = 0;
  2883. new_colv[0] = "sql";
  2884. new_colv[1] = 0;
  2885. callback(&data, 1, new_argv, new_colv);
  2886. rc = SQLITE_OK;
  2887. }else{
  2888. zShellStatic = azArg[1];
  2889. rc = sqlite3_exec(p->db,
  2890. "SELECT sql FROM "
  2891. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  2892. " FROM sqlite_master UNION ALL"
  2893. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  2894. "WHERE lower(tbl_name) LIKE shellstatic()"
  2895. " AND type!='meta' AND sql NOTNULL "
  2896. "ORDER BY rowid",
  2897. callback, &data, &zErrMsg);
  2898. zShellStatic = 0;
  2899. }
  2900. }else if( nArg==1 ){
  2901. rc = sqlite3_exec(p->db,
  2902. "SELECT sql FROM "
  2903. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  2904. " FROM sqlite_master UNION ALL"
  2905. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  2906. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  2907. "ORDER BY rowid",
  2908. callback, &data, &zErrMsg
  2909. );
  2910. }else{
  2911. fprintf(stderr, "Usage: .schema ?LIKE-PATTERN?\n");
  2912. rc = 1;
  2913. goto meta_command_exit;
  2914. }
  2915. if( zErrMsg ){
  2916. fprintf(stderr,"Error: %s\n", zErrMsg);
  2917. sqlite3_free(zErrMsg);
  2918. rc = 1;
  2919. }else if( rc != SQLITE_OK ){
  2920. fprintf(stderr,"Error: querying schema information\n");
  2921. rc = 1;
  2922. }else{
  2923. rc = 0;
  2924. }
  2925. }else
  2926. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  2927. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  2928. extern int sqlite3SelectTrace;
  2929. sqlite3SelectTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  2930. }else
  2931. #endif
  2932. #ifdef SQLITE_DEBUG
  2933. /* Undocumented commands for internal testing. Subject to change
  2934. ** without notice. */
  2935. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  2936. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  2937. int i, v;
  2938. for(i=1; i<nArg; i++){
  2939. v = booleanValue(azArg[i]);
  2940. fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  2941. }
  2942. }
  2943. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  2944. int i; sqlite3_int64 v;
  2945. for(i=1; i<nArg; i++){
  2946. char zBuf[200];
  2947. v = integerValue(azArg[i]);
  2948. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  2949. fprintf(p->out, "%s", zBuf);
  2950. }
  2951. }
  2952. }else
  2953. #endif
  2954. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  2955. if( nArg<2 || nArg>3 ){
  2956. fprintf(stderr, "Usage: .separator SEPARATOR ?NEWLINE?\n");
  2957. rc = 1;
  2958. }
  2959. if( nArg>=2 ){
  2960. sqlite3_snprintf(sizeof(p->separator), p->separator, azArg[1]);
  2961. }
  2962. if( nArg>=3 ){
  2963. sqlite3_snprintf(sizeof(p->newline), p->newline, azArg[2]);
  2964. }
  2965. }else
  2966. if( c=='s'
  2967. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  2968. ){
  2969. char *zCmd;
  2970. int i, x;
  2971. if( nArg<2 ){
  2972. fprintf(stderr, "Usage: .system COMMAND\n");
  2973. rc = 1;
  2974. goto meta_command_exit;
  2975. }
  2976. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  2977. for(i=2; i<nArg; i++){
  2978. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  2979. zCmd, azArg[i]);
  2980. }
  2981. x = system(zCmd);
  2982. sqlite3_free(zCmd);
  2983. if( x ) fprintf(stderr, "System command returns %d\n", x);
  2984. }else
  2985. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  2986. int i;
  2987. if( nArg!=1 ){
  2988. fprintf(stderr, "Usage: .show\n");
  2989. rc = 1;
  2990. goto meta_command_exit;
  2991. }
  2992. fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  2993. fprintf(p->out,"%9.9s: %s\n","eqp", p->autoEQP ? "on" : "off");
  2994. fprintf(p->out,"%9.9s: %s\n","explain", p->normalMode.valid ? "on" :"off");
  2995. fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  2996. fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  2997. fprintf(p->out,"%9.9s: ", "nullvalue");
  2998. output_c_string(p->out, p->nullvalue);
  2999. fprintf(p->out, "\n");
  3000. fprintf(p->out,"%9.9s: %s\n","output",
  3001. strlen30(p->outfile) ? p->outfile : "stdout");
  3002. fprintf(p->out,"%9.9s: ", "separator");
  3003. output_c_string(p->out, p->separator);
  3004. fprintf(p->out," ");
  3005. output_c_string(p->out, p->newline);
  3006. fprintf(p->out, "\n");
  3007. fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
  3008. fprintf(p->out,"%9.9s: ","width");
  3009. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  3010. fprintf(p->out,"%d ",p->colWidth[i]);
  3011. }
  3012. fprintf(p->out,"\n");
  3013. }else
  3014. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  3015. if( nArg==2 ){
  3016. p->statsOn = booleanValue(azArg[1]);
  3017. }else{
  3018. fprintf(stderr, "Usage: .stats on|off\n");
  3019. rc = 1;
  3020. }
  3021. }else
  3022. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  3023. sqlite3_stmt *pStmt;
  3024. char **azResult;
  3025. int nRow, nAlloc;
  3026. char *zSql = 0;
  3027. int ii;
  3028. open_db(p, 0);
  3029. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  3030. if( rc ) return rc;
  3031. zSql = sqlite3_mprintf(
  3032. "SELECT name FROM sqlite_master"
  3033. " WHERE type IN ('table','view')"
  3034. " AND name NOT LIKE 'sqlite_%%'"
  3035. " AND name LIKE ?1");
  3036. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3037. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  3038. if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
  3039. if( strcmp(zDbName,"temp")==0 ){
  3040. zSql = sqlite3_mprintf(
  3041. "%z UNION ALL "
  3042. "SELECT 'temp.' || name FROM sqlite_temp_master"
  3043. " WHERE type IN ('table','view')"
  3044. " AND name NOT LIKE 'sqlite_%%'"
  3045. " AND name LIKE ?1", zSql);
  3046. }else{
  3047. zSql = sqlite3_mprintf(
  3048. "%z UNION ALL "
  3049. "SELECT '%q.' || name FROM \"%w\".sqlite_master"
  3050. " WHERE type IN ('table','view')"
  3051. " AND name NOT LIKE 'sqlite_%%'"
  3052. " AND name LIKE ?1", zSql, zDbName, zDbName);
  3053. }
  3054. }
  3055. sqlite3_finalize(pStmt);
  3056. zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
  3057. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3058. sqlite3_free(zSql);
  3059. if( rc ) return rc;
  3060. nRow = nAlloc = 0;
  3061. azResult = 0;
  3062. if( nArg>1 ){
  3063. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  3064. }else{
  3065. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  3066. }
  3067. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3068. if( nRow>=nAlloc ){
  3069. char **azNew;
  3070. int n = nAlloc*2 + 10;
  3071. azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n);
  3072. if( azNew==0 ){
  3073. fprintf(stderr, "Error: out of memory\n");
  3074. break;
  3075. }
  3076. nAlloc = n;
  3077. azResult = azNew;
  3078. }
  3079. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  3080. if( azResult[nRow] ) nRow++;
  3081. }
  3082. sqlite3_finalize(pStmt);
  3083. if( nRow>0 ){
  3084. int len, maxlen = 0;
  3085. int i, j;
  3086. int nPrintCol, nPrintRow;
  3087. for(i=0; i<nRow; i++){
  3088. len = strlen30(azResult[i]);
  3089. if( len>maxlen ) maxlen = len;
  3090. }
  3091. nPrintCol = 80/(maxlen+2);
  3092. if( nPrintCol<1 ) nPrintCol = 1;
  3093. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  3094. for(i=0; i<nPrintRow; i++){
  3095. for(j=i; j<nRow; j+=nPrintRow){
  3096. char *zSp = j<nPrintRow ? "" : " ";
  3097. fprintf(p->out, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  3098. }
  3099. fprintf(p->out, "\n");
  3100. }
  3101. }
  3102. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  3103. sqlite3_free(azResult);
  3104. }else
  3105. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  3106. static const struct {
  3107. const char *zCtrlName; /* Name of a test-control option */
  3108. int ctrlCode; /* Integer code for that option */
  3109. } aCtrl[] = {
  3110. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
  3111. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
  3112. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
  3113. { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
  3114. { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
  3115. { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
  3116. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
  3117. { "assert", SQLITE_TESTCTRL_ASSERT },
  3118. { "always", SQLITE_TESTCTRL_ALWAYS },
  3119. { "reserve", SQLITE_TESTCTRL_RESERVE },
  3120. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
  3121. { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
  3122. { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
  3123. { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
  3124. };
  3125. int testctrl = -1;
  3126. int rc = 0;
  3127. int i, n;
  3128. open_db(p, 0);
  3129. /* convert testctrl text option to value. allow any unique prefix
  3130. ** of the option name, or a numerical value. */
  3131. n = strlen30(azArg[1]);
  3132. for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
  3133. if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
  3134. if( testctrl<0 ){
  3135. testctrl = aCtrl[i].ctrlCode;
  3136. }else{
  3137. fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  3138. testctrl = -1;
  3139. break;
  3140. }
  3141. }
  3142. }
  3143. if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  3144. if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  3145. fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  3146. }else{
  3147. switch(testctrl){
  3148. /* sqlite3_test_control(int, db, int) */
  3149. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  3150. case SQLITE_TESTCTRL_RESERVE:
  3151. if( nArg==3 ){
  3152. int opt = (int)strtol(azArg[2], 0, 0);
  3153. rc = sqlite3_test_control(testctrl, p->db, opt);
  3154. fprintf(p->out, "%d (0x%08x)\n", rc, rc);
  3155. } else {
  3156. fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  3157. azArg[1]);
  3158. }
  3159. break;
  3160. /* sqlite3_test_control(int) */
  3161. case SQLITE_TESTCTRL_PRNG_SAVE:
  3162. case SQLITE_TESTCTRL_PRNG_RESTORE:
  3163. case SQLITE_TESTCTRL_PRNG_RESET:
  3164. case SQLITE_TESTCTRL_BYTEORDER:
  3165. if( nArg==2 ){
  3166. rc = sqlite3_test_control(testctrl);
  3167. fprintf(p->out, "%d (0x%08x)\n", rc, rc);
  3168. } else {
  3169. fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
  3170. }
  3171. break;
  3172. /* sqlite3_test_control(int, uint) */
  3173. case SQLITE_TESTCTRL_PENDING_BYTE:
  3174. if( nArg==3 ){
  3175. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  3176. rc = sqlite3_test_control(testctrl, opt);
  3177. fprintf(p->out, "%d (0x%08x)\n", rc, rc);
  3178. } else {
  3179. fprintf(stderr,"Error: testctrl %s takes a single unsigned"
  3180. " int option\n", azArg[1]);
  3181. }
  3182. break;
  3183. /* sqlite3_test_control(int, int) */
  3184. case SQLITE_TESTCTRL_ASSERT:
  3185. case SQLITE_TESTCTRL_ALWAYS:
  3186. if( nArg==3 ){
  3187. int opt = booleanValue(azArg[2]);
  3188. rc = sqlite3_test_control(testctrl, opt);
  3189. fprintf(p->out, "%d (0x%08x)\n", rc, rc);
  3190. } else {
  3191. fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  3192. azArg[1]);
  3193. }
  3194. break;
  3195. /* sqlite3_test_control(int, char *) */
  3196. #ifdef SQLITE_N_KEYWORD
  3197. case SQLITE_TESTCTRL_ISKEYWORD:
  3198. if( nArg==3 ){
  3199. const char *opt = azArg[2];
  3200. rc = sqlite3_test_control(testctrl, opt);
  3201. fprintf(p->out, "%d (0x%08x)\n", rc, rc);
  3202. } else {
  3203. fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
  3204. azArg[1]);
  3205. }
  3206. break;
  3207. #endif
  3208. case SQLITE_TESTCTRL_BITVEC_TEST:
  3209. case SQLITE_TESTCTRL_FAULT_INSTALL:
  3210. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  3211. case SQLITE_TESTCTRL_SCRATCHMALLOC:
  3212. default:
  3213. fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
  3214. azArg[1]);
  3215. break;
  3216. }
  3217. }
  3218. }else
  3219. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  3220. open_db(p, 0);
  3221. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  3222. }else
  3223. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  3224. if( nArg==2 ){
  3225. enableTimer = booleanValue(azArg[1]);
  3226. if( enableTimer && !HAS_TIMER ){
  3227. fprintf(stderr, "Error: timer not available on this system.\n");
  3228. enableTimer = 0;
  3229. }
  3230. }else{
  3231. fprintf(stderr, "Usage: .timer on|off\n");
  3232. rc = 1;
  3233. }
  3234. }else
  3235. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  3236. open_db(p, 0);
  3237. output_file_close(p->traceOut);
  3238. if( nArg!=2 ){
  3239. fprintf(stderr, "Usage: .trace FILE|off\n");
  3240. rc = 1;
  3241. goto meta_command_exit;
  3242. }
  3243. p->traceOut = output_file_open(azArg[1]);
  3244. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  3245. if( p->traceOut==0 ){
  3246. sqlite3_trace(p->db, 0, 0);
  3247. }else{
  3248. sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
  3249. }
  3250. #endif
  3251. }else
  3252. #if SQLITE_USER_AUTHENTICATION
  3253. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  3254. if( nArg<2 ){
  3255. fprintf(stderr, "Usage: .user SUBCOMMAND ...\n");
  3256. rc = 1;
  3257. goto meta_command_exit;
  3258. }
  3259. open_db(p, 0);
  3260. if( strcmp(azArg[1],"login")==0 ){
  3261. if( nArg!=4 ){
  3262. fprintf(stderr, "Usage: .user login USER PASSWORD\n");
  3263. rc = 1;
  3264. goto meta_command_exit;
  3265. }
  3266. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  3267. (int)strlen(azArg[3]));
  3268. if( rc ){
  3269. fprintf(stderr, "Authentication failed for user %s\n", azArg[2]);
  3270. rc = 1;
  3271. }
  3272. }else if( strcmp(azArg[1],"add")==0 ){
  3273. if( nArg!=5 ){
  3274. fprintf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  3275. rc = 1;
  3276. goto meta_command_exit;
  3277. }
  3278. rc = sqlite3_user_add(p->db, azArg[2],
  3279. azArg[3], (int)strlen(azArg[3]),
  3280. booleanValue(azArg[4]));
  3281. if( rc ){
  3282. fprintf(stderr, "User-Add failed: %d\n", rc);
  3283. rc = 1;
  3284. }
  3285. }else if( strcmp(azArg[1],"edit")==0 ){
  3286. if( nArg!=5 ){
  3287. fprintf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  3288. rc = 1;
  3289. goto meta_command_exit;
  3290. }
  3291. rc = sqlite3_user_change(p->db, azArg[2],
  3292. azArg[3], (int)strlen(azArg[3]),
  3293. booleanValue(azArg[4]));
  3294. if( rc ){
  3295. fprintf(stderr, "User-Edit failed: %d\n", rc);
  3296. rc = 1;
  3297. }
  3298. }else if( strcmp(azArg[1],"delete")==0 ){
  3299. if( nArg!=3 ){
  3300. fprintf(stderr, "Usage: .user delete USER\n");
  3301. rc = 1;
  3302. goto meta_command_exit;
  3303. }
  3304. rc = sqlite3_user_delete(p->db, azArg[2]);
  3305. if( rc ){
  3306. fprintf(stderr, "User-Delete failed: %d\n", rc);
  3307. rc = 1;
  3308. }
  3309. }else{
  3310. fprintf(stderr, "Usage: .user login|add|edit|delete ...\n");
  3311. rc = 1;
  3312. goto meta_command_exit;
  3313. }
  3314. }else
  3315. #endif /* SQLITE_USER_AUTHENTICATION */
  3316. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  3317. fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  3318. sqlite3_libversion(), sqlite3_sourceid());
  3319. }else
  3320. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  3321. const char *zDbName = nArg==2 ? azArg[1] : "main";
  3322. char *zVfsName = 0;
  3323. if( p->db ){
  3324. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  3325. if( zVfsName ){
  3326. fprintf(p->out, "%s\n", zVfsName);
  3327. sqlite3_free(zVfsName);
  3328. }
  3329. }
  3330. }else
  3331. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  3332. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  3333. extern int sqlite3WhereTrace;
  3334. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  3335. }else
  3336. #endif
  3337. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  3338. int j;
  3339. assert( nArg<=ArraySize(azArg) );
  3340. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  3341. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  3342. }
  3343. }else
  3344. {
  3345. fprintf(stderr, "Error: unknown command or invalid arguments: "
  3346. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  3347. rc = 1;
  3348. }
  3349. meta_command_exit:
  3350. if( p->outCount ){
  3351. p->outCount--;
  3352. if( p->outCount==0 ) output_reset(p);
  3353. }
  3354. return rc;
  3355. }
  3356. /*
  3357. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  3358. ** of string z[].
  3359. */
  3360. static int line_contains_semicolon(const char *z, int N){
  3361. int i;
  3362. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  3363. return 0;
  3364. }
  3365. /*
  3366. ** Test to see if a line consists entirely of whitespace.
  3367. */
  3368. static int _all_whitespace(const char *z){
  3369. for(; *z; z++){
  3370. if( IsSpace(z[0]) ) continue;
  3371. if( *z=='/' && z[1]=='*' ){
  3372. z += 2;
  3373. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  3374. if( *z==0 ) return 0;
  3375. z++;
  3376. continue;
  3377. }
  3378. if( *z=='-' && z[1]=='-' ){
  3379. z += 2;
  3380. while( *z && *z!='\n' ){ z++; }
  3381. if( *z==0 ) return 1;
  3382. continue;
  3383. }
  3384. return 0;
  3385. }
  3386. return 1;
  3387. }
  3388. /*
  3389. ** Return TRUE if the line typed in is an SQL command terminator other
  3390. ** than a semi-colon. The SQL Server style "go" command is understood
  3391. ** as is the Oracle "/".
  3392. */
  3393. static int line_is_command_terminator(const char *zLine){
  3394. while( IsSpace(zLine[0]) ){ zLine++; };
  3395. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  3396. return 1; /* Oracle */
  3397. }
  3398. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  3399. && _all_whitespace(&zLine[2]) ){
  3400. return 1; /* SQL Server */
  3401. }
  3402. return 0;
  3403. }
  3404. /*
  3405. ** Return true if zSql is a complete SQL statement. Return false if it
  3406. ** ends in the middle of a string literal or C-style comment.
  3407. */
  3408. static int line_is_complete(char *zSql, int nSql){
  3409. int rc;
  3410. if( zSql==0 ) return 1;
  3411. zSql[nSql] = ';';
  3412. zSql[nSql+1] = 0;
  3413. rc = sqlite3_complete(zSql);
  3414. zSql[nSql] = 0;
  3415. return rc;
  3416. }
  3417. /*
  3418. ** Read input from *in and process it. If *in==0 then input
  3419. ** is interactive - the user is typing it it. Otherwise, input
  3420. ** is coming from a file or device. A prompt is issued and history
  3421. ** is saved only if input is interactive. An interrupt signal will
  3422. ** cause this routine to exit immediately, unless input is interactive.
  3423. **
  3424. ** Return the number of errors.
  3425. */
  3426. static int process_input(ShellState *p, FILE *in){
  3427. char *zLine = 0; /* A single input line */
  3428. char *zSql = 0; /* Accumulated SQL text */
  3429. int nLine; /* Length of current line */
  3430. int nSql = 0; /* Bytes of zSql[] used */
  3431. int nAlloc = 0; /* Allocated zSql[] space */
  3432. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  3433. char *zErrMsg; /* Error message returned */
  3434. int rc; /* Error code */
  3435. int errCnt = 0; /* Number of errors seen */
  3436. int lineno = 0; /* Current line number */
  3437. int startline = 0; /* Line number for start of current input */
  3438. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  3439. fflush(p->out);
  3440. zLine = one_input_line(in, zLine, nSql>0);
  3441. if( zLine==0 ){
  3442. /* End of input */
  3443. if( stdin_is_interactive ) printf("\n");
  3444. break;
  3445. }
  3446. if( seenInterrupt ){
  3447. if( in!=0 ) break;
  3448. seenInterrupt = 0;
  3449. }
  3450. lineno++;
  3451. if( nSql==0 && _all_whitespace(zLine) ){
  3452. if( p->echoOn ) printf("%s\n", zLine);
  3453. continue;
  3454. }
  3455. if( zLine && zLine[0]=='.' && nSql==0 ){
  3456. if( p->echoOn ) printf("%s\n", zLine);
  3457. rc = do_meta_command(zLine, p);
  3458. if( rc==2 ){ /* exit requested */
  3459. break;
  3460. }else if( rc ){
  3461. errCnt++;
  3462. }
  3463. continue;
  3464. }
  3465. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  3466. memcpy(zLine,";",2);
  3467. }
  3468. nLine = strlen30(zLine);
  3469. if( nSql+nLine+2>=nAlloc ){
  3470. nAlloc = nSql+nLine+100;
  3471. zSql = realloc(zSql, nAlloc);
  3472. if( zSql==0 ){
  3473. fprintf(stderr, "Error: out of memory\n");
  3474. exit(1);
  3475. }
  3476. }
  3477. nSqlPrior = nSql;
  3478. if( nSql==0 ){
  3479. int i;
  3480. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  3481. assert( nAlloc>0 && zSql!=0 );
  3482. memcpy(zSql, zLine+i, nLine+1-i);
  3483. startline = lineno;
  3484. nSql = nLine-i;
  3485. }else{
  3486. zSql[nSql++] = '\n';
  3487. memcpy(zSql+nSql, zLine, nLine+1);
  3488. nSql += nLine;
  3489. }
  3490. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  3491. && sqlite3_complete(zSql) ){
  3492. p->cnt = 0;
  3493. open_db(p, 0);
  3494. BEGIN_TIMER;
  3495. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  3496. END_TIMER;
  3497. if( rc || zErrMsg ){
  3498. char zPrefix[100];
  3499. if( in!=0 || !stdin_is_interactive ){
  3500. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  3501. "Error: near line %d:", startline);
  3502. }else{
  3503. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  3504. }
  3505. if( zErrMsg!=0 ){
  3506. fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
  3507. sqlite3_free(zErrMsg);
  3508. zErrMsg = 0;
  3509. }else{
  3510. fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  3511. }
  3512. errCnt++;
  3513. }
  3514. nSql = 0;
  3515. if( p->outCount ){
  3516. output_reset(p);
  3517. p->outCount = 0;
  3518. }
  3519. }else if( nSql && _all_whitespace(zSql) ){
  3520. if( p->echoOn ) printf("%s\n", zSql);
  3521. nSql = 0;
  3522. }
  3523. }
  3524. if( nSql ){
  3525. if( !_all_whitespace(zSql) ){
  3526. fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
  3527. errCnt++;
  3528. }
  3529. free(zSql);
  3530. }
  3531. free(zLine);
  3532. return errCnt>0;
  3533. }
  3534. /*
  3535. ** Return a pathname which is the user's home directory. A
  3536. ** 0 return indicates an error of some kind.
  3537. */
  3538. static char *find_home_dir(void){
  3539. static char *home_dir = NULL;
  3540. if( home_dir ) return home_dir;
  3541. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  3542. {
  3543. struct passwd *pwent;
  3544. uid_t uid = getuid();
  3545. if( (pwent=getpwuid(uid)) != NULL) {
  3546. home_dir = pwent->pw_dir;
  3547. }
  3548. }
  3549. #endif
  3550. #if defined(_WIN32_WCE)
  3551. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  3552. */
  3553. home_dir = "/";
  3554. #else
  3555. #if defined(_WIN32) || defined(WIN32)
  3556. if (!home_dir) {
  3557. home_dir = getenv("USERPROFILE");
  3558. }
  3559. #endif
  3560. if (!home_dir) {
  3561. home_dir = getenv("HOME");
  3562. }
  3563. #if defined(_WIN32) || defined(WIN32)
  3564. if (!home_dir) {
  3565. char *zDrive, *zPath;
  3566. int n;
  3567. zDrive = getenv("HOMEDRIVE");
  3568. zPath = getenv("HOMEPATH");
  3569. if( zDrive && zPath ){
  3570. n = strlen30(zDrive) + strlen30(zPath) + 1;
  3571. home_dir = malloc( n );
  3572. if( home_dir==0 ) return 0;
  3573. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  3574. return home_dir;
  3575. }
  3576. home_dir = "c:\\";
  3577. }
  3578. #endif
  3579. #endif /* !_WIN32_WCE */
  3580. if( home_dir ){
  3581. int n = strlen30(home_dir) + 1;
  3582. char *z = malloc( n );
  3583. if( z ) memcpy(z, home_dir, n);
  3584. home_dir = z;
  3585. }
  3586. return home_dir;
  3587. }
  3588. /*
  3589. ** Read input from the file given by sqliterc_override. Or if that
  3590. ** parameter is NULL, take input from ~/.sqliterc
  3591. **
  3592. ** Returns the number of errors.
  3593. */
  3594. static int process_sqliterc(
  3595. ShellState *p, /* Configuration data */
  3596. const char *sqliterc_override /* Name of config file. NULL to use default */
  3597. ){
  3598. char *home_dir = NULL;
  3599. const char *sqliterc = sqliterc_override;
  3600. char *zBuf = 0;
  3601. FILE *in = NULL;
  3602. int rc = 0;
  3603. if (sqliterc == NULL) {
  3604. home_dir = find_home_dir();
  3605. if( home_dir==0 ){
  3606. #if !defined(__RTP__) && !defined(_WRS_KERNEL)
  3607. fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
  3608. #endif
  3609. return 1;
  3610. }
  3611. sqlite3_initialize();
  3612. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  3613. sqliterc = zBuf;
  3614. }
  3615. in = fopen(sqliterc,"rb");
  3616. if( in ){
  3617. if( stdin_is_interactive ){
  3618. fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
  3619. }
  3620. rc = process_input(p,in);
  3621. fclose(in);
  3622. }
  3623. sqlite3_free(zBuf);
  3624. return rc;
  3625. }
  3626. /*
  3627. ** Show available command line options
  3628. */
  3629. static const char zOptions[] =
  3630. " -bail stop after hitting an error\n"
  3631. " -batch force batch I/O\n"
  3632. " -column set output mode to 'column'\n"
  3633. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  3634. " -csv set output mode to 'csv'\n"
  3635. " -echo print commands before execution\n"
  3636. " -init FILENAME read/process named file\n"
  3637. " -[no]header turn headers on or off\n"
  3638. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  3639. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  3640. #endif
  3641. " -help show this message\n"
  3642. " -html set output mode to HTML\n"
  3643. " -interactive force interactive I/O\n"
  3644. " -line set output mode to 'line'\n"
  3645. " -list set output mode to 'list'\n"
  3646. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  3647. " -mmap N default mmap size set to N\n"
  3648. #ifdef SQLITE_ENABLE_MULTIPLEX
  3649. " -multiplex enable the multiplexor VFS\n"
  3650. #endif
  3651. " -newline SEP set newline character(s) for CSV\n"
  3652. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  3653. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  3654. " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
  3655. " -separator SEP set output field separator. Default: '|'\n"
  3656. " -stats print memory stats before each finalize\n"
  3657. " -version show SQLite version\n"
  3658. " -vfs NAME use NAME as the default VFS\n"
  3659. #ifdef SQLITE_ENABLE_VFSTRACE
  3660. " -vfstrace enable tracing of all VFS calls\n"
  3661. #endif
  3662. ;
  3663. static void usage(int showDetail){
  3664. fprintf(stderr,
  3665. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  3666. "FILENAME is the name of an SQLite database. A new database is created\n"
  3667. "if the file does not previously exist.\n", Argv0);
  3668. if( showDetail ){
  3669. fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  3670. }else{
  3671. fprintf(stderr, "Use the -help option for additional information\n");
  3672. }
  3673. exit(1);
  3674. }
  3675. /*
  3676. ** Initialize the state information in data
  3677. */
  3678. static void main_init(ShellState *data) {
  3679. memset(data, 0, sizeof(*data));
  3680. data->mode = MODE_List;
  3681. memcpy(data->separator,"|", 2);
  3682. memcpy(data->newline,"\r\n", 3);
  3683. data->showHeader = 0;
  3684. data->shellFlgs = SHFLG_Lookaside;
  3685. sqlite3_config(SQLITE_CONFIG_URI, 1);
  3686. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  3687. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  3688. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  3689. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  3690. }
  3691. /*
  3692. ** Output text to the console in a font that attracts extra attention.
  3693. */
  3694. #ifdef _WIN32
  3695. static void printBold(const char *zText){
  3696. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  3697. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  3698. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  3699. SetConsoleTextAttribute(out,
  3700. FOREGROUND_RED|FOREGROUND_INTENSITY
  3701. );
  3702. printf("%s", zText);
  3703. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  3704. }
  3705. #else
  3706. static void printBold(const char *zText){
  3707. printf("\033[1m%s\033[0m", zText);
  3708. }
  3709. #endif
  3710. /*
  3711. ** Get the argument to an --option. Throw an error and die if no argument
  3712. ** is available.
  3713. */
  3714. static char *cmdline_option_value(int argc, char **argv, int i){
  3715. if( i==argc ){
  3716. fprintf(stderr, "%s: Error: missing argument to %s\n",
  3717. argv[0], argv[argc-1]);
  3718. exit(1);
  3719. }
  3720. return argv[i];
  3721. }
  3722. int main(int argc, char **argv){
  3723. char *zErrMsg = 0;
  3724. ShellState data;
  3725. const char *zInitFile = 0;
  3726. char *zFirstCmd = 0;
  3727. int i;
  3728. int rc = 0;
  3729. int warnInmemoryDb = 0;
  3730. #if USE_SYSTEM_SQLITE+0!=1
  3731. if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  3732. fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  3733. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  3734. exit(1);
  3735. }
  3736. #endif
  3737. Argv0 = argv[0];
  3738. main_init(&data);
  3739. stdin_is_interactive = isatty(0);
  3740. /* Make sure we have a valid signal handler early, before anything
  3741. ** else is done.
  3742. */
  3743. #ifdef SIGINT
  3744. signal(SIGINT, interrupt_handler);
  3745. #endif
  3746. /* Do an initial pass through the command-line argument to locate
  3747. ** the name of the database file, the name of the initialization file,
  3748. ** the size of the alternative malloc heap,
  3749. ** and the first command to execute.
  3750. */
  3751. for(i=1; i<argc; i++){
  3752. char *z;
  3753. z = argv[i];
  3754. if( z[0]!='-' ){
  3755. if( data.zDbFilename==0 ){
  3756. data.zDbFilename = z;
  3757. continue;
  3758. }
  3759. if( zFirstCmd==0 ){
  3760. zFirstCmd = z;
  3761. continue;
  3762. }
  3763. fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
  3764. fprintf(stderr,"Use -help for a list of options.\n");
  3765. return 1;
  3766. }
  3767. if( z[1]=='-' ) z++;
  3768. if( strcmp(z,"-separator")==0
  3769. || strcmp(z,"-nullvalue")==0
  3770. || strcmp(z,"-newline")==0
  3771. || strcmp(z,"-cmd")==0
  3772. ){
  3773. (void)cmdline_option_value(argc, argv, ++i);
  3774. }else if( strcmp(z,"-init")==0 ){
  3775. zInitFile = cmdline_option_value(argc, argv, ++i);
  3776. }else if( strcmp(z,"-batch")==0 ){
  3777. /* Need to check for batch mode here to so we can avoid printing
  3778. ** informational messages (like from process_sqliterc) before
  3779. ** we do the actual processing of arguments later in a second pass.
  3780. */
  3781. stdin_is_interactive = 0;
  3782. }else if( strcmp(z,"-heap")==0 ){
  3783. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  3784. const char *zSize;
  3785. sqlite3_int64 szHeap;
  3786. zSize = cmdline_option_value(argc, argv, ++i);
  3787. szHeap = integerValue(zSize);
  3788. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  3789. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  3790. #endif
  3791. }else if( strcmp(z,"-scratch")==0 ){
  3792. int n, sz;
  3793. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3794. if( sz>400000 ) sz = 400000;
  3795. if( sz<2500 ) sz = 2500;
  3796. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3797. if( n>10 ) n = 10;
  3798. if( n<1 ) n = 1;
  3799. sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
  3800. data.shellFlgs |= SHFLG_Scratch;
  3801. }else if( strcmp(z,"-pagecache")==0 ){
  3802. int n, sz;
  3803. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3804. if( sz>70000 ) sz = 70000;
  3805. if( sz<800 ) sz = 800;
  3806. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3807. if( n<10 ) n = 10;
  3808. sqlite3_config(SQLITE_CONFIG_PAGECACHE, malloc(n*sz+1), sz, n);
  3809. data.shellFlgs |= SHFLG_Pagecache;
  3810. }else if( strcmp(z,"-lookaside")==0 ){
  3811. int n, sz;
  3812. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3813. if( sz<0 ) sz = 0;
  3814. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  3815. if( n<0 ) n = 0;
  3816. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  3817. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  3818. #ifdef SQLITE_ENABLE_VFSTRACE
  3819. }else if( strcmp(z,"-vfstrace")==0 ){
  3820. extern int vfstrace_register(
  3821. const char *zTraceName,
  3822. const char *zOldVfsName,
  3823. int (*xOut)(const char*,void*),
  3824. void *pOutArg,
  3825. int makeDefault
  3826. );
  3827. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  3828. #endif
  3829. #ifdef SQLITE_ENABLE_MULTIPLEX
  3830. }else if( strcmp(z,"-multiplex")==0 ){
  3831. extern int sqlite3_multiple_initialize(const char*,int);
  3832. sqlite3_multiplex_initialize(0, 1);
  3833. #endif
  3834. }else if( strcmp(z,"-mmap")==0 ){
  3835. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  3836. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  3837. }else if( strcmp(z,"-vfs")==0 ){
  3838. sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  3839. if( pVfs ){
  3840. sqlite3_vfs_register(pVfs, 1);
  3841. }else{
  3842. fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  3843. exit(1);
  3844. }
  3845. }
  3846. }
  3847. if( data.zDbFilename==0 ){
  3848. #ifndef SQLITE_OMIT_MEMORYDB
  3849. data.zDbFilename = ":memory:";
  3850. warnInmemoryDb = argc==1;
  3851. #else
  3852. fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
  3853. return 1;
  3854. #endif
  3855. #ifdef SQLITE_SHELL_DBNAME_PROC
  3856. { extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  3857. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  3858. warnInmemoryDb = 0; }
  3859. #endif
  3860. }
  3861. data.out = stdout;
  3862. /* Go ahead and open the database file if it already exists. If the
  3863. ** file does not exist, delay opening it. This prevents empty database
  3864. ** files from being created if a user mistypes the database name argument
  3865. ** to the sqlite command-line tool.
  3866. */
  3867. if( access(data.zDbFilename, 0)==0 ){
  3868. open_db(&data, 0);
  3869. }
  3870. /* Process the initialization file if there is one. If no -init option
  3871. ** is given on the command line, look for a file named ~/.sqliterc and
  3872. ** try to process it.
  3873. */
  3874. rc = process_sqliterc(&data,zInitFile);
  3875. if( rc>0 ){
  3876. return rc;
  3877. }
  3878. /* Make a second pass through the command-line argument and set
  3879. ** options. This second pass is delayed until after the initialization
  3880. ** file is processed so that the command-line arguments will override
  3881. ** settings in the initialization file.
  3882. */
  3883. for(i=1; i<argc; i++){
  3884. char *z = argv[i];
  3885. if( z[0]!='-' ) continue;
  3886. if( z[1]=='-' ){ z++; }
  3887. if( strcmp(z,"-init")==0 ){
  3888. i++;
  3889. }else if( strcmp(z,"-html")==0 ){
  3890. data.mode = MODE_Html;
  3891. }else if( strcmp(z,"-list")==0 ){
  3892. data.mode = MODE_List;
  3893. }else if( strcmp(z,"-line")==0 ){
  3894. data.mode = MODE_Line;
  3895. }else if( strcmp(z,"-column")==0 ){
  3896. data.mode = MODE_Column;
  3897. }else if( strcmp(z,"-csv")==0 ){
  3898. data.mode = MODE_Csv;
  3899. memcpy(data.separator,",",2);
  3900. }else if( strcmp(z,"-separator")==0 ){
  3901. sqlite3_snprintf(sizeof(data.separator), data.separator,
  3902. "%s",cmdline_option_value(argc,argv,++i));
  3903. }else if( strcmp(z,"-newline")==0 ){
  3904. sqlite3_snprintf(sizeof(data.newline), data.newline,
  3905. "%s",cmdline_option_value(argc,argv,++i));
  3906. }else if( strcmp(z,"-nullvalue")==0 ){
  3907. sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
  3908. "%s",cmdline_option_value(argc,argv,++i));
  3909. }else if( strcmp(z,"-header")==0 ){
  3910. data.showHeader = 1;
  3911. }else if( strcmp(z,"-noheader")==0 ){
  3912. data.showHeader = 0;
  3913. }else if( strcmp(z,"-echo")==0 ){
  3914. data.echoOn = 1;
  3915. }else if( strcmp(z,"-eqp")==0 ){
  3916. data.autoEQP = 1;
  3917. }else if( strcmp(z,"-stats")==0 ){
  3918. data.statsOn = 1;
  3919. }else if( strcmp(z,"-bail")==0 ){
  3920. bail_on_error = 1;
  3921. }else if( strcmp(z,"-version")==0 ){
  3922. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  3923. return 0;
  3924. }else if( strcmp(z,"-interactive")==0 ){
  3925. stdin_is_interactive = 1;
  3926. }else if( strcmp(z,"-batch")==0 ){
  3927. stdin_is_interactive = 0;
  3928. }else if( strcmp(z,"-heap")==0 ){
  3929. i++;
  3930. }else if( strcmp(z,"-scratch")==0 ){
  3931. i+=2;
  3932. }else if( strcmp(z,"-pagecache")==0 ){
  3933. i+=2;
  3934. }else if( strcmp(z,"-lookaside")==0 ){
  3935. i+=2;
  3936. }else if( strcmp(z,"-mmap")==0 ){
  3937. i++;
  3938. }else if( strcmp(z,"-vfs")==0 ){
  3939. i++;
  3940. #ifdef SQLITE_ENABLE_VFSTRACE
  3941. }else if( strcmp(z,"-vfstrace")==0 ){
  3942. i++;
  3943. #endif
  3944. #ifdef SQLITE_ENABLE_MULTIPLEX
  3945. }else if( strcmp(z,"-multiplex")==0 ){
  3946. i++;
  3947. #endif
  3948. }else if( strcmp(z,"-help")==0 ){
  3949. usage(1);
  3950. }else if( strcmp(z,"-cmd")==0 ){
  3951. if( i==argc-1 ) break;
  3952. z = cmdline_option_value(argc,argv,++i);
  3953. if( z[0]=='.' ){
  3954. rc = do_meta_command(z, &data);
  3955. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  3956. }else{
  3957. open_db(&data, 0);
  3958. rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  3959. if( zErrMsg!=0 ){
  3960. fprintf(stderr,"Error: %s\n", zErrMsg);
  3961. if( bail_on_error ) return rc!=0 ? rc : 1;
  3962. }else if( rc!=0 ){
  3963. fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  3964. if( bail_on_error ) return rc;
  3965. }
  3966. }
  3967. }else{
  3968. fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  3969. fprintf(stderr,"Use -help for a list of options.\n");
  3970. return 1;
  3971. }
  3972. }
  3973. if( zFirstCmd ){
  3974. /* Run just the command that follows the database name
  3975. */
  3976. if( zFirstCmd[0]=='.' ){
  3977. rc = do_meta_command(zFirstCmd, &data);
  3978. if( rc==2 ) rc = 0;
  3979. }else{
  3980. open_db(&data, 0);
  3981. rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
  3982. if( zErrMsg!=0 ){
  3983. fprintf(stderr,"Error: %s\n", zErrMsg);
  3984. return rc!=0 ? rc : 1;
  3985. }else if( rc!=0 ){
  3986. fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
  3987. return rc;
  3988. }
  3989. }
  3990. }else{
  3991. /* Run commands received from standard input
  3992. */
  3993. if( stdin_is_interactive ){
  3994. char *zHome;
  3995. char *zHistory = 0;
  3996. int nHistory;
  3997. printf(
  3998. "SQLite version %s %.19s\n" /*extra-version-info*/
  3999. "Enter \".help\" for usage hints.\n",
  4000. sqlite3_libversion(), sqlite3_sourceid()
  4001. );
  4002. if( warnInmemoryDb ){
  4003. printf("Connected to a ");
  4004. printBold("transient in-memory database");
  4005. printf(".\nUse \".open FILENAME\" to reopen on a "
  4006. "persistent database.\n");
  4007. }
  4008. zHome = find_home_dir();
  4009. if( zHome ){
  4010. nHistory = strlen30(zHome) + 20;
  4011. if( (zHistory = malloc(nHistory))!=0 ){
  4012. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  4013. }
  4014. }
  4015. #if defined(HAVE_READLINE)
  4016. if( zHistory ) read_history(zHistory);
  4017. #endif
  4018. rc = process_input(&data, 0);
  4019. if( zHistory ){
  4020. stifle_history(100);
  4021. write_history(zHistory);
  4022. free(zHistory);
  4023. }
  4024. }else{
  4025. rc = process_input(&data, stdin);
  4026. }
  4027. }
  4028. set_table_name(&data, 0);
  4029. if( data.db ){
  4030. sqlite3_close(data.db);
  4031. }
  4032. sqlite3_free(data.zFreeOnClose);
  4033. return rc;
  4034. }